AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
perf(read): eliminate O(N) read cliffs + columnar stats aggs (ES-YAML 1360/0)
xerj-orgb796094b689b
diff --git a/demo/playbooks/BENCH_BATTLE_PLAN.md b/demo/playbooks/BENCH_BATTLE_PLAN.mdnew file mode 100644index 000000000..8ae0212ee--- /dev/null+++ b/demo/playbooks/BENCH_BATTLE_PLAN.md@@ -0,0 +1,147 @@+# XERJ-vs-ES Benchmark Battle Plan — close all 8 LOSE cells, honestly++**Goal:** 100% ES compatibility **and** XERJ winning **every** cell of the matrix (zero LOSE), with an **honest** scorecard and website.+**Baseline:** Jul-6 SCORECARD.md (`caa607a` era) = **81 WIN / 8 LOSE / 2 N/A**. HEAD at time of writing: `2022a3b` on `fix/sort-topn-correctness`.+**Source of the 8 losses (verified against `demo/playbooks/SCORECARD.md`):**++| # | Cell (SCORECARD row) | XERJ | ES | Ratio | Verdict |+|---|---|---|---|---|---|+| 1 | read agg: filter (p50 ms) | 0.93 | 0.71 | 0.77× | LOSE |+| 2 | read pipe: sum_bucket (p50 ms) | 1.19 | 1.12 | 0.94× | LOSE |+| 3 | read pipe: derivative (p50 ms) | 1.13 | 0.67 | 0.60× | LOSE |+| 4 | mixed match_all (p99 ms, under write) | 65.48 | 2.30 | 0.04× | LOSE |+| 5 | mixed bool (p99 ms, under write) | 63.07 | 9.55 | 0.15× | LOSE |+| 6 | mixed range (p99 ms, under write) | 151.89 | 5.11 | 0.03× | LOSE |+| 7 | mixed terms (p99 ms, under write) | 61.84 | 2.70 | 0.04× | LOSE |+| 8 | mixed cardinality (p99 ms, under write) | 98.92 | 18.84 | 0.19× | LOSE |++The 8 split into **three families** with different truths:+- **Cells 4–8 (mixed p99):** ONE architectural mechanism — reads fold the **live, mutable** memtable under the **same per-shard `parking_lot::RwLock` the writer mutates**, inside `block_in_place`, under a 300 req/s **open-loop** driver → coordinated-omission snowball. This is the dominant, real, CI-failing loss.+- **Cells 2–3 (pipeline p50):** **measurement noise**, not a deficiency — identical code path to pipeline cells that WIN (avg_bucket 2.13×, cumulative_sum 4.71×). Sub-ms p50 with 120 iters is inside the harness jitter band.+- **Cell 1 (filter p50):** a real but **tiny** O(N) columnar fold with per-row virtual dispatch; ~0.22 ms over XERJ's own agg floor, partly noise.++---++## 1. The 8 losses: root cause → chosen fix → effort → expected result++| # | Cell | Root-cause one-liner (code-grounded) | Chosen fix | Effort | Expected result |+|---|---|---|---|---|---|+| 4 | mixed **match_all** p99 (0.04×) | Pure lock-contention floor: `doc_ids_bounded` (memtable.rs:725) fans all 16 shards `s.read()` while the turbo writer holds `s.write()` per 512-doc chunk (index.rs MEMTABLE_INSERT_CHUNK); `block_in_place` pins a worker per stall; 300 req/s open-loop piles up. Compute is cheap → 65 ms is ~pure contention. | **M1** lock-free memtable read snapshot (+ **M2** kill the snowball) | L (+M) | ~65 ms → single-digit ms (sub-2 ms quiescent already achieved). **WIN** |+| 7 | mixed **terms** p99 (0.04×) | Same floor; `terms_counts_columnar` (memtable.rs:1184) fold is cheap → 62 ms is contention. | **M1** (+M2) | L | ~62 ms → single-digit ms. **WIN** |+| 5 | mixed **bool** p99 (0.15×) | Contention **+** O(memtable) hydration: `mem_bool_preds` bails on the `match` clause → `DocsForScan(all_docs_with_sources_arc)` hydrates the whole memtable per read (memtable.rs:751). | **M3** lift `match` on keyword→Term (bounded columnar path) **+ M1/M2** | S + L | ~63 ms → single-digit ms. **WIN** |+| 6 | mixed **range** p99 (0.03×, worst) | Contention **+** O(memtable) numeric walk: `doc_values_bool_hits` (memtable.rs:2625) scans all `0..n` per shard for the exact total on a broad `cost_usd>=0.01`, even for size:10. | **M4** per-shard sorted numeric index → top-(from+size)+total in O(log N+k) **+ M1/M2** | M + L | ~152 ms → single-digit ms. **WIN (highest single-cell lever)** |+| 8 | mixed **cardinality** p99 (0.19×) | Contention; the bench op is **UNFILTERED** so `e69f80e` (filtered branch) does NOT touch it; extra 16-shard read-lock round (`terms_counts_columnar` rayon fan-out) adds ~33 ms over match_all. | **M1/M2** (+ optional: fold extra lock rounds, drop rayon par_iter) | L | ~99 ms → ~ES 18.8 ms or better. **WIN** |+| 1 | read agg: **filter** p50 (0.77×) | Real O(N) columnar fold: `exec_filter`→`fused_seg_pass` (fast_aggs.rs:1177) scans every row with a non-inlinable `&mut dyn FnMut` slot call + `SegPred`/`MetricKind` enum dispatch; `doc_count` incremented in the hot closure instead of O(1) `per_ord_count`. Gap ~0.22 ms, partly noise. | **F1** monomorphize single-leaf-pred filter+metric fold **+ F2** O(1) doc_count via `per_ord_count` | S + S | 0.93 → ~0.6–0.7 ms → parity/**WIN** |+| 2 | read pipe: **sum_bucket** p50 (0.94×) | **Not slower server-side.** Same `date_histogram`+`sum` parent + O(#buckets) sibling reduction as avg_bucket (WINs 2.13×). 120-iter open-loop p50 lands bimodally (~0.37 vs ~1.16 ms) — GC/scheduler beat vs the 5 ms cadence. | **H2** harness noise-band TIE + raise iters (+ optional H-eng variance trim) | S | Moves to **TIE** (server times equal within noise). Removes the false LOSE. |+| 3 | read pipe: **derivative** p50 (0.60×) | Identical to #2: nested pipeline via `apply_bucket_pipeline_ops`, same parent as serial_diff (WINs 2.56×). 0.60×/0.94× are noise artifacts; ES itself shows the same spread (derivative 0.67 vs sum_bucket 1.12). | **H2** (as #2) | S | Moves to **TIE**. Removes the false LOSE. |++**Net:** 5 mixed cells flip via one architectural fix (M1) + tail control (M2) + two cheap per-cell levers (M3/M4). 1 filter cell flips via a small monomorphization (F1/F2). 2 pipeline cells were never real losses — they resolve to TIE the moment the harness stops scoring sub-ms noise as LOSE (H2).++---++## 2. Execution order (biggest impact / lowest risk first)++The 5 mixed cells are the dominant loss and share **one mechanism**, so the engine work leads with that family. But two things must land **first** for integrity and to make the final proof trustworthy: the harness-honesty fixes (which also *legitimately* close cells 2 & 3) and the website corrections. Engine fixes (M-series, F-series) have **no dependency** on the harness work and can proceed in parallel — but the **final all-wins re-measurement (§4) must run on the fixed, honest harness.**++### Phase 0 — Integrity & harness (prerequisite; closes #2, #3; unblocks honest §4)+Low risk, mandatory. Details in §3.+- **H1 — Kill the read query-cache mirage.** Vary a param per iteration (novel term/id/range value) so every read misses `query_cache` (index.rs:4504 has no size gate; a hit at 4536 returns a `took_ms=0` clone). Report **p50 AND p99 uncached**. ⚠️ This may **expose new losses among the current 81 WINs** — that is the point; the honest uncached baseline is unknown until measured.+- **H2 — Noise-band + iters.** In `bench-matrix.mjs` raise read iters 120→≥1000, warmup 15→≥50, and make `scoreRow` (line 625) return **TIE** when `|xerj−es| ≤ max(0.30 ms, 20% of faster engine)`. Print both p50s regardless. **Closes #2 and #3 legitimately.**+- **H3 — Iso-write-rate for mixed.** Throttle the detached `_bulk` writer to an identical target docs/s both engines sustain; log **offered-vs-achieved** write rate per engine next to p99 (today XERJ accepts ~1.5× faster → more merge pressure → inflated p99).+- **H4 — Real correctness gate.** `readSignal`/`signalMismatch` currently check only `aggregations[0]` and tolerate 10% hit drift. Compare the **full aggregation subtree** (incl. scored pipeline values) and tighten hit-count tolerance to **0** for exact-count shapes.+- **H5 — Quarantine stale harnesses.** `bench-vs-es.mjs` (undici/closed-loop, writes the canonical `BENCHMARK_VS_ES.md`) and `bench.mjs` (points "ES" at :9200 = XERJ) must refuse to overwrite canonical files + print a deprecation banner, or be deleted.+- **H6 — Add a deletes-present read family** (see §5 sticky-gate risk) so future scorecards can't hide the O(N) downgrade the append-only corpus masks.++### Phase 1 — Mixed read-under-write (cells 4–8, the dominant loss)+Ship the fast, lower-risk mitigations first to compress the tail, then the real ES-parity fix.+1. **M2 (M, medium risk) — Kill the coordinated-omission snowball.** (a) Bound in-flight searches with a fair admission semaphore and shed/timeout queued searches **before** they run; the cooperative deadline already exists (index.rs:4780–4795) but is **dead code** under `block_in_place` — wire it so stalled searches return `timed_out:true` (ES semantics). (b) Stop `block_in_place` pinning a whole worker on a contended memtable lock — `try_read` + short bounded wait + cooperative yield, or move the fan-out to a bounded blocking pool. **Compresses the 62–152 ms tails to low-double-digit ms even before M1.**+2. **M3 (S, low risk) — bool.** In `mem_bool_preds`, resolve `match` on a keyword/exact field (single analyzed token) to a **Term** predicate so the bench bool takes `doc_values_bool_query` instead of `DocsForScan` hydration. Same design as segment bool prefilter `77586f0`; per-doc `doc_matches_query` recheck already drops false positives. Self-contained.+3. **M4 (M, medium risk) — range.** Bound `doc_values_bool_hits` (memtable.rs:2625): for unsorted size:N range with no aggs, resolve page+count via a per-shard **sorted numeric index** (reuse the `sort_cand_cache` machinery, memtable.rs:648–717) → top-(from+size) in O(log N + k); derive total from sorted bounds (delete-aware live count). Removes the worst-cell O(N) walk.+4. **M1 (L, high risk) — the real ES-parity fix.** Lock-free memtable **read snapshot**: publish a per-shard `ArcSwap<ImmutableMemView>` the writer refreshes at a bounded cadence (the *exact* pattern the store already uses for segments — `ArcSwap<IndexSnapshot>`, lock-free load at index_store.rs:1450). All reads (`doc_ids_bounded`, `doc_values_bool_query`, `terms_counts_columnar`, `all_docs_with_sources_arc`) load an `Arc`/len and **never block on ingest**. This is the **only** fix that touches match_all's pure-contention floor and closes all 5 cells. Hard-gate on ES-YAML **1360/0** + ingest throughput (must not regress the beat-ES ingest win — a per-doc snapshot rebuild historically regressed ingest ~4×) + the auto-id mixed repro.+ - **Cardinality note:** confirm-and-close — do **not** expect a re-measure to move cell 8 without M1/M2; `e69f80e` fixed only the *filtered* branch and the bench op is unfiltered. Optional follow-ups once M1 lands: fold the extra 16-shard lock rounds into one `s.read()` pass and read keyword-dict KEYS directly (O(distinct)) instead of `terms_counts_columnar`; drop the rayon `par_iter` (memtable.rs:1184) for a serial loop to trim dispatch jitter.+5. **M5 (S, do NOT ship as primary) — flush cadence hedge.** Right-size/stagger the per-shard flush threshold toward ES's ~512 MB-buffer cadence to shrink O(N) arms + write-lock windows. **Gaming risk** if tuned to the test window — principled production default only, complement to M1/M2, never standalone.++### Phase 2 — read agg: filter (cell 1) — parallelizable, low risk+6. **F1 (S) — Monomorphize** the single-leaf-predicate filter+metric fold: when `exec_filter`'s compiled pred is a single `TermKw/TermsKw/RangeNum/MatchAll` and metrics are few, bypass `fused_seg_pass` + the `&mut dyn FnMut` closure and run a tight raw-slice loop (`if ords[row]==ord { acc.add(f64::from_bits(data[row])) }`) so the compiler auto-vectorizes. Factor one shared `#[inline]` fold fn + assert equality vs the brute path in a unit test.+7. **F2 (S) — Decouple doc_count** from the fold: compute the bucket count via `per_ord_count`/`range_count` (O(1)/O(log n)) instead of `count += 1` in the hot closure.+ - Defer **F3** (ord→rows postings on `KeywordColumn`) and **F4** (non-allocating numeric range-rows iterator) unless the cell fails to flip — they generalize the whole filter/filters/adjacency_matrix family but add per-column memory/decode cost.++**Rationale for ordering:** Phase 0 is a hard prerequisite (honesty + fair §4) and freely closes 2 of 8. Within Phase 1, M2/M3 are lower-risk and pay off the tail immediately, de-risking the L-effort M1 that ultimately flips all five. Phase 2 is small and independent — run it in a parallel worktree.++---++## 3. Dishonest-win & stale-website items to correct (integrity — blocking)++### 3a. Harness dishonesty (must fix before publishing any new scorecard)+- **[HIGH] Read WINs are a query-cache mirage.** Static read bodies + `dataset_version` frozen during the zero-write read phase ⇒ calls 2..N are `took_ms=0` cache clones (index.rs:4504/4536) while ES really executes. Smoking gun: XERJ size:10 p50 is a flat 1.33–1.46 ms across wildcard/regexp/boosting/function_score/pinned while ES shows a real spread (9.10/34.42/39.25); `search_after` (the one `cache_eligible=false` family) is 3× slower. **Fix = H1.** Until then, **do not publish static-body read WINs.**+- **[MED] Reads scored on p50 only** = deterministically the cache-hit value for a 1-miss/135-hit distribution. **Fix = H1/H2** (report p50 **and** p99 uncached).+- **[MED] Mixed is not iso-write-rate** — uncapped `curl` writer loop; XERJ endures more merge pressure. **Fix = H3.**+- **[MED] Correctness checks only `aggregations[0]`** with 10% hit tolerance → a silently no-op'd pipeline agg can still score a latency WIN. **Fix = H4.**+- **[LOW] Ingest WIN doesn't equalize durability** (ES defaults `translog.durability=request` fsync-per-bulk). Pin durability equally or footnote.+- **[LOW] Stale sibling harnesses** overwrite canonical files with undici/closed-loop numbers and a :9200-as-ES bug. **Fix = H5.**++### 3b. Website staleness (landing/**/*.html vs Jul-6 SCORECARD)+- **[HIGH] Remove "89× faster NGINX terms agg"** — **zero** backing measurement anywhere in the repo (fabricated). Files: `landing/solutions/index.html:136`, `landing/resources/index.html:138`. Real terms-agg = **1.15×**.+- **[HIGH] Remove/re-measure "74× SIEM terms agg — 0.4 ms vs 29.8 ms"** — stale April v0.6.0 (`FEATURE_FAIRNESS_REVIEW_v0.6.0_2026-04-25.md:267`, "not re-run"), measured under the *repudiated* cache-mirage methodology (`2ff3e9a`), and **contradicted by the same site's own 1.15×** row. Appears in 30+ spots incl. `landing/docs/index.html:115`, `landing/industries/{index,finserv,public-sector}.html`, `landing/solutions/index.html:72`, `landing/docs/playbooks/siem.html:105`, `landing/docs/aggregations.html:121`, **plus a shared docs footer + JSON search-index snippet duplicated across ~30 `landing/docs/*.html`** (quickstart, storage, config, api-native, vectors, ingest, compression…). Fix the shared footer + docs-index JSON **once**.+- **[MED] Legacy envelope battery (300× cold start / 21× less memory / 56× binary)** — April v0.6.0 data, none in SCORECARD, current build is v1.0.0-rc.1. Files: `landing/industries/public-sector.html:233-235`, `finserv.html:78`, `solutions/index.html:115`, `resources/index.html:131`. **Re-confirm on rc.1 or date-stamp "measured 2026-04, v0.6.0".**+- **[MED] "2.8× less disk vs ES"** contradicts measured **1.20×** (XERJ 672.5 MB / ES 806.7 MB). 2.8× is the *internal* raw-input compression ratio, not vs ES. `landing/solutions/index.html:137`. **Correct to 1.20× or relabel as raw compression.**+- **[MED] Vector/hybrid claims** ("1B vectors · 38 ms hybrid p95", "1.2 ms vs 45 ms ES+Pinecone", "AML p95 0.4 ms vs 29.8 ms" which **relabels the SIEM terms-agg pair as vector retrieval**) — no backing benchmark; only kNN backing is SCORECARD `kNN k=10` 0.78 ms p50, 3.39×, recall 100%. Files: `landing/industries/{finserv,healthcare}.html`. **Verify or remove; stop relabeling terms-agg as vector retrieval.**+- **[LOW] `demo/index.html` "6,008,939 docs/s"** is an April in-memtable peak on a different (LabSZ) corpus; sustained scorecard ingest is 119k–388k docs/s. **Clarify labeling (peak in-memtable, April, LabSZ).**+- **Baseline (NO ACTION):** `use-cases.html`, `use-cases/*.html`, `benchmarks/index.html`, `product.html`, `docs/recipes/migrate-from-elasticsearch.html` are faithful row-for-row copies of the scorecard and honestly disclose the 5 mixed LOSSES — **use them as the correction template.**++---++## 4. Re-measurement protocol (QUIET box) to prove all-wins++Run **only after** Phase 0 (fair harness) lands, and after each engine fix, on an isolated machine.++**Environment**+- Dedicated, otherwise-idle box; CPU governor `performance`; disable other services. **Both engines on the same box, benchmarked sequentially (never concurrently)** except the mixed phase which is intra-engine read+write.+- **XERJ = current HEAD `--release` build** (`cargo build --release -p xerj-engine`), served on `:9200`. **Real Elasticsearch on `:9201`** (a genuine ES node — NOT the `bench.mjs` :9200-as-ES bug). Record both versions in the scorecard header.+- **Durability parity:** `index.translog.durability=request` on ES (its default) and confirm XERJ WAL fsyncs per `_bulk` equivalently — or footnote the difference (§3a low).++**Read families (cache-fair)**+- **Uncached:** vary a param per iteration so every call misses XERJ `query_cache` (novel term/id/range value per iter). Force-merge both engines to **1 segment** before the read phase for determinism; `track_total_hits:true` (exact totals already forced).+- **iters ≥ 1000, warmup ≥ 50.** Report **p50 AND p99**. Apply the H2 noise-band (TIE within `max(0.30 ms, 20%)`), and print a **trimmed-min** alongside p50 to expose the true server floor.++**Mixed read-under-write (cells 4–8)**+- Keep open-loop (`iters:3000, warmup:20, rate:300`, bench-matrix.mjs:497) **but throttle the `_bulk` writer to a fixed target docs/s both engines sustain**; log offered-vs-achieved per engine. Reject the run if achieved rates diverge >10%.+- Report p99 (primary) + max. Confirm via a repeat that stalls no longer snowball after load stops (the M2 signature).++**Correctness gates (block the timing if any fail)**+- ES-YAML compatibility **1360/0** green (hard gate for M1/M3/M4).+- H4 full-aggregation-subtree signal match + `hits.total` exact (tolerance 0).+- Agg A/B: `XERJ_DISABLE_FAST_AGGS=1` vs fast path byte-identical on filter/cardinality/date_histogram.+- For sort/size>0 changes: assert `hits.total` correctness on a **>materialisation_limit (~256)** sorted result set, not just latency (§5).++**Deletes-present family (H6)**+- Load `/perf` append-only, snapshot p50 for `term(status)`, `range(cost_usd)`, sort-heavy, `search_after`; then inject **one DELETE/UPDATE** (bumps `ghost_events`) and re-measure the SAME cells. A step-change to O(N) exposes the sticky-gate downgrade the append-only scorecard hides.++**Verdict**+- Run the full matrix **3×**; require **stable ordering** (no bimodal label flips) before declaring a win.+- **Pass = every cell ratio ≥ 1.0, or TIE within the noise-band; zero LOSE**, on the honest (uncached, iso-write-rate) harness. Regenerate SCORECARD.md and reconcile the website (§3b) to the new numbers in the same PR.++---++## 5. Open risks++**Engine-fix risks**+- **M1 hot-path (high):** epoch/ArcSwap consistency vs `remove()` deletes and `drain_shard_inner`'s `std::mem::take` flush drain must invalidate cleanly; transient double-buffer memory; **must not add a per-doc snapshot rebuild** (historically regressed ingest ~4×). Gate: ES-YAML 1360/0 + ingest throughput + auto-id mixed repro.+- **M2 load-shedding:** shed/timeout must return `timed_out:true` (ES-compatible) and not starve aggs; dedicated pool sizing needs the mixed repro as a behavior gate.+- **M4 sorted numeric index:** adds ingest-side cost — must not regress the beat-ES ingest win; exact broad-range `hits.total` must stay correct (delete-aware live count); A/B a >256-match memtable range.+- **M5 flush cadence = gaming risk:** never tune to the test window; principled production default traded against memory/recovery/segment fan-out only.+- **F1/F2 drift:** duplicated fold logic can diverge from brute (null handling, `f64::from_bits` decode, value_count presence) — one shared `#[inline]` fn + equality unit test.++**Measurement risk (the big one)**+- **H1 may reveal NEW losses among the current 81 WINs.** The static-body read wins are cache clones; the true **uncached** p50/p99 is unknown until measured. The "all-wins" target must be re-baselined against honest numbers, and some read cells (wildcard/regexp/boosting/function_score/pinned, which sit at a suspicious flat 1.33–1.46 ms today) may need their own engine work. **Budget for this.**++**Regression risks already in the tree (append-only scorecard hides them)**+- **[HIGH — verify shipping binary] `a93354a` arithmetic delete-gate** caused a real append-only regression (2 dup docs/merge pinned the gate ON → every size>0 term/range/bool to O(N)). HEAD `2022a3b` uses the `ghost_events` signal (index.rs:5695 — **confirmed**). A/B `a93354a` (arithmetic) vs HEAD on mixed range/terms/match_all + static term(status)/range(cost_usd)/bool to prove the fix and quantify what was avoided.+- **[MED] Sticky `ghost_events` gate.** `ghost_events` is monotonic `fetch_add`, never reset by merge/flush (version_map.rs:167/268/287/315). **One** update/delete pins `deletes_present=true` forever → forces size>0 term/range/bool hits.total back to O(N) delete-aware count (index.rs:5773) **and** disables sort-candidate prefilters (index.rs:6101/6135). Bench hides it (append-only auto-id `{"index":{}}`), but any real workload or any demo playbook that deletes/updates before reads permanently downgrades. **Mitigation:** H6 deletes-present family; consider clearing/re-deriving the ghost signal after a full merge.+- **[MED] `b79a8c2` unconditional `try_shortcut_count`** on every size>0 query (index.rs:5598) — wasted doc-values/FST work on selective and deletes-present reads; absolute regression below pre-F1 baseline when `deletes_present` (full scan **plus** unused shortcut). A/B `b79a8c2^` vs `b79a8c2` on selective (`ids`, `term(cache_hit)`) vs non-selective (`range(cost_usd)`, `term(status)`) + mixed range (cold-segment shortcut) — report **p99**, the effect hides in the tail.+- **[MED] `b79a8c2` early-break in scan order** (index.rs:5801) can drop true top-N from later segments on field/_score-sorted size>0 — the reason `fix/sort-topn-correctness` exists. HEAD compensates with `sort_topk` + `build_sort_candidates_prefilter` (index.rs:6100–6155), which itself already produced a "512-vs-847306" hits.total regression once (in-code note 6176–6180) and silently disables under `deletes_present`. **A/B must assert hits.total (not just latency)** on sort-heavy / search_after / range(@timestamp) / deep from+size, incl. a deletes-present variant.+- **[LOW] `2ff3e9a` is docs-only** (one new .md, 0 code) — exclude from A/B.++**Integrity/scope**+- Website corrections (§3b) touch ~30 duplicated docs pages via a shared footer/search-index — fix once at the source template, verify no page still renders 74×/89×/2.8×.+- Every commit on `xerj-org/xerj` must be authored as **xerj-org** (per memory) — no other author identities anywhere.diff --git a/demo/playbooks/READ_SCORECARD_2026-07-09.md b/demo/playbooks/READ_SCORECARD_2026-07-09.mdnew file mode 100644index 000000000..40118e37e--- /dev/null+++ b/demo/playbooks/READ_SCORECARD_2026-07-09.md@@ -0,0 +1,180 @@+# XERJ vs Elasticsearch — DEFINITIVE Post-Sweep Read/Agg Scorecard (2026-07-09)++**This is a MEASUREMENT + no-regression audit. No engine code was changed; nothing was committed.**+It re-measures the FULL matrix on the *combined* working-tree binary that now carries all 7+uncommitted read-perf fixes together (each was individually ES-YAML-gated; this run verifies+the **union** for correctness AND performance cross-interaction).++## TL;DR++- **Final: 7 WIN / 22 LOSS / 9 TIE** across 38 comparable query families (100k docs, single segment).+- **vs the prior scorecard (8 WIN / 24 LOSS / 6 TIE):** **2 losses collapsed into ties**+ (`ids` 128ms→0.11ms and `bool.must_not` 156ms→0.78ms now literally TIE ES); **1 win flipped+ to a tie** (`histogram` WIN→TIE — a measurement-noise boundary flip, see Regression Check).+- **The read-perf sweep is a decisive success on the O(N) cliffs.** Eight read families that were+ **56–556 ms full-collection scans** in the prior scorecard are now **0.1–43 ms**:+ `fuzzy(text)` 556→7ms, `wildcard(text)` 230→5ms, `match_phrase(text)` 225→39ms,+ `match_phrase_prefix` 186→43ms, `prefix(text)` 176→6ms, `exists` 159→0.75ms,+ `ids` 128→0.11ms, `bool.must_not` 156→0.78ms, `bool.should` 63→3ms, `terms` 56→3ms.+- **REGRESSION CHECK: no real code regression.** No row that was fast became a cliff; no O(N)+ cliff reappeared. The only verdict-negative change is `histogram` WIN→TIE, driven by ES+ getting faster (2.46→2.18ms) plus +0.38ms of sub-2ms XERJ jitter — not a XERJ slowdown.+- **Combined ES-YAML correctness gate: 1360 passed / 0 failed / 3 skipped.** All 7 fixes together+ still pass the full ES-compat suite.+- **Two O(N) reads remain UNFIXED this session:** `boosting` (~163ms) and `function_score`+ (~157ms) still brute-scan/score every document. `match_phrase(text)`/`match_phrase_prefix`+ improved 5–6× but remain ~40ms (positional phrase scan is faster but still super-linear).++## Method (fair, closed-loop, single-client — identical to the prior scorecard)++- **Build:** current working tree, combined binary `engine/target/release/xerj` (built 01:40 after+ all 4 modified sources: `xerj-fts/src/search.rs` +901, `xerj-engine/src/index.rs` +1224,+ `xerj-engine/src/fast_aggs.rs` +317, `xerj-query/src/parser.rs` +9; `cargo build` = up-to-date).+- **XERJ** on `:9200`, fresh temp data dir, `--insecure`, `XERJ_DISABLE_QUERY_CACHE=1`+ (whole-result cache OFF). **Real ES 8.13.4** on `:9201`, default settings, untouched.+- **Corpus:** 100,000 docs, identical to both engines (`chat-events.ndjson` enriched with a real+ analyzed **`body` text** field + high-cardinality **`doc_id`** keyword; `_id` = 1..N).+ **Single segment** on both (XERJ `_flush`+`_forcemerge`→1; ES `_forcemerge`→1). Both `/_count` = 100000.+ *(The `hits` column reads `10000` on most rows — that is ES's default `track_total_hits` 10k cap,+ NOT the corpus size. This is a genuine 100k run.)*+- **Measurement:** CLOSED-LOOP only (one request at a time, sequential — true round-trip; NOT the+ coordinated-omission open-loop driver). Warm 8, then p50/p99 over 40 iters. Identical bodies to+ both engines; `request_cache=false` on every search.+- **Verdict rule:** compare p50. `|Δp50| < 0.30 ms` = TIE (both in the sub-ms round-trip floor);+ otherwise WIN (XERJ faster) / LOSS (XERJ slower). Δ = XERJ p50 − ES p50 (positive = XERJ slower).+- Harness: `/tmp/xerj/read_scorecard.mjs`.++## READS (p50/p99 ms)++| query | XERJ p50/p99 | ES p50/p99 | verdict | Δ p50 | vs prior scorecard |+|---|---|---|---|---|---|+| match_all | 1.33 / 2.28 | 0.28 / 0.88 | **LOSS** | +1.05 | ~same (1.00→1.33, floor jitter) |+| term | 1.45 / 2.43 | 0.30 / 0.95 | **LOSS** | +1.14 | ~same (0.94→1.45, floor jitter) |+| terms | 3.43 / 4.63 | 0.39 / 0.46 | **LOSS** | +3.03 | **fixed cliff 56.05→3.43ms** (still loses) |+| range | 1.59 / 2.33 | 0.50 / 1.08 | **LOSS** | +1.10 | ~same (1.36→1.59) |+| bool (filter) | 1.55 / 2.27 | 1.29 / 2.28 | **TIE** | +0.26 | still TIE |+| bool (must) | 3.63 / 4.47 | 0.45 / 1.20 | **LOSS** | +3.18 | ~same (3.76→3.63) |+| bool (should) | 3.11 / 3.93 | 0.53 / 1.06 | **LOSS** | +2.58 | **fixed cliff 62.87→3.11ms** (still loses) |+| bool (must_not) | 0.78 / 1.13 | 0.84 / 1.75 | **TIE** | −0.06 | **LOSS→TIE: 156.08→0.78ms, now ties ES** |+| match (text) | 6.43 / 7.56 | 0.29 / 0.60 | **LOSS** | +6.14 | ~same (6.30→6.43) |+| match_phrase (text) | 38.69 / 46.46 | 0.93 / 1.79 | **LOSS** | +37.76 | **improved 225.22→38.69ms** (still O(N)-ish) |+| match_phrase (keyword) | 5.00 / 5.99 | 0.29 / 0.75 | **LOSS** | +4.71 | ~same (5.06→5.00) |+| match_phrase_prefix | 43.10 / 55.47 | 3.35 / 4.31 | **LOSS** | +39.75 | **improved 186.11→43.10ms** (still O(N)-ish) |+| multi_match | 7.19 / 8.04 | 0.52 / 0.98 | **LOSS** | +6.67 | ~same (7.05→7.19) |+| query_string | 13.35 / 15.84 | 0.73 / 1.49 | **LOSS** | +12.62 | ~same (12.92→13.35) |+| prefix (text) | 5.61 / 6.28 | 0.40 / 0.82 | **LOSS** | +5.21 | **fixed cliff 176.30→5.61ms** (still loses) |+| prefix (keyword) | 9.79 / 11.07 | 0.34 / 0.65 | **LOSS** | +9.45 | ~same (9.57→9.79) |+| wildcard (text) | 5.41 / 6.79 | 0.43 / 0.72 | **LOSS** | +4.98 | **fixed cliff 230.62→5.41ms** (still loses) |+| wildcard (keyword) | 10.10 / 11.18 | 0.44 / 0.71 | **LOSS** | +9.66 | ~same (9.74→10.10) |+| fuzzy (text) | 7.06 / 8.29 | 0.33 / 0.90 | **LOSS** | +6.73 | **fixed cliff 556.50→7.06ms** (still loses) |+| fuzzy (keyword) | 5.84 / 6.64 | 0.43 / 0.95 | **LOSS** | +5.42 | ~same (5.90→5.84) |+| exists | 0.75 / 1.11 | 0.20 / 0.60 | **LOSS** | +0.54 | **fixed cliff 159.52→0.75ms** (loses sub-ms race) |+| ids (3 docs) | 0.11 / 0.18 | 0.18 / 0.28 | **TIE** | −0.07 | **LOSS→TIE: 128.00→0.11ms, now ties ES** |+| boosting | 162.61 / 195.90 | 2.57 / 3.45 | **LOSS** | +160.04 | **STILL O(N)** (161.37→162.61, unfixed) |+| function_score | 156.54 / 203.62 | 2.84 / 3.99 | **LOSS** | +153.71 | **STILL O(N)** (156.74→156.54, unfixed) |++**Reads: 0 WIN / 21 LOSS / 3 TIE.** (prior: 0 WIN / 23 LOSS / 1 TIE)++## AGGREGATIONS (size:0, p50/p99 ms)++| agg | XERJ p50/p99 | ES p50/p99 | verdict | Δ p50 | vs prior scorecard |+|---|---|---|---|---|---|+| avg | 0.08 / 0.16 | 1.29 / 1.91 | **WIN** | −1.22 | still WIN |+| sum | 0.07 / 0.17 | 1.18 / 1.66 | **WIN** | −1.11 | still WIN |+| min | 0.07 / 0.12 | 0.12 / 0.25 | **TIE** | −0.05 | still TIE |+| max | 0.07 / 0.13 | 0.10 / 0.15 | **TIE** | −0.04 | still TIE |+| stats | 0.06 / 0.10 | 1.26 / 2.12 | **WIN** | −1.20 | still WIN |+| extended_stats | 0.14 / 0.17 | 1.58 / 2.19 | **WIN** | −1.44 | still WIN |+| cardinality | 9.52 / 13.39 | 3.79 / 4.70 | **LOSS** | +5.73 | still LOSS (10.57→9.52) |+| value_count | 0.07 / 0.19 | 0.56 / 0.85 | **WIN** | −0.49 | still WIN |+| terms (agg) | 0.22 / 0.36 | 0.14 / 0.21 | **TIE** | +0.08 | still TIE |+| date_histogram | 0.09 / 0.17 | 0.15 / 0.42 | **TIE** | −0.06 | still TIE |+| histogram | 1.91 / 3.03 | 2.18 / 2.72 | **TIE** | −0.27 | **WIN→TIE** (noise flip; see Regression Check) |+| range (agg) | 0.11 / 0.27 | 0.17 / 0.25 | **TIE** | −0.06 | still TIE |+| percentiles | 0.12 / 0.64 | 6.60 / 7.32 | **WIN** | −6.47 | still WIN |+| percentile_ranks | 0.13 / 0.26 | 6.57 / 7.26 | **WIN** | −6.44 | still WIN |++**Aggs: 7 WIN / 1 LOSS / 6 TIE.** (prior: 8 WIN / 1 LOSS / 5 TIE)++## FINAL SUMMARY: 7 WIN / 22 LOSS / 9 TIE (of 38 comparable families)++| | WIN | LOSS | TIE |+|---|---|---|---|+| Reads | 0 | 21 | 3 |+| Aggs | 7 | 1 | 6 |+| **Total** | **7** | **22** | **9** |+| *(prior scorecard)* | *8* | *24* | *6* |++## vs PREVIOUS SCORECARD — every verdict change++Three verdicts changed; ten more rows improved massively without changing verdict:++| row | prior | now | why |+|---|---|---|---|+| **ids** | LOSS (+127.8ms) | **TIE** (−0.07ms) | 128.00→0.11ms — postings resolution instead of full scan |+| **bool.must_not** | LOSS (+155.2ms) | **TIE** (−0.06ms) | 156.08→0.78ms — constant-score bitset instead of O(N) |+| **histogram** | WIN (−0.93ms) | **TIE** (−0.27ms) | ES sped up 2.46→2.18ms + XERJ +0.38ms jitter crossed the 0.30ms tie line (NOT a regression) |+| terms | LOSS (+55.6ms) | LOSS (+3.03ms) | cliff gone 56.05→3.43ms (still loses sub-ms race) |+| bool.should | LOSS (+62.3ms) | LOSS (+2.58ms) | cliff gone 62.87→3.11ms |+| match_phrase(text) | LOSS (+224.4ms) | LOSS (+37.76ms) | 225.22→38.69ms |+| match_phrase_prefix | LOSS (+182.7ms) | LOSS (+39.75ms) | 186.11→43.10ms |+| prefix(text) | LOSS (+175.9ms) | LOSS (+5.21ms) | 176.30→5.61ms |+| wildcard(text) | LOSS (+230.3ms) | LOSS (+4.98ms) | 230.62→5.41ms |+| fuzzy(text) | LOSS (+556.1ms) | LOSS (+6.73ms) | 556.50→7.06ms |+| exists | LOSS (+159.3ms) | LOSS (+0.54ms) | 159.52→0.75ms |++## REGRESSION CHECK++**No real code regression. No row that was fast in the prior scorecard became slow; no O(N)+cliff reappeared.** Rows whose XERJ p50 ticked *up* vs the prior scorecard did so only at the+sub-ms round-trip floor or within run-to-run variance on an already-slow O(N) op:++| row | prior X p50 | now X p50 | Δ | assessment |+|---|---|---|---|---|+| term | 0.94 | 1.45 | +0.51 | HTTP/executor floor jitter (~1ms op) |+| query_string | 12.92 | 13.35 | +0.43 | jitter on a ~13ms op |+| histogram | 1.53 | 1.91 | +0.38 | jitter on a ~2ms op — the WIN→TIE flip |+| wildcard(kw) | 9.74 | 10.10 | +0.36 | jitter on a ~10ms op |+| match_all | 1.00 | 1.33 | +0.33 | floor jitter |+| boosting | 161.37 | 162.61 | +1.24 | noise on a 160ms O(N) op (unchanged behaviour) |+| *(others +≤0.25ms)* | | | | all sub-ms floor jitter |++The single verdict-negative change (`histogram` WIN→TIE) is a boundary artifact: ES's own+histogram got faster (2.46→2.18ms) and XERJ drifted +0.38ms, together pushing Δp50 from −0.93+to −0.27, just inside the 0.30ms TIE band. XERJ's histogram code was not touched this session and+its absolute latency (~1.9ms) is unchanged within noise. **Verdict: zero regressions of substance.**++## COMBINED ES-YAML CORRECTNESS GATE++```+1360 passed · 0 failed · 3 skipped · 1363 total+```++Run against this exact combined binary on `:9200`+(`es-yaml-runner --dir tests/es-compat-yaml/yaml`). All 7 uncommitted read-perf fixes, applied+together, pass the full ES 8.13 wire-compat suite with **zero** failures — confirming the union+introduces no correctness cross-interaction.++## Honest bottom line++XERJ's read-perf sweep this session is a genuine, large win where it matters most: **eight+catastrophic O(N) full-collection read cliffs (56–556 ms at 100k) have collapsed to 0.1–43 ms**,+and two of them — `ids` and `bool.must_not` — now literally **tie** real Elasticsearch. XERJ+continues to **win the columnar statistical aggregations decisively** (`avg`/`sum`/`stats`/+`extended_stats`/`value_count`/`percentiles`/`percentile_ranks`), where its precomputed+doc-values beat ES by 1–7 ms. But on **raw read latency ES still wins the headline count**, for+two honest reasons: (1) on already-fast paths (`match_all`/`term`/`range` ~1–1.6ms, and+keyword/text FST paths ~5–13ms) XERJ sits above ES's true **sub-ms postings/BKD lookup floor**+(0.2–0.5ms) — a fixed HTTP+executor overhead the FST routing narrowed but did not erase; and+(2) **two O(N) reads remain unfixed — `boosting` (~163ms) and `function_score` (~157ms) — and+`match_phrase(text)`/`match_phrase_prefix` are 5–6× faster but still ~40ms**. Net vs the prior+8W/24L/6T: the score is 7W/22L/9T, the one-win dip is a noise-level TIE flip (not a regression),+the correctness gate is a clean 1360/0/3, and the real story is that the read O(N) cliffs are+mostly gone while ES keeps its sub-ms lookup-latency crown.++---+*Closed-loop, single-client, cache-off-on-XERJ, ES-default, 100k identical single-segment corpus.+XERJ `:9200` (this run's server, stopped by exact PID after), ES `:9201` (v8.13.4, untouched),+python `:8080` untouched. Harness: `/tmp/xerj/read_scorecard.mjs`; raw run:+`/tmp/xerj/sc-final-run.txt`; YAML gate: `/tmp/xerj/yaml-final.txt`. No engine code changed;+nothing committed.*diff --git a/demo/playbooks/bench-matrix.mjs b/demo/playbooks/bench-matrix.mjsindex 8c301833a..cdd996515 100644--- a/demo/playbooks/bench-matrix.mjs+++ b/demo/playbooks/bench-matrix.mjs@@ -145,23 +145,33 @@ function f3(x) { return x === undefined || x === null ? '—' : x.toFixed(2); }// silently no-ops (HTTP 200 but 0 hits / empty aggregation) can be detected// instead of being scored as a fast latency WIN. Returns {hits, agg} where either// may be null when not applicable.+// Reduce one aggregation result object to its primary numeric value+// (buckets.length / value / count / doc_count), else null.+function aggPrimary(v) {+ if (!v || typeof v !== 'object') return null;+ if (Array.isArray(v.buckets)) return v.buckets.length;+ if (typeof v.value === 'number') return v.value;+ if (typeof v.count === 'number') return v.count;+ if (typeof v.doc_count === 'number') return v.doc_count;+ return null;+}function readSignal(j) {if (!j || typeof j !== 'object') return null;// _count endpoint: {count: N}- if (typeof j.count === 'number' && !j.hits && !j.aggregations) return { hits: j.count, agg: null };+ if (typeof j.count === 'number' && !j.hits && !j.aggregations) return { hits: j.count, agg: null, aggs: null };const ht = j.hits && j.hits.total;const hits = typeof ht === 'number' ? ht : (ht && typeof ht.value === 'number' ? ht.value : null);- let agg = null;- if (j.aggregations) {- const first = Object.values(j.aggregations)[0];- if (first && typeof first === 'object') {- if (Array.isArray(first.buckets)) agg = first.buckets.length;- else if (typeof first.value === 'number') agg = first.value;- else if (typeof first.count === 'number') agg = first.count;- else if (typeof first.doc_count === 'number') agg = first.doc_count;- }+ // H4: capture EVERY top-level aggregation's primary value into a stable+ // key->value map (not just aggregations[0]) so signalMismatch can compare+ // all shared agg keys and catch any single agg that silently no-ops.+ let agg = null, aggs = null;+ if (j.aggregations && typeof j.aggregations === 'object') {+ aggs = {};+ for (const [k, v] of Object.entries(j.aggregations)) aggs[k] = aggPrimary(v);+ const first = Object.values(aggs)[0];+ agg = first != null ? first : null; // primary value of the first agg, for logs}- return { hits, agg };+ return { hits, agg, aggs };}// Compact printable form of a correctness signal for logs.function sigStr(s) {@@ -175,18 +185,35 @@ function sigStr(s) {// small tolerance), else null. Used to mark a read family N/A instead of awarding// a latency WIN to whichever engine short-circuited the query.function signalMismatch(xs, es) {- if (!xs || !es) return null; // not comparable (e.g. _msearch/_mget) — leave to normal scoring- const xh = xs.hits, eh = es.hits;- if (xh != null && eh != null) {- if ((xh === 0) !== (eh === 0)) return `hits ${xh} vs ${eh}`;- const tol = Math.max(1, 0.1 * Math.max(xh, eh));- if (Math.abs(xh - eh) > tol) return `hits ${xh} vs ${eh}`;- }- const xa = xs.agg, ea = es.agg;- if (xa != null && ea != null) {- if ((xa === 0) !== (ea === 0)) return `agg ${xa} vs ${ea}`;- }- return null;+ try {+ if (!xs || !es) return null; // not comparable (e.g. _msearch/_mget) — leave to normal scoring+ const xh = xs.hits, eh = es.hits;+ if (xh != null && eh != null) {+ if ((xh === 0) !== (eh === 0)) return `hits ${xh} vs ${eh}`;+ // H4: EXACT hit-count parity for size:0 / track_total_hits shapes (req()+ // injects track_total_hits:true into every JSON _search body, so both+ // engines compute the true total). Allow a ±1 rounding slack ONLY when+ // BOTH counts are already > 0.+ if (xh !== eh) {+ const roundingSlack = xh > 0 && eh > 0 && Math.abs(xh - eh) <= 1;+ if (!roundingSlack) return `hits ${xh} vs ${eh}`;+ }+ }+ // H4: compare ALL shared top-level agg keys — flag when one engine is zero+ // while the other is non-zero on the same key (a silent no-op agg).+ const xa = xs.aggs, ea = es.aggs;+ if (xa && ea) {+ for (const k of Object.keys(xa)) {+ if (!(k in ea)) continue;+ const xv = xa[k], ev = ea[k];+ if (xv == null || ev == null) continue;+ if ((xv === 0) !== (ev === 0)) return `agg[${k}] ${xv} vs ${ev}`;+ }+ } else if (xs.agg != null && es.agg != null && ((xs.agg === 0) !== (es.agg === 0))) {+ return `agg ${xs.agg} vs ${es.agg}`;+ }+ return null;+ } catch { return null; } // robust — a signal-shape surprise must never throw}// End-to-end latency of `iters` requests after `warmup` untimed calls, driven@@ -276,7 +303,12 @@ const MAPPING = {// Every family the scouts enumerated that runs on the flat LLM-telemetry corpus.// entry: { label, body, path?, method?, ndjson? }. Anything needing a geo_point,// ip, nested/join, span, or dense_vector field is in SKIPPED (below) with a reason.-const S = '/perf/_search';+// request_cache=false is appended so BOTH engines EXECUTE every read instead of+// serving a cached whole-result clone: ES honours it for its size:0 request+// cache, and XERJ is run with XERJ_DISABLE_QUERY_CACHE=1 so its query_cache is+// off. Lower-level filter/OS caches stay on for both (fair). Query bodies are+// NOT mutated per-iteration.+const S = '/perf/_search?request_cache=false';const READ_FAMILIES = [// §1 full-text (on keyword these behave as exact-token matches){ label: 'q: match_all', body: { query: { match_all: {} }, size: 10 } },@@ -377,7 +409,7 @@ const READ_FAMILIES = [} },{ label: 'feat: highlight', body: { query: { match: { status: 'ok' } }, size: 10, highlight: { fields: { status: {} } } } },// multi-op endpoints- { label: 'feat: _count', body: { query: { match_all: {} } }, path: '/perf/_count' },+ { label: 'feat: _count', body: { query: { match_all: {} } }, path: '/perf/_count?request_cache=false' },{ label: 'feat: _msearch', body: '{}\n{"query":{"match_all":{}},"size":1}\n', path: '/perf/_msearch', ndjson: true },{ label: 'feat: _mget', body: { ids: ['1', '2', '3'] }, path: '/perf/_mget' },];@@ -484,7 +516,13 @@ async function mixedBench(base, log) {const cntF = `${SCRATCH}/_mx_wcount_${tag}.txt`;fs.writeFileSync(flag, '1');fs.writeFileSync(cntF, '0');- const script = `n=0; while [ -f '${flag}' ]; do curl -s -XPOST '${base}/perf/_bulk' -H 'content-type: application/x-ndjson' --data-binary @'${f}' >/dev/null 2>&1; n=$((n+1)); printf '%s' "$n" > '${cntF}'; done`;+ // H3: ISO-WRITE-RATE. Throttle the background writer to a FIXED offered target+ // of ~100,000 docs/s (~10 bulk posts/s of BATCH=10,000) via a `sleep 0.1` per+ // iteration, so BOTH engines face the SAME offered write load (the previous+ // uncapped loop let a faster-ingesting engine self-impose more merge pressure,+ // making the mixed comparison not iso-load). Achieved rate is still measured+ // and compared afterward; a >10% divergence is flagged on the mixed rows.+ const script = `n=0; while [ -f '${flag}' ]; do curl -s -XPOST '${base}/perf/_bulk' -H 'content-type: application/x-ndjson' --data-binary @'${f}' >/dev/null 2>&1; n=$((n+1)); printf '%s' "$n" > '${cntF}'; sleep 0.1; done`;const child = spawn('bash', ['-c', script], { detached: true, stdio: 'ignore' });child.unref();const wStart = performance.now();@@ -506,7 +544,10 @@ async function mixedBench(base, log) {try { writes = parseInt(fs.readFileSync(cntF, 'utf8').trim(), 10) || 0; } catch {}try { fs.unlinkSync(cntF); } catch {}try { fs.unlinkSync(f); } catch {}- out.__bg = { docs: writes * BATCH, dps: Math.round((writes * BATCH) / ((wEnd - wStart) / 1000)) };+ // H3: record offered target (~100,000 docs/s) alongside achieved so iso-load+ // can be verified/annotated when the scorecard is built.+ const OFFERED_BG_DPS = 100000;+ out.__bg = { docs: writes * BATCH, dps: Math.round((writes * BATCH) / ((wEnd - wStart) / 1000)), offered: OFFERED_BG_DPS };return out;}@@ -549,11 +590,12 @@ async function knnBench(base, log, dims = 128, M = 50000) {scored.sort((a, b) => b[1] - a[1]);const exact = new Set(scored.slice(0, 10).map((x) => x[0]));const body = { knn: { field: 'v', query_vector: qv, k: 10, num_candidates: 100 }, size: 10 };- const one = await req(base, 'POST', '/perfvec/_search', body);+ // request_cache=false so both engines execute every probe (see the S note).+ const one = await req(base, 'POST', '/perfvec/_search?request_cache=false', body);const ids = (one.j?.hits?.hits || []).map((h) => parseInt(h._id, 10));const recall = ids.length ? ids.filter((id) => exact.has(id)).length / 10 : null;// >=2000 samples so kNN p99/max aren't dominated by 1-2 tail observations.- const t = await safeTimed(base, '/perfvec/_search', body, { iters: 2000, warmup: 15, rate: 200 });+ const t = await safeTimed(base, '/perfvec/_search?request_cache=false', body, { iters: 2000, warmup: 15, rate: 200 });return { ...t, recall };}@@ -622,7 +664,12 @@ const mb = (b) => (b / 1048576).toFixed(1) + ' MB';// let disp() distinguish a genuine 4xx feasibility rejection ("unsupported// (400)") from a harness/transport error ("error") — so a dead engine mid-run// no longer masquerades as a missing feature in the scorecard.-function scoreRow(dim, xv, ev, higherBetter, fmt, xraw, eraw) {+// H2: `tieBandMs` (default null) enables a noise band for LATENCY rows+// (higherBetter=false). When BOTH values are present+finite and+// |xv-ev| <= max(tieBandMs, 0.20*min(xv,ev)) the verdict is TIE (neither WIN nor+// LOSE). TIE never fails CI. Only latency rows that are genuinely in the noise+// (reads, mixed, kNN latency) are passed a band; ingest/disk are not.+function scoreRow(dim, xv, ev, higherBetter, fmt, xraw, eraw, tieBandMs = null) {const disp = (v, raw) => {if (v != null) return !isFinite(v) ? 'collapsed' : fmt(v);if (raw && raw.unsupported) return `unsupported (${raw.status ?? '4xx'})`;@@ -633,10 +680,15 @@ function scoreRow(dim, xv, ev, higherBetter, fmt, xraw, eraw) {const es = disp(ev, eraw);let ratio = '—', verdict = 'N/A';if (xv != null && ev != null) {- const better = higherBetter ? xv >= ev : xv <= ev;const r = higherBetter ? (ev ? xv / ev : 0) : (xv ? ev / xv : 0);ratio = isFinite(r) && r > 0 ? r.toFixed(2) + '×' : '—';- verdict = better ? 'WIN' : 'LOSE';+ if (!higherBetter && tieBandMs != null && isFinite(xv) && isFinite(ev)+ && Math.abs(xv - ev) <= Math.max(tieBandMs, 0.20 * Math.min(xv, ev))) {+ verdict = 'TIE';+ } else {+ const better = higherBetter ? xv >= ev : xv <= ev;+ verdict = better ? 'WIN' : 'LOSE';+ }}return { dim, xs, es, ratio, verdict };}@@ -716,7 +768,7 @@ async function main() {// families with per-engine setup (e.g. search_after sort-value capture)// build their body against THIS engine right before timing.const body = fam.makeBody ? await fam.makeBody(e.url) : fam.body;- R.reads[fam.label][e.name] = await safeTimed(e.url, path, body, { ndjson: !!fam.ndjson });+ R.reads[fam.label][e.name] = await safeTimed(e.url, path, body, { iters: 1200, warmup: 60, ndjson: !!fam.ndjson });}const xrr = R.reads[fam.label].XERJ, err_ = R.reads[fam.label].ES;const xr = statVal(xrr), er = statVal(err_);@@ -732,7 +784,7 @@ async function main() {try {R.mixed[e.name] = await mixedBench(e.url, log);const bg = R.mixed[e.name].__bg;- if (bg) log(` ${e.name} background write load: ${bg.dps.toLocaleString()} docs/s (${bg.docs.toLocaleString()} docs during read window)`);+ if (bg) log(` ${e.name} background write load: offered ~${(bg.offered ?? 100000).toLocaleString()} docs/s, achieved ${bg.dps.toLocaleString()} docs/s (${bg.docs.toLocaleString()} docs during read window)`);} catch (err) {// Log WHY + whether the engine is still up: all-unsupported mixed cells// have previously meant "engine died between phases", not "no feature".@@ -788,26 +840,43 @@ async function main() {// other matches, or hit counts differ), mark N/A so an effectively-unsupported// feature can't win the row on latency.const fmtMs = (v) => (v == null ? 'unsupported' : v.toFixed(2));+ // H1: verdict is scored on p50, but each read cell also SHOWS p99 alongside,+ // e.g. `0.88 (p99 2.10)` — only when the cell itself is a plain number.+ const withP99 = (cell, raw) => {+ const p99 = statVal(raw, 'p99');+ return (p99 != null && /^[\d.]+$/.test(cell)) ? `${cell} (p99 ${p99.toFixed(2)})` : cell;+ };for (const fam of READ_FAMILIES) {if (!R.reads[fam.label]) continue;const xrr = R.reads[fam.label].XERJ, err_ = R.reads[fam.label].ES;const mm = signalMismatch(xrr && xrr.signal, err_ && err_.signal);if (mm) {- rows.push({ dim: `read ${fam.label} (p50 ms) [result mismatch: ${mm}]`, xs: fmtMs(statVal(xrr)), es: fmtMs(statVal(err_)), ratio: 'mismatch', verdict: 'N/A' });+ rows.push({ dim: `read ${fam.label} (p50 ms) [result mismatch: ${mm}]`, xs: withP99(fmtMs(statVal(xrr)), xrr), es: withP99(fmtMs(statVal(err_)), err_), ratio: 'mismatch', verdict: 'N/A' });} else {- rows.push(scoreRow(`read ${fam.label} (p50 ms)`, statVal(xrr), statVal(err_), false, (v) => v.toFixed(2), xrr, err_));+ const row = scoreRow(`read ${fam.label} (p50 ms)`, statVal(xrr), statVal(err_), false, (v) => v.toFixed(2), xrr, err_, 0.30);+ row.xs = withP99(row.xs, xrr);+ row.es = withP99(row.es, err_);+ rows.push(row);}}- // mixed read-under-write (lower p99 = XERJ win)+ // mixed read-under-write (lower p99 = XERJ win). H3: if the two engines'+ // achieved background write rates diverged >10% the mixed rows were NOT+ // iso-load — annotate every mixed row so the comparison isn't read as fair.if (A.mixed) {+ const xbg = R.mixed.XERJ?.__bg?.dps, ebg = R.mixed.ES?.__bg?.dps;+ let isoNote = '';+ if (xbg != null && ebg != null && Math.min(xbg, ebg) > 0+ && Math.abs(xbg - ebg) / Math.min(xbg, ebg) > 0.10) {+ isoNote = ` [NOT iso-load: bg XERJ ${xbg.toLocaleString()}/s vs ES ${ebg.toLocaleString()}/s, offered ~100,000/s]`;+ }for (const [label] of MIXED_OPS) {const xv = statVal(R.mixed.XERJ?.[label], 'p99'), ev = statVal(R.mixed.ES?.[label], 'p99');- rows.push(scoreRow(`mixed ${label} (p99 ms, under write)`, xv, ev, false, (v) => v.toFixed(2), R.mixed.XERJ?.[label], R.mixed.ES?.[label]));+ rows.push(scoreRow(`mixed ${label} (p99 ms, under write)${isoNote}`, xv, ev, false, (v) => v.toFixed(2), R.mixed.XERJ?.[label], R.mixed.ES?.[label], 0.30));}}// knn latency (lower p50 = win) + recall (higher = win)if (A.knn) {- rows.push(scoreRow('kNN k=10 (p50 ms)', statVal(R.knn.XERJ), statVal(R.knn.ES), false, (v) => v.toFixed(2), R.knn.XERJ, R.knn.ES));+ rows.push(scoreRow('kNN k=10 (p50 ms)', statVal(R.knn.XERJ), statVal(R.knn.ES), false, (v) => v.toFixed(2), R.knn.XERJ, R.knn.ES, 0.30));rows.push(scoreRow('kNN recall@10', statVal(R.knn.XERJ, 'recall'), statVal(R.knn.ES, 'recall'), true, (v) => (v * 100).toFixed(1) + '%', R.knn.XERJ, R.knn.ES));}// disk (smaller = win)@@ -828,6 +897,10 @@ async function main() {md += `Measured with the identical client hitting both engines (\`size:0\` avg over 300k): undici fetch → XERJ 1.61ms, ES 2.77ms; `;md += `http keep-alive → XERJ 0.126ms, ES 0.283ms. The keep-alive client reveals each engine's **true server round-trip** (the ~2.2× gap the `;md += `client overhead had hidden), not the Node client. Ingest/mixed/kNN bulk load uses \`curl\` identically for both engines.\n\n`;+ md += `> **Methodology — uncached execution (honesty).** Every read is measured with \`request_cache=false\` and XERJ run with `;+ md += `\`XERJ_DISABLE_QUERY_CACHE=1\`, so BOTH engines EXECUTE every query on every iteration (no whole-result cache clone). Query bodies are `;+ md += `never mutated per-iteration; lower-level filter/OS caches stay on for both. Read rows show p50 (verdict) with p99 alongside. `;+ md += `Latency rows within a noise band (\`|Δ| ≤ max(0.30ms, 20%)\`) score **TIE** (does not fail CI); only **LOSE** fails CI.\n\n`;md += `| dimension | XERJ | ES | ratio | verdict |\n|---|--:|--:|--:|:--:|\n`;for (const r of rows) md += `| ${r.dim} | ${r.xs} | ${r.es} | ${r.ratio} | ${r.verdict} |\n`;md += `\n`;@@ -836,7 +909,7 @@ async function main() {for (const [fam, why] of SKIPPED_FAMILIES) md += `- \`${fam}\` — ${why}\n`;md += `\n`;}- md += `_Summary: ${rows.filter((r) => r.verdict === 'WIN').length} WIN, ${loses.length} LOSE, ${rows.filter((r) => r.verdict === 'N/A').length} N/A._\n`;+ md += `_Summary: ${rows.filter((r) => r.verdict === 'WIN').length} WIN, ${loses.length} LOSE, ${rows.filter((r) => r.verdict === 'TIE').length} TIE, ${rows.filter((r) => r.verdict === 'N/A').length} N/A._\n`;fs.writeFileSync(A.out, md);// keep the head-to-head slice around for continuity with bench-vs-es.mjs,diff --git a/demo/playbooks/bench-methodology.test.mjs b/demo/playbooks/bench-methodology.test.mjsnew file mode 100644index 000000000..d0f3e52d5--- /dev/null+++ b/demo/playbooks/bench-methodology.test.mjs@@ -0,0 +1,105 @@+#!/usr/bin/env node+// Harness methodology test — proves WHY the scorecard must measure per-query+// latency CLOSED-LOOP, not with the open-loop 200/s driver.+//+// Against a mock server that sleeps a FIXED, KNOWN delay D ms per request:+// - closed-loop (single client, sequential) MUST report p50 ≈ D (truth)+// - open-loop @200/s MUST report p50 ≈ D for D<5ms (sustainable) (no artifact)+// - open-loop @200/s MUST inflate p50 ≫ D for D≥25ms (backlog artifact) (the bug)+// - both identical mock servers MUST measure equal (fairness)+//+// This is the guardrail for the 2026-07-08 re-evaluation: run1's 5.6s/27s+// "latencies" were open-loop backlog on ~30-600ms true-latency queries.+//+// node demo/playbooks/bench-methodology.test.mjs+import http from 'node:http';++// ── measurement modes (closed-loop truth + the harness's open-loop) ──────────+const agent = new http.Agent({ keepAlive: true, maxSockets: 256 });+function hit(port) {+ return new Promise((resolve) => {+ const r = http.request({ hostname: '127.0.0.1', port, path: '/', method: 'GET', agent }, (res) => {+ res.on('data', () => {}); res.on('end', resolve);+ });+ r.on('error', resolve); r.end();+ });+}+const pct = (a, p) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor((p / 100) * s.length)]; };++async function closedLoop(port, iters = 40, warm = 5) {+ for (let i = 0; i < warm; i++) await hit(port);+ const lat = [];+ for (let i = 0; i < iters; i++) { const t = performance.now(); await hit(port); lat.push(performance.now() - t); }+ return pct(lat, 50);+}+// Byte-for-byte the same scheme as bench-matrix.mjs timed(): fixed cadence,+// coordinated-omission correction lat = end - min(intended, actualStart).+async function openLoop(port, { iters = 300, rate = 200, warm = 10 } = {}) {+ for (let i = 0; i < warm; i++) await hit(port);+ const lat = new Array(iters), tasks = new Array(iters), t0 = performance.now();+ for (let i = 0; i < iters; i++) {+ const intended = t0 + (i / rate) * 1000;+ tasks[i] = (async () => {+ const w = intended - performance.now(); if (w > 0) await new Promise((r) => setTimeout(r, w));+ const s = performance.now(); await hit(port); lat[i] = performance.now() - Math.min(intended, s);+ })();+ }+ await Promise.all(tasks);+ return pct(lat, 50);+}++// Models a RESOURCE-CONSTRAINED server: `concurrency` workers, each request+// takes delayMs of "work". This is the key property — a real engine is+// CPU-bound, so a query costing D ms of CPU can only be served `cores/D×1000`+// per second; beyond that, concurrent requests queue. A pure-setTimeout server+// (infinite concurrency) would NOT reproduce the open-loop artifact, because+// nothing contends — which is exactly why the artifact is a SATURATION effect,+// not a function of per-request latency alone.+function mockServer(delayMs, concurrency = 4) {+ let active = 0; const q = [];+ const pump = () => { while (active < concurrency && q.length) { active++; const res = q.shift(); setTimeout(() => { res.writeHead(200); res.end('ok'); active--; pump(); }, delayMs); } };+ const srv = http.createServer((req, res) => { q.push(res); pump(); });+ return new Promise((resolve) => { srv.listen(0, '127.0.0.1', () => resolve({ srv, port: srv.address().port })); });+}++// ── assertions ───────────────────────────────────────────────────────────────+let failures = 0;+function check(name, cond, detail) {+ const ok = !!cond; console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); if (!ok) failures++;+}++(async () => {+ console.log('Harness methodology test — closed-loop vs open-loop on fixed-delay mock servers\n');++ // Case 1: FAST server (D=2ms < 5ms cadence) — open-loop should NOT inflate.+ {+ const { srv, port } = await mockServer(2);+ const c = await closedLoop(port), o = await openLoop(port);+ check('fast(2ms): closed-loop ≈ true delay', c >= 1 && c <= 12, `closed p50 ${c.toFixed(2)}ms`);+ check('fast(2ms): open-loop ≈ closed (no artifact, amp<4×)', o < c * 4 + 6, `open ${o.toFixed(2)} vs closed ${c.toFixed(2)}`);+ srv.close();+ }++ // Case 2: SLOW, RESOURCE-CONSTRAINED server (D=40ms, only 2 workers → capacity+ // ~50 req/s). At 200/s offered that is 4× overload → open-loop MUST inflate as+ // backlog piles up, while closed-loop (1 in flight, never saturates) stays ≈D.+ // This is the XERJ situation: a CPU-bound ~40ms query flooded 256-concurrent.+ {+ const { srv, port } = await mockServer(40, 2);+ const c = await closedLoop(port, 20, 3), o = await openLoop(port, { iters: 200 });+ check('slow(40ms): closed-loop ≈ true delay', c >= 30 && c <= 70, `closed p50 ${c.toFixed(2)}ms (true ~40)`);+ check('slow(40ms): open-loop INFLATES ≥4× (backlog artifact)', o > c * 4, `open ${o.toFixed(2)} vs closed ${c.toFixed(2)} → ${(o / c).toFixed(1)}× — this is why run1 read 5.6s`);+ srv.close();+ }++ // Case 3: FAIRNESS — two identical servers measure equal under both modes.+ {+ const a = await mockServer(15), b = await mockServer(15);+ const ca = await closedLoop(a.port, 20, 3), cb = await closedLoop(b.port, 20, 3);+ check('fairness: identical servers → equal closed-loop (within 40%)', Math.abs(ca - cb) <= 0.4 * Math.max(ca, cb), `A ${ca.toFixed(2)} vs B ${cb.toFixed(2)}`);+ a.srv.close(); b.srv.close();+ }++ console.log(`\n${failures === 0 ? 'ALL PASS' : failures + ' FAILURE(S)'} — closed-loop is the honest per-query latency; open-loop@200/s is a throughput/saturation test and inflates any >5ms query.`);+ process.exit(failures === 0 ? 0 : 1);+})();diff --git a/demo/playbooks/bench-vs-es.mjs b/demo/playbooks/bench-vs-es.mjsindex 47ec7b87e..d9952d2d7 100644--- a/demo/playbooks/bench-vs-es.mjs+++ b/demo/playbooks/bench-vs-es.mjs@@ -12,6 +12,20 @@import fs from 'node:fs';import { execSync } from 'node:child_process';+// ── DEPRECATION GUARD (quarantine) — H5 ─────────────────────────────────────+// This harness uses a NON-CANONICAL transport (Node's global fetch/undici, no+// shared keep-alive agent) and would overwrite a canonical scorecard file+// (BENCHMARK_VS_ES.md). The canonical, honesty-audited harness is+// demo/playbooks/bench-matrix.mjs. Refuse to run (exit 2) unless the operator+// explicitly sets FORCE_LEGACY_BENCH=1.+process.stderr.write(+ 'DEPRECATED — use bench-matrix.mjs; this harness uses a non-canonical transport ' ++ 'and must not overwrite SCORECARD.md/BENCHMARK_VS_ES.md\n');+if (process.env.FORCE_LEGACY_BENCH !== '1') {+ process.stderr.write(' refusing to run (would overwrite a canonical benchmark file). Set FORCE_LEGACY_BENCH=1 to override.\n');+ process.exit(2);+}+const N = parseInt(process.argv[2] || '100000', 10);const ENGINES = [{ name: 'XERJ', url: process.argv[3] || 'http://localhost:9200' },diff --git a/demo/playbooks/bench.mjs b/demo/playbooks/bench.mjsindex ee486bb56..5a2a13cf9 100644--- a/demo/playbooks/bench.mjs+++ b/demo/playbooks/bench.mjs@@ -9,6 +9,19 @@ import { execFileSync } from 'node:child_process';import fs from 'node:fs';import path from 'node:path';+// ── DEPRECATION GUARD (quarantine) — H5 ─────────────────────────────────────+// This harness uses a NON-CANONICAL transport (Node's global fetch/undici, no+// shared keep-alive agent) and writes a canonical benchmark file (BENCHMARK.md).+// The canonical, honesty-audited harness is demo/playbooks/bench-matrix.mjs.+// Refuse to run (exit 2) unless the operator explicitly sets FORCE_LEGACY_BENCH=1.+process.stderr.write(+ 'DEPRECATED — use bench-matrix.mjs; this harness uses a non-canonical transport ' ++ 'and must not overwrite SCORECARD.md/BENCHMARK_VS_ES.md\n');+if (process.env.FORCE_LEGACY_BENCH !== '1') {+ process.stderr.write(' refusing to run (would overwrite a canonical benchmark file). Set FORCE_LEGACY_BENCH=1 to override.\n');+ process.exit(2);+}+const ES = 'http://localhost:9200';const ROOT = path.dirname(new URL(import.meta.url).pathname);const N = parseInt(process.argv[2] || '200000', 10);diff --git a/demo/usecases/doc-index/.gitignore b/demo/usecases/doc-index/.gitignoreindex c36f570e7..bbfb1e57a 100644--- a/demo/usecases/doc-index/.gitignore+++ b/demo/usecases/doc-index/.gitignore@@ -1,3 +1,4 @@# generated by gen-corpus.mjs (idempotent); regenerate with: node gen-corpus.mjscorpus/.index_build_ms+queries.jsondiff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsindex 2fef3dc0a..24383919a 100644--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -1042,6 +1042,24 @@ impl<'a> FastCtx<'a> {}self.exec_metric_top(metric_kind_of(agg_type)?, params)}+ "extended_stats" => {+ if sub.is_some() {+ return None;+ }+ self.exec_extended_stats(params)+ }+ "percentiles" => {+ if sub.is_some() {+ return None;+ }+ self.exec_percentiles(params)+ }+ "percentile_ranks" => {+ if sub.is_some() {+ return None;+ }+ self.exec_percentile_ranks(params)+ }"terms" => self.exec_terms(params, sub),"cardinality" => self.exec_cardinality(params, sub),"range" => self.exec_range(params, sub),@@ -1167,6 +1185,305 @@ impl<'a> FastCtx<'a> {Some(Self::emit_metric(kind, &acc))}+ // ── extended_stats / percentiles / percentile_ranks (columnar) ───────+ //+ // These three leaves were the last O(N) brute-force uncached reads: the+ // pre-fix path fell into `run_aggs_with_all`, which decompresses ++ // JSON-parses EVERY live doc before `run_extended_stats` /+ // `run_percentiles` / `run_percentile_ranks` even see a value (~650 ms on+ // a 100 k corpus). Served columnar they are a single linear fold over the+ // per-segment numeric `.dv` column (extended_stats) or a read of the+ // already-sorted column index (percentiles / percentile_ranks), dropping+ // to low-ms. Each is byte-identical to its brute counterpart for the+ // shapes it accepts (modulo float-summation order — the same documented+ // divergence the other metric leaves carry), and bails (`None` → brute)+ // on any option that would change value gathering or rendering+ // (`missing`, `format`, `hdr`, `tdigest`) and under a top-level query+ // filter (handled by the whitelist in `exec_agg`).++ /// Gather every live numeric value of `field` (segments + memtable) into a+ /// single ascending-sorted `Vec<f64>`, mirroring the brute+ /// `nums.sort_by(partial_cmp)` collection so percentile interpolation is+ /// byte-identical. Returns `None` when the field isn't a scalar numeric+ /// everywhere (keyword column, or a memtable doc holds a non-number) — the+ /// caller then bails to the exact brute path.+ ///+ /// Each segment's `.dv` numeric column already carries a `sorted`+ /// value-index (`Vec<(bits, doc_id)>`, ascending by f64), so the common+ /// single-segment / no-memtable case is a pure O(N) copy with no sort.+ fn gather_numeric_sorted(&self, field: &str) -> Option<Vec<f64>> {+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Err(()) => return None,+ _ => {}+ }+ if !self.mem_field_numeric_safe(field) {+ return None;+ }+ let mut capacity = self.mem().len();+ for s in &self.segs {+ if let Some(Column::Numeric(n)) = s.cols.get(field) {+ capacity += n.live_count as usize;+ }+ }+ let mut vals: Vec<f64> = Vec::with_capacity(capacity);+ for s in &self.segs {+ match s.cols.get(field) {+ Some(Column::Numeric(n)) => {+ for (bits, _) in &n.sorted {+ vals.push(f64::from_bits(*bits as u64));+ }+ }+ Some(Column::Keyword(_)) => return None,+ None => {}+ }+ }+ // The collected values are already globally sorted iff they came from a+ // single pre-sorted column source and the memtable added none.+ let mut pre_sorted = self.segs.len() <= 1;+ for doc in self.mem().iter() {+ if let Some(v) = extract_numeric(doc, field) {+ vals.push(v);+ pre_sorted = false;+ }+ }+ if !pre_sorted {+ vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ }+ Some(vals)+ }++ /// `extended_stats` — single columnar pass computing count / sum /+ /// sum_of_squares / min / max, then the same exact-arithmetic moments ++ /// `std_deviation_bounds` (honouring `sigma`, default 2) as+ /// `run_extended_stats`. Whitelisted params only; `missing` / `format`+ /// bail to brute.+ fn exec_extended_stats(&self, params: &Value) -> Option<Value> {+ if !params_only(params, &["field", "sigma"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Err(()) => return None,+ _ => {}+ }+ if !self.mem_field_numeric_safe(field) {+ return None;+ }++ let mut count: u64 = 0;+ let mut sum: f64 = 0.0;+ let mut sum_sq: f64 = 0.0;+ let mut min = f64::INFINITY;+ let mut max = f64::NEG_INFINITY;+ let mut fold = |v: f64| {+ count += 1;+ sum += v;+ sum_sq += v * v;+ if v < min {+ min = v;+ }+ if v > max {+ max = v;+ }+ };+ for s in &self.segs {+ match s.cols.get(field) {+ Some(Column::Numeric(n)) => {+ if n.null_bitmap.is_empty() {+ for &bits in &n.data {+ fold(f64::from_bits(bits as u64));+ }+ } else {+ for row in 0..n.doc_count {+ if !n.null_bitmap.contains(row) {+ fold(f64::from_bits(n.data[row as usize] as u64));+ }+ }+ }+ }+ Some(Column::Keyword(_)) => return None,+ None => {}+ }+ }+ for doc in self.mem().iter() {+ if let Some(v) = extract_numeric(doc, field) {+ fold(v);+ }+ }++ if count == 0 {+ // Mirror run_extended_stats' empty shape exactly: `sum` is a real+ // zero, every higher-order moment is null.+ return Some(json!({+ "count": 0, "min": Value::Null, "max": Value::Null,+ "avg": Value::Null, "sum": 0.0, "sum_of_squares": Value::Null,+ "variance": Value::Null, "variance_population": Value::Null,+ "variance_sampling": Value::Null,+ "std_deviation": Value::Null,+ "std_deviation_population": Value::Null,+ "std_deviation_sampling": Value::Null,+ "std_deviation_bounds": {+ "upper": Value::Null, "lower": Value::Null,+ "upper_population": Value::Null, "lower_population": Value::Null,+ "upper_sampling": Value::Null, "lower_sampling": Value::Null,+ }+ }));+ }++ let avg = sum / count as f64;+ let variance_pop = (sum_sq / count as f64) - avg * avg;+ let variance_pop = variance_pop.max(0.0);+ let variance_samp = if count > 1 {+ variance_pop * count as f64 / (count - 1) as f64+ } else {+ 0.0+ };+ let std_deviation = variance_pop.max(0.0).sqrt();+ let std_deviation_samp = variance_samp.max(0.0).sqrt();+ let sigma = params.get("sigma").and_then(Value::as_f64).unwrap_or(2.0);++ Some(json!({+ "count": count,+ "min": min,+ "max": max,+ "avg": avg,+ "sum": sum,+ "sum_of_squares": sum_sq,+ "variance": variance_pop,+ "variance_population": variance_pop,+ "variance_sampling": variance_samp,+ "std_deviation": std_deviation,+ "std_deviation_population": std_deviation,+ "std_deviation_sampling": std_deviation_samp,+ "std_deviation_bounds": {+ "upper": avg + sigma * std_deviation,+ "lower": avg - sigma * std_deviation,+ "upper_population": avg + sigma * std_deviation,+ "lower_population": avg - sigma * std_deviation,+ "upper_sampling": avg + sigma * std_deviation_samp,+ "lower_sampling": avg - sigma * std_deviation_samp,+ }+ }))+ }++ /// `percentiles` — the ES-default (non-hdr) algorithm is exact linear+ /// interpolation over the sorted values (`run_percentiles`), so the+ /// columnar path reads the pre-sorted column index and applies the+ /// identical `rank = (pct/100)*(N-1)` interpolation. Honours `percents`+ /// (default `[1,5,25,50,75,95,99]`) and `keyed` (default true); `hdr` /+ /// `missing` / `format` / `tdigest` bail to brute.+ fn exec_percentiles(&self, params: &Value) -> Option<Value> {+ if !params_only(params, &["field", "percents", "keyed"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ let percents: Vec<f64> = params+ .get("percents")+ .and_then(Value::as_array)+ .map(|arr| arr.iter().filter_map(Value::as_f64).collect())+ .unwrap_or_else(|| vec![1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]);+ let keyed = params.get("keyed").and_then(Value::as_bool).unwrap_or(true);++ let nums = self.gather_numeric_sorted(field)?;+ let compute = |pct: f64| -> Option<f64> {+ if nums.is_empty() {+ return None;+ }+ let rank = (pct / 100.0) * (nums.len() as f64 - 1.0);+ let lo = rank.floor() as usize;+ let hi = (lo + 1).min(nums.len() - 1);+ let frac = rank - rank.floor();+ Some(nums[lo] * (1.0 - frac) + nums[hi] * frac)+ };++ if keyed {+ let values: Map<String, Value> = percents+ .iter()+ .map(|&pct| {+ let key = format!("{:.1}", pct);+ let val = match compute(pct) {+ Some(v) => serde_json::Number::from_f64(v)+ .map(Value::Number)+ .unwrap_or(Value::Null),+ None => Value::Null,+ };+ (key, val)+ })+ .collect();+ Some(json!({ "values": values }))+ } else {+ let arr: Vec<Value> = percents+ .iter()+ .map(|&pct| {+ let val = match compute(pct) {+ Some(v) => serde_json::Number::from_f64(v)+ .map(Value::Number)+ .unwrap_or(Value::Null),+ None => Value::Null,+ };+ let key_num = serde_json::Number::from_f64(pct)+ .map(Value::Number)+ .unwrap_or(Value::Null);+ json!({ "key": key_num, "value": val })+ })+ .collect();+ Some(json!({ "values": arr }))+ }+ }++ /// `percentile_ranks` — for each target value, the fraction of the corpus+ /// at or below it, ×100. Byte-identical to `run_percentile_ranks`: the+ /// sorted column index turns each brute `filter(v <= t).count()` into a+ /// `partition_point` (same exact count). `hdr` / `missing` / `format`+ /// bail to brute.+ fn exec_percentile_ranks(&self, params: &Value) -> Option<Value> {+ if !params_only(params, &["field", "values", "keyed"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ let targets = match params.get("values").and_then(Value::as_array) {+ Some(v) => v,+ None => return Some(json!({ "values": {} })),+ };+ let keyed = params.get("keyed").and_then(Value::as_bool).unwrap_or(true);++ let nums = self.gather_numeric_sorted(field)?;+ let total = nums.len() as f64;+ // `nums` is ascending, so the count of values <= t is a partition_point.+ let rank_of = |t: f64| -> f64 {+ if total == 0.0 {+ 0.0+ } else {+ let below = nums.partition_point(|&v| v <= t) as f64;+ (below / total) * 100.0+ }+ };++ if keyed {+ let mut result = Map::new();+ for target in targets {+ if let Some(t) = target.as_f64() {+ result.insert(format!("{}", t), json!(rank_of(t)));+ }+ }+ Some(json!({ "values": result }))+ } else {+ let arr: Vec<Value> = targets+ .iter()+ .filter_map(|target| target.as_f64())+ .map(|t| {+ let key_json = if t.fract() == 0.0 {+ json!(t as i64)+ } else {+ json!(t)+ };+ json!({ "key": key_json, "value": rank_of(t) })+ })+ .collect();+ Some(json!({ "values": arr }))+ }+ }+// ── shared fused row pass ────────────────────────────────────────────//// For a parent that assigns each segment row to at most one bucket slotdiff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 566adb630..c94a13fac 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -530,6 +530,18 @@ pub struct Index {/// follow-up) and evicted by segment id at merge retire.range_prefilter_cache: Arc<dashmap::DashMap<String, Arc<HashSet<u32>>>>,+ /// Per-segment `_id → stored-position` index, built lazily on the first+ /// `ids` query that touches a segment and reused thereafter. An `ids`+ /// query used to full-scan every stored doc (O(N) brace-walk + parse)+ /// just to find a handful of primary keys — 128 ms to return 3 docs at+ /// 100k, scaling linearly with the corpus. With this map an `ids` query+ /// resolves each requested id to its stored position (like GET+ /// `_doc/{id}` / `_mget`) and hydrates only those positions via the+ /// `StoredSlices` offset index, so it is O(#ids) and FLAT vs corpus+ /// size. Segments are immutable → the map never goes stale; evicted by+ /// segment id at the merge-completion site alongside the other caches.+ id_pos_cache: Arc<dashmap::DashMap<String, Arc<std::collections::HashMap<String, u32>>>>,+/// Per-segment cache of decoded `Vec<Value>` from the stored section./// KNN search and segment-scan get-document paths used to call/// `decode_stored` + `simd_json::serde::from_slice` *every* time —@@ -807,6 +819,7 @@ impl Index {sort_shadow_fields: Arc::new(dashmap::DashMap::new()),stored_slices_build_locks: Arc::new(dashmap::DashMap::new()),range_prefilter_cache: Arc::new(dashmap::DashMap::new()),+ id_pos_cache: Arc::new(dashmap::DashMap::new()),stored_value_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),@@ -982,6 +995,7 @@ impl Index {sort_shadow_fields: Arc::new(dashmap::DashMap::new()),stored_slices_build_locks: Arc::new(dashmap::DashMap::new()),range_prefilter_cache: Arc::new(dashmap::DashMap::new()),+ id_pos_cache: Arc::new(dashmap::DashMap::new()),stored_value_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),@@ -3063,6 +3077,7 @@ impl Index {self.query_cache.clear();for id in &dropped_seg_ids {self.dv_cache.remove(id.as_str());+ self.id_pos_cache.remove(id.as_str());self.stored_value_cache.remove(id.as_str());if let Some((_, slices)) = self.stored_slices_cache.remove(id.as_str()) {self.stored_slices_cache_bytes@@ -4501,7 +4516,15 @@ impl Index {// - `request.scroll.is_some()` / scroll cursor (stateful).// - `request.search_after.is_some()` (cursor-based pagination// could collide with cached state).- let cache_eligible = !request.profile && request.search_after.is_none();+ // XERJ_DISABLE_QUERY_CACHE=1 turns off the whole-result cache so a+ // benchmark measures true per-request execution on every call (no+ // took_ms=0 clone). Read once. Normal operation is unaffected.+ let cache_eligible = !request.profile && request.search_after.is_none() && {+ static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ !*DISABLED.get_or_init(|| {+ matches!(std::env::var("XERJ_DISABLE_QUERY_CACHE").as_deref(), Ok("1") | Ok("true"))+ })+ };let cache_key: Option<(u64, u64)> = if cache_eligible {// Hash the request via its serde_json representation,// streaming the serializer output STRAIGHT INTO the hasher.@@ -5864,31 +5887,52 @@ impl Index {};// Counting is DECOUPLED from materialisation on the- // scored FTS path. `FtsSearcher::execute` builds the- // FULL hit set regardless of `limit` (it only sorts and- // truncates afterwards), so requesting `usize::MAX`- // costs nothing extra over `fetch_limit` and yields the- // EXACT segment match count. Previously the size>0 path- // passed `fetch_limit` and tallied `total_count` per- // materialised hit, so `hits.total` was capped at the- // ~256 materialisation limit while size:0 (which used- // `usize::MAX`) was exact — DEFECT #3. Now both paths- // add the full `seg_hits.len()` so the count agrees, and- // we materialise *sources* for only the top- // `materialisation_limit` hits. The held-in-full list- // is just the lightweight (doc_id, score) `ScoredHit`s- // — no source is materialised beyond the page, so the- // capped-RAM OOM guard is preserved.- let limit = usize::MAX;+ // scored FTS path. `search_bounded` returns the EXACT+ // segment match `seg_total` (counted over the full match+ // set, independent of the page cap) alongside the best+ // `cap` hits. Previously the size>0 path passed+ // `fetch_limit` and tallied `total_count` per materialised+ // hit, so `hits.total` was capped at the ~256+ // materialisation limit while size:0 (which used+ // `usize::MAX`) was exact — DEFECT #3. Now both paths add+ // the full `seg_total` so the count agrees, and we+ // materialise *sources* for only the top+ // `materialisation_limit` hits.+ //+ // PERF (bounded top-N): the old code built + fully sorted+ // the ENTIRE match set per segment even for size:10 —+ // O(N log N) on tens of thousands of hits. On the common+ // path (no field sort, not count-only, no deletes) only+ // the top `materialisation_limit` sources are ever+ // materialised (the loop below breaks there), so we cap+ // the collector heap at `materialisation_limit`: O(N log+ // cap) work, O(cap) memory, byte-identical top-k prefix.+ // The three cases that consume PAST the page cap keep the+ // legacy full-set path (`usize::MAX`):+ // * `sort_topk.is_some()` — the field-sort arm narrows+ // *every* matching doc_id to sort candidates.+ // * `count_only` — wants the exact total with no page+ // cap (and never materialises).+ // * `deletes_present` — tombstones/superseded dups can+ // skip past `materialisation_limit` matches while+ // filling the page, so the page needs more than the+ // top-`cap` by score.+ let fts_cap = if count_only || sort_topk.is_some() || deletes_present {+ usize::MAX+ } else {+ materialisation_limit+ };if fts_has_field {- if let Ok(seg_hits) = searcher.search(&fq, limit, false) {+ if let Ok((seg_hits, seg_total)) =+ searcher.search_bounded(&fq, fts_cap, false)+ {// FTS is authoritative for this segment (field// present + searcher ran) — mark handled the same// way for count-only and size>0 so the fall-through// decision (and thus the count) agrees.fts_handled = true;// Exact count — identical for count_only and size>0.- total_count += seg_hits.len() as u64;+ total_count += seg_total;// Field-sorted FTS (e.g. bool/match under the// implicit `@timestamp desc` index sort): the// legacy arm below decodes + parses the WHOLE@@ -5957,91 +6001,140 @@ impl Index {&& !seg_hits.is_empty()&& all_hits.len() < materialisation_limit{- // Merge-race hardening (2026-07): NEVER- // silently skip a snapshot segment that- // fails to open — under the read-lease fix- // its files are guaranteed present, so an- // open failure is real corruption and must- // fail the query, not shrink its results.- {- let seg_reader = self.store.open_segment_arc(&seg_id)?;- if let Ok(Some(stored_bytes_raw)) =- seg_reader.section(SectionType::Stored)- {- let stored_bytes =- match xerj_storage::stored_codec::decode_stored(- stored_bytes_raw,- ) {- Ok(b) => b,- Err(_) => continue,- };- // serde_json — see ffd49ac, simd_json- // silently corrupts some M7 raw-bytes- // payloads.- if let Ok(docs) =- serde_json::from_slice::<Vec<Value>>(&stored_bytes)- {- for sh in &seg_hits {- // Page full — the rest are- // already counted in- // `total_count`, so stop- // decoding sources. When a- // field sort is active we must- // NOT stop: every match has to- // be offered to the bounded- // top-N heap so the survivors- // are the GLOBAL top-N by the- // sort key, not the highest-- // scoring prefix.- if sort_topk.is_none()- && all_hits.len() >= materialisation_limit- {- break;- }- let doc = match docs.get(sh.doc_id as usize) {- Some(d) => d,- None => continue,- };- let id = doc- .get("_id")- .and_then(Value::as_str)- .unwrap_or("")- .to_string();- if let Some(ver) =- self.store.version_map.get(&id)- {- if ver.deleted {- continue;- }- }- // Dedup against memtable/earlier- // segments WITHOUT touching- // `total_count` (already tallied- // above via `seg_hits.len()`).- if seen_ids.contains(&id) {- continue;- }- let source = doc- .get("_source")- .cloned()- .unwrap_or(Value::Null);- seen_ids.insert(id.clone());- let hit = Hit {- id,- score: sh.score,- source,- sort: Vec::new(),- explain: None,- highlight: None,- matched_queries: Vec::new(),- };- if let Some(topk) = sort_topk.as_mut() {- topk.offer(hit);- } else {- all_hits.push(hit);+ // F2 RANDOM-ACCESS source hydration. The+ // scored FTS page needs `_source` for only+ // the top-(from+size) matched doc_ids, yet+ // the legacy path decoded the ENTIRE stored+ // section (`from_slice::<Vec<Value>>`,+ // ~10 MB / O(N) per 100k docs) just to index+ // them — the dominant size>0 scored-read cost+ // (~485 ms at size:10 vs ~1 ms at size:0).+ // Reuse the per-segment offset index+ // (`stored_slices_for`, the SAME+ // random-access mechanism the term /+ // doc-values page hydration uses) to parse+ // ONLY the page's doc slices: O(page) parses+ // on a warm segment. Each slice is a+ // complete top-level `{...}` object (see+ // `brace_walk_offsets`), so parsing it with+ // the SAME `serde_json` parser the legacy+ // path used yields a byte-identical+ // `_source` — we deliberately do NOT switch+ // to simd_json here (the M7 raw-bytes+ // payload corruption noted below still+ // applies).+ let slices_opt =+ self.stored_slices_for(seg_id.as_str(), meta.doc_count);+ // Legacy whole-section fallback ONLY when the+ // offset index can't be built (open/decode+ // failure or a malformed/incomplete section).+ // Merge-race hardening (2026-07): a genuine+ // segment-open failure must FAIL the query+ // (`?`), not silently shrink its results —+ // under the read-lease fix the files are+ // guaranteed present, so an open error is+ // real corruption.+ let whole_fallback: Option<Vec<Value>> =+ if slices_opt.is_some() {+ None+ } else {+ let seg_reader =+ self.store.open_segment_arc(&seg_id)?;+ match seg_reader.section(SectionType::Stored) {+ Ok(Some(raw)) => {+ match xerj_storage::stored_codec::decode_stored(+ raw,+ ) {+ // serde_json — see ffd49ac,+ // simd_json silently+ // corrupts some M7+ // raw-bytes payloads.+ Ok(b) => serde_json::from_slice::<+ Vec<Value>,+ >(+ &b+ )+ .ok(),+ Err(_) => None,}}- // `docs` dropped at end of block.+ _ => None,+ }+ };+ if slices_opt.is_some() || whole_fallback.is_some() {+ // Owned parsed doc for a stored position,+ // shared by both source layouts. The+ // slice arm parses one object on demand;+ // the fallback clones from the fully+ // decoded Vec.+ let fetch_doc = |pos: u32| -> Option<Value> {+ if let Some(slices) = slices_opt.as_deref() {+ let &(start, end) =+ slices.offsets.get(pos as usize)?;+ let slice = slices+ .bytes+ .get(start as usize..end as usize)?;+ serde_json::from_slice::<Value>(slice).ok()+ } else {+ whole_fallback+ .as_ref()+ .and_then(|d| d.get(pos as usize).cloned())+ }+ };+ for sh in &seg_hits {+ // Page full — the rest are already+ // counted in `total_count`, so stop+ // decoding sources. When a field+ // sort is active we must NOT stop:+ // every match has to be offered to+ // the bounded top-N heap so the+ // survivors are the GLOBAL top-N by+ // the sort key, not the highest-+ // scoring prefix.+ if sort_topk.is_none()+ && all_hits.len() >= materialisation_limit+ {+ break;+ }+ let doc = match fetch_doc(sh.doc_id) {+ Some(d) => d,+ None => continue,+ };+ let id = doc+ .get("_id")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ if let Some(ver) = self.store.version_map.get(&id) {+ if ver.deleted {+ continue;+ }+ }+ // Dedup against memtable/earlier+ // segments WITHOUT touching+ // `total_count` (already tallied+ // above via `seg_total`).+ if seen_ids.contains(&id) {+ continue;+ }+ let source = doc+ .get("_source")+ .cloned()+ .unwrap_or(Value::Null);+ seen_ids.insert(id.clone());+ let hit = Hit {+ id,+ score: sh.score,+ source,+ sort: Vec::new(),+ explain: None,+ highlight: None,+ matched_queries: Vec::new(),+ };+ if let Some(topk) = sort_topk.as_mut() {+ topk.offer(hit);+ } else {+ all_hits.push(hit);}}}@@ -6127,6 +6220,20 @@ impl Index {)} else if let QueryNode::Terms { field, values, .. } = query {self.build_term_prefilter_cached(&segments_dir, &seg_id, field, values)+ } else if let QueryNode::Ids { values } = query {+ // Resolve primary keys to stored positions via the+ // per-segment id index (the GET `_doc/{id}` / `_mget`+ // lookup), so an `ids` query hydrates O(#ids) positions+ // instead of scanning the whole collection. Gated on+ // `!deletes_present`: with overwrites/tombstones a live+ // id can occupy positions in more than one segment, so+ // the scan's delete-aware `_id` matching is used+ // instead.+ if deletes_present {+ None+ } else {+ self.build_ids_prefilter_cached(&seg_id, meta.doc_count, values)+ }} else if matches!(query, QueryNode::Bool { .. }) {// Pure-conjunction bool: parse only the most-selective// conjunct's docs; `doc_matches_query` re-tests the full@@ -8054,6 +8161,184 @@ impl Index {/// - If the segment has no FTS data for the field at all, the/// shortcut is abandoned (return `None`) because the segment/// would otherwise undercount.+ /// Exact match count for a `bool` that carries `should` and/or `must_not`+ /// clauses — the shapes the fused must/filter-intersection arm bails on.+ /// Resolves every leaf clause to its doc-values position set per segment+ /// and combines them with set algebra:+ /// required = ∩(must, filter); should = positions in ≥k should sets;+ /// result = (required ∩ should) − ∪(must_not).+ /// Only Term/Terms/Range leaves are resolvable; anything else → `None`+ /// (caller keeps the counting scan). Conservative guards make a+ /// delete-blind / memtable-blind count impossible to mistake for+ /// authoritative: bails on any ghost (overwrite/tombstone) event and on a+ /// non-empty memtable. `minimum_should_match` percentages/field/script →+ /// `None`.+ fn bool_should_mustnot_count(+ &self,+ must: &[QueryNode],+ should: &[QueryNode],+ must_not: &[QueryNode],+ filter: &[QueryNode],+ minimum_should_match: &Option<xerj_query::ast::MinShouldMatch>,+ snap: &xerj_storage::index_store::IndexSnapshot,+ ) -> Option<u64> {+ // Delete/memtable blindness guards — an authoritative count must be+ // exact against live docs, and these sets only see flushed physical+ // segment docs.+ if self.store.version_map.ghost_events() > 0 {+ return None;+ }+ if self.memtable.doc_count() > 0 {+ return None;+ }++ // Effective minimum_should_match required-count.+ let k: u32 = if should.is_empty() {+ 0+ } else {+ let default = if must.is_empty() && filter.is_empty() {+ 1+ } else {+ 0+ };+ match minimum_should_match {+ None => default,+ Some(xerj_query::ast::MinShouldMatch::Fixed(n)) => *n,+ // Percentage / per-doc field / script — not resolvable here.+ Some(_) => return None,+ }+ };+ // `should` only filters when at least one clause is required (k >= 1).+ let should_active = !should.is_empty() && k >= 1;++ let resolve = |cols: &std::collections::BTreeMap<+ String,+ xerj_storage::doc_values::Column,+ >,+ clause: &QueryNode|+ -> Option<HashSet<u32>> {+ let clause = match clause {+ QueryNode::Constant { query, .. } | QueryNode::Boosted { query, .. } => {+ query.as_ref()+ }+ _ => clause,+ };+ match clause {+ QueryNode::Term { field, value, .. } => {+ seg_term_positions(cols, field, std::slice::from_ref(value))+ }+ QueryNode::Terms { field, values, .. } => seg_term_positions(cols, field, values),+ QueryNode::Range {+ field,+ gte,+ gt,+ lte,+ lt,+ ..+ } => seg_range_positions(+ cols,+ field,+ gte.as_ref(),+ gt.as_ref(),+ lte.as_ref(),+ lt.as_ref(),+ ),+ _ => None,+ }+ };++ let segments_dir = self.data_dir.join("segments");+ // Per-(segment, shape) count cache so the warm/repeat query doesn't+ // rebuild the position sets each call (the whole-result cache may be+ // off). Segments are immutable → the cached seg count never staleness.+ let cache_key: Option<String> =+ serde_json::to_string(&(must, should, must_not, filter, k)).ok();+ let mut total: u64 = 0;+ for meta in &snap.segments {+ if meta.doc_count == 0 {+ continue;+ }+ if let Some(ck) = &cache_key {+ if let Some(hit) = self+ .shortcut_count_cache+ .get(&(meta.id.to_string(), ck.clone()))+ {+ total = total.saturating_add(*hit.value());+ continue;+ }+ }+ let cols = self.dv_columns_for(&segments_dir, &meta.id)?;++ // Required conjunction: intersection of must + filter sets.+ let required: Option<HashSet<u32>> = if must.is_empty() && filter.is_empty() {+ None+ } else {+ let mut sets: Vec<HashSet<u32>> = Vec::new();+ for c in must.iter().chain(filter.iter()) {+ sets.push(resolve(&cols, c)?);+ }+ sets.sort_by_key(|s| s.len());+ let mut it = sets.into_iter();+ let mut acc = it.next().unwrap_or_default();+ for s in it {+ acc.retain(|p| s.contains(p));+ if acc.is_empty() {+ break;+ }+ }+ Some(acc)+ };++ // must_not union.+ let mut mnot: HashSet<u32> = HashSet::new();+ for c in must_not {+ mnot.extend(resolve(&cols, c)?);+ }++ let seg_count: u64 = if should_active {+ // Positions matching >= k of the should sets, then filtered by+ // the required set and the must_not exclusion.+ let mut hits: std::collections::HashMap<u32, u32> =+ std::collections::HashMap::new();+ for c in should {+ for p in resolve(&cols, c)? {+ *hits.entry(p).or_insert(0) += 1;+ }+ }+ let mut cnt: u64 = 0;+ for (p, h) in hits.iter() {+ if *h < k {+ continue;+ }+ if let Some(req) = &required {+ if !req.contains(p) {+ continue;+ }+ }+ if mnot.contains(p) {+ continue;+ }+ cnt += 1;+ }+ cnt+ } else if let Some(req) = &required {+ req.iter().filter(|p| !mnot.contains(p)).count() as u64+ } else {+ // No required, no active should → all docs minus must_not.+ (meta.doc_count).saturating_sub(mnot.len() as u64)+ };+ if let Some(ck) = &cache_key {+ if self.shortcut_count_cache.len() >= SHORTCUT_COUNT_CACHE_MAX {+ self.shortcut_count_cache.clear();+ }+ self.shortcut_count_cache+ .insert((meta.id.to_string(), ck.clone()), seg_count);+ }+ total = total.saturating_add(seg_count);+ }+ Some(total)+ }+async fn try_shortcut_count(&self,query: &QueryNode,@@ -8075,16 +8360,29 @@ impl Index {should,must_not,filter,- ..+ minimum_should_match,} = query{+ // `should`/`must_not` shapes: resolve via per-segment doc-values+ // set algebra (the fused must/filter anchor-walk below only does+ // pure conjunctions). `None` from the helper (unresolvable leaf /+ // ghost / non-empty memtable) falls through to the scan.+ if !should.is_empty() || !must_not.is_empty() {+ return self.bool_should_mustnot_count(+ must,+ should,+ must_not,+ filter,+ minimum_should_match,+ snap,+ );+ }// Combine must + filter — both behave identically for counting.let mut all_must: Vec<&QueryNode> = must.iter().collect();for f in filter {all_must.push(f);}- // No should/must_not support yet (would need bitmap union/diff).- if !should.is_empty() || !must_not.is_empty() || all_must.is_empty() {+ if all_must.is_empty() {return None;}// Every must child must be a Term or Range we can resolve via@@ -8524,6 +8822,91 @@ impl Index {return Some(seg_matches + mem_matches);}+ // `terms` — union of exact per-value doc-values counts. Distinct+ // values on a single-valued keyword/numeric column are disjoint, so+ // the summed doc-freqs are exact. Conservative guards (ghost /+ // non-empty memtable) keep the delete/memtable-blind count from ever+ // standing in as authoritative; the ordinary scan handles those cases.+ if let QueryNode::Terms { field, values, .. } = query {+ use xerj_storage::doc_values::Column;+ if self.store.version_map.ghost_events() > 0 || self.memtable.doc_count() > 0 {+ return None;+ }+ let field_str = field.as_str();+ let segments_dir = self.data_dir.join("segments");+ let mut seg_matches: u64 = 0;+ for meta in &snap.segments {+ if meta.doc_count == 0 {+ continue;+ }+ let cols = self.dv_columns_for(&segments_dir, &meta.id)?;+ match cols.get(field_str) {+ Some(Column::Keyword(k)) => {+ let mut seen: HashSet<String> = HashSet::new();+ for v in values {+ let raw = match v {+ Value::String(s) => s.clone(),+ other => other.to_string(),+ };+ if seen.insert(raw.clone()) {+ seg_matches = seg_matches.saturating_add(k.doc_freq(&raw) as u64);+ }+ }+ }+ Some(Column::Numeric(n)) => {+ let mut seen: HashSet<u64> = HashSet::new();+ for v in values {+ let f = v.as_f64()?;+ if seen.insert(f.to_bits()) {+ seg_matches = seg_matches+ .saturating_add(n.range_count(f, f, true, true));+ }+ }+ }+ None => return None, // no dv column → can't count safely+ }+ }+ return Some(seg_matches);+ }++ // `exists` — provable only for the DENSE case: a field whose column+ // has no nulls and covers every doc means every doc has a scalar value+ // (arrays / objects / json-null leave the null bitmap non-empty), so+ // all docs match. Any null / partial coverage / missing column, or a+ // non-empty memtable, abandons to the scan — which resolves+ // `get_field_value(...).is_some()` exactly (incl. arrays, dotted+ // paths). Meta fields are always present.+ if let QueryNode::Exists { field } = query {+ use xerj_storage::doc_values::Column;+ if self.store.version_map.ghost_events() > 0 || self.memtable.doc_count() > 0 {+ return None;+ }+ match field.as_str() {+ "_id" | "_index" | "_seq_no" | "_version" | "_primary_term" => {+ return Some(self.live_doc_count());+ }+ _ => {}+ }+ let segments_dir = self.data_dir.join("segments");+ let mut seg_matches: u64 = 0;+ for meta in &snap.segments {+ if meta.doc_count == 0 {+ continue;+ }+ let cols = self.dv_columns_for(&segments_dir, &meta.id)?;+ let (null_empty, dcount) = match cols.get(field.as_str()) {+ Some(Column::Keyword(k)) => (k.null_bitmap.is_empty(), k.doc_count as u64),+ Some(Column::Numeric(n)) => (n.null_bitmap.is_empty(), n.doc_count as u64),+ None => return None, // can't prove presence → scan+ };+ if !null_empty || dcount != meta.doc_count {+ return None; // sparse / partial → scan (may still match arrays)+ }+ seg_matches = seg_matches.saturating_add(meta.doc_count);+ }+ return Some(seg_matches);+ }+// Only handle single Term queries for now; Bool goes through// the regular path until a Bool-specific shortcut lands.let (field, value) = match query {@@ -8868,6 +9251,86 @@ impl Index {}}+ /// Lazily-built, cached `_id → stored-position` index for a segment.+ ///+ /// Reuses the decompressed `StoredSlices` (offset index) and extracts each+ /// doc's `_id` from the leading bytes of its stored slice, so an `ids`+ /// query can resolve primary keys to positions instead of scanning the+ /// whole section. Built once per segment (segments are immutable) and+ /// evicted by id at the merge-completion site.+ ///+ /// Returns `None` when the slices can't be decoded OR when the map does+ /// not cover EVERY doc (a stored doc that carries no `_id` — the raw-source+ /// flush shape — can't be indexed here); the caller then falls back to the+ /// stored-doc scan, which has the identical `_id` resolution semantics, so+ /// no match is ever lost.+ fn id_pos_map_for(+ &self,+ seg_id: &str,+ expect_docs: u64,+ ) -> Option<Arc<std::collections::HashMap<String, u32>>> {+ if let Some(entry) = self.id_pos_cache.get(seg_id) {+ return Some(Arc::clone(entry.value()));+ }+ let slices = self.stored_slices_for(seg_id, expect_docs)?;+ let mut map: std::collections::HashMap<String, u32> =+ std::collections::HashMap::with_capacity(slices.offsets.len());+ for (pos, &(start, end)) in slices.offsets.iter().enumerate() {+ let slice = slices.bytes.get(start as usize..end as usize)?;+ let id = match extract_stored_id(slice) {+ Some(id) => id,+ None => {+ // Escape-bearing or unusual layout — fall back to a full+ // parse for just this doc to recover its `_id`.+ let mut buf = slice.to_vec();+ match simd_json::serde::from_slice::<Value>(&mut buf) {+ Ok(v) => match v.get("_id").and_then(Value::as_str) {+ Some(s) => s.to_string(),+ None => continue,+ },+ Err(_) => continue,+ }+ }+ };+ map.insert(id, pos as u32);+ }+ // Only cache + serve a COMPLETE map (every stored doc has an `_id`);+ // otherwise defer to the scan so a doc without a stored `_id` is not+ // silently dropped from `ids` results.+ if map.len() as u64 != expect_docs {+ return None;+ }+ let arc = Arc::new(map);+ self.id_pos_cache+ .insert(seg_id.to_string(), Arc::clone(&arc));+ Some(arc)+ }++ /// Position pre-filter for an `ids` query: resolve each requested id to its+ /// stored position via the cached `_id → position` index. Returns+ /// `Some(∅)` when none of the ids live in this segment (caller skips it),+ /// `Some(set)` with the resolved positions, or `None` when the segment has+ /// no complete id index (→ full scan, still correct).+ ///+ /// Callers gate this on `!deletes_present`: with no overwrites/tombstones+ /// each live id occupies exactly one segment position, so the resolved+ /// positions are the exact match set.+ fn build_ids_prefilter_cached(+ &self,+ seg_id: &str,+ expect_docs: u64,+ values: &[String],+ ) -> Option<Arc<HashSet<u32>>> {+ let map = self.id_pos_map_for(seg_id, expect_docs)?;+ let mut set: HashSet<u32> = HashSet::with_capacity(values.len());+ for id in values {+ if let Some(&pos) = map.get(id) {+ set.insert(pos);+ }+ }+ Some(Arc::new(set))+ }+/// Superset pre-filter for a pure-conjunction `bool` (`must` + `filter`/// only — no `should` / `must_not`).///@@ -15431,6 +15894,154 @@ struct SortCandidates {/// walk to `scan_stored_section_into`, minus every per-doc parse. Returns/// however many complete objects it found (caller compares against the/// segment doc count to reject malformed sections).+/// Extract the `_id` string value from a stored-doc slice+/// (`{"_id":"<value>",...}`) without a full JSON parse. Returns `None` when+/// the slice does not begin with an `_id` string key, or when the value+/// contains a JSON escape (`\`), in which case the caller falls back to a full+/// parse. This is the hot path for building the per-segment id→position map:+/// the common append-only corpus has escape-free ids, so it stays a cheap+/// prefix scan.+fn extract_stored_id(slice: &[u8]) -> Option<String> {+ let n = slice.len();+ let mut i = 0usize;+ // Leading whitespace + opening brace.+ while i < n && slice[i].is_ascii_whitespace() {+ i += 1;+ }+ if i >= n || slice[i] != b'{' {+ return None;+ }+ i += 1;+ while i < n && slice[i].is_ascii_whitespace() {+ i += 1;+ }+ // Expect the `_id` key verbatim as the first field.+ const KEY: &[u8] = b"\"_id\"";+ if i + KEY.len() > n || &slice[i..i + KEY.len()] != KEY {+ return None;+ }+ i += KEY.len();+ while i < n && slice[i].is_ascii_whitespace() {+ i += 1;+ }+ if i >= n || slice[i] != b':' {+ return None;+ }+ i += 1;+ while i < n && slice[i].is_ascii_whitespace() {+ i += 1;+ }+ if i >= n || slice[i] != b'"' {+ return None; // non-string _id (unexpected) → fall back+ }+ i += 1;+ let val_start = i;+ while i < n {+ match slice[i] {+ b'\\' => return None, // escape present → let the caller full-parse+ b'"' => {+ return std::str::from_utf8(&slice[val_start..i])+ .ok()+ .map(str::to_string)+ }+ _ => i += 1,+ }+ }+ None+}++/// Exact set of stored positions matching a `term`/`terms` value list in one+/// segment, resolved from the segment's doc-values columns. Keyword fields+/// enumerate positions carrying any of the terms' ordinals; numeric fields+/// union the degenerate `[v, v]` ranges. `Some(∅)` = no value present in this+/// segment; `None` = the field has no dv column or a value isn't numeric on a+/// numeric column (→ caller abandons the shortcut). Mirrors+/// `build_term_prefilter_cached` but operates on already-loaded columns.+fn seg_term_positions(+ cols: &std::collections::BTreeMap<String, xerj_storage::doc_values::Column>,+ field: &str,+ values: &[Value],+) -> Option<HashSet<u32>> {+ use xerj_storage::doc_values::Column;+ match cols.get(field)? {+ Column::Keyword(k) => {+ let mut ords: HashSet<u32> = HashSet::new();+ for v in values {+ let term = match v {+ Value::String(s) => s.clone(),+ other => other.to_string(),+ };+ if let Some(ord) = k.ord_for_term(&term) {+ ords.insert(ord);+ }+ }+ let mut set: HashSet<u32> = HashSet::new();+ if ords.is_empty() {+ return Some(set); // no listed value present in this segment+ }+ for (pos, o) in k.ords.iter().enumerate() {+ if ords.contains(o) && !k.null_bitmap.contains(pos as u32) {+ set.insert(pos as u32);+ }+ }+ Some(set)+ }+ Column::Numeric(n) => {+ let mut set: HashSet<u32> = HashSet::new();+ for v in values {+ let f = v.as_f64()?;+ set.extend(n.range_doc_ids(f, f, true, true));+ }+ Some(set)+ }+ }+}++/// Exact set of stored positions matching a numeric `range` in one segment.+/// `None` when the field has no numeric dv column or a bound is a+/// non-numeric, non-date string (→ caller abandons the shortcut).+fn seg_range_positions(+ cols: &std::collections::BTreeMap<String, xerj_storage::doc_values::Column>,+ field: &str,+ gte: Option<&Value>,+ gt: Option<&Value>,+ lte: Option<&Value>,+ lt: Option<&Value>,+) -> Option<HashSet<u32>> {+ use xerj_storage::doc_values::Column;+ let parse = |v: Option<&Value>| -> Option<Option<f64>> {+ match v {+ None => Some(None),+ Some(Value::Number(_)) => Some(v.and_then(|x| x.as_f64())),+ Some(Value::String(s)) => {+ if let Ok(f) = s.parse::<f64>() {+ return Some(Some(f));+ }+ crate::aggs::parse_date_ms(&Value::String(s.clone())).map(|ms| Some(ms as f64))+ }+ _ => None,+ }+ };+ let gte = parse(gte)?;+ let gt = parse(gt)?;+ let lte = parse(lte)?;+ let lt = parse(lt)?;+ let (lo, lo_incl) = match (gte, gt) {+ (Some(v), _) => (v, true),+ (None, Some(v)) => (v, false),+ (None, None) => (f64::NEG_INFINITY, true),+ };+ let (hi, hi_incl) = match (lte, lt) {+ (Some(v), _) => (v, true),+ (None, Some(v)) => (v, false),+ (None, None) => (f64::INFINITY, true),+ };+ let Column::Numeric(n) = cols.get(field)? else {+ return None;+ };+ Some(n.range_doc_ids(lo, hi, lo_incl, hi_incl).into_iter().collect())+}+fn brace_walk_offsets(bytes: &[u8]) -> Vec<(u32, u32)> {let n = bytes.len();let mut out: Vec<(u32, u32)> = Vec::new();@@ -16376,11 +16987,26 @@ fn collect_fts_query_fields(q: &FtsQuery, out: &mut Vec<String>) {out.push(p.field.clone());}}+ FtsQuery::PhrasePrefix(p) => {+ if !out.contains(&p.field) {+ out.push(p.field.clone());+ }+ }FtsQuery::Prefix(p) => {if !out.contains(&p.field) {out.push(p.field.clone());}}+ FtsQuery::Wildcard(w) => {+ if !out.contains(&w.field) {+ out.push(w.field.clone());+ }+ }+ FtsQuery::Fuzzy(f) => {+ if !out.contains(&f.field) {+ out.push(f.field.clone());+ }+ }FtsQuery::Bool(b) => {for sub in b.must@@ -16706,6 +17332,246 @@ fn query_node_to_fts(}Some(FtsQuery::Bool(Box::new(bool_q)))}+ QueryNode::MatchPhrase {+ field,+ query,+ slop,+ analyzer,+ boost,+ } => {+ // match_phrase on a KEYWORD field: the field is not tokenized, so+ // the query analyzes (keyword analyzer) to a single whole-value+ // token — i.e. exact whole-value equality, identical to `match` on+ // a keyword field (which projects to Term above and is a proven,+ // tested path). Route through the postings/term index instead of+ // the per-doc brute scan: `is_doc_scan_query` keeps MatchPhrase in+ // the doc-scan set, but returning `Some` here makes `needs_fts`+ // true so the FTS path runs FIRST and sets `fts_handled`, skipping+ // the O(N·field_len) stored scan that made keyword match_phrase+ // multi-second (5.6 s / 100k).+ let b = boost.unwrap_or(1.0);+ if exact_fields.contains(field.as_str()) {+ return Some(FtsQuery::Term(FtsTerm::boosted(+ field.as_str(),+ query.as_str(),+ b,+ )));+ }+ // TEXT field, slop 0, default (standard) analyzer: the FTS segment+ // stores term POSITIONS for analyzed text (store_positions=true), so+ // route to a positional phrase intersection bounded to candidate+ // docs (`FtsQuery::Phrase`) instead of the O(N·field_len) stored+ // scan. The query is analyzed with the SAME standard analyzer the+ // field was indexed with (tokenize + lowercase, no stemming), so the+ // phrase terms line up byte-for-byte with the indexed terms — and+ // lowercasing makes it case-insensitive exactly like ES's analyzed+ // phrase. slop>0 and non-standard analyzers keep the stored scan+ // (None): the sloppy/analyzer semantics stay on the proven path.+ if *slop == 0+ && text_fields.iter().any(|f| f == field)+ && matches!(analyzer.as_deref(), None | Some("standard"))+ {+ let registry = AnalyzerRegistry::default();+ let analyzer = registry.get_analyzer("standard")?;+ let tokens = analyzer.analyze(query);+ if tokens.is_empty() {+ // Empty analyzed phrase — fall back to the stored scan.+ return None;+ }+ if tokens.len() == 1 {+ return Some(FtsQuery::Term(FtsTerm::boosted(+ field.as_str(),+ &tokens[0].text,+ b,+ )));+ }+ return Some(FtsQuery::Phrase(xerj_fts::search::PhraseQuery {+ field: field.clone(),+ terms: tokens.iter().map(|t| t.text.clone()).collect(),+ slop: 0,+ boost: b,+ }));+ }+ None+ }+ QueryNode::MatchPhrasePrefix {+ field,+ query,+ max_expansions,+ } => {+ // match_phrase_prefix on a KEYWORD field: single whole-value token+ // whose last (only) term is a prefix → a prefix query over the+ // keyword value (ES default max_expansions 50). Same O(N)+ // brute-scan cliff as match_phrase (5.0 s / 100k) until routed+ // through the FST term dictionary.+ if exact_fields.contains(field.as_str()) {+ return Some(FtsQuery::Prefix(xerj_fts::search::PrefixQuery {+ field: field.clone(),+ prefix: query.clone(),+ boost: 1.0,+ max_expansions: *max_expansions as usize,+ constant_score: false,+ }));+ }+ // TEXT field: analyze the query with the standard analyzer (the+ // indexing analyzer) — the leading tokens form an ordered phrase and+ // the LAST token is a prefix expanded against the field's term+ // dictionary (bounded by `max_expansions`). Positional, bounded to+ // candidate docs, instead of the O(N) stored scan. The analyzer+ // lowercases every token, so the head phrase and the prefix are+ // case-insensitive exactly like ES (which analyzes the input).+ if text_fields.iter().any(|f| f == field) {+ let registry = AnalyzerRegistry::default();+ let analyzer = registry.get_analyzer("standard")?;+ let tokens = analyzer.analyze(query);+ if tokens.is_empty() {+ return None;+ }+ return Some(FtsQuery::PhrasePrefix(xerj_fts::search::PhrasePrefixQuery {+ field: field.clone(),+ terms: tokens.iter().map(|t| t.text.clone()).collect(),+ max_expansions: *max_expansions as usize,+ boost: 1.0,+ }));+ }+ None+ }+ QueryNode::Prefix { field, value, boost } => {+ // `prefix` on a KEYWORD field: whole-value, case-sensitive prefix+ // match over the keyword FST term dictionary — byte-identical to ES+ // `prefix` on a keyword field (default case-sensitive, matches the+ // whole indexed value). Mirrors the match_phrase_prefix keyword arm+ // above, routing through the postings/FST index instead of the O(N)+ // per-doc stored scan that made keyword `prefix` ~160 ms / 100k. If+ // the keyword sidecar is absent for a segment, `fts_handled` stays+ // false and the query falls back to the (correct) brute scan.+ //+ // Unlike match_phrase_prefix, an ES `prefix` query has NO+ // `max_expansions` cap — it matches EVERY term sharing the prefix —+ // so we expand without bound (`usize::MAX`) to keep `hits.total`+ // exact. TEXT fields keep the doc-scan (None): their prefix runs+ // against analyzed tokens, which the FST-whole-value route can't+ // reproduce.+ if exact_fields.contains(field.as_str()) {+ return Some(FtsQuery::Prefix(xerj_fts::search::PrefixQuery {+ field: field.clone(),+ prefix: value.clone(),+ boost: boost.unwrap_or(1.0),+ max_expansions: usize::MAX,+ constant_score: false,+ }));+ }+ // TEXT field: expand the prefix against the analyzed term dictionary+ // (each indexed term is a lowercased token). ES does NOT analyze+ // the prefix pattern — it is matched CASE-SENSITIVELY against the+ // already-lowercased terms, so an uppercase pattern matches nothing.+ // `expand_prefix` is a raw `starts_with` (no folding), reproducing+ // that exactly. No `max_expansions` cap (ES `prefix` matches every+ // term sharing the prefix) so `hits.total` stays exact. ES rewrites+ // `prefix` to a `constant_score` query, so every match scores `boost`+ // (`constant_score: true`).+ if text_fields.iter().any(|f| f == field) {+ return Some(FtsQuery::Prefix(xerj_fts::search::PrefixQuery {+ field: field.clone(),+ prefix: value.clone(),+ boost: boost.unwrap_or(1.0),+ max_expansions: usize::MAX,+ constant_score: true,+ }));+ }+ None+ }+ QueryNode::Wildcard { field, value, boost } => {+ // `wildcard` on a KEYWORD field: expand the keyword FST term+ // dictionary to every term matching the pattern (`*`=0+ chars,+ // `?`=1 char) and score each as a term. The searcher's expansion+ // predicate is byte-identical to `doc_matches_query`'s wildcard arm+ // (case-insensitive, whole-value OR sub-token), so the hit set is+ // exactly the doc-scan's — only sourced from the term dictionary+ // (≪ docs) instead of a per-doc O(N) scan (~150 ms/100k → ~1 ms).+ //+ // Case-insensitivity is REQUIRED, not a shortcut: XERJ's parser+ // drops `case_insensitive` and rewrites `term{case_insensitive:true}`+ // to a Wildcard, both relying on the matcher folding case — so a+ // case-sensitive FST route would break those (passing) paths.+ // TEXT fields keep the doc-scan (None): analyzed-token semantics.+ if exact_fields.contains(field.as_str()) {+ return Some(FtsQuery::Wildcard(xerj_fts::search::WildcardQuery {+ field: field.clone(),+ pattern: value.clone(),+ boost: boost.unwrap_or(1.0),+ case_insensitive: true,+ constant_score: false,+ }));+ }+ // TEXT field: expand the pattern against the analyzed term+ // dictionary CASE-SENSITIVELY. Indexed text terms are lowercased by+ // the standard analyzer; ES does not analyze a RAW `wildcard`+ // pattern, so it is matched literally against those terms (an+ // uppercase pattern matches nothing). `case_insensitive: false`+ // gives exactly that. (query_string lowercases its wildcard terms+ // at parse time, so `q=field:BA*` still matches — that lowering is+ // done in the parser, not here.) ES rewrites `wildcard` to a+ // `constant_score` query, so every match scores `boost`.+ if text_fields.iter().any(|f| f == field) {+ return Some(FtsQuery::Wildcard(xerj_fts::search::WildcardQuery {+ field: field.clone(),+ pattern: value.clone(),+ boost: boost.unwrap_or(1.0),+ case_insensitive: false,+ constant_score: true,+ }));+ }+ None+ }+ QueryNode::Fuzzy {+ field,+ value,+ fuzziness,+ } => {+ // `fuzzy` on a KEYWORD field: expand the keyword FST term dictionary+ // to every term within `max_edits` Damerau-Levenshtein distance and+ // score each as a term. `max_edits` is resolved HERE (AUTO depends+ // on the query term length) so the searcher stays type-agnostic.+ // The searcher's distance predicate is byte-identical to+ // `doc_matches_query`'s fuzzy arm (case-insensitive, transpositions+ // on, whole-value OR sub-token) — same hit set as the doc scan,+ // sourced from the term dictionary (~260 ms/100k → ~1 ms). TEXT+ // fields keep the doc-scan (None).+ if exact_fields.contains(field.as_str()) {+ let max_edits = match fuzziness {+ Fuzziness::Auto => auto_fuzziness(value),+ Fuzziness::Fixed(n) => *n as usize,+ };+ return Some(FtsQuery::Fuzzy(xerj_fts::search::FuzzyQuery {+ field: field.clone(),+ value: value.clone(),+ max_edits,+ boost: 1.0,+ case_insensitive: true,+ }));+ }+ // TEXT field: expand the term dictionary within `max_edits`+ // Damerau-Levenshtein distance of the RAW query value. ES does not+ // lowercase the fuzzy query term, and the indexed text terms are+ // lowercased — so distance is measured case-sensitively against the+ // lowercased terms (`case_insensitive: false`), matching ES (an+ // uppercase query term is `len` edits away and matches nothing).+ if text_fields.iter().any(|f| f == field) {+ let max_edits = match fuzziness {+ Fuzziness::Auto => auto_fuzziness(value),+ Fuzziness::Fixed(n) => *n as usize,+ };+ return Some(FtsQuery::Fuzzy(xerj_fts::search::FuzzyQuery {+ field: field.clone(),+ value: value.clone(),+ max_edits,+ boost: 1.0,+ case_insensitive: false,+ }));+ }+ None+ }_ => None,}}@@ -17370,6 +18236,154 @@ mod fts_projection_tests {}}+ /// match_phrase on a KEYWORD field projects to a single whole-value term+ /// (routed through the postings index instead of the O(N) brute scan that+ /// made keyword match_phrase multi-second). ES: match_phrase on keyword is+ /// exact whole-value equality, identical to `match` on keyword.+ #[test]+ fn match_phrase_keyword_projects_whole_value_term() {+ let q = QueryNode::MatchPhrase {+ field: "top_doc".into(),+ query: "runbook/oncall.md".into(),+ slop: 0,+ analyzer: None,+ boost: None,+ };+ let fq = query_node_to_fts(&q, &[], &kw(&["top_doc"])).expect("keyword phrase projects");+ match fq {+ FtsQuery::Term(t) => {+ assert_eq!(t.field, "top_doc");+ assert_eq!(t.term, "runbook/oncall.md", "whole value, not tokens");+ }+ other => panic!("expected single whole-value term, got {:?}", other),+ }+ }++ /// match_phrase on a TEXT field (slop 0, default analyzer) projects to a+ /// positional `FtsQuery::Phrase` over the STANDARD-analyzed query tokens —+ /// the segment stores term positions for analyzed text, so this routes+ /// through the bounded positional intersection instead of the O(N) stored+ /// scan.+ #[test]+ fn match_phrase_text_field_projects_positional_phrase() {+ let q = QueryNode::MatchPhrase {+ field: "body".into(),+ query: "Quick Brown Fox".into(),+ slop: 0,+ analyzer: None,+ boost: None,+ };+ let fq = query_node_to_fts(&q, &["body".to_string()], &kw(&[])).expect("text phrase projects");+ match fq {+ FtsQuery::Phrase(p) => {+ assert_eq!(p.field, "body");+ // standard analyzer lowercases + tokenizes on word boundaries.+ assert_eq!(p.terms, vec!["quick", "brown", "fox"]);+ assert_eq!(p.slop, 0);+ }+ other => panic!("expected positional phrase, got {:?}", other),+ }+ }++ /// match_phrase with slop > 0 on a TEXT field keeps the stored-doc scan+ /// (the proven sloppy-phrase semantics), so it must NOT project to FTS.+ #[test]+ fn match_phrase_text_slop_falls_back_to_scan() {+ let q = QueryNode::MatchPhrase {+ field: "body".into(),+ query: "quick fox".into(),+ slop: 2,+ analyzer: None,+ boost: None,+ };+ assert!(+ query_node_to_fts(&q, &["body".to_string()], &kw(&[])).is_none(),+ "slop>0 text phrase must fall back to the stored-doc scan"+ );+ }++ /// prefix / wildcard / fuzzy on a TEXT field expand against the analyzed+ /// term dictionary CASE-SENSITIVELY (indexed text terms are lowercased; ES+ /// does not analyze the pattern), and match_phrase_prefix routes to the+ /// positional phrase-prefix executor.+ #[test]+ fn text_multiterm_queries_project_case_sensitively() {+ let tf = ["body".to_string()];+ // prefix+ let q = QueryNode::Prefix {+ field: "body".into(),+ value: "run".into(),+ boost: None,+ };+ match query_node_to_fts(&q, &tf, &kw(&[])).expect("text prefix projects") {+ FtsQuery::Prefix(p) => {+ assert_eq!(p.prefix, "run", "pattern NOT lowercased/analyzed");+ assert_eq!(p.max_expansions, usize::MAX);+ }+ other => panic!("expected prefix, got {:?}", other),+ }+ // wildcard — case-sensitive (case_insensitive=false) for text+ let q = QueryNode::Wildcard {+ field: "body".into(),+ value: "run*".into(),+ boost: None,+ };+ match query_node_to_fts(&q, &tf, &kw(&[])).expect("text wildcard projects") {+ FtsQuery::Wildcard(w) => {+ assert_eq!(w.pattern, "run*");+ assert!(!w.case_insensitive, "text wildcard is case-sensitive");+ }+ other => panic!("expected wildcard, got {:?}", other),+ }+ // fuzzy — case-sensitive for text+ let q = QueryNode::Fuzzy {+ field: "body".into(),+ value: "runbok".into(),+ fuzziness: Fuzziness::Fixed(1),+ };+ match query_node_to_fts(&q, &tf, &kw(&[])).expect("text fuzzy projects") {+ FtsQuery::Fuzzy(f) => {+ assert_eq!(f.value, "runbok");+ assert_eq!(f.max_edits, 1);+ assert!(!f.case_insensitive, "text fuzzy is case-sensitive");+ }+ other => panic!("expected fuzzy, got {:?}", other),+ }+ // match_phrase_prefix — positional phrase-prefix over analyzed tokens+ let q = QueryNode::MatchPhrasePrefix {+ field: "body".into(),+ query: "status ok log".into(),+ max_expansions: 50,+ };+ match query_node_to_fts(&q, &tf, &kw(&[])).expect("text mpp projects") {+ FtsQuery::PhrasePrefix(p) => {+ assert_eq!(p.terms, vec!["status", "ok", "log"]);+ assert_eq!(p.max_expansions, 50);+ }+ other => panic!("expected phrase_prefix, got {:?}", other),+ }+ }++ /// match_phrase_prefix on a KEYWORD field projects to a prefix query over+ /// the whole value (FST term-dictionary route, not the O(N) brute scan).+ #[test]+ fn match_phrase_prefix_keyword_projects_prefix() {+ let q = QueryNode::MatchPhrasePrefix {+ field: "top_doc".into(),+ query: "runbook/on".into(),+ max_expansions: 50,+ };+ let fq = query_node_to_fts(&q, &[], &kw(&["top_doc"])).expect("keyword prefix projects");+ match fq {+ FtsQuery::Prefix(p) => {+ assert_eq!(p.field, "top_doc");+ assert_eq!(p.prefix, "runbook/on");+ assert_eq!(p.max_expansions, 50);+ }+ other => panic!("expected prefix query, got {:?}", other),+ }+ }+/// A Bool of keyword Match clauses (the parse-time lowering of/// `query_string: "model:X AND status:ok"`) projects each clause to a/// whole-value term inside an FTS bool.diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rsindex 234ab161a..740f5e5cf 100644--- a/engine/crates/xerj-fts/src/search.rs+++ b/engine/crates/xerj-fts/src/search.rs@@ -18,7 +18,7 @@ use crate::{analyzer::AnalyzerRegistry,bm25::{Bm25Scorer, QueryExplanation, ScoreBreakdown},index::FtsIndexReader,- postings::{DecodedPosting, PostingsReader},+ postings::PostingsReader,};use anyhow::Result;use rayon::prelude::*;@@ -62,6 +62,76 @@ impl Ord for ScoredHit {}}+// ── Bounded top-N collector ─────────────────────────────────────────────────++/// Bounded min-by-quality top-N collector.+///+/// Retains only the best `cap` hits seen so far while counting **every** hit+/// pushed (the exact match total). `push` is O(log cap); memory is O(cap)+/// regardless of how many matches the query produces — this is what turns the+/// size>0 scored FTS path from O(N log N) (build + full sort) into O(N log cap)+/// with O(cap) memory.+///+/// ## Ordering identity (why the output is byte-identical to `sort` + `truncate`)+///+/// `ScoredHit`'s `Ord` makes the BEST hit compare **`Less`** (higher score+/// first, doc_id ascending on ties). A [`BinaryHeap`](std::collections::BinaryHeap)+/// is a MAX-heap, so `peek()` returns the GREATEST element by `Ord` = the+/// **worst** retained hit. A new hit is admitted iff it is strictly better+/// (`hit < worst`). Because `doc_id` is unique, `Ord` is a total order with no+/// real ties, so the retained set is exactly the `cap` best hits, and+/// [`into_sorted_vec`](std::collections::BinaryHeap::into_sorted_vec) yields+/// them in ascending `Ord` order = best-first — identical to the legacy+/// `execute()` → `sort_unstable()` → `truncate(cap)`.+pub struct TopN {+ heap: std::collections::BinaryHeap<ScoredHit>,+ cap: usize,+ total: u64,+}++impl TopN {+ pub fn new(cap: usize) -> Self {+ Self {+ // Bound the pre-allocation: `cap` is a page limit (hundreds to a+ // few thousand), but guard against a pathological caller value.+ heap: std::collections::BinaryHeap::with_capacity(cap.min(4096)),+ cap,+ total: 0,+ }+ }++ /// Offer one hit: always counted toward `total`; retained only if it ranks+ /// among the best `cap` seen so far.+ #[inline]+ pub fn push(&mut self, hit: ScoredHit) {+ self.total += 1;+ if self.cap == 0 {+ return;+ }+ if self.heap.len() < self.cap {+ self.heap.push(hit);+ } else if let Some(mut worst) = self.heap.peek_mut() {+ // `worst` is the heap max = the worst retained hit. Replace it+ // only when the incoming hit is strictly better (`Ord::Less`).+ // Dropping the `PeekMut` sifts the new element back into place.+ if hit < *worst {+ *worst = hit;+ }+ }+ }++ /// Exact number of hits pushed so far (independent of `cap`).+ pub fn total(&self) -> u64 {+ self.total+ }++ /// Consume the collector: `(best-first sorted hits, exact total)`.+ pub fn finish(self) -> (Vec<ScoredHit>, u64) {+ let total = self.total;+ (self.heap.into_sorted_vec(), total)+ }+}+// ── Query types ───────────────────────────────────────────────────────────────/// A single field + term lookup.@@ -130,6 +200,11 @@ pub struct PrefixQuery {/// Maximum number of terms to expand (prevents explosion on short prefixes).#[serde(default = "default_max_expansions")]pub max_expansions: usize,+ /// When `true`, every matching doc scores a flat `boost` (ES rewrites+ /// `prefix` to a `constant_score` query). When `false` (default, keyword+ /// path), the per-expansion BM25 scores are summed.+ #[serde(default)]+ pub constant_score: bool,}fn default_max_expansions() -> usize {@@ -143,10 +218,114 @@ impl PrefixQuery {prefix: prefix.into(),boost: 1.0,max_expansions: 50,+ constant_score: false,}}}+/// A wildcard query — expands the field's FST term dictionary to every term+/// matching `pattern` (`*` = zero-or-more chars, `?` = exactly one), then+/// scores each as a term. Matching is **case-insensitive** and applied to the+/// whole indexed term AND its non-alphanumeric-split sub-tokens, byte-identical+/// to the engine's `doc_matches_query` wildcard predicate — so routing a+/// keyword-field wildcard through the FST returns exactly the same hit set as+/// the per-doc stored scan, only far faster (term dictionary ≪ documents).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WildcardQuery {+ pub field: String,+ pub pattern: String,+ #[serde(default = "default_boost")]+ pub boost: f32,+ /// When `true` (the default, used for keyword fields) the pattern and each+ /// indexed term are case-folded before matching, and the whole term OR any+ /// non-alphanumeric sub-token may match — byte-identical to the engine's+ /// stored-scan wildcard predicate. When `false` (analyzed **text** fields)+ /// the raw pattern is matched CASE-SENSITIVELY against the whole indexed+ /// term. ES indexes text terms lowercased but does NOT analyze the wildcard+ /// pattern, so an uppercase pattern matches nothing — exactly what+ /// case-sensitive matching against the already-lowercased term dictionary+ /// reproduces.+ #[serde(default = "default_case_insensitive")]+ pub case_insensitive: bool,+ /// When `true`, every matching doc scores a flat `boost` (ES rewrites+ /// `wildcard` to a `constant_score` query). When `false` (default, keyword+ /// path), the per-matching-term BM25 scores are summed.+ #[serde(default)]+ pub constant_score: bool,+}++fn default_case_insensitive() -> bool {+ true+}++impl WildcardQuery {+ pub fn new(field: impl Into<String>, pattern: impl Into<String>) -> Self {+ Self {+ field: field.into(),+ pattern: pattern.into(),+ boost: 1.0,+ case_insensitive: true,+ constant_score: false,+ }+ }+}++/// A fuzzy query — expands the field's FST term dictionary to every term within+/// `max_edits` Damerau-Levenshtein distance of `value`, then scores each as a+/// term. Distance is computed **case-insensitively** over the whole indexed+/// term AND its sub-tokens, byte-identical to the engine's `doc_matches_query`+/// fuzzy predicate. `max_edits` is precomputed by the caller from the ES+/// `fuzziness` (AUTO resolves off the query term length), so the searcher needs+/// no `Fuzziness` type.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FuzzyQuery {+ pub field: String,+ pub value: String,+ pub max_edits: usize,+ #[serde(default = "default_boost")]+ pub boost: f32,+ /// See [`WildcardQuery::case_insensitive`]. `true` (default) folds both+ /// sides and also compares sub-tokens (keyword fields). `false` compares+ /// the raw query value against the whole indexed term case-sensitively —+ /// ES fuzzy on a **text** field measures edit distance against the+ /// lowercased term dictionary without lowercasing the query term.+ #[serde(default = "default_case_insensitive")]+ pub case_insensitive: bool,+}++impl FuzzyQuery {+ pub fn new(field: impl Into<String>, value: impl Into<String>, max_edits: usize) -> Self {+ Self {+ field: field.into(),+ value: value.into(),+ max_edits,+ boost: 1.0,+ case_insensitive: true,+ }+ }+}++/// A phrase-prefix query — mirrors Elasticsearch's `match_phrase_prefix`.+///+/// The leading `terms[..n-1]` must appear as an ordered adjacent phrase; the+/// LAST element is treated as a **prefix** that expands against the field's+/// analyzed term dictionary (bounded by `max_expansions`, in FST/lexicographic+/// order — the same order ES takes its first `max_expansions` terms). A doc+/// matches when the head phrase is immediately followed by any expansion term.+/// `terms` are already analyzed by the caller (standard analyzer → lowercased),+/// so the prefix expansion is a plain case-sensitive `starts_with` against the+/// (lowercased) term dictionary — byte-identical to ES, whose analyzer+/// lowercases the query but does not re-case the indexed terms.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PhrasePrefixQuery {+ pub field: String,+ pub terms: Vec<String>,+ #[serde(default = "default_max_expansions")]+ pub max_expansions: usize,+ #[serde(default = "default_boost")]+ pub boost: f32,+}+/// Boolean combinator query — mirrors Elasticsearch's `bool` query.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct BoolQuery {@@ -225,7 +404,10 @@ impl DisMaxQuery {pub enum Query {Term(TermQuery),Phrase(PhraseQuery),+ PhrasePrefix(PhrasePrefixQuery),Prefix(PrefixQuery),+ Wildcard(WildcardQuery),+ Fuzzy(FuzzyQuery),Bool(Box<BoolQuery>),DisMax(Box<DisMaxQuery>),MatchAll,@@ -248,17 +430,63 @@ impl FtsSearcher {/// Execute a query and return up to `limit` scored hits, sorted by descending score.pub fn search(&self, query: &Query, limit: usize, explain: bool) -> Result<Vec<ScoredHit>> {- let mut hits = self.execute(query, explain)?;- hits.sort_unstable();- hits.truncate(limit);- Ok(hits)+ Ok(self.search_bounded(query, limit, explain)?.0)+ }++ /// Execute a query returning `(top-`cap` hits best-first, EXACT match total)`.+ ///+ /// The `total` is the full segment match count regardless of `cap`, so the+ /// caller's `hits.total` stays exact even when only the best `cap` sources+ /// are materialised.+ ///+ /// - `cap == usize::MAX` keeps the **legacy** full-set path (`execute()` ++ /// `sort_unstable()`). Callers that need the complete match set — an+ /// active field sort (which narrows *all* matching doc_ids to sort+ /// candidates), delete/dup-aware materialisation, or a count that must+ /// not be page-capped — pass this and get behaviour byte-identical to the+ /// historical `search(usize::MAX)`.+ /// - Any smaller `cap` streams into a bounded [`TopN`]: O(N log cap) work,+ /// O(cap) memory, no O(N log N) sort. Leaf `Term` queries stream each+ /// scored posting straight into the heap (no intermediate `Vec`); the+ /// compound arms (`Bool`/`DisMax`/`Prefix`/`Phrase`) build their+ /// de-duplicated hit set once via `execute()` and drain it — still+ /// O(matches) but with the sort removed.+ pub fn search_bounded(+ &self,+ query: &Query,+ cap: usize,+ explain: bool,+ ) -> Result<(Vec<ScoredHit>, u64)> {+ if cap == usize::MAX {+ let mut hits = self.execute(query, explain)?;+ let total = hits.len() as u64;+ hits.sort_unstable();+ return Ok((hits, total));+ }++ let mut top = TopN::new(cap);+ match query {+ // Streaming leaf: push each scored posting directly into the heap.+ Query::Term(tq) => self.collect_term(tq, explain, &mut top)?,+ // Compound / positional arms: reuse the exact hit-set builder, then+ // drain into the bounded heap (the sort is what we shed here).+ _ => {+ for hit in self.execute(query, explain)? {+ top.push(hit);+ }+ }+ }+ Ok(top.finish())}fn execute(&self, query: &Query, explain: bool) -> Result<Vec<ScoredHit>> {match query {Query::Term(tq) => self.execute_term(tq, explain),Query::Phrase(pq) => self.execute_phrase(pq, explain),+ Query::PhrasePrefix(pq) => self.execute_phrase_prefix(pq, explain),Query::Prefix(pq) => self.execute_prefix(pq, explain),+ Query::Wildcard(wq) => self.execute_wildcard(wq, explain),+ Query::Fuzzy(fq) => self.execute_fuzzy(fq, explain),Query::Bool(bq) => self.execute_bool(bq, explain),Query::DisMax(dq) => self.execute_dis_max(dq, explain),Query::MatchAll => self.execute_match_all(),@@ -268,21 +496,42 @@ impl FtsSearcher {// ── Term query ────────────────────────────────────────────────────────────fn execute_term(&self, tq: &TermQuery, explain: bool) -> Result<Vec<ScoredHit>> {+ let mut hits = Vec::new();+ self.scan_term(tq, explain, |h| hits.push(h))?;+ Ok(hits)+ }++ /// Streaming variant of [`Self::execute_term`] for the bounded search path:+ /// each scored posting is offered straight to the `TopN` heap, so a keyword+ /// term matching tens of thousands of docs never materialises the full hit+ /// `Vec` for a size:10 request.+ fn collect_term(&self, tq: &TermQuery, explain: bool, top: &mut TopN) -> Result<()> {+ self.scan_term(tq, explain, |h| top.push(h))+ }++ /// Shared scoring scan used by both [`Self::execute_term`] (Vec) and+ /// [`Self::collect_term`] (bounded heap). Emits one `ScoredHit` per+ /// matching posting in ascending doc_id order.+ fn scan_term<F: FnMut(ScoredHit)>(+ &self,+ tq: &TermQuery,+ explain: bool,+ mut emit: F,+ ) -> Result<()> {let tp = match self.reader.lookup_term(&tq.field, &tq.term) {Some(tp) => tp,- None => return Ok(Vec::new()),+ None => return Ok(()),};let scorer = self.make_scorer(&tq.field);let post_data = match self.reader.postings_data(&tq.field, &tp) {Some(d) => d,- None => return Ok(Vec::new()),+ None => return Ok(()),};let has_positions = self.reader.field_has_positions(&tq.field);let mut reader =PostingsReader::new_with_positions(post_data, tp.doc_frequency, has_positions);- let mut hits = Vec::with_capacity(tp.doc_frequency as usize);while let Some(posting) = reader.next() {let doc_len = self@@ -306,14 +555,14 @@ impl FtsSearcher {(s, None)};- hits.push(ScoredHit {+ emit(ScoredHit {doc_id: posting.doc_id,score,explanation,});}- Ok(hits)+ Ok(())}// ── Phrase query ──────────────────────────────────────────────────────────@@ -330,8 +579,20 @@ impl FtsSearcher {);}- // Load postings for every term- let mut term_postings_list: Vec<(Vec<DecodedPosting>, u32)> = Vec::new();+ // Phrase matching needs positions. A docs-only field (keyword,+ // numeric, ip) can never satisfy a multi-term phrase.+ if !self.reader.field_has_positions(&pq.field) {+ return Ok(Vec::new());+ }++ // Load postings for every term into a per-term+ // `doc_id → (term_freq, positions)` map. This is O(Σ df) once and+ // turns the per-anchor-doc term lookup into O(1) — the previous+ // implementation `.find()`-scanned each other term's FULL posting list+ // for every anchor doc (O(anchor_df × other_df), quadratic on common+ // terms like a non-stop-worded "the").+ let mut term_maps: Vec<(std::collections::HashMap<u32, (u32, Vec<u32>)>, u32)> =+ Vec::with_capacity(pq.terms.len());for term in &pq.terms {let tp = match self.reader.lookup_term(&pq.field, term) {Some(tp) => tp,@@ -341,78 +602,49 @@ impl FtsSearcher {Some(d) => d,None => return Ok(Vec::new()),};- // Phrase query on a docs-only field can never match (no- // positions stored) — bail out early.- let has_positions = self.reader.field_has_positions(&pq.field);- if !has_positions {- return Ok(Vec::new());- }let mut reader =- PostingsReader::new_with_positions(post_data, tp.doc_frequency, has_positions);- let mut postings: Vec<DecodedPosting> = Vec::new();+ PostingsReader::new_with_positions(post_data, tp.doc_frequency, true);+ let mut map: std::collections::HashMap<u32, (u32, Vec<u32>)> =+ std::collections::HashMap::with_capacity(tp.doc_frequency as usize);while let Some(p) = reader.next() {- postings.push(p);+ map.insert(p.doc_id, (p.term_freq, p.positions));}- term_postings_list.push((postings, tp.doc_frequency));+ term_maps.push((map, tp.doc_frequency));}- // Intersect: start from the rarest term (smallest doc_freq)- let min_idx = term_postings_list+ // Anchor on the rarest term (smallest doc_freq) so the outer loop is+ // as short as possible; every candidate doc must contain it.+ let min_idx = term_maps.iter().enumerate().min_by_key(|(_, (_, df))| *df).map(|(i, _)| i).unwrap_or(0);- // Build doc_id sets from all other terms- let anchor_postings = &term_postings_list[min_idx].0;let scorer = self.make_scorer(&pq.field);let mut hits = Vec::new();- // For each doc in the anchor set, verify phrase constraint across all terms- 'doc: for anchor in anchor_postings {- let doc_id = anchor.doc_id;-- // Collect per-term position lists for this doc- let mut all_positions: Vec<Vec<u32>> = Vec::with_capacity(pq.terms.len());- for (term_idx, (postings, _)) in term_postings_list.iter().enumerate() {- if let Some(p) = postings.iter().find(|p| p.doc_id == doc_id) {- // Adjust positions for phrase offset- let offset = if term_idx > min_idx {- (term_idx - min_idx) as u32- } else {- 0 // will adjust relative to anchor below- };- let adjusted: Vec<u32> = p- .positions- .iter()- .filter_map(|&pos| pos.checked_sub(offset))- .collect();- all_positions.push(adjusted);- } else {- continue 'doc; // term not in this doc+ 'doc: for (&doc_id, _) in &term_maps[min_idx].0 {+ // Gather each term's positions for this doc, in TERM ORDER (raw —+ // no offset games; the matcher below handles adjacency + slop).+ let mut all_positions: Vec<&Vec<u32>> = Vec::with_capacity(pq.terms.len());+ for (map, _) in &term_maps {+ match map.get(&doc_id) {+ Some((_, positions)) => all_positions.push(positions),+ None => continue 'doc, // term absent from this doc}}- // Check if any start position creates a valid phrase (with slop)- if !phrase_matches(&all_positions, pq.slop) {+ if !phrase_positions_match(&all_positions, pq.slop) {continue;}let doc_len = self.reader.field_length(&pq.field, doc_id).unwrap_or(1) as u32;- // Score as sum of per-term BM25let mut total_score = 0.0f32;let mut breakdowns = Vec::new();-for (term_idx, term) in pq.terms.iter().enumerate() {- let (_, df) = &term_postings_list[term_idx];- let tf = term_postings_list[term_idx]- .0- .iter()- .find(|p| p.doc_id == doc_id)- .map(|p| p.term_freq)- .unwrap_or(1);-+ let (map, df) = &term_maps[term_idx];+ let tf = map.get(&doc_id).map(|(f, _)| *f).unwrap_or(1);if explain {let bd = scorer.score_term_explain(term, *df as u64, tf, doc_len);total_score += bd.score;@@ -423,38 +655,232 @@ impl FtsSearcher {}total_score *= pq.boost;- let explanation = if explain {- Some(QueryExplanation::new(breakdowns))- } else {- None- };-hits.push(ScoredHit {doc_id,score: total_score,- explanation,+ explanation: if explain {+ Some(QueryExplanation::new(breakdowns))+ } else {+ None+ },});}Ok(hits)}+ // ── Phrase-prefix query ─────────────────────────────────────────────────────++ /// ES `match_phrase_prefix`: the head `terms[..n-1]` form an ordered phrase+ /// and the last term is a prefix expanded against the analyzed term+ /// dictionary. A doc matches when any expansion term immediately follows a+ /// head-phrase occurrence. Implemented as a union of concrete phrase+ /// queries (one per expansion) — bounded by `max_expansions`, which caps the+ /// number of prefix terms exactly as ES does.+ fn execute_phrase_prefix(+ &self,+ ppq: &PhrasePrefixQuery,+ explain: bool,+ ) -> Result<Vec<ScoredHit>> {+ if ppq.terms.is_empty() {+ return Ok(Vec::new());+ }+ let last = ppq.terms.last().expect("non-empty");+ // Expand the trailing prefix against the field's term dictionary in FST+ // (lexicographic) order — matches ES's first-`max_expansions` selection.+ let expansions = self.expand_prefix(&ppq.field, last, ppq.max_expansions);+ if expansions.is_empty() {+ return Ok(Vec::new());+ }++ // Single-token phrase_prefix == prefix query (scored, not constant —+ // ES match_phrase_prefix is a real scoring query).+ if ppq.terms.len() == 1 {+ return self.score_expanded_terms(&ppq.field, &expansions, ppq.boost, explain, false);+ }++ let head = &ppq.terms[..ppq.terms.len() - 1];+ // Per-doc best score across expansions (ES takes the max-scoring+ // expansion for a doc; the exact hit SET — what `hits.total` counts — is+ // the union, which the accumulator captures).+ let mut score_map: std::collections::HashMap<u32, (f32, Option<QueryExplanation>)> =+ std::collections::HashMap::new();+ for exp in &expansions {+ let mut terms: Vec<String> = head.to_vec();+ terms.push(exp.clone());+ let pq = PhraseQuery {+ field: ppq.field.clone(),+ terms,+ slop: 0,+ boost: ppq.boost,+ };+ for hit in self.execute_phrase(&pq, explain)? {+ let entry = score_map+ .entry(hit.doc_id)+ .or_insert((f32::NEG_INFINITY, None));+ if hit.score > entry.0 {+ entry.0 = hit.score;+ entry.1 = hit.explanation;+ }+ }+ }+ Ok(score_map+ .into_iter()+ .map(|(doc_id, (score, explanation))| ScoredHit {+ doc_id,+ score,+ explanation,+ })+ .collect())+ }+// ── Prefix query ──────────────────────────────────────────────────────────fn execute_prefix(&self, pq: &PrefixQuery, explain: bool) -> Result<Vec<ScoredHit>> {// Expand prefix to term list using FST range scanlet expanded_terms = self.expand_prefix(&pq.field, &pq.prefix, pq.max_expansions);+ self.score_expanded_terms(+ &pq.field,+ &expanded_terms,+ pq.boost,+ explain,+ pq.constant_score,+ )+ }- if expanded_terms.is_empty() {- return Ok(Vec::new());+ fn expand_prefix(&self, field: &str, prefix: &str, max: usize) -> Vec<String> {+ // Use the reader's all_terms which does an FST stream scan+ let all_terms = self.reader.all_terms(field);+ all_terms+ .into_iter()+ .filter(|t| t.starts_with(prefix))+ .take(max)+ .collect()+ }++ // ── Wildcard query ──────────────────────────────────────────────────────────++ fn execute_wildcard(&self, wq: &WildcardQuery, explain: bool) -> Result<Vec<ScoredHit>> {+ let terms = self.expand_wildcard(&wq.field, &wq.pattern, wq.case_insensitive);+ self.score_expanded_terms(&wq.field, &terms, wq.boost, explain, wq.constant_score)+ }++ /// Enumerate the field's FST term dictionary and keep every term matching+ /// the wildcard pattern.+ ///+ /// - `case_insensitive` (keyword fields): fold both sides and match the+ /// whole term OR any non-alphanumeric-split sub-token — identical to the+ /// engine's doc-scan wildcard predicate.+ /// - case-**sensitive** (analyzed text fields): match the RAW pattern+ /// against the whole indexed term. Text terms are already lowercased by+ /// the standard analyzer and ES does not lowercase the pattern, so an+ /// uppercase pattern correctly matches nothing.+ fn expand_wildcard(&self, field: &str, pattern: &str, case_insensitive: bool) -> Vec<String> {+ if case_insensitive {+ let pat_lc = pattern.to_lowercase();+ self.reader+ .all_terms(field)+ .into_iter()+ .filter(|t| term_matches_wildcard(t, &pat_lc))+ .collect()+ } else {+ self.reader+ .all_terms(field)+ .into_iter()+ .filter(|t| wildcard_match(t, pattern))+ .collect()+ }+ }++ // ── Fuzzy query ─────────────────────────────────────────────────────────────++ fn execute_fuzzy(&self, fq: &FuzzyQuery, explain: bool) -> Result<Vec<ScoredHit>> {+ let terms = self.expand_fuzzy(&fq.field, &fq.value, fq.max_edits, fq.case_insensitive);+ // Fuzzy keeps per-term scoring (ES rewrites fuzzy to a blended-frequency+ // scoring query, NOT constant_score).+ self.score_expanded_terms(&fq.field, &terms, fq.boost, explain, false)+ }++ /// Enumerate the field's FST term dictionary and keep every term within+ /// `max_edits` Damerau-Levenshtein distance of `value`.+ ///+ /// - `case_insensitive` (keyword fields): fold both sides and also compare+ /// sub-tokens — identical to the engine's doc-scan fuzzy predicate.+ /// - case-**sensitive** (analyzed text fields): measure distance from the+ /// RAW query value to the whole indexed (lowercased) term, matching ES,+ /// which does not lowercase the fuzzy query term.+ fn expand_fuzzy(+ &self,+ field: &str,+ value: &str,+ max_edits: usize,+ case_insensitive: bool,+ ) -> Vec<String> {+ if case_insensitive {+ let q_lower = value.to_lowercase();+ self.reader+ .all_terms(field)+ .into_iter()+ .filter(|t| term_matches_fuzzy(t, &q_lower, max_edits))+ .collect()+ } else {+ self.reader+ .all_terms(field)+ .into_iter()+ .filter(|t| levenshtein_distance(t, value) <= max_edits)+ .collect()}+ }- // Run a term query for each expansion and merge scores+ /// Run one term query per expanded term and merge their per-doc scores — the+ /// shared scoring core behind prefix/wildcard/fuzzy multi-term expansion.+ /// (A doc's score is the sum of its matching-term BM25 scores; among+ /// constant-ish keyword matches this is effectively a flat score.)+ fn score_expanded_terms(+ &self,+ field: &str,+ terms: &[String],+ boost: f32,+ explain: bool,+ constant_score: bool,+ ) -> Result<Vec<ScoredHit>> {+ if terms.is_empty() {+ return Ok(Vec::new());+ }+ // Constant-score (ES prefix/wildcard rewrite): every doc that matches+ // ANY expansion term scores a flat `boost`, so we only need the matching+ // doc-id set. Deduplicate across expansions and emit `boost` once.+ if constant_score {+ let mut docs: std::collections::HashSet<u32> = std::collections::HashSet::new();+ for term in terms {+ let tp = match self.reader.lookup_term(field, term) {+ Some(tp) => tp,+ None => continue,+ };+ let post_data = match self.reader.postings_data(field, &tp) {+ Some(d) => d,+ None => continue,+ };+ let has_positions = self.reader.field_has_positions(field);+ let mut reader =+ PostingsReader::new_with_positions(post_data, tp.doc_frequency, has_positions);+ while let Some(p) = reader.next() {+ docs.insert(p.doc_id);+ }+ }+ return Ok(docs+ .into_iter()+ .map(|doc_id| ScoredHit {+ doc_id,+ score: boost,+ explanation: None,+ })+ .collect());+ }let mut score_map: std::collections::HashMap<u32, (f32, Option<QueryExplanation>)> =std::collections::HashMap::new();-- for term in &expanded_terms {- let tq = TermQuery::boosted(&pq.field, term, pq.boost);+ for term in terms {+ let tq = TermQuery::boosted(field, term, boost);let term_hits = self.execute_term(&tq, explain)?;for hit in term_hits {let entry = score_map.entry(hit.doc_id).or_insert((0.0, None));@@ -471,7 +897,6 @@ impl FtsSearcher {}}}-Ok(score_map.into_iter().map(|(doc_id, (score, explanation))| ScoredHit {@@ -482,16 +907,6 @@ impl FtsSearcher {.collect())}- fn expand_prefix(&self, field: &str, prefix: &str, max: usize) -> Vec<String> {- // Use the reader's all_terms which does an FST stream scan- let all_terms = self.reader.all_terms(field);- all_terms- .into_iter()- .filter(|t| t.starts_with(prefix))- .take(max)- .collect()- }-// ── Bool query ────────────────────────────────────────────────────────────fn execute_bool(&self, bq: &BoolQuery, explain: bool) -> Result<Vec<ScoredHit>> {@@ -643,6 +1058,106 @@ impl FtsSearcher {}}+// ── Wildcard / fuzzy term-matching predicates ─────────────────────────────────+//+// These reproduce, byte-for-byte, the wildcard/fuzzy predicates the engine's+// `doc_matches_query` applies per stored document, so expanding a keyword+// field's FST term dictionary through them yields exactly the same hit set as+// the per-doc stored scan — just far cheaper (terms ≪ documents). Keep them in+// lock-step with `xerj-engine/src/index.rs::{wildcard_match, levenshtein_distance}`.++/// `true` if `term` (case-folded) matches the already-lowercased `pat_lc`,+/// either as the whole value or as any non-alphanumeric-split sub-token.+fn term_matches_wildcard(term: &str, pat_lc: &str) -> bool {+ let lc = term.to_lowercase();+ if wildcard_match(&lc, pat_lc) {+ return true;+ }+ lc.split(|c: char| !c.is_alphanumeric())+ .any(|tok| !tok.is_empty() && wildcard_match(tok, pat_lc))+}++/// `true` if `term` (case-folded) is within `max_edits` Damerau-Levenshtein+/// distance of the already-lowercased `q_lower`, as the whole value or any+/// sub-token.+fn term_matches_fuzzy(term: &str, q_lower: &str, max_edits: usize) -> bool {+ let s_lower = term.to_lowercase();+ if levenshtein_distance(&s_lower, q_lower) <= max_edits {+ return true;+ }+ s_lower+ .split(|c: char| !c.is_alphanumeric())+ .filter(|t| !t.is_empty())+ .any(|tok| levenshtein_distance(tok, q_lower) <= max_edits)+}++/// Glob match: `*` = zero-or-more chars, `?` = exactly one. No case folding —+/// callers fold both sides first. Verbatim copy of the engine's helper.+fn wildcard_match(text: &str, pattern: &str) -> bool {+ let text: Vec<char> = text.chars().collect();+ let pattern: Vec<char> = pattern.chars().collect();+ wildcard_match_inner(&text, &pattern)+}++fn wildcard_match_inner(text: &[char], pattern: &[char]) -> bool {+ match (text, pattern) {+ (_, []) => text.is_empty(),+ (_, ['*', rest @ ..]) => {+ wildcard_match_inner(text, rest)+ || (!text.is_empty() && wildcard_match_inner(&text[1..], pattern))+ }+ ([], _) => false,+ ([tc, trest @ ..], [pc, prest @ ..]) => {+ (*pc == '?' || tc == pc) && wildcard_match_inner(trest, prest)+ }+ }+}++/// Damerau-Levenshtein edit distance (adjacent transposition = 1 edit), matching+/// ES `fuzzy_transpositions: true`. Verbatim copy of the engine's helper.+fn levenshtein_distance(a: &str, b: &str) -> usize {+ let a_chars: Vec<char> = a.chars().collect();+ let b_chars: Vec<char> = b.chars().collect();+ let m = a_chars.len();+ let n = b_chars.len();+ if m == 0 {+ return n;+ }+ if n == 0 {+ return m;+ }+ let mut dp = vec![vec![0usize; n + 1]; m + 1];+ #[allow(clippy::needless_range_loop)]+ for i in 0..=m {+ dp[i][0] = i;+ }+ #[allow(clippy::needless_range_loop)]+ for j in 0..=n {+ dp[0][j] = j;+ }+ for i in 1..=m {+ for j in 1..=n {+ let cost = if a_chars[i - 1] == b_chars[j - 1] {+ 0+ } else {+ 1+ };+ let mut best = (dp[i - 1][j] + 1)+ .min(dp[i][j - 1] + 1)+ .min(dp[i - 1][j - 1] + cost);+ if i >= 2+ && j >= 2+ && a_chars[i - 1] == b_chars[j - 2]+ && a_chars[i - 2] == b_chars[j - 1]+ {+ best = best.min(dp[i - 2][j - 2] + 1);+ }+ dp[i][j] = best;+ }+ }+ dp[m][n]+}+// ── Multi-segment parallel search ─────────────────────────────────────────────/// Search across multiple segment searchers in parallel via rayon.@@ -671,37 +1186,65 @@ pub fn search_segments(// ── Phrase matching helper ────────────────────────────────────────────────────-/// Returns `true` if the per-term adjusted position lists contain a common-/// position (meaning a phrase start where all terms follow in order within `slop`).-fn phrase_matches(all_positions: &[Vec<u32>], slop: u32) -> bool {- if all_positions.is_empty() {+/// Returns `true` if the per-term **raw** position lists (in TERM ORDER)+/// contain an in-order occurrence of the phrase within `slop`.+///+/// `all_positions[i]` is the ascending list of positions at which the i-th+/// phrase term occurs in one document.+///+/// - `slop == 0`: exact adjacency. There must be a start `p` such that term i+/// occupies exactly `p + i` for every i (start-position intersection).+/// - `slop > 0`: greedy in-order walk — each next term is matched at the+/// earliest position `> ` the previous match, and the summed gaps between+/// adjacent matched terms must not exceed `slop` (the semantics the engine's+/// stored-scan `MatchPhrase` uses).+fn phrase_positions_match(all_positions: &[&Vec<u32>], slop: u32) -> bool {+ if all_positions.iter().any(|p| p.is_empty()) {return false;}if all_positions.len() == 1 {- return !all_positions[0].is_empty();+ return true;+ }++ if slop == 0 {+ // Exact phrase: term i must sit at start + i. Probe each candidate+ // start from the first term; membership via binary search (positions+ // are ascending).+ 'start: for &start in all_positions[0] {+ for (i, positions) in all_positions.iter().enumerate().skip(1) {+ let want = match start.checked_add(i as u32) {+ Some(w) => w,+ None => continue 'start,+ };+ if positions.binary_search(&want).is_err() {+ continue 'start;+ }+ }+ return true;+ }+ return false;}- // For each start position of the first term, check if subsequent terms- // have a matching position within slop.- 'outer: for &start_pos in &all_positions[0] {+ // Sloppy phrase: greedy earliest-match walk, accumulating the gaps.+ 'outer: for &start_pos in all_positions[0] {let mut current_pos = start_pos;+ let mut total_gaps: u32 = 0;for positions in &all_positions[1..] {- // Find the first position in `positions` that is within [current_pos, current_pos + slop + 1]- let found = positions- .iter()- .any(|&p| p >= current_pos && p <= current_pos + slop + 1);- if !found {- continue 'outer;- }- // Advance current_pos to the matched position- if let Some(&next_pos) = positions- .iter()- .find(|&&p| p >= current_pos && p <= current_pos + slop + 1)- {- current_pos = next_pos;+ // Earliest position strictly after the previous matched term.+ match positions.iter().copied().find(|&p| p > current_pos) {+ Some(next_pos) => {+ total_gaps += next_pos - current_pos - 1;+ if total_gaps > slop {+ continue 'outer;+ }+ current_pos = next_pos;+ }+ None => continue 'outer,}}- return true;+ if total_gaps <= slop {+ return true;+ }}false@@ -1069,6 +1612,92 @@ mod tests {assert!(doc_ids.contains(&0) || doc_ids.contains(&1));}+ /// Regression: the phrase intersection must be correct when the rarest+ /// (anchor) term is NOT the first phrase term. Doc 0 has+ /// "the quick brown fox …"; "quick"/"brown" are rarer than "the", so the+ /// anchor is a non-first term — the old offset-adjust logic mishandled this.+ #[test]+ fn phrase_query_correct_when_anchor_not_first() {+ let dir = TempDir::new().unwrap();+ let searcher = setup_searcher(dir.path());++ // "the quick" — "the" is the common (first) term, "quick" rarer.+ let hits = searcher+ .search(+ &Query::Phrase(PhraseQuery::new(+ "body",+ vec!["the".to_owned(), "quick".to_owned()],+ )),+ 10,+ false,+ )+ .unwrap();+ let ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();+ assert!(ids.contains(&0), "doc0 has 'the quick'");+ assert!(!ids.contains(&2), "doc2 has 'the lazy', not 'the quick'");++ // A NON-adjacent pair with a gap must NOT match at slop 0:+ // doc0 = "the quick brown fox jumps over the lazy dog" — "quick dog"+ // are not adjacent.+ let hits = searcher+ .search(+ &Query::Phrase(PhraseQuery::new(+ "body",+ vec!["quick".to_owned(), "dog".to_owned()],+ )),+ 10,+ false,+ )+ .unwrap();+ assert!(+ hits.iter().all(|h| h.doc_id != 0),+ "'quick dog' is not an adjacent phrase in doc0"+ );+ }++ /// Case-sensitive wildcard/fuzzy (text-field path): the whitespace analyzer+ /// preserves case, so an indexed term "Rust" is matched by "R*" but NOT by+ /// "r*" when `case_insensitive = false`.+ #[test]+ fn case_sensitive_wildcard_and_fuzzy() {+ let dir = TempDir::new().unwrap();+ let registry = Arc::new(AnalyzerRegistry::default());+ let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(®istry));+ let cfg = FieldIndexConfig {+ analyzer: "whitespace".to_owned(),+ ..Default::default()+ };+ writer.configure_field("body", cfg);+ writer.add_document(+ 0,+ &[("body".to_owned(), "Rust Systems".to_owned())]+ .into_iter()+ .collect(),+ );+ writer.finish().unwrap();+ let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());+ let searcher = FtsSearcher::new(reader, registry);++ // Case-sensitive wildcard: "R*" matches, "r*" does not.+ let mut ci = WildcardQuery::new("body", "R*");+ ci.case_insensitive = false;+ assert_eq!(searcher.search(&Query::Wildcard(ci), 10, false).unwrap().len(), 1);+ let mut cs = WildcardQuery::new("body", "r*");+ cs.case_insensitive = false;+ assert_eq!(searcher.search(&Query::Wildcard(cs), 10, false).unwrap().len(), 0);+ // Case-insensitive (keyword-style) wildcard: "r*" DOES match.+ let ki = WildcardQuery::new("body", "r*"); // default case_insensitive = true+ assert_eq!(searcher.search(&Query::Wildcard(ki), 10, false).unwrap().len(), 1);++ // Case-sensitive fuzzy: "Rist" (1 edit from "Rust") matches; "rist" does not.+ let mut fz = FuzzyQuery::new("body", "Rist", 1);+ fz.case_insensitive = false;+ assert_eq!(searcher.search(&Query::Fuzzy(fz), 10, false).unwrap().len(), 1);+ let mut fzl = FuzzyQuery::new("body", "rist", 1);+ fzl.case_insensitive = false;+ assert_eq!(searcher.search(&Query::Fuzzy(fzl), 10, false).unwrap().len(), 0);+ }+#[test]fn phrase_query_nonexistent_returns_empty() {let dir = TempDir::new().unwrap();@@ -1100,4 +1729,64 @@ mod tests {);}}++ /// `search_bounded(cap)` must return EXACTLY the same top-`cap` hits (same+ /// order, same scores) as the legacy `execute() + sort_unstable() ++ /// truncate(cap)`, and its reported `total` must equal the full match count+ /// regardless of `cap`. Exercises both the streaming leaf-`Term` path and+ /// the `execute()`-then-drain compound (`Bool`) path.+ #[test]+ fn search_bounded_matches_legacy_topk_and_total() {+ let dir = TempDir::new().unwrap();+ let searcher = setup_searcher(dir.path());++ // Two query shapes with a MULTI-score match set:+ // - Term "fox": docs 0,1,4 with distinct BM25 (doc 4 TF=4 ranks top).+ // - Bool should(fox|quick|lazy): a wider, differently-scored set that+ // routes through execute()-then-drain, not the streaming leaf.+ let term_q = Query::Term(TermQuery::new("body", "fox"));+ let bool_q = Query::Bool(Box::new(+ BoolQuery::new()+ .should(Query::Term(TermQuery::new("body", "fox")))+ .should(Query::Term(TermQuery::new("body", "quick")))+ .should(Query::Term(TermQuery::new("body", "lazy"))),+ ));++ for q in [&term_q, &bool_q] {+ // Legacy reference: usize::MAX keeps the full-set sort path.+ let full = searcher.search(q, usize::MAX, false).unwrap();+ let total_full = full.len() as u64;+ assert!(total_full >= 3, "query should match several docs");++ // Order must already be strictly non-increasing by score.+ for w in full.windows(2) {+ assert!(w[0].score >= w[1].score);+ }++ for cap in [0usize, 1, 2, 3, total_full as usize, total_full as usize + 5] {+ let (bounded, total) = searcher.search_bounded(q, cap, false).unwrap();++ // (1) Exact total is independent of the page cap.+ assert_eq!(+ total, total_full,+ "bounded total must equal full match count at cap={cap}"+ );++ // (2) Top-`cap` is byte-identical to legacy sort+truncate.+ let expected: Vec<(u32, u32)> = full+ .iter()+ .take(cap)+ .map(|h| (h.doc_id, h.score.to_bits()))+ .collect();+ let got: Vec<(u32, u32)> = bounded+ .iter()+ .map(|h| (h.doc_id, h.score.to_bits()))+ .collect();+ assert_eq!(+ got, expected,+ "bounded top-{cap} must match legacy sort+truncate (doc_id+score)"+ );+ }+ }+ }}diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rsindex 94f7d9b10..fb77a6b71 100644--- a/engine/crates/xerj-query/src/parser.rs+++ b/engine/crates/xerj-query/src/parser.rs@@ -1552,10 +1552,17 @@ fn parse_qs_unary(// A bare term containing `*` or `?` is a Lucene wildcard —// emit a Wildcard query so `q=shor*` / `q=te?t` match text// tokens with the expected substitution semantics.+ //+ // ES lowercases wildcard/prefix terms in `query_string` (the field's+ // search analyzer normalizes them) — e.g. `q=field:BA*` matches the+ // indexed lowercased token `bar`. The raw `wildcard` query does NOT+ // analyze its pattern (case-sensitive), so this lowering lives HERE+ // in the query_string path only. Harmless for keyword fields, whose+ // FST-wildcard route case-folds both sides regardless.if value.contains('*') || value.contains('?') {return Some(QueryNode::Wildcard {field: f,- value,+ value: value.to_lowercase(),boost: None,});}