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.
invC8
rootCause
The c8 bulk-ingest ceiling is NOT rayon-pool starvation or WAL fsync — it is a fixed 2.9s-per-1M-docs serial stall from per-shard flush drains, amplified by P2.1's all-shard fan-out, plus heavy work executed inside the memtable shard write locks. Concretely: (1) 39µs/doc; 30s tokenize CPU per 1M docs) under the same shard write locks, inflating insert wall 27→72ms/batch at c8 and producing the observed futex(67%)+sched_yield(29%) storm.drain_shard_inner (engine/crates/xerj-engine/src/memtable.rs:883-899) holds the shard's parking_lot write lock for ~95ms per flush while it deallocates the shard's entire inverted index / doc-values maps (32 flushes per 1M docs = ~3.0s of lock-held stall); since every bulk request fans across ALL 16 shards (index.rs:1344-1362) and joins on the slowest shard, each drain stalls all 8 in-flight requests — an Amdahl serial term that exactly reproduces the measured 3.1x c1→c8 curve. (2) FtsMemtable::insert (memtable.rs:1099-1225) runs text-collection + analyzer tokenization + SipHash-hashed nested posting-map merges + a full source deep-clone (
evidence
Live 1M-doc runs on :9303 (32-core box, same 10k-batch harness as bench-matrix.mjs): c1/c2/c4/c8 = 53.1k/90.4k/152.7k/194.8k docs/s (T = 18.8/11.1/6.6/5.1s). Least-squares Amdahl fit T(c) = 2.93s + 15.91s/c reproduces all four points to <2% — the bend is a fixed 2.9s serial component. (a) XERJ_PROF flush lines: every do_flush_shard drain reports drain_us≈87,000–104,000 (95ms) at ~30k docs/shard; 1M docs / (500k doc-threshold /16 shards, index.rs:432,1851-1856) = 32 flushes × 95ms = 3.0s — exactly the fitted serial term. The 95ms is spent inside ShardedFtsMemtable::drain_shard_inner (memtable.rs:883-899) which holds the shard parking_lot write lock while g.index = HashMap::new(); g.doc_values = DocValues::default(); g.field_lengths = ... frees the shard's entire inverted index + doc-values (millions of String entries). Because P2.1 fan-out (index.rs:1344-1362) buckets EVERY 10k bulk request across ALL 16 shards and only completes when the slowest shard sub-insert finishes, one draining shard stalls all 8 in-flight requests. (b) strace -c -f during c8: futex 66.8% + sched_yield 29.3% (100k yields/3s) of syscall time; fsync only 182 calls/5s at 163µs (WAL soft_flush, not a bottleneck); CPU only ~17/32 cores → lock waits, not CPU or I/O. (c) XERJ_PROF batch phases: insert_us median 27ms(c1)→72ms(c8) for identical work = shard-lock contention; cum insert counters per 1M docs: tokenize 30.0s, text-collect 3.2s, size 1.7s, dv 2.0s, source deep-clone 1.7s — all executed under the shard write lock (FtsMemtable::insert, memtable.rs:1099-1225; clone at :1219). (d) Symbolized perf during c8: top-of-profile is SipHash (core::hash::sip::Hasher::write 11.8% + BuildHasher::hash_one 9.7% + hashbrown reserve_rehash) + FtsMemtable::insert 9.3% — the nested HashMap<field, HashMap<token, HashMap<doc_id, u32>>> posting merges (memtable.rs:91,1027,1190-1194). (e) Causal prototype: replacing the in-lock m.insert(...) with the deferred insert_pretokenized_with_seq (removes tokenize+dv+drop from the lock) took c8 from 195k to 283–337k docs/s (3 runs) and drain_us from ~95,000 to ~3,000, at only ~14/32 cores — confirming the lock-held work is the scaling ceiling (prototype then reverted; it breaks pre-flush match-query visibility since memtable search needs self.index, memtable.rs:1560-1565, so it is a probe, not the fix). Control: ingest_shards 16→64 gave only +8.6% (211k), ruling out plain shard-width.
fixPlan
Three surgical changes, all correctness-preserving (memtable stays fully indexed on the hot path, unlike the X-Turbo deferred path):
F1 (biggest, do first) — drop drained maps OUTSIDE the shard lock. In drain_shard_inner, engine/crates/xerj-engine/src/memtable.rs:883-899: inside the self.shards[shard_idx].write() block, replace the reset assignments with std::mem::take into locals (let dead_index = std::mem::take(&mut g.index); let dead_dv = std::mem::replace(&mut g.doc_values, DocValues::default()); let dead_fl = std::mem::take(&mut g.field_lengths); let dead_afl = std::mem::take(&mut g.avg_field_lengths); let dead_dii = std::mem::take(&mut g.doc_id_index); let dead_gfl = std::mem::take(&mut g.ghost_field_len); let dead_gdf = std::mem::take(&mut g.ghost_doc_freq); g.total_bytes = 0; g.ghost_docs = 0; and let d = std::mem::take(&mut g.docs); instead of drain().collect()), close the lock scope, then drop the dead maps after release — ideally via std::thread::spawn(move || drop((dead_index, dead_dv, dead_fl, dead_afl, dead_dii, dead_gfl, dead_gdf))) (or rayon::spawn) so the ~95ms of frees also leaves the flush task's critical path. This removes the entire 2.9s serial term.
F2 — pre-analyze outside the shard lock in the ES bulk path. In index_batch_turbo_raw, engine/crates/xerj-engine/src/index.rs:1316-1363: (a) change the rayon parse phase (:1318-1324) to produce Vec<Arc<Value>> AND, per doc, the analyzed token lists: factor the front half of FtsMemtable::insert (memtable.rs:1101-1195: schema text-field extraction + collect_text_fields + analyzer.analyze per field) into a free function fn analyze_doc(source:&Value, schema:&Schema, analyzer:&Analyzer) -> Vec<(String field, Vec<Token>)> (analyzer via the existing registry: same registry.get_analyzer("default").or(standard) lookup, hoisted once per batch); run it inside the same par_iter. (b) add FtsMemtable::insert_analyzed(&mut self, seq_no:u64, doc_id:String, source:Arc<Value>, analyzed:&[(String, Vec<Token>)]) next to insert (memtable.rs:1225) that performs ONLY the back half of insert (field_lengths/avg_field_lengths updates :1180-1188, posting merges :1190-1194, size accounting :1199-1202, doc_values.push :1208-1209, doc_id_index + docs.push :1214-1222) and stores the passed Arc<Value> directly in MemEntry — eliminating the per-doc Arc::new(source.clone()) deep clone at memtable.rs:1219. (c) in the bucketed par_iter (index.rs:1348-1362) call m.remove(id); m.insert_analyzed(seq_nos[i], id.clone(), Arc::clone(&sources[i]), &analyzed[i]). Lock-held work drops from ~39µs/doc to ~9µs/doc.
F3 — replace SipHash with FxHash in the memtable hot maps: add rustc-hash = "2" to engine/Cargo.toml [workspace.dependencies] and xerj-engine/Cargo.toml; change type PostingList = HashMap<String,u32> (memtable.rs:91), index (:1027), field_lengths (:1035), doc_id_index (:1039) and the DocValues maps (memtable.rs:109-140: numeric/keyword/keyword_set/keyword_counts/numeric_counts) to rustc_hash::FxHashMap/FxHashSet (constructors at :1064-1070, :1085-1091 become FxHashMap::default()). perf shows 21%+ of on-CPU time in SipHash/hash_one; this cuts both the residual in-lock posting merges and flush-prep cost.
Gate: cargo run -p es-yaml-runner -- --dir tests/es-compat-yaml/yaml must stay at current pass rate, then re-run node demo/playbooks/bench-matrix.mjs --ingest-only --docs 1m --clients 1,4,8. Follow-up if still short of ES: flush finalize is ~1.1s per 30k-doc segment (XERJ_PROF finalize: stored_codec encode ≈390ms + FTS sidecar) = ~35s CPU per 1M docs competing with ingest — lower zstd level / parallelize encode_stored_v2 in engine/crates/xerj-storage/src/index_store.rs:864.
expectedGain
c8 bulk ingest: 205k → ≥285k docs/s guaranteed (measured floor: prototype that removed the same lock-held work hit 283-337k), realistically 320-420k with F1+F2+F3 (Amdahl model with the 2.9s serial term removed predicts T(8)≈2.3s ≈ 430k upper bound; flush-side CPU ~35s/1M docs is the next ceiling at ~300-340k unless the follow-up lands). c8/c1 scaling improves from 3.1x to ≥5x, closing most of the 0.55x gap vs ES (374k); with the flush-encode follow-up XERJ should reach parity or better. c1 also gains ~15% (prototype: 53k→62k).
confidence: high
invC1
rootCause
The dominant XERJ-side serial cost today is NOT the WAL lock (0.10s/1M lock hold — hypothesis 1.2 refuted) and only marginally the insert clones (1.3). It is the flush path's triple-handling of every document (hypothesis 1.1, confirmed with one correction to the plan's premise): after P2.1, do_flush_shard no longer re-parses JSON on the HTTP path — instead it (a) deep-clones every parsed Value at drain-prep (index.rs ~7062, 3.7s CPU/1M), (b) fully RE-TOKENIZES every doc for the FTS sidecar (add_documents_parallel, 10.3s CPU), (c) re-serializes every doc into a 10MB JSON array (index_store.rs:849, 1.4s), and (d) encode_stored_v2 re-parses that whole array back to Vec and clones every field into columns (stored_codec.rs:146, 10.6s). Total 35.3s of background CPU during a 15.3s run, which contends with the client-blocking rayon parse/insert phases: measured per-batch engine time inflates 48.5→63.2ms (+30%) once flushes start, worth ~0.7-1.0s of the ~0.9s gap to ES. Secondary client-blocking waste confirmed: memtable insert does source.to_string() purely for size accounting (memtable.rs:1188, 1.5s CPU) and Arc::new(source.clone()) (memtable.rs:1203, 1.7s CPU); serial version_map.set loop (0.73s); per-doc schema-evolve loop (0.44s); handler-side rewrite_bulk_ignore_malformed parses+re-serializes every doc whenever ANY mapping exists (es_compat.rs:19388/9310, part of 1.45s handler overhead).
evidence
Reproduced benchmark on instrumented build (scratchpad target; port 9304): 1M docs @ 66,090 docs/s (benchmark: 65,225 vs ES 69,328). Phase timing (XERJ_PROF, log at scratchpad/xerj9304.log): wall 15.33s = 8.3s outside server took (curl+3MB up/2.1MB down per batch — common-mode with ES side) + 1.45s handler pre/post (es_compat.rs:9306-9317 rewrite passes + bulk.rs parse/item-build) + 5.56s engine index_batch_turbo_raw. Engine split: fts-insert 3.34s wall / 37.3s CPU (tokenize+postings-hash 29.2s, text-extract 3.1s, to_string-size 1.5s at memtable.rs:1188, DV 1.8s, deep-clone 1.7s at memtable.rs:1203), WAL 0.99s (lock hold only 0.10s — hypothesis 1.2 REFUTED; serial version_map.set loop 0.73s at index_store.rs:1885), parse 0.62s, evolve 0.44s. Background flush = 35.3s CPU over 32 flushes (1.1-1.27s per 31k-doc flush): FTS re-tokenize 10.3s (do_flush_shard→add_documents_parallel, index.rs:7150), encode_stored_v2 10.6s (re-parses the just-serialized 10MB JSON array per flush, stored_codec.rs:146), prep deep-clone (**arc).clone() 3.7s (index.rs:~7062), stored re-serialize 1.4s (index_store.rs:849), DV sidecar 3.3s, drain (shard write-lock held) 2.2s. Contention is client-visible: avg engine time per batch 48.5ms for batches 1-49 (flushes only start after 500k docs; per-shard threshold 31,250 = 500k/16, index.rs:1850) vs 63.2ms for batches 52-100 (+30%; parse wall 1.7→11.8ms). perf flat profile (42k samples, scratchpad/perf.data): SipHash string hashing 20.8% (hash_one 11.4 + Hasher::write 9.4), FtsMemtable::insert 9.7% self, jemalloc ~9%, encode_stored_v2 1.8%, tokenize 2.2%.
fixPlan
P2.2 no-reparse/no-retokenize flush (confirmed highest-impact). (1) memtable.rs FtsMemtable::insert (1092): accept 1351: build source: Arc<Value> + raw_len: usize; replace source.to_string().len() (1188) with raw_len (turbo caller knows docs[i].1.len()); store the passed Arc in MemEntry (deletes Arc::new(source.clone()) at 1203). Caller index.rs:sources: Vec<Arc<Value>> once from the parallel parse. (2) Token carry: insert already computes per-(field,token) counts (memtable.rs:1165-1185); attach them to MemEntry (Option<Vec<(field, Vec<(token,count)>)>>, 10MB/shard peak at 31k docs) and add FtsIndexWriter::add_documents_pretokenized so do_flush_shard's sidecar build skips re-analysis (kills 10.3s CPU). (3) do_flush_shard (index.rs:6995): drained_fts carries Arc — replace 7062) with Arc::clone (kills 3.7s); keep the just-in-time parse only for the raw-bytes/CLI branch. (4) stored_codec.rs: add (**arc).clone() (encode_stored_v2_from_values(&[(id, seq_no, &Value)]) -> Vec<u8> building col_order/columns directly from Values (kills the 10MB serialize at index_store.rs:830-855 + re-parse at stored_codec.rs:146; 6-7s CPU); serialize the JSON array ONLY inside the v1/LZ4 fallback branch (docs < V2_MIN_DOCS or shape mismatch). Wire into finalize_flush_with_publisher (index_store.rs:862) for entries with empty source_bytes. (5) Parity gate: behind XERJ_FLUSH_PARITY=1, run the old serialize+encode path too and assert byte-identical section bytes before add_section; land only with full es-yaml 1326/0 + crash-recovery test green. Stackable follow-ups found during verification (separate commits, in impact order): (a) swap the memtable postings HashMaps' SipHash for ahash/FxHash — 20.8% of ALL CPU samples is string SipHash, the single biggest lever beyond P2.2; (b) gate rewrite_bulk_ignore_malformed (es_compat.rs:9310) on per-index 'has ignore_malformed/strict-format fields' instead of 'any mapping exists' — it currently parses+re-serializes every doc serially; (c) batch the serial version_map.set loop (index_store.rs:1885, 0.73s); (d) evolve schema once per unique field-shape per batch instead of per doc (index.rs:1323, 0.44s).
expectedGain
Removes ~24-26s of the 35.3s background flush CPU and roughly halves flush duration (1.1-1.27s -> ~0.5s per 31k-doc flush), eliminating the measured +30% client-batch inflation during flush windows (48.5 -> 63.2ms engine/batch). Estimated 0.7-1.2s off the 15.3s single-client wall: ~66k -> ~69-71k docs/s, i.e. parity-to-win vs ES 69.3k (gain estimate is the softest number — contention relief on the 8.3s client/HTTP portion was measured only indirectly). Larger wins under concurrent-client ingest (CPU-bound, where the 26s redundant CPU caps throughput directly) and on the open during-ingest read-p99 axis (shorter flush windows, shorter drain shard-lock holds, less rayon-pool theft). Follow-up (a) ahash targets the 20.8% SipHash CPU and could add another ~1-2s wall on top.
confidence: high
invFuzzy
rootCause
Fuzzy query token-comparison asymmetry in doc_matches_query (engine/crates/xerj-engine/src/index.rs, QueryNode::Fuzzy arm, formerly lines 10063-10089): the DOCUMENT value is tokenized on non-alphanumerics but the QUERY value is compared as the whole untokenized string. Doc "claude-haiku-4-5" becomes tokens [claude, haiku, 4, 5], each Levenshtein-compared against the full 16-char query "claude-haiku-4-6" (distance >= 10), so no hyphenated/multi-token keyword value can ever match within fuzziness 1. ES fuzzy is term-level with an unanalyzed query term, and for a keyword field the indexed term is the WHOLE value ("claude-haiku-4-5" vs "claude-haiku-4-6" = distance 1 = match, 277,449 docs). This is NOT a memtable-vs-segment divergence: both the memtable DocsForScan path (index.rs ~3971/4043) and the segment stored-doc scan (scan_stored_section_into via index.rs ~4545) call the same doc_matches_query; fuzzy correctly bypasses FTS (query_node_to_fts returns None) and has no shortcut_count path. The earlier hand probe passed only because it used single-token typo values (e.g. "hauku" -> doc token "haiku"), where the untokenized query happens to equal a valid single term.
evidence
Harness body: demo/playbooks/bench-matrix.mjs:227 sends {fuzzy:{model:{value:'claude-haiku-4-6',fuzziness:1}}}; corpus demo/data/extras/chat-events.ndjson has 1112/4008 lines with model=claude-haiku-4-5 (1112/4008*1e6 ~= 277,445 ~= ES's 277,449; no other of the 6 distinct values is within 1 edit). Code anchor: engine/crates/xerj-engine/src/index.rs:10073-10078 (pre-fix) — token_match splits s.to_lowercase() on !is_alphanumeric and compares each token to the FULL q_lower. Live repro on port 9301 (release binary, keyword-mapped "model", docs flushed to segment): pre-fix, harness body -> hits.total 0 on BOTH memtable and segment data; control "gpt-4" fuzziness 1 vs doc "gpt-5" -> 0 (doc tokenized to [gpt,5]); control "hauku" -> 2 hits (single-token path works, explaining the earlier passing probe); exact term query -> 2 hits (data present). Post-fix (rebuilt binary): harness body -> 2 hits, both claude-haiku-4-5; "gpt-4" -> 1; negative control 2-edit "claude-haiku-3-9" -> 0; "claude-sonnet-4-5" fuzziness 1 -> only claude-sonnet-4-6, haiku correctly excluded. cargo test -p xerj-engine fuzzy: test_fuzzy_query_typo passes.
fixPlan
APPLIED AND VERIFIED (change is in the working tree on branch fix/sort-topn-correctness): in engine/crates/xerj-engine/src/index.rs, QueryNode::Fuzzy arm of doc_matches_query (~line 10073), change token_match to first compare the FULL case-folded doc string against q_lower — let s_lower = s.to_lowercase(); if levenshtein_distance(&s_lower, &q_lower) <= max_edits { return true; } — then fall back to the existing per-token split/compare for text-field semantics. This makes keyword values match as whole terms (ES term-level semantics) while preserving existing text-field token matching. Rebuild with cargo build --release -p xerj-server. Known edge (acceptable, note in commit body): a multi-word TEXT field whose entire source string is within max_edits of the query now over-matches vs ES (ES only compares indexed terms); doc_matches_query has no schema access, so the mapping-aware refinement (gate whole-string compare on FieldType::Keyword, threaded from Index::search or via a schema-aware Fuzzy rewrite near the rewrite site at index.rs:8562) is optional hardening. Perf follow-up shared with the regexp sibling: try_shortcut_count (index.rs:5996) only handles Term/Range/Bool — extend it to Fuzzy (and Regexp) by iterating the DISTINCT terms of the segment KeywordColumn dictionary (dv_columns_for) and summing per_ord_count for matching ords: 6 distinct models means ~6 Levenshtein calls per segment instead of a 1M-doc stored-source scan. Regexp sibling anchor: index.rs Regexp arm (now ~10104) calls Regex::new PER DOCUMENT inside the scan closure — 1M compiles per query — which plus the full stored scan explains the 11s+ regexp collapse; compile once per query and/or use the same distinct-term dictionary path.
expectedGain
Correctness: harness fuzzy(model) body goes from 0 hits to the exact ES-matching total (~277,449 on the 1M corpus; verified exact-set equivalence on a live segment-flushed index — only claude-haiku-4-5 is within 1 edit of claude-haiku-4-6 among corpus values). Closes the fuzzy(model) MISMATCH row in the XERJ-vs-ES scorecard. With the optional keyword-dictionary shortcut, fuzzy (and regexp) counting drops from O(docs) stored-scan to O(distinct terms) per segment.
confidence: high
invRegexp
rootCause
XERJ executes regexp as a brute-force stored-document scan and — the killer — recompiles the regex once PER DOCUMENT. Regexp is classified as a doc-scan query (engine/crates/xerj-engine/src/index.rs:9488), has no doc-values or FST shortcut (try_doc_values_query index.rs:8790 covers only Term/Terms/Range; try_shortcut_count index.rs:5996 covers MatchAll/Term/Bool{Term,Range}), so the segment loop decompresses the whole stored section, brace-scans and simd_json-parses all 500k-1M docs (scan_stored_section_into index.rs:6739, parse at 6849, source clone + _id injection at 6873-6881), then calls doc_matches_query per doc, whose Regexp arm calls Regex::new(&anchored) inside the per-doc closure (index.rs:9819-9830, compile at 9824-9825). At ~150µs/compile × 500k docs that alone is ~76s; at the harness's 1M docs it is ~158s per request — the harness times out, i.e. the observed collapse. ES instead rewrites regexp against the keyword field's term dictionary (6 distinct values here) and unions postings, hence 11.38ms.
evidence
Live reproduction on a fresh XERJ (release binary, port 9302, own data dir): ingested 500k docs cycling the real harness corpus /home/claude/ai/xerj/demo/data/extras/chat-events.ndjson (6 distinct model keyword values; the 3 claude-* values = 84.7% ≈ 847k/1M, matching the benchmark fact), flushed to a single 500k-doc segment. Exact harness body from demo/playbooks/bench-matrix.mjs:226 {"query":{"regexp":{"model":"claude-[a-z]+.*"}},"size":10}: cold took=79,041ms; cache-busted repeat (size:11) took=79,088ms; an identical repeat returned took=0 (query-cache hit — consistent with the known "query-cache mirage", so any fast re-run is not real). Controls on the SAME stored-scan path, same segment, cold: wildcard(model:"claude-*") took=2,683ms, term took=2,528ms — proving ~76.5s of the 79s is the per-doc Regex::new at index.rs:9824-9825 (76.5s/500k ≈ 153µs = typical regex compile cost) and the residual ~2.6s is the generic full stored-doc scan (index.rs:6739-6883). Code anchors: doc-scan classification index.rs:9453/9488; per-doc compile index.rs:9819-9830; no regexp shortcut index.rs:8790-8860, 5996-6010; planner already documents "Regexp: full scan cost" xerj-query/src/planner.rs:405. Linear scaling → ~158s at the 1M-doc benchmark corpus, past the harness timeout. ES p50 11.38ms.
fixPlan
Two stages, both in engine/crates/xerj-engine/src/index.rs.
Stage 1 — stop per-doc regex compilation (tiny, removes the collapse): in the QueryNode::Regexp arm of doc_matches_query (index.rs:9819-9830), compile once per query instead of per doc via a thread_local RefCell<HashMap<String, Option<Regex>>> keyed by the anchored pattern (doc_matches_query is a free fn with no state, so a TL cache is the minimal change; cap it at ~64 entries). Do the same audit for the Wildcard/MatchPhrasePrefix arms if they build matchers per doc. Result: 79s → ~2.6s (measured wildcard parity).
Stage 2 — ES-equivalent term-dictionary expansion (gets to ms): add fn try_expand_pattern_to_terms(&self, field, pattern, snap, segments_dir) -> Option<Vec<String>> and call it at the top of Index::search (index.rs:3423, before the MemSnapshot block) to rewrite the query node. Implementation: (a) collect distinct terms of the keyword column from every segment via the existing dv_columns_for cache (index.rs:6437) — Column::Keyword(k).terms is already the sorted distinct-term dictionary (xerj-storage/src/doc_values.rs:343-358, terms: Vec<String>), and union the memtable keyword doc-values column's distinct values; (b) compile the anchored regex ONCE and filter the distinct terms — O(distinct terms), here 6; (c) if every source had a keyword column and matched-term count ≤ cap (e.g. 1024, ES-style rewrite bound), replace the node with QueryNode::Terms { field, values }; else fall back to the Stage-1 scan. Then make Terms fast end-to-end: extend try_shortcut_count (index.rs:5996) with a Terms arm that sums KeywordColumn::per_ord_count[ord] per segment (ord via k.ord_for_term, exactly like the existing Term pred at index.rs:6060-6075) plus memtable counts — the existing deletes_present gate (index.rs:4209) already keeps it correct under deletes; and add a Terms doc-position pre_filter in the segment loop analogous to build_range_prefilter_cached (index.rs:6487, wired at ~4466): positions where k.ords[i] ∈ matched_ord_set and not null, so scan_stored_section_into parses only top-(from+size) candidates and the F1 bounded-scan early-break (index.rs:4270-4284) fires. Apply the same expansion to Wildcard (glob→regex: escape literals, *→.*, ?→.), Fuzzy (levenshtein_distance(term, q) <= max_edits over distinct terms, reusing the helper at index.rs:9805), and Prefix. Guard with a schema check that the field is keyword-typed; verify with the ES-compat YAML regexp/wildcard/fuzzy suites and add a bench-matrix re-run.
expectedGain
Stage 1: 79s → ~2.6s cold on 500k docs (measured wildcard control on the identical scan path); un-collapses the benchmark (no more timeouts at 1M). Stage 2: count becomes O(segments × distinct_terms) from per_ord_count (6 terms here) and materialisation becomes O(from+size)=10 docs via the pre_filter + bounded scan — single-digit ms, i.e. ~10,000× vs today and at or below ES's 11.38ms p50; wildcard/prefix/fuzzy families get the same win for free.
confidence: high