Files
xerj-org 46b58eef99 knn: scalar8 codes written at ingest, slot-addressed (#392)
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 8a22900f, 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 8a22900f)
    for a docs-gate failure pre-existing at this branch's base
    9c64a7c6 — without it `docs_do_not_promise_the_next_release`
    fails on a file this change never touches.
2026-09-21 00:31:55 +00:00
..