Skip to content

Commit bee02f2

Browse files
committed
fix: harden hnsw+vec0, add true RaBitQ
1 parent 391dcee commit bee02f2

15 files changed

Lines changed: 1798 additions & 278 deletions

‎BENCHMARKS.md‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,42 @@
22

33
Apple M4 Max, 16-core, macOS 26.5. YAMS debug build with asan+coverage.
44

5+
## Quantized two-stage HNSW search (quantized_search_benchmark)
6+
7+
10,000 Gaussian vectors, 100 queries, k=10, debugoptimized build. True RaBitQ
8+
(arXiv:2405.12497: FWHT rotation + unbiased estimator + 4-bit query planes)
9+
replaced the previous sign-quantization heuristic in 2026-06.
10+
11+
### 128d, ef_search=100
12+
13+
| Method | Latency (us) | Recall@10 | Quant Memory |
14+
|--------|--------------|-----------|--------------|
15+
| FP32 baseline | 214 | 98.1% | 0 B |
16+
| LVQ-8 (3x rerank) | 430 | 99.8% | 1,360,000 B |
17+
| LVQ-4 (3x rerank) | 435 | 99.9% | 720,000 B |
18+
| RaBitQ (3x rerank) | 437 | 94.9% | 240,544 B |
19+
| RaBitQ (5x rerank) | 609 | 98.0% | 240,544 B |
20+
21+
Previous sign-quantization RaBitQ at this cell: 76.6% (3x) / 85.5% (5x).
22+
23+
### 768d, ef_search=100/200
24+
25+
| Method | Latency (us) | Recall@10 | Quant Memory |
26+
|--------|--------------|-----------|--------------|
27+
| FP32 baseline (ef=100) | 921 | 90.2% | 0 B |
28+
| LVQ-8 (3x, ef=100) | 1,430 | 99.3% | 7,760,000 B |
29+
| LVQ-4 (3x, ef=100) | 1,470 | 99.4% | 3,920,000 B |
30+
| RaBitQ (3x, ef=100) | 733 | 96.7% | 1,363,328 B |
31+
| RaBitQ (5x, ef=100) | 1,233 | 99.3% | 1,363,328 B |
32+
| RaBitQ (3x, ef=200) | 1,152 | 99.6% | 1,363,328 B |
33+
| RaBitQ (5x, ef=200) | 1,586 | 100.0% | 1,363,328 B |
34+
35+
At 768d RaBitQ dominates the latency/recall/memory frontier: popcount cost
36+
scales with D/8 while LVQ scales with D. Extended (multi-bit) RaBitQ was
37+
evaluated as a follow-up and deferred: 1-bit codes + FP32 rerank already match
38+
LVQ-8 recall at 5.7x less memory, so extra bits buy nothing in the two-stage
39+
configuration.
40+
541
## Search engine comparison (vector_backend_engine_compare)
642

743
2000 normalized random vectors, 50 queries, 128 dimensions, k=10.
@@ -13,6 +49,55 @@ Apple M4 Max, 16-core, macOS 26.5. YAMS debug build with asan+coverage.
1349

1450
Note: vec0-l2 mean is inflated by first-query HNSW build; evaluate p95 for steady-state.
1551

