8000 perf(knn): exact scan ranks from vector columns, hydrates only winners (#1091) by Vinz2168 · Pull Request #1217 · xerj-org/xerj · GitHub
[go: up one dir, main page]

Skip to content

perf(knn): exact scan ranks from vector columns, hydrates only winners (#1091) - #1217

Merged
xerj-org merged 1 commit into
xerj-org:mainfrom
Vinz2168:fix/1091-hybrid-fiqa-latency
Oct 7, 2026
Merged

xerj-org merged 1 commit into
xerj-org:mainfrom
Vinz2168:fix/1091-hybrid-fiqa-latency

Conversation

@Vinz2168
@Vinz2168 Vinz2168 commented Oct 7, 2026
Copy link
Copy Markdown
8000
Collaborator

Written by an AI coding agent (Claude Code), run by @Vinz2168, who has reviewed this change.

Fixes the latency half of #1091. On FiQA (57,638 docs) the semantic leg goes from a 3.9 s p50 to 261 ms, and hybrid from 5.8 s to 289 ms. Answers are identical: 50/50 ranked ids per arm, and score bits match the existing oracle.

What this changes, and why

Root cause. Reproduced on rc.87 with the default lexical embedder, so the model is not involved. The semantic leg alone took 6-7 s a query; BM25 took 25-160 ms. Three links cause it:

  1. The guard sends the field to the exact scan. run_knn_hnsw declines body_vector at passage_chunks_require_exact, because 29,508 of FiQA's 57,638 docs carry body_vector_chunks (p99 document 3,700 chars). This is the deliberate passage-exact guard from 309f0b6.
  2. The exact scan parses every stored document. It loaded each segment's parsed stored documents via stored_values_for_async on every query, even with the segment's vector column cached. It only needed _id and _seq_no per candidate. With vectors held as serde_json::Value, those documents are about 53 KB each.
  3. The caches cannot hold them, and get wiped. The parsed documents overflow the segment hydration budget. Measured on the node: auto limit 1.72 GB, of which stored_values 806 MB and stored_slices 794 MB, vector_column only 52 MB, 75 refusals. The transient decode also pushes RSS over the memory watermark. The breaker's drain (release_memory) then empties every cache, cached columns included, so every query pays the whole decode again.

Why not the direction in 309f0b6. That commit says accelerating these fields "requires passage-node ANN rather than weakening this guard". This PR does not weaken the guard: every guarded field still gets the authoritative exact scan, bit-identical to before. It removes waste inside that exact scan. Passage-node ANN is still the way to get sub-linear scoring, and it stays open (see Follow-ups). I did not take it on here for three reasons:

  • It changes the HNSW graph's identity (one node per passage, a passage→document map, max-sim dedup), its persistence, and the coverage gate. That is an architectural decision for the maintainers.
  • It is approximate, so recall would have to be re-measured. This change is exact by construction.
  • Most of the 3.9-5.8 s was not scoring. Scoring 57,638 candidates from the column takes about 30 ms once the parse is gone. Passage-node ANN would still have paid the parse to hydrate.

What changes. Only unfiltered, non-scalar8 exact scans are affected:

  • Identity in the column. SegmentVectorColumn records each position's _id and _seq_no, so a cached column is enough to choose candidates. Liveness and dedup go through one shared predicate (admit_exact_scan_candidate), so the column path and the stored-document path cannot disagree.
  • Building a missing column. It is built from the storage layer's typed kNN projection, decode_stored_v2_knn_projection (a4396b7 / 24826b7; until now no engine code used it). Identity and vector columns decode straight to f32, with no _source reconstructed. Elements are converted exactly as the Value path does (as_f64() as f32). Any cell the Value path would have had to drop or skip makes the storage decoder refuse the whole column. That case, legacy LZ4 (under 128 docs) and ZBS3 all fall back to the parsed-document build. The build is bounded by the request deadline.
  • Hydrating the winners. Winners are hydrated row-selectively from the immutable segment that was scored (decode_stored_v2_rows[_projected]), one decode per segment. The generated embedding companions are skipped when the request provably cannot see them: default _source, and no aggs, fields, scripts, sort, collapse or rescore. apply_source_filter_measured drops them from a default _source without reporting a saving, and they are the largest columns. A new helper, stored_v2_source_column_names, lists a section's columns without decoding payloads.
  • Fallbacks. A segment the row decoder cannot address hydrates from parsed documents, as before. Only a segment retired between scoring and hydration sends the whole request back to the stored-document scan.

Not changed:

  • filtered scans and scalar8;
  • the HNSW path and the passage guard;
  • the write path;
  • the response shape;
  • savings reporting.

Evidence

Matched release builds of e4c6c027 (the branch point) and this change, on the same machine. Each run used a fresh node, FiQA loaded with load.py, and 50 queries per arm, cache off. Raw per-query walls and ids are in benchmarks/beir-hybrid/results/2026-10-07-issue-1091/; the full procedure is in its manifest.txt.

== baseline e4c6c027
semantic  n=50 first=7164ms p50=3865ms p95=6398ms max=6987ms (p50/p95/max exclude the first)
hybrid    n=50 first=10708ms p50=5772ms p95=7368ms max=9355ms (p50/p95/max exclude the first)
watermark crossings: 25
== fix
semantic  n=50 first=8511ms p50=261ms p95=293ms max=305ms (p50/p95/max exclude the first)
hybrid    n=50 first=377ms p50=289ms p95=330ms max=344ms (p50/p95/max exclude the first)
watermark crossings: 0
semantic  identical ranked ids: 50/50
hybrid    identical ranked ids: 50/50

The fix's first semantic query (8.5 s) is the cold one: it builds every segment's column. The hybrid arm runs second and finds the columns warm.

The new test fails before the fix and passes after. I ran it on a worktree at the base commit with only the test hunk applied:

---- unfiltered_exact_scan_never_parses_stored_documents (on e4c6c027 + test only)
assertion `left == right` failed: round 0 k=1: the scan parsed a segment's stored documents
  left: 3
 right: 0
---- same test on this branch: ok
Claim Test or reproduction Result on final head
Unfiltered scans never parse stored documents, even after the parsed-document cache is cleared unfiltered_exact_scan_never_parses_stored_documents (columnar segments, updates, deletes, live memtable) pass (fails on base: 3 decodes)
Same ids, order and score bits as the pre-#939 clone-everything oracle same test, plus the existing exact_scan_is_bit_identical_to_the_clone_everything_scan (LZ4 segments, malformed passages; its warm pass now goes through the column path and the per-segment hydration fallback) pass
Default _source is exactly the oracle's document minus generated companions unfiltered_exact_scan_never_parses_stored_documents pass
An explicit _source still returns the companions column_scanned_hits_keep_companions_when_the_source_is_asked_for pass
Projected column identity matches the Value path stored_documents_carry_their_identity_and_sources_do_not, source_column_names_list_the_directory_without_identity_columns pass
Identical answers on a real corpus latency_1091.py diff 50/50, 50/50

Checks

  • cargo fmt --all (--check clean)
  • Scoped release builds: -p xerj-server -p es-yaml-runner; cargo clippy --release -p xerj-storage -p xerj-engine --all-targets -- -D warnings clean
  • cargo test -p xerj-storage: 225 + 9 + 1 passed. cargo test -p xerj-engine --no-fail-fast on the final head: 1,230 passed, 4 failed. The 4 are the /var vs /private/var snapshot-path tests, which fail the same way without this change on this macOS machine: snapshot_path_security_tests ×2, restoring_from_a_snapshot_clears_the_recorded_failure, test_restore_snapshot_honors_indices_filter. An earlier run on the pre-rebase head also failed painless_cpu_budget::the_time_budget_trips_on_its_own_inside_an_expired_request (the op ceiling tripped before the wall clock). It failed the same way on e4c6c027 and passed on the final head, so it is timing-flaky on this machine, not caused by this change.
  • ES-YAML conformance on the final head (rc.88 + this change): 1385 passed · 0 failed · 4 skipped
  • New ES-compatible behaviour has a matching YAML case: N/A, no wire behaviour changes
  • CHANGELOG ([Unreleased] → Performance)
  • Audit per docs/CONTRIBUTION_REVIEW.md. Optional-optimisation section: every admission failure falls back to the stored-document path, and the fallbacks are exercised by the existing oracle test's LZ4 segments.

Not run:

  • workspace-wide clippy (repo rule: builds are scoped);
  • --embed-mode neural, the issue's original setting;
  • the 8-pinned-core box where 13-26 s was measured;
  • the onnx-experimental clippy job.

Provenance

  • Written by: an AI coding agent (Claude Code), run by @Vinz2168, who has reviewed it.
  • Verified (commands run, output observed): everything in Evidence and Checks above. The root-cause chain was verified with temporary gate tracing, since removed: passage_chunks_require_exact is the HNSW exit taken, there are 29,508 chunked docs, and the hydration-budget snapshot and the crossed the memory watermark log lines appear in the node log.
  • Assumed (not tested):
    • Neural mode. It behaves the same, because only the embedder differs and the scan is embedder-agnostic. A neural run where the column path is not taken, or answers differ, would falsify this.
    • Larger memory limits. On a machine with a larger memory limit the baseline is less bad but not fixed. The parse cost per query remains even when nothing is evicted: about 2.3 s/query measured here with XERJ_SEGMENT_HYDRATION_CACHE_MB at its 4 GB clamp.

Follow-ups (not in this PR)

  • Hydration residue. The remaining ~250 ms is mostly row hydration. A RAW_JSON column must be walked to reach its rows, which is a stored-format limit. A per-row offset index for text columns would remove it.
  • Passage-node ANN (309f0b6), for sub-linear scoring on passage-chunked fields.
  • Small segments. A segment under V2_MIN_DOCS (128) documents is LZ4, so it still builds its column from parsed documents. These segments are small by definition.

Also in this PR, under benchmarks/beir-hybrid/:

  • latency_1091.py, the A/B harness. It refuses to measure an incompletely loaded index.
  • A 429 retry in load.py. A first A/B attempt lost 21,218 FiQA documents of one arm to the memory breaker; it was discarded.

🤖 Generated with Claude Code

xerj-org#1091)

Motivation. xerj-org#1091: a `hybrid` (BM25 + semantic) top-30 request on FiQA
(57,638 docs) took 13-26 s; the BM25 leg alone was normal. Reproduced on
rc.87 with the default lexical embedder, so the model is not involved:
the `semantic` leg alone took 6-7 s a query.

Root cause, in three links:
1. `run_knn_hnsw` declines `body_vector` because 29,508 of FiQA's docs
   carry `body_vector_chunks` (p99 document 3,700 chars), and the
   passage-exact guard from 309f0b6 sends such a field to the exact scan.
   That guard is deliberate and is left alone: its own commit says
   accelerating it "requires passage-node ANN rather than weakening this
   guard".
2. The exact scan loaded every segment's parsed stored documents
   (`stored_values_for_async`) even when the segment's vector column was
   cached — only to read `_id` and `_seq_no` per candidate. On a
   passage-chunked corpus those parsed documents are ~53 KB each.
3. They overflow the segment hydration budget (1.72 GB auto here:
   stored_values 806 MB + stored_slices 794 MB, vector_column 52 MB, 75
   refusals), and the transient decode pushes RSS over the memory
   watermark, whose drain (`release_memory`) then drops every cached
   column too. Every query paid the whole decode again.

Change (unfiltered, non-scalar8 exact scans only):
- `SegmentVectorColumn` records each position's `_id`/`_seq_no`, so a
  cached column is enough to choose candidates. Liveness/dedup goes
  through one shared predicate (`admit_exact_scan_candidate`) for both
  paths.
- A missing column is built from the storage layer's typed kNN projection
  (`decode_stored_v2_knn_projection`, a4396b7/24826b7b, unused by the
  engine until now): identity and vector columns decoded straight to f32,
  no `_source` reconstructed. It converts elements exactly as the Value
  path does (`as_f64() as f32`) and refuses any column the Value path would
  have had to drop or skip — that, legacy LZ4 (<128 docs) and ZBS3 fall
  back to the parsed-document build. Bounded by the request deadline.
- Winners are hydrated row-selectively from the immutable segment that was
  scored (`decode_stored_v2_rows[_projected]`), one decode per segment.
  When the request provably cannot see them (default `_source`, no aggs,
  fields, scripts, sort, collapse or rescore) the generated embedding
  companions are not decoded: `apply_source_filter_measured` drops them
  from the default `_source` without reporting a saving, and they are the
  largest columns. New storage helper `stored_v2_source_column_names`
  lists a section's columns without decoding payloads. A segment the row
  decoder cannot address hydrates from parsed documents as before; only a
  segment retired between scoring and hydration sends the request back to
  the full stored-document scan.

Evidence (benchmarks/beir-hybrid/results/2026-10-07-issue-1091/, matched
release builds of e4c6c02 and this change, same machine, fresh node each,
50 FiQA queries, cache off):
  semantic p50 3,865 -> 261 ms   p95 6,398 -> 293 ms
  hybrid   p50 5,772 -> 289 ms   p95 7,368 -> 330 ms
  first (cold) semantic query 7,164 -> 8,511 ms (builds all columns)
  memory-watermark crossings during the run 25 -> 0
  ranked ids identical: semantic 50/50, hybrid 50/50

Tests:
- `unfiltered_exact_scan_never_parses_stored_documents` (new): on columnar
  segments with updates, deletes and a live memtable, six rounds of
  unfiltered scans — one after the parsed-document cache is cleared —
  never decode stored documents, and match the pre-xerj-org#939 oracle in ids,
  order and score bits, and in the default `_source`. Fails on
  e4c6c02 (3 decodes in round 0), passes here.
- `column_scanned_hits_keep_companions_when_the_source_is_asked_for` (new).
- `exact_scan_is_bit_identical_to_the_clone_everything_scan` (existing,
  LZ4 segments, malformed passages) now also runs its warm pass through
  the column-only path and its per-segment hydration fallback.
- `source_column_names_list_the_directory_without_identity_columns` and
  `stored_documents_carry_their_identity_and_sources_do_not` (new, unit).

benchmarks/beir-hybrid: `latency_1091.py` (the A/B harness, refuses to
measure an incompletely loaded index) and a 429 retry in `load.py` — the
first A/B attempt lost 21,218 FiQA documents of one arm to the memory
breaker and was discarded.

Written by an AI coding agent (Claude Code), run and reviewed by
@Vinz2168.
@xerj-org xerj-org left a comment
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the engine/storage diff in full. Approving.

What I checked and liked

  • The A/B is honest: matched builds off the same merge base, same machine, latency_1091.py refuses to measure unless _count == 57638, and the manifest records that a first fix-arm attempt lost 21,218 docs to a breaker 429 and was discarded rather than measured. That is exactly the discipline the honest-claims rules ask for.
  • The oracle does not share code with what it checks (legacy_similarity verbatim, legacy_scan independent), and the test asserts ids, order, score bits, and per-hit _source equality — not just counts.
  • unfiltered_exact_scan_never_parses_stored_documents asserts test_stored_value_load_count == 0 across rounds, including after a stored_value_cache.clear() — it proves the headline claim, including the re-parse-after-drain failure mode from the issue.
  • Every admission failure falls back rather than erroring: ProjectedColumn::Unavailable → stored documents; a row the decoder cannot address → parsed documents; a segment gone between scoring and hydration → Ok(None) → full rescan; deadline → timed_out partial, as before.
  • The post-hydration identity re-check (column.identity(position) must equal the hydrated row's _id) is good belt-and-braces against any segment mutation under the scan.
  • omit_companions is conservatively scoped: only SourceFilter::Default with no aggs/fields/script_fields/sort/collapse/rescore — the shapes that provably never read the companions — and the second test pins that an explicit _source: true still gets them.

One finding, non-blocking, filed as #1220

admit_exact_scan_candidate reads the live version map per candidate. The inline predicate it extracts did the identical live reads (b8 T2 fix, 2026-07-12), so this PR introduces no new tear — and by cutting the scan ~15× it shrinks any window — but the capture-scoping belongs with #1218's CapturedEntryVerdict machinery. Follow-up filed; nothing to change here.

Will merge when CI is green.

@xerj-org
xerj-org merged commit e5f3d61 into xerj-org:main Oct 7, 2026
22 checks passed
thomas-villani pushed a commit to thomas-villani/xerj that referenced this pull request Oct 9, 2026
Two walls kept the finalize-verify window off the columnar agg fast
path, both measured live on the 402,814-doc autoindex-catalog (the
index autoindex rewrites on every finalize-catalog):

Wall 1 - exists had no arm in the fast-agg predicate compiler. The
verify window is `bool.filter [terms ax_file <digests>, exists text]`
+ a terms agg; the exists leaf alone demoted the whole request to the
brute `_source` path (15.9 s live vs 63 ms cold for the exists-free
twin; at catalog scale the brute corpus materialisation charges
836.7 MB against max_query_memory_mb=512MB and refuses with 429 —
the "finalize deadlock" signature of xerj-org#1183's verify pass).

  * `query_node_to_agg_filter` (index.rs): Exists node previously
    fell to the catch-all None, dropping the filtered-agg fast path
    for ANY query containing an exists leaf. Now reconstructs
    `{"exists":{"field":...}}` for compile_pred.
  * `Pred::Exists` + `compile_pred` arm (params_only-exact, meta
    fields bail - brute answers them from bookkeeping), `SegPred::
    KwExists`/`NumExists` (non-null column row), resolve/matches/
    count arms (per_ord_count sum / live_count - both O(1)),
    `check_pred_kinds` accepts either column kind.
  * aggs.rs `doc_matches_filter` exists arm: a directly-object-valued
    field now counts as present, aligning it with the brute query
    path's `value_present` (flatten(Object)=[] disagreed with
    value_present(Object)=true on buffered memtable docs).

Wall 2 - the deletes_present bail keyed on the MONOTONIC
`ghost_events` counter: an index that has EVER seen an overwrite
never re-qualified, even after merges compacted every ghost away.
Replaced with per-segment admission via `ghost_positions_for` - the
exact ghost-position bitmap whose row space IS the `.dv` column row
space (merge survivor filter guarantees at most one live copy per
id). A segment with a non-empty bitmap still bails (its delete-blind
O(1) stats would double-count ghosts); all-empty bitmaps mean
live == physical, which is exactly the invariant the executors were
built under, so the row arithmetic runs unchanged. Memtable views
(`mem`/`filtered_mem`) drop stale pre-drain copies under the gate -
with a SNAP-MEMBERSHIP predicate, not the fold's plain
`!= IN_MEMORY_SEGMENT_ID`, because this path reads the snapshot
first and the memtable lazily after. Delete-blind memtable columnar
summaries (terms_counts_columnar) switch off under the gate in
favour of the exact per-doc walks. The version-map epoch is
re-checked before returning (xerj-org#1217 capture-scope discipline): an
overwrite/delete landing mid-request bails to brute instead of
answering from stale admission.

Measured on a synthetic 402,814-doc catalog replica (1024-digest
terms + exists + terms agg, this build, private throwaway server):

  clean index                     57 ms cold        (was: brute 429)
  post-rewrite, unmerged ghosts   429 (836.7 MB)    (unchanged: bail)
  post-forcemerge                 599 ms cold / 4.4 ms warm,
                                  output byte-identical to clean
  exists-free twin post-merge     12.8 ms

Tests: engine/tests/fast_aggs_exists_and_deletes.rs - fast==brute
parity for keyword and numeric exists, meta-field bail, unmerged-
ghost bail, post-merge re-qualification with a live memtable (the
catalog's steady shape), object-valued memtable doc parity; all
served/bailed states pinned via aggs::fast_path_aggs_served.
Existing fast-agg suites pass unchanged; ES-YAML conformance
1385 passed / 0 failed; fmt + clippy clean.

Reference-code note: the engine-code corpora were not loadable on
the :9200 reference server during this change (mid cyber-corpus
rebuild; re-indexing would collide with the running crawlers), so
the mandate's retrieval pass was skipped - the design derives from
this repository's own primitives (ghost_positions_for, the merge
survivor filter, fold_match_sources' liveness predicates) and is
stated as such rather than cited from peers.
neoneye pushed a commit to agent-memory-atlas-archive/xerj-org--xerj that referenced this pull request Oct 10, 2026
Workspace version + Cargo.lock (17 member entries). Release window:
xerj-org#1211, xerj-org#1213, xerj-org#1215, xerj-org#1216, xerj-org#1217, xerj-org#1218.
neoneye pushed a commit to agent-memory-atlas-archive/xerj-org--xerj that referenced this pull request Oct 10, 2026
Six window entries: xerj-org#1211 (blog guest post), xerj-org#1217 (kNN exact-scan
column ranking, its Unreleased entry carried verbatim under
Performance), xerj-org#1213/xerj-org#1216 (the two xerj-org#1212 client legs: explicit page
timeouts + observed-vs-projection re-walk), xerj-org#1215 (xerj-org#1214: corpus
index refuses an unresumable run over a recorded build), xerj-org#1218 (the
xerj-org#1212 engine half: capture-scoped version-map reads). Every xerj-org#1212
entry says the issue stays open — it closes only on a released,
verified standing rebuild. xerj-org#1220 cited as the follow-up the xerj-org#1217
review surfaced.
neoneye pushed a commit to agent-memory-atlas-archive/xerj-org--xerj that referenced this pull request Oct 10, 2026
Shortlist nine -> eleven: xerj-org#1212 and xerj-org#1220 added (both filed inside the
rc.88 window; xerj-org#1212 was missing from the rc.88 roll). xerj-org#1091 parenthetical
now carries the rc.89 latency-half fix (PR xerj-org#1217, measured numbers) and
what remains. xerj-org#1183 note records the resume3 abort and the rc.89 legs
resume4 runs on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0