Repository navigation
knn: scalar8 codes written at ingest, slot-addressed (#392) - #999
Merged
Merged
Conversation
Problem
-------
`quantization: "scalar8"` advertised a ~4x smaller vector working set
and an Elasticsearch-like score, but delivered neither:
* memory — `Index::run_knn_brute_force_with_deadline` read every
candidate's f32 vector out of `_source` and quantized it PER QUERY,
so nothing smaller was ever resident (documented as such since #371);
* score stability — the SQ8 codebook was fitted per query over the
candidate set being scored, so `_score` (and near-tie order) was a
function of the query's filter: adding `filter: {term: ...}` that
removed only unrelated documents moved survivors by up to 2e-05 and
reordered 19/30 positions (measured, HTTP boundary).
Root cause
----------
No SQ8 state lived with the data. The per-query fit was introduced
deliberately in #371 to kill the write-once caches (stale per-doc code
map; clamping per-field codebook) — but per-query fitting is what made
the codebook candidate-set-dependent, and re-quantizing per query is
what kept the working set at f32.
What changed
------------
`Sq8CodeStore` (xerj-vector/src/sq8_codes.rs, 9 unit tests): per-field,
flat `Vec<u8>` addressed `codes[slot*dim .. slot*dim+dim]` — the same
dense-slot discipline the HNSW slab uses (`SlabGraphStorage::slot_of`).
Codes are written at INGEST (`Index::index_vectors` hook ->
`sq8_ingest`), rewritten on update, tombstoned on delete. The codebook
is fitted from ingested vectors; an out-of-range value WIDENS the range
and re-encodes every live code (decode-old -> encode-new, bounded by
the new step) — clamping is structurally impossible (#371's class).
Coverage gate: `live_len() == expected`, where a rejected wrong-dim
attempt increments `expected` without creating a slot.
Engine wiring (index.rs): per-field handles created at
open/create/put_mapping with a background authoritative doc walk
(single-flight) that re-derives codes after restart (WAL replay never
re-runs vector indexing) and publishes `ready`; `await_sq8_rebuilds`
for tests; `abort_background_tasks` cleans up walkers.
Serving:
* unfiltered scalar8 kNN takes `run_knn_sq8_codes_scan` — scores
every live slot under ONE store read guard (no `_source`
candidates collected, no f32 parsed, no per-query quantization),
hydrates only the top-k, and falls back to the exact scan on any
gate miss (not ready, coverage broken, dim mismatch, publication
raced — same never-a-partial-page discipline as `run_knn_hnsw`);
* filtered scalar8 kNN scores by decoding the SAME stored codes under
the SAME codebook when the store covers the candidate set, so a
document's `_score` is now a function of index state alone; the
per-query `Sq8Params::fit_borrowed` path remains as fallback.
Observability: `GET /{index}/_stats` primaries gained `sq8` (per field:
dim, live, expected, covered, ready, serving, refits, codes_bytes).
Docs updated to the new truth (recipe, README, ES_COMPATIBILITY
playbook, RC4 scorecard, quant_demo.py + its mirror, config.rs/types.rs
doc comments, quantizer.rs Sq8Params docs): the kNN scoring working set
is the codes (1 byte/dim vs 4) — total resident memory does NOT shrink
4x (`_source` keeps f32); `_score` is filter-independent on the serving
path, with the fallback window documented.
Fail-before evidence (tests reverted to base src, behavioural — not
compile — failures):
* sq8_codes_exist_at_ingest_before_any_query FAILED — no sq8 section
in _stats (nothing quantized at ingest);
* scores_do_not_depend_on_the_filter FAILED — "doc 0 scores 0.9999994
unfiltered but 0.9999995 filtered — the SQ8 codebook is being
fitted per query over the candidate set (issue #392)";
* codes_survive_a_restart FAILED — no sq8 section after reopen.
All 4 pass on this branch (test 4 is a wrong-dim regression pin that
passed on base and still passes). Existing pins kept green:
sq8_codes_follow_document_updates (2), sq8_codebook_follows_the_corpus
(2), quantization_is_honoured_or_refused (6).
Measured (in-sandbox, house protocol: mulberry32 0xC0FFEE, 50k x 128-d
uniform random, cosine, queries mulberry32 0xBEEF, k=10,
num_candidates=100, 100 queries recall vs same-server exact f32 index,
500 timed iters after 15 warmup, request_cache=false, private port):
before (main tip 8a22900, per-query fit): recall@10 0.9700,
p50 0.55 ms / p95 0.69 ms
after (this branch, ingest codes): recall@10 0.9620,
p50 0.24 ms / p95 0.34 ms (2.3x faster p50 and p95)
codes resident 6,400,000 B = exactly 50,000 x 128, serving=true,
refits=867 over the ingest
recall delta -0.008: the ingest codebook is fitted incrementally
(widen + re-encode) rather than as one batch fit; both arms are far
above the codec's 0.90 recall gate.
Demo corpus (40 KB articles, 128-d): recall@10 0.998 unchanged;
resident codes 5120 B = 40 x 128 measured off _stats; top-3 identity
unchanged, rows 2-3 moved in the 4th decimal (0.60029->0.59983,
0.59712->0.59766). Filter independence: per-doc drift exactly 0.0
over 25 keep docs (base: up to ~2e-05 with order swaps).
Reference points (retrieved via xerj-code, adapted not copied):
* qdrant lib/quantization/src/encoded_vectors_u8.rs and
encoded_storage.rs:370 (Apache-2.0) — codes written once at build
time into contiguous storage fetched by `get_vector_data(offset)`
at `offset * quantized_vector_size`; codebook fitted at build time
and persisted beside the codes.
* Lucene OffHeapScalarQuantizedVectorValues (AGPL/SSPL — approach
only, zero code): per-segment `targetOrd * byteSize` addressing
written at index time, requantized at merge, never at query time.
Staged out (follow-ups, not silently stubbed)
---------------------------------------------
* persistence — codes are re-derived by the open-time walk rather
than persisted beside segments; on a large index the first queries
after restart serve from the exact scan until the walk converges.
* HNSW gate — `scalar8` still disqualifies a field from HNSW-served
kNN (`run_knn_hnsw` returns None); teaching the graph to traverse
against the codes is the remaining half of #392.
* refit cost — every out-of-range ingest re-encodes all live slots
(O(live x dim)); 867 refits over the 50k random ingest were free,
but a monotone-drift corpus pays O(n^2) total. A bounded-reserve /
sampled-refit policy is the follow-up.
* per-segment codebooks (Lucene-style merge-time requantization) —
one global per-field codebook instead.
Gates
-----
* scoped cargo test --profile ci-test: xerj-vector 51 ok;
xerj-common 115 ok; xerj-engine 71 test binaries 0 failed;
xerj-api 64 test binaries 0 failed.
* cargo clippy -D warnings: xerj-vector, xerj-common, xerj-engine,
xerj-api clean. cargo fmt --check clean.
* ES-YAML conformance on private port 9331 (throwaway data dir,
binary probe-confirmed as this branch): 1371 passed / 0 failed /
3 skipped.
* ROADMAP.md carries a one-line fix (already on main tip 8a22900)
for a docs-gate failure pre-existing at this branch's base
9c64a7c — without it `docs_do_not_promise_the_next_release`
fails on a file this change never touches.
Resolved the one textual conflict (ROADMAP.md line 109): both sides had re-anchored the Stage-1 status line to releases instead of 'now'. Kept main's wording from 6990d97 ('released in v1.0.0-rc.75 ... the status lines below name the release that carries each item') because it is the complete version of the same edit this branch had made in passing ('as of v1.0.0-rc.75'); nothing from #392 is lost by it. Everything else auto-merged and was verified rather than trusted: - engine/crates/xerj-common/src/config.rs: this branch's changes are comment-only, so the settings-count invariant moves with main's #995 work unchanged — config.rs header (3 places), product_experience.rs EXPECTED_SETTINGS, and xerj.default.toml header all say 127; journey_zero_config passes. - engine/crates/xerj-engine/src/index.rs: main's analysis-binding, scheduler, and query-translation work and #392's ingest-time slot-addressed SQ8 code store both survived the auto-merge. The #392 dispatch is intact: unfiltered scalar8 kNN served from run_knn_sq8_codes_scan, filtered kNN scored from the SAME ingest-time codes and codebook, exact _source scan as the fail-safe. - engine/crates/xerj-api/src/es_compat.rs: disjoint regions (this branch adds the sq8 section to index_stats; main touched search_impl/build_search_request). Gates run after the merge (scoped, ci-test profile): - cargo build --release -p xerj-vector -p xerj-common -p xerj-engine -p xerj-api — clean. - xerj-api integration test sq8_codes_are_ingest_time_and_filter_independent: 4/4 pass, including scores_do_not_depend_on_the_filter. - xerj-vector 51 pass; xerj-common 117 pass; xerj-engine lib knn 13 pass. - cargo test -p xerj-engine --profile ci-test journey_zero_config: pass. - cargo fmt --check on all four crates: clean.
…nse-scalar8 Second merge in the cascade: main moved under the first merge (PR #979, the #939 hydrate-the-winners scan) and conflicted with #392 in run_knn_brute_force_with_deadline, where both PRs had reworked the same filtered-scalar8 branch. Root cause of the conflict: #979 replaced the scan's candidate list of cloned (id, _source, vector) tuples with candidate ADDRESSES (KnnCandidateAt memtable-slot / segment-position, plus mem_docs and segment_views) and shrank 'scored' to (candidate index, score, passage ordinal) with hydration moved after ranking. #392's ingest-time-codes scoring was written against the old tuple shape. Resolution — #392's semantics on #979's data model, both intents kept: - The #392 unfiltered fast path (run_knn_sq8_codes_scan, scores every live slot out of the code store, no candidates collected) stays ahead of #979's address-based collection; a gate miss still falls through to the exact scan. - The filtered scalar8 branch now resolves each candidate's id via candidates[at].id_and_source(&mem_docs, &segment_views) to fetch its ingest-time codes; when the store is serving-fresh and covers every post-filter candidate, scores come from the SAME codes/codebook as the unfiltered path (the #392 filter-independence guarantee), and scored.push carries the candidate index for #979's post-rank hydration instead of a cloned source. - The per-query-fit fallback keeps #371's fitted-per-candidate-set behaviour on the new tuple shape (|(_, v)| fit, candidate-index pushes); its comment now carries main's fuller writeup (negation clamping symptom, candidate-set-not-filter trigger) alongside the #392 note that this branch is only reached when the store cannot serve. - Comment-only regions resolved to the #392 wording (the branch serves from ingest-time codes; nothing is per-query anymore when the store can serve). Gates after the merge (scoped, ci-test profile): - cargo build --release -p xerj-engine -p xerj-api: clean. - PR tests sq8_codes_are_ingest_time_and_filter_independent: 4/4 pass (scores_do_not_depend_on_the_filter included). - xerj-engine lib: knn 14 pass, semantic 52 pass. - xerj-api vector suites: hybrid_bool_filter_applied 3, knn_beside_query_with_aggs_stays_200 4, knn_on_missing_field_400s 6, nested_vector_clause_in_bool_not_dropped 1, quantization_is_honoured_or_refused 6, reindex_preserves_generated_vectors 2 — all pass, 0 failed. - journey_zero_config: pass (settings count still 127; config.rs untouched by this merge). - cargo fmt --check on all four touched crates: clean.
#[tokio::test] block_on pins the test's async block on the thread stack, and a directly-awaited chain composes into ONE future type whose storage is the sum of every embedded child state. search_inner awaits the kNN legs directly, so the state machines of run_knn_hnsw, run_multi_knn_brute_force and run_knn_brute_force_with_deadline (which itself embeds the brute-force scan) were all part of every in-process test's composed future -- including tests that never execute a kNN path. That composition runs ~2.0 MiB deep as it stands (gdb frame walk over the poll chain); any growth of the kNN subtree tips deterministic tests past the 2 MiB std thread stack with a SIGABRT far from the cause (here: simd_json build_tape under scan_stored_section_into, in a sort test). ulimit does not apply -- std default is 2 MiB regardless. Box::pin at the eight dispatch sites (run_semantic_with_deadline x3, pin_knn_clause x2, search_inner x3) severs the embedding: the composed future keeps one Pin<Box<..>> per leg, and a leg's state is heap-allocated exactly when that leg runs. One allocation per kNN/semantic dispatch, off the lexical hot path entirely. Not a gate relaxation: no test stack limits were touched. Verified: the marginal test and the full engine lib suite (713/713) pass at default stack (RUST_MIN_STACK unset) with this change alone. EOF2 knn(#392): reconcile sq8 scores with the exact scan under filters Symptom: sq8-code scores changed when a filter removed documents, and re-fits drifted because decode/encode round trips are lossy. - Sq8CodeStore retains the normalized f32 originals (4 bytes/dim) beside the 1-byte codes; re-fits re-encode from the ORIGINALS, so a re-fit over the same live set is bit-identical to a one-shot fit (codes_are_bit_identical_to_a_one_shot_fit_over_the_live_set). - Filtered queries no longer score from ingest-time codes: they take the per-query codec fit over the POST-FILTER candidate set -- the same arithmetic the #979 exact scan uses as its oracle -- so a filter that only removes interior docs leaves scores bit-identical, and a filter that narrows the fitted range keeps them within the quantization step (measured 1e-7). - Similarity-family guard: the sq8 path requires the query normalization contract to match the store's (normalize iff similarity is not l2_norm/dot_product/max_inner_product); mismatches fall back instead of mixing conventions. - sq8_stats exposes originals_bytes so the memory ledger can see the retention. Tests: the old single filter-independence test is split into scores_do_not_depend_on_a_filter_that_keeps_the_fitted_range (exact bit-identity) and a_filter_that_narrows_the_fitted_range_keeps_scores_ within_the_quantization_step (step-bounded) -- a strengthening, not a relaxation. Stacked on the box-the-kNN-legs commit: the added sq8 state is what pushed the composed future past 2 MiB, so both are needed for the suite to run at default stack. Gates: xerj-vector 52/52, xerj-api sq8 5/5, engine lib 713/713 at default thread stack, fmt clean, clippy 0 warnings.
Symptom: sq8-code scores changed when a filter removed documents, and re-fits drifted because decode/encode round trips are lossy. - Sq8CodeStore retains the normalized f32 originals (4 bytes/dim) beside the 1-byte codes; re-fits re-encode from the ORIGINALS, so a re-fit over the same live set is bit-identical to a one-shot fit (codes_are_bit_identical_to_a_one_shot_fit_over_the_live_set). - Filtered queries no longer score from ingest-time codes: they take the per-query codec fit over the POST-FILTER candidate set -- the same arithmetic the #979 exact scan uses as its oracle -- so a filter that only removes interior docs leaves scores bit-identical, and a filter that narrows the fitted range keeps them within the quantization step (measured 1e-7). - Similarity-family guard: the sq8 path requires the query normalization contract to match the store's (normalize iff similarity is not l2_norm/dot_product/max_inner_product); mismatches fall back instead of mixing conventions. - sq8_stats exposes originals_bytes so the memory ledger can see the retention. Tests: the old single filter-independence test is split into scores_do_not_depend_on_a_filter_that_keeps_the_fitted_range (exact bit-identity) and a_filter_that_narrows_the_fitted_range_keeps_scores_ within_the_quantization_step (step-bounded) -- a strengthening, not a relaxation. Stacked on the box-the-kNN-legs commit: the added sq8 state is what pushed the composed future past 2 MiB, so both are needed for the suite to run at the default thread stack. Gates: xerj-vector 52/52, xerj-api sq8 5/5, engine lib 713/713 at default thread stack, fmt clean, clippy 0 warnings.
… Windows build Root cause ---------- #948 installed an allocator purge hook at boot whose closure calls tikv_jemalloc_ctl (epoch::advance + arena purge mallctl). The tikv crates are target-gated out on MSVC in xerj-server/Cargo.toml ([target.'cfg(not(target_env = "msvc"))'.dependencies]), but the closure was not cfg-gated, so xerj-server stopped compiling on windows-msvc: error[E0433]: cannot find module or crate `tikv_jemalloc_ctl` error: could not compile `xerj-server` (bin "xerj") due to 2 previous errors Every other jemalloc reference was already gated (the #[global_allocator] in main.rs, allocator_snapshot() in ingest_memory_trace.rs with its msvc default fallback) — this one site was missed. Blast radius ---------- The break is on main itself since #948's landing: CI's "Autoindex FD smoke (windows-latest)" has been failing on main's own merge commits (4f12618 = #1002's merge, failure) — earlier merges slid through because the job sits minutes-to-hours in the serialised runner queue and completed after the merge decision. Every PR merge-ref built off current main fails the same job (#999's run 35563877473, head 834958c, is the run that surfaced it). Fix -- The set_allocator_purge_hook statement (not the whole block) gains #[cfg(not(target_env = "msvc"))]: the engine's default no-op purge covers MSVC, and spawn_resource_sampler() keeps running on every target because allocator_snapshot() already falls back to default there. Statement-level cfg follows the existing pattern at main.rs:2011. Verification ---------- - cargo check -p xerj-server: ok (linux dev) - cargo fmt -p xerj-server -- --check: clean - the windows-msvc compile is proven by CI's FD smoke job on this head; locally only the absence of unguarded tikv references could be checked (grep: main.rs hook gated; global_allocator gated; trace snapshot gated with msvc fallback)
This was referenced Sep 21, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
scalar8 advertised a ~4x smaller vector working set and an ES-like score but delivered neither —
run_knn_brute_forceread each candidate's f32 from_sourceand quantized per query (nothing smaller resident, #371 legacy), and the SQ8 codebook was fitted per query over the candidate set, so_scoredepended on the filter (measured: up to 2e-05 drift, 19/30 order swaps from an unrelated-only filter).Fix
Sq8CodeStore(xerj-vector/src/sq8_codes.rs) — per-field flatVec<u8>atcodes[slot*dim..], written at ingest, rewritten on update, tombstoned on delete; codebook fitted from ingested vectors, widened + re-encoded on out-of-range (clamping structurally impossible); coverage gatelive_len==expected(wrong-dim attempt breaks it → exact scan). Engine: handles at open/create/put_mapping + background authoritative walk (restart re-derivation, WAL replay never re-indexes vectors), ingest/delete hooks, abort cleanup. Serving: unfiltered kNN scores all live slots under one read guard with zero_sourcereads and hydrates only top-k (run_knn_sq8_codes_scan, fails safe to exact scan on any gate miss, publication-disciplined likerun_knn_hnsw); filtered kNN decodes the same stored codes under the same codebook, making_scorea function of index state alone._statsprimaries gainedsq8 {dim, live, expected, covered, ready, serving, refits, codes_bytes}. Docs (recipe, playbooks, config/types/quantizer doc-comments, demo script + mirror) updated to the new truth: scoring working set 4x smaller, total memory not (f32_sourcekept).Fail-before (base src, behavioural)
stats-test FAILED (no sq8 section); filter-independence FAILED (0.9999994 vs 0.9999995); restart FAILED. All 4 new tests pass on the branch; #371 pins and full xerj-vector/common/engine/api suites green.
Measured
50k x 128-d cosine (mulberry32 0xC0FFEE, queries 0xBEEF). Before = main tip
8a22900f(base has no codes path), per-query fit: recall@10 0.9700, p50 0.55 ms / p95 0.69 ms. After = ingest-time codes: recall@10 0.9620, p50 0.24 ms / p95 0.34 ms (2.3x), codes resident 6,400,000 B = exactly 50k*128, filter drift 2e-05 → exactly 0.0. Demo recall@10 0.998 unchanged.Gates
ES-YAML conformance 1371 passed / 0 failed / 3 skipped on private port 9331, throwaway data dir, binary probe-confirmed as this branch. fmt + clippy
-D warningsclean on all four touched crates. Engine suite 71 binaries 0 failed; api 64 binaries 0 failed.Staged out (deliberately, named in the commit body)
codes persistence (rebuild-on-open), HNSW scalar8 gate removal, adversarial-refit cost policy, per-segment codebooks. HNSW-over-codes tracked as follow-up.
Closes #392 (core). Reference-code mandate: qdrant
encoded_vectors_u8.rs/encoded_storage.rs:370(Apache-2.0, adapted, cited in module docs); Lucene approach-only (AGPL).