52+
### simeon-pq rerank fix (2026-06-09)
53+
54+
The historical 73.6% recall was caused by a rerank bug in
55+
`simeonPqSearchUnlocked`: candidates were selected in approximate-ADC order
56+
and the exact cosine was computed for display only, so `rerank_factor` had no
57+
effect on selection. After the fix (exact-score all `k*rerank` candidates,
58+
sort by exact similarity, take top-k), the `--spq-sweep` cell at the same
59+
2K/128d configuration measures:
60+
61+
| m | rerank | recall@10 | mean (us) |
62+
|---|--------|-----------|-----------|
63+
| 32 | 2 (default) | 94.0% | 14,535 |
64+
| 32 | 4 | 99.4% | 18,693 |
65+
| 32 | 8 | 100.0% | 23,668 |
66+
| 16 | 8 | 96.0% | 20,161 |
67+
| 64 | 2 | 100.0% | 21,314 |
68+
69+
Pre-fix, every rerank row measured identically (73.6% at m=32). Remaining
70+
latency is the brute-force ADC scan plus per-candidate record fetch, not the
71+
rerank stage.
72+
73+
At 768d on random Gaussian vectors (PQ worst case, no structure), the fix
74+
makes rerank effective (m=8: 16.0% → 37.2% across rerank 2→8) but absolute
75+
recall stays low (m=32/rerank=2: 34.4%; m=64/rerank=4: 67.8%) — consistent
76+
with the existing PQ-recall-vs-dimension section. For ≥768d corpora prefer
77+
the vec0-l2 engine or m≥64 with rerank≥4; judge real (non-Gaussian) corpora
78+
separately before changing defaults.
79+
80+
## HNSW delete-policy churn (hnsw_churn_benchmark)
81+
82+
10K Gaussian vectors, 128d, 10 cycles of (delete 500 + insert 500), k=10,
83+
ef_search=100. Recall measured against brute force over the active set;
84+
`fresh` is a from-scratch build of the final active set.
85+
86+
| Policy | Recall@10 range (cycles 1-10) | Latency growth | Churn cost/cycle |
87+
|--------|------------------------------|----------------|------------------|
88+
| soft (default) | 98.4% – 99.2% | 230 → 492 us | ~1.4 s |
89+
| isolate_deleted | 93.0% – 97.4% (degrading) | 260 → 324 us | ~1.0 s |
90+
| compact each cycle | 96.0% – 97.8% | stable | 19 – 31 s |
91+
| fresh reference | 97.2% | 222 us | — |
92+
93+
Verdict: soft deletion (retaining deleted nodes as traversal waypoints)
94+
*exceeds* fresh-built recall through 50% corpus turnover, so MN-RU-style
95+
repair-on-delete (arXiv:2407.07871) is unnecessary for the default policy —
96+
it only addresses the degradation that `isolate_deleted()` introduces.
97+
The costs of soft deletion are graph growth (memory, ~2x latency at 50%
98+
turnover), which periodic `compact()` at the `needs_compaction()` threshold
99+
already bounds.
100+
16101
## Build-time scaling by dimension (2000 vectors)
17102

18103
| Engine | 128d (ms) | 384d (ms) | 1024d (ms) |

‎CHANGELOG.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,53 @@ All notable changes to sqlite-vec-cpp will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [Unreleased] - 2026-06-09
9+
10+
### Fixed
11+
- **Correctness audit (Phase A)**:
12+
- HNSW persistence: cap `num_layers` (`kMaxHnswLayers = 64`) and per-layer
13+
neighbor counts during node deserialization — corrupt shadow-table blobs
14+
previously triggered unbounded allocations (OOM). Deleted-ids blobs now
15+
validate their count against the blob size before `reserve`.
16+
- `load_hnsw_index`: validate node-id consistency between the shadow-table
17+
rowid and the serialized blob, reject a missing entry point, and prune
18+
dangling neighbor edges referencing nodes absent from the shadow table.
19+
- `get_hnsw_checkpoint_info`: bounds-check the entry-point meta blob before
20+
dereferencing (previously an unchecked cast + read).
21+
- vec0: `dimensions * sizeof(float)` size checks now use `size_t` arithmetic
22+
(previously truncated through `int`); `CREATE VIRTUAL TABLE` rejects
23+
dimensions outside `[1, 65536]` and embedding column names containing `"`.
24+
- vec0 xFilter: ANN plans without an explicit `k` constraint no longer
25+
dereference a disengaged `std::optional` (use `kVec0DefaultK`).
26+
- HNSW greedy descent: NaN distances no longer "improve" the current
27+
candidate — NaN/Inf vectors previously caused an infinite traversal loop
28+
on insert and search (found by the new adversarial test).
29+
- HNSW concurrent search: `nodes_.empty()` was read before acquiring
30+
`nodes_mutex_` in `search_with_filter_impl` / `search_quantized_rerank` /
31+
`search_batch_with_filter` — a data race against concurrent `insert()`
32+
(found by the new TSan concurrency stress test).
33+
- `insert_single_threaded`: debug-build guard asserts on concurrent callers.
34+
35+
### Added
36+
- **True RaBitQ quantization** (arXiv:2405.12497), replacing the previous
37+
sign-quantization heuristic: seeded FWHT-based random rotation, the paper's
38+
unbiased inner-product estimator with per-vector correction factors, and
39+
4-bit scalar quantization of the rotated query so distance estimation stays
40+
popcount-only (5 popcounts per candidate). Recall@10 on 10K Gaussian
41+
vectors (3x rerank, ef=100): 76.6% → 94.9% at 128d, and at 768d RaBitQ now
42+
dominates the LVQ latency/recall/memory frontier (99.6% @ ef=200/3x, ~2.9x
43+
less memory than LVQ-4, faster than FP32 traversal). See BENCHMARKS.md.
44+
- **Hardening tests**: deterministic persistence fuzzing (truncations, byte
45+
flips, hostile length splices), adversarial vector tests (NaN/Inf/zero/
46+
denormal through distances, HNSW, LVQ/RaBitQ), vec0 overflow/validation
47+
tests, and a concurrent insert+search stress test (TSan-clean).
48+
- **hnsw_churn_benchmark**: recall/latency under sustained insert+delete
49+
churn per delete policy (soft / isolate_deleted / compact). Verdict: soft
50+
deletion exceeds fresh-built recall through 50% corpus turnover, so
51+
MN-RU-style repair-on-delete (arXiv:2407.07871) was evaluated and rejected
52+
— it only addresses degradation introduced by isolate_deleted(). See
53+
BENCHMARKS.md.
54+
855
## [0.1.0] - 2025-11-02
956

1057
### Added
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
// Benchmark: HNSW recall and latency under sustained insert/delete churn.
2+
//
3+
// Quantifies the delete-policy tradeoff before any repair-on-delete work
4+
// (MN-RU, arXiv:2407.07871) is considered:
5+
// - soft: remove() only — deleted nodes stay as traversal waypoints
6+
// - isolate: remove() + isolate_deleted() each cycle — edges to deleted
7+
// nodes are cut, which can strand their former in-neighbors
8+
// - compact: remove() + full compact() rebuild each cycle (upper bound)
9+
//
10+
// Each cycle deletes `batch` random active ids and inserts `batch` new
11+
// vectors. After each cycle we measure recall@k against brute force over the
12+
// active set, plus query latency. A fresh-built index over the same active
13+
// set is measured at the final cycle as the reference ceiling.
14+
//
15+
// Usage:
16+
// ./hnsw_churn_benchmark [--corpus N] [--dim D] [--cycles C] [--batch B]
17+
18+
#include <algorithm>
19+
#include <chrono>
20+
#include <cmath>
21+
#include <cstring>
22+
#include <iomanip>
23+
#include <iostream>
24+
#include <random>
25+
#include <span>
26+
#include <string>
27+
#include <unordered_set>
28+
#include <vector>
29+
30+
#include <sqlite-vec-cpp/distances/l2.hpp>
31+
#include <sqlite-vec-cpp/index/hnsw.hpp>
32+
33+
using namespace sqlite_vec_cpp::index;
34+
using namespace sqlite_vec_cpp::distances;
35+
36+
namespace {
37+
38+
using Index = HNSWIndex<float, L2Metric<float>>;
39+
40+
std::vector<float> generate_vector(size_t dim, std::mt19937& rng) {
41+
std::normal_distribution<float> dist(0.0f, 1.0f);
42+
std::vector<float> vec(dim);
43+
for (auto& v : vec)
44+
v = dist(rng);
45+
return vec;
46+
}
47+
48+
struct ActiveSet {
49+
std::vector<std::vector<float>> vectors; // indexed by id
50+
std::vector<size_t> active_ids;
51+
};
52+
53+
std::vector<size_t> brute_force_knn(std::span<const float> query, const ActiveSet& set, size_t k) {
54+
L2Metric<float> metric;
55+
std::vector<std::pair<size_t, float>> distances;
56+
distances.reserve(set.active_ids.size());
57+
for (size_t id : set.active_ids) {
58+
distances.emplace_back(id, metric(query, std::span<const float>(set.vectors[id])));
59+
}
60+
std::partial_sort(distances.begin(), distances.begin() + std::min(k, distances.size()),
61+
distances.end(),
62+
[](const auto& a, const auto& b) { return a.second < b.second; });
63+
distances.resize(std::min(k, distances.size()));
64+
std::vector<size_t> ids;
65+
ids.reserve(distances.size());
66+
for (const auto& [id, d] : distances)
67+
ids.push_back(id);
68+
return ids;
69+
}
70+
71+
struct CycleStats {
72+
float recall = 0.0f;
73+
double avg_latency_us = 0.0;
74+
size_t graph_nodes = 0;
75+
size_t deleted = 0;
76+
};
77+
78+
CycleStats measure(const Index& index, const ActiveSet& set,
79+
const std::vector<std::vector<float>>& queries, size_t k, size_t ef_search) {
80+
CycleStats stats;
81+
stats.graph_nodes = index.size();
82+
stats.deleted = index.deleted_count();
83+
84+
size_t hits = 0;
85+
auto start = std::chrono::high_resolution_clock::now();
86+
std::vector<std::vector<size_t>> all_results;
87+
all_results.reserve(queries.size());
88+
for (const auto& q : queries) {
89+
auto results = index.search_read_mostly(std::span<const float>(q), k, ef_search);
90+
std::vector<size_t> ids;
91+
ids.reserve(results.size());
92+
for (const auto& [id, d] : results)
93+
ids.push_back(id);
94+
all_results.push_back(std::move(ids));
95+
}
96+
auto end = std::chrono::high_resolution_clock::now();
97+
stats.avg_latency_us = std::chrono::duration<double, std::micro>(end - start).count() /
98+
static_cast<double>(queries.size());
99+
100+
for (size_t qi = 0; qi < queries.size(); ++qi) {
101+
auto truth = brute_force_knn(std::span<const float>(queries[qi]), set, k);
102+
std::unordered_set<size_t> truth_set(truth.begin(), truth.end());
103+
for (size_t id : all_results[qi]) {
104+
hits += truth_set.contains(id) ? 1 : 0;
105+
}
106+
}
107+
stats.recall = static_cast<float>(hits) /
108+
static_cast<float>(queries.size() * std::min(k, set.active_ids.size()));
109+
return stats;
110+
}
111+
112+
enum class Policy { Soft, Isolate, Compact };
113+
114+
const char* policy_name(Policy p) {
115+
switch (p) {
116+
case Policy::Soft:
117+
return "soft";
118+
case Policy::Isolate:
119+
return "isolate";
120+
case Policy::Compact:
121+
return "compact";
122+
}
123+
return "?";
124+
}
125+
126+
} // namespace
127+
128+
int main(int argc, char* argv[]) {
129+
size_t corpus_size = 10000;
130+
size_t dim = 128;
131+
size_t cycles = 10;
132+
size_t batch = 500;
133+
size_t num_queries = 50;
134+
size_t k = 10;
135+
size_t ef_search = 100;
136+
137+
for (int i = 1; i < argc; ++i) {
138+
if (std::strcmp(argv[i], "--corpus") == 0 && i + 1 < argc) {
139+
corpus_size = std::stoul(argv[++i]);
140+
} else if (std::strcmp(argv[i], "--dim") == 0 && i + 1 < argc) {
141+
dim = std::stoul(argv[++i]);
142+
} else if (std::strcmp(argv[i], "--cycles") == 0 && i + 1 < argc) {
143+
cycles = std::stoul(argv[++i]);
144+
} else if (std::strcmp(argv[i], "--batch") == 0 && i + 1 < argc) {
145+
batch = std::stoul(argv[++i]);
146+
}
147+
}
148+
149+
std::cout << "=== HNSW Churn Benchmark ===" << std::endl;
150+
std::cout << "corpus=" << corpus_size << " dim=" << dim << " cycles=" << cycles
151+
<< " batch=" << batch << " k=" << k << " ef_search=" << ef_search << std::endl;
152+
153+
for (Policy policy : {Policy::Soft, Policy::Isolate, Policy::Compact}) {
154+
std::mt19937 rng(42);
155+
std::mt19937 churn_rng(777);
156+
157+
ActiveSet set;
158+
set.vectors.reserve(corpus_size + cycles * batch);
159+
for (size_t i = 0; i < corpus_size; ++i) {
160+
set.vectors.push_back(generate_vector(dim, rng));
161+
set.active_ids.push_back(i);
162+
}
163+
std::vector<std::vector<float>> queries;
164+
for (size_t i = 0; i < num_queries; ++i) {
165+
queries.push_back(generate_vector(dim, rng));
166+
}
167+
168+
Index index;
169+
for (size_t i = 0; i < corpus_size; ++i) {
170+
index.insert_single_threaded(i, std::span<const float>(set.vectors[i]));
171+
}
172+
173+
std::cout << std::endl
174+
<< "--- policy=" << policy_name(policy) << " ---" << std::endl;
175+
std::cout << "| Cycle | Recall@10 | Latency (us) | Nodes | Deleted | Churn (ms) |"
176+
<< std::endl;
177+
std::cout << "|-------|-----------|--------------|-------|---------|------------|"
178+
<< std::endl;
179+
180+
auto baseline = measure(index, set, queries, k, ef_search);
181+
std::cout << "| 0 | " << std::fixed << std::setprecision(1) << baseline.recall * 100
182+
<< "% | " << baseline.avg_latency_us << " | " << baseline.graph_nodes << " | "
183+
<< baseline.deleted << " | - |" << std::endl;
184+
185+
size_t next_id = corpus_size;
186+
std::optional<Index> compacted_holder;
187+
Index* live = &index;
188+
189+
for (size_t cycle = 1; cycle <= cycles; ++cycle) {
190+
auto churn_start = std::chrono::high_resolution_clock::now();
191+
192+
std::shuffle(set.active_ids.begin(), set.active_ids.end(), churn_rng);
193+
for (size_t b = 0; b < batch && !set.active_ids.empty(); ++b) {
194+
live->remove(set.active_ids.back());
195+
set.active_ids.pop_back();
196+
}
197+
for (size_t b = 0; b < batch; ++b) {
198+
set.vectors.push_back(generate_vector(dim, churn_rng));
199+
set.active_ids.push_back(next_id);
200+
live->insert(next_id, std::span<const float>(set.vectors[next_id]));
201+
++next_id;
202+
}
203+
204+
if (policy == Policy::Isolate) {
205+
live->isolate_deleted();
206+
} else if (policy == Policy::Compact) {
207+
compacted_holder = live->compact();
208+
live = &*compacted_holder;
209+
}
210+
211+
auto churn_end = std::chrono::high_resolution_clock::now();
212+
double churn_ms =
213+
std::chrono::duration<double, std::milli>(churn_end - churn_start).count();
214+
215+
auto stats = measure(*live, set, queries, k, ef_search);
216+
std::cout << "| " << cycle << " | " << std::fixed << std::setprecision(1)
217+
<< stats.recall * 100 << "% | " << stats.avg_latency_us << " | "
218+
<< stats.graph_nodes << " | " << stats.deleted << " | "
219+
<< std::setprecision(1) << churn_ms << " |" << std::endl;
220+
}
221+
222+
Index fresh;
223+
for (size_t id : set.active_ids) {
224+
fresh.insert_single_threaded(id, std::span<const float>(set.vectors[id]));
225+
}
226+
auto fresh_stats = measure(fresh, set, queries, k, ef_search);
227+
std::cout << "| fresh | " << std::fixed << std::setprecision(1)
228+
<< fresh_stats.recall * 100 << "% | " << fresh_stats.avg_latency_us << " | "
229+
<< fresh_stats.graph_nodes << " | 0 | - |" << std::endl;
230+
}
231+
232+
return 0;
233+
}

‎benchmarks/meson.build‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,12 @@ profile_vec0_query_exe = executable(
151151
install: false
152152
)
153153
message(' ./profile_vec0_query (cold/hot vec0 ANN profiling with SQLite statement timings)')
154+
155+
hnsw_churn_benchmark_exe = executable(
156+
'hnsw_churn_benchmark',
157+
'hnsw_churn_benchmark.cpp',
158+
include_directories: include_directories('../include'),
159+
cpp_args: cpp_args_list,
160+
install: false
161+
)
162+
message(' ./hnsw_churn_benchmark (recall/latency under insert+delete churn per delete policy)')

0 commit comments

Comments
 (0)