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
fix(#1260): columnar exists + delete-aware fast-agg admission
xerj-orgc13d59190955
diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rsindex d4c164eb1..b9b0f242d 100644--- a/engine/crates/xerj-engine/src/aggs.rs+++ b/engine/crates/xerj-engine/src/aggs.rs@@ -7090,7 +7090,16 @@ pub(crate) fn doc_matches_filter(doc: &Value, filter: &Value) -> bool {"exists" => {// exists: {"field": "price"} — match docs that have the field.if let Some(field) = query_body.get("field").and_then(Value::as_str) {- let has_field = !extract_field_values(doc, field).is_empty();+ // #1260: a field whose value is directly an OBJECT counts+ // as present. `extract_field_values` flattens objects to+ // `[]` while the query path's `value_present`+ // (`doc_matches_query_typed`'s Exists arm) treats an+ // object as present — the two disagreeed, and the fast+ // aggs exists arm is built on them agreeing. Scalars,+ // arrays and nulls are unchanged: `extract_field_values`+ // already mirrors `value_present` for them.+ let has_field = !extract_field_values(doc, field).is_empty()+ || matches!(get_nested_field(doc, field), Value::Object(_));if !has_field {return false;}diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsindex d92280e41..22c57c5fe 100644--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -33,8 +33,14 @@//! * Index must have ≥ `FAST_AGG_MIN_DOCS` docs — small indices are fast on//! the brute path anyway, and this keeps the (tiny-corpus) ES-YAML//! conformance suite pinned to the reference implementation.-//! * No deletes/updates present (`.dv` columns are physical → delete-blind;-//! same `deletes_present` signal as the F1 shortcut-count gate).+//! * Deletes: either none present, or (since #1260) every non-empty snapshot+//! segment's ghost-position bitmap is empty — per-segment admission via+//! `ghost_positions_for`, with the memtable views liveness-gated, the+//! delete-blind memtable columnar summaries switched off, and the+//! version-map epoch re-checked before the result is returned. A single+//! superseded row in ANY segment still bails; what changed is that a+//! MERGED index (ghosts compacted away) re-qualifies instead of staying+//! disabled forever on the monotonic `ghost_events` counter.//! * Every non-empty segment must have a decodable `.dv` sidecar.//!//! Known accepted divergences vs brute (documented, benign for the fast-path@@ -460,6 +466,15 @@ pub(super) struct FastCtx<'a> {/// memtable's own "columnar path applicable?" answer (`None` == a bailout,/// fall back to full `mem()`).mem_filtered: std::sync::OnceLock<Option<Vec<(String, std::sync::Arc<Value>)>>>,+ /// [#1260] `Some(segment-ids-of-the-snapshot)` iff the request was+ /// admitted under the delete-aware gate (every snapshot segment's ghost+ /// bitmap empty — live == physical). The memtable views (`mem`,+ /// `filtered_mem`) then drop buffered docs whose live copy already sits+ /// in one of those segments (`mem_doc_live`), and the delete-blind+ /// memtable columnar summaries are switched off in favour of the exact+ /// per-doc walks. `None` == the classic no-deletes path, byte-for-byte+ /// as before.+ mem_live_gate: Option<std::collections::HashSet<String>>,}impl<'a> FastCtx<'a> {@@ -472,11 +487,13 @@ impl<'a> FastCtx<'a> {return MemDocs::Owned(Vec::new());}if self.needs_owned_mem {+ let gate = self.mem_live_gate.as_ref();MemDocs::Owned(self.idx.memtable.all_docs_with_sources().into_iter()+ .filter(|(id, _)| gate.is_none_or(|s| self.mem_doc_live(id, s))).map(|(id, mut v)| {if let Some(o) = v.as_object_mut() {o.entry("_id".to_string())@@ -492,7 +509,10 @@ impl<'a> FastCtx<'a> {.collect(),)} else {- let pairs = self.idx.memtable.all_docs_with_sources_arc();+ let mut pairs = self.idx.memtable.all_docs_with_sources_arc();+ if let Some(snap_ids) = &self.mem_live_gate {+ pairs.retain(|(id, _)| self.mem_doc_live(id, snap_ids));+ }let mut ids = Vec::with_capacity(pairs.len());let mut srcs = Vec::with_capacity(pairs.len());for (id, src) in pairs {@@ -504,6 +524,24 @@ impl<'a> FastCtx<'a> {})}+ /// [#1260] Liveness of a buffered memtable doc under the admission gate —+ /// the fast path's counterpart of `fold_match_sources`'s memtable check,+ /// adjusted for the OPPOSITE capture order (snapshot first, memtable+ /// lazily after). A doc is live when nothing in the version map+ /// supersedes it: not deleted, and either still in-memory or repointed+ /// into a segment OUTSIDE this snapshot (that copy is invisible to this+ /// request, so the buffered one remains its only sight).+ fn mem_doc_live(&self, id: &str, snap_ids: &std::collections::HashSet<String>) -> bool {+ match self.idx.store.version_map.get(id) {+ None => true,+ Some(ver) => {+ !ver.deleted+ && (ver.segment_id.as_ref() == xerj_storage::version_map::IN_MEMORY_SEGMENT_ID+ || !snap_ids.contains(ver.segment_id.as_ref()))+ }+ }+ }+/// Columnar-filtered memtable docs for the top-level filter, or `None` when/// the columnar fold doesn't apply — the caller then walks the full `mem()`/// gated by `doc_matches_filter`, exactly as before.@@ -523,7 +561,15 @@ impl<'a> FastCtx<'a> {}let preds = self.top_filter_mem_preds.as_ref()?;self.mem_filtered- .get_or_init(|| self.idx.memtable.filtered_docs_arc(preds))+ .get_or_init(|| {+ let mut docs = self.idx.memtable.filtered_docs_arc(preds)?;+ // [#1260] Same liveness fold as `mem` — the columnar+ // candidate set may still hold stale pre-drain copies.+ if let Some(snap_ids) = &self.mem_live_gate {+ docs.retain(|(id, _)| self.mem_doc_live(id, snap_ids));+ }+ Some(docs)+ }).as_deref()}}@@ -709,11 +755,56 @@ impl Index {// `VersionMap::ghost_events` (the old live-vs-physical arithmetic// false-positived on physical-count drift and disabled this fast// path under append-only write load).- let deletes_present = snap.segments.iter().any(|m| m.has_tombstones)- || self.store.version_map.ghost_events() > 0;- if deletes_present {- return None;- }+ let admission_epoch = self.store.version_map.ghost_events();+ let deletes_present = snap.segments.iter().any(|m| m.has_tombstones) || admission_epoch > 0;+ // [#1260] Deletes no longer disable the fast path outright. Every+ // O(1) stat the executors use (per_ord_count, live_count,+ // range_count, the sorted run) is DELETE-BLIND — it counts physical+ // rows — which is why one superseded row anywhere used to bail the+ // whole request. But `ghost_events` is MONOTONIC: after a merge+ // compacts the ghosts away the index is clean again, while the gate+ // stayed tripped forever (measured live: the 402,814-doc+ // autoindex-catalog, rewritten by every finalize-catalog, served a+ // filtered terms agg from the brute path until it hit 429 "query+ // allocation would exceed limits.max_query_memory_mb" — its+ // overwrite history had the gate tripped for its whole life).+ //+ // Admission instead, per non-empty segment: fetch the exact+ // ghost-position bitmap (`ghost_positions_for` — bit pos set ⇔ the+ // stored doc at that row is deleted or superseded; the merge+ // survivor filter guarantees at most one live copy per id, so the+ // id-level predicate is exact and its row space IS the `.dv`+ // column row space). A segment with a NON-EMPTY bitmap still bails+ // (its stats would double-count ghosts); a segment with an EMPTY+ // bitmap is provably ghost-free — live == physical — which is+ // exactly the invariant every executor was built under, so the+ // row-level arithmetic runs unchanged. Steady state after merges+ // is clean bitmaps, so the fast path comes BACK; active rewrite+ // windows keep falling to brute, as before. `None` (stored+ // section unreadable) keeps today's bail.+ let mem_live_gate: Option<std::collections::HashSet<String>> = if deletes_present {+ for meta in &snap.segments {+ if meta.doc_count == 0 {+ continue;+ }+ let ghosts = self.ghost_positions_for(&meta.id, meta.doc_count)?;+ if ghosts.iter().any(|w| *w != 0) {+ return None;+ }+ }+ // The memtable leg of the same gate: a buffered doc whose live+ // copy already sits in a snapshot segment is a stale pre-drain+ // duplicate (the liveness check `fold_match_sources` applies).+ // The SNAP-MEMBERSHIP form — not the fold's plain+ // `!= IN_MEMORY_SEGMENT_ID` — is required because this path+ // reads the snapshot FIRST and the memtable lazily AFTER (the+ // fold reads mem first): a fold-style check would also drop+ // docs drained into a segment this snapshot does not contain,+ // undercounting exactly the docs the request must still see.+ Some(snap.segments.iter().map(|m| m.id.clone()).collect())+ } else {+ None+ };// Warm the per-segment column cache in parallel first: a cold// many-segment index would otherwise decode every `.dv` sidecar@@ -770,6 +861,7 @@ impl Index {top_filter_query,top_filter_mem_preds,mem_filtered: std::sync::OnceLock::new(),+ mem_live_gate,};// Filtered `hits.total`: the number of live docs matching the query.@@ -812,10 +904,32 @@ impl Index {// What the top level of an aggs tree publishes as its document count:// the filtered total when a top-level query narrowed the corpus, else// the whole live corpus. Physical rows either way — the same number- // `docs.len()` gives `aggs::run_aggs_with_all` on the brute path (the- // fast path is gated on there being no deletes, so live == physical).- let top_doc_count = filtered_total.unwrap_or(total_physical);+ // `docs.len()` gives `aggs::run_aggs_with_all` on the brute path+ // (live == physical: by the no-deletes gate, or by the [#1260]+ // admission bitmaps — with the memtable leg taken from the+ // live-filtered `mem()` view, whose length drops the stale pre-drain+ // copies `total_physical` still counts).+ let top_doc_count = filtered_total.unwrap_or_else(|| {+ if ctx.mem_live_gate.is_some() {+ ctx.segs.iter().map(|s| s.docs as u64).sum::<u64>() + ctx.mem().len() as u64+ } else {+ total_physical+ }+ });let result = ctx.eval_aggs_object(aggs_obj, top_doc_count)?;+ // Capture-scope re-check (#1217's discipline, applied to the+ // admission): an overwrite or delete that landed while the executors+ // ran invalidates the per-segment bitmaps and the memtable liveness+ // fold above. `ghost_events` only bumps on overwrite/delete — never+ // on a pure flush repoint — so an unchanged epoch proves the+ // admission still holds for everything this request read. On bump,+ // bail: the caller reruns the whole aggregation on the brute path.+ // (A pure drain straddling the request is NOT caught by the epoch —+ // the same pre-existing window as the lazily built `mem()` view,+ // unchanged by the gate.)+ if self.store.version_map.ghost_events() != admission_epoch {+ return None;+ }// Served columnarly — record it. The two executors are INTENDED to// return the same bytes, so a caller cannot tell them apart from the// response and a test needs this signal (see@@ -1239,11 +1353,16 @@ impl<'a> FastCtx<'a> {top_filter_query: None,top_filter_mem_preds: None,mem_filtered: std::sync::OnceLock::new(),+ // [#1260] carry the admission gate: the child walks the same+ // (possibly ghost-admitted) segment set, so its `mem()` view+ // must apply the same liveness fold.+ mem_live_gate: self.mem_live_gate.clone(),};let mut bucket = Map::new();- // Whole-corpus doc_count (no deletes on the fast path; segment rows are- // weight-1, memtable docs honour `_doc_count`, matching every other- // fast-path executor).+ // Whole-corpus doc_count (live == physical: no deletes, or the+ // [#1260] admission gate + the live-filtered `mem()` view; segment+ // rows are weight-1, memtable docs honour `_doc_count`, matching+ // every other fast-path executor).let mut doc_count: u64 = 0;for seg in &child.segs {doc_count += seg.docs as u64;@@ -2654,7 +2773,10 @@ impl<'a> FastCtx<'a> {// extraction walk below was the cardinality read-under-write tail// at a drain-lagged memtable.let mem_columnar: Option<(std::collections::HashMap<String, u64>, u64)> =- if !field.contains('.') {+ if self.mem_live_gate.is_none() && !field.contains('.') {+ // [#1260] the memtable columnar summary is delete-blind;+ // under the admission gate the exact per-doc walk below+ // (over the live-only `mem()` view) serves instead.self.idx.memtable.terms_counts_columnar(field)} else {None@@ -2943,7 +3065,9 @@ impl<'a> FastCtx<'a> {// memtable under a sustained bulk writer — the terms-agg// read-under-write p95/p99 tail.let mem_columnar: Option<(std::collections::HashMap<String, u64>, u64)> =- if !has_row_work && !field.contains('.') {+ if self.mem_live_gate.is_none() && !has_row_work && !field.contains('.') {+ // [#1260] delete-blind summary — under the admission gate the+ // exact walks below (live-only views) serve instead.self.idx.memtable.terms_counts_columnar(field)} else {None@@ -3156,7 +3280,15 @@ impl<'a> FastCtx<'a> {_ => return None, // non-keyword column for a keyword field → bail}}- match self.idx.memtable.terms_counts_columnar(field) {+ // [#1260] delete-blind summary — under the admission gate this+ // executor has no exact memtable arm, so it bails whole (same as its+ // array-valued-field bailout immediately below).+ let mem_summary = if self.mem_live_gate.is_some() {+ None+ } else {+ self.idx.memtable.terms_counts_columnar(field)+ };+ match mem_summary {Some((mem_counts, _missing)) => {for (term, cnt) in mem_counts {if cnt > 0 && !term.is_empty() {@@ -3236,11 +3368,18 @@ impl<'a> FastCtx<'a> {return None;}// Whole-corpus live doc count = brute's `result_docs.len()` ==- // `all_docs.len()` (no deletes on the fast path; `run_significant_terms`- // counts docs, unweighted). Foreground == background ⇒ every term scores- // 0.0 ⇒ empty buckets.+ // `all_docs.len()` (live == physical by the no-deletes gate or the+ // [#1260] admission bitmaps; `run_significant_terms` counts docs,+ // unweighted). Foreground == background ⇒ every term scores 0.0 ⇒+ // empty buckets. Under the gate the memtable leg must come from the+ // live-filtered `mem()` view — the raw `doc_count()` still counts+ // stale pre-drain copies.let total: u64 = self.segs.iter().map(|s| s.docs as u64).sum::<u64>()- + self.idx.memtable.doc_count() as u64;+ + if self.mem_live_gate.is_some() {+ self.mem().len() as u64+ } else {+ self.idx.memtable.doc_count() as u64+ };Some(json!({"doc_count": total,"bg_count": total,@@ -3878,6 +4017,11 @@ impl<'a> FastCtx<'a> {Ok(Some(ColKind::Keyword)) | Ok(None) => Some(()),_ => None,},+ // Either column kind can answer "row is non-null".+ Pred::Exists { field } => match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Ok(Some(ColKind::Numeric)) | Ok(None) => Some(()),+ _ => None,+ },Pred::And(subs) => {for s in subs {self.check_pred_kinds(s)?;@@ -5086,6 +5230,27 @@ enum Pred {hi: Option<String>,hi_incl: bool,},+ /// `exists: {field}` — the row's column entry is non-null. Brute+ /// parity, both legs:+ /// * segments — `doc_matches_query_typed`'s Exists arm resolves the+ /// `_source` field and applies `value_present` (Null → false, arrays →+ /// any-present, everything else — including objects and `""` — →+ /// true). The column builder pushes nothing for null values, so a+ /// non-null column row ⇔ a present `_source` value for every scalar+ /// shape; object/array/multi-valued shapes never get a column and are+ /// caught by `miss_is_genuinely_empty`/`field_needs_brute_fallback`.+ /// * memtable — `doc_matches_filter`'s exists arm; its one divergence+ /// from `value_present` (a directly-object-valued field:+ /// `flatten(Object)=[]` vs `value_present(Object)=true`) is closed in+ /// `aggs.rs` alongside this variant.+ ///+ /// Meta fields (`_id`, `_index`, …) are answered from bookkeeping on the+ /// brute query path (always true) but have no column and no consistent+ /// memtable answer (owned views inject `_id`, shared views don't) →+ /// bail at compile.+ Exists {+ field: String,+ },/// Conjunction of leaf predicates — a `bool` with only `must`/`filter`/// clauses (produced by `compile_top_pred` for the top-level query filter;/// `compile_pred` never yields this, so the filter/filters/adjacency@@ -5280,6 +5445,22 @@ fn compile_pred(filter: &Value) -> Option<Pred> {hi_incl,})}+ "exists" => {+ if !params_only(body, &["field"]) {+ return None;+ }+ let field = body.get("field").and_then(Value::as_str)?;+ if field.is_empty() || field.starts_with('_') {+ // Meta fields: brute's Exists arm answers them from+ // bookkeeping (`_id`/`_index`/`_seq_no` always true,+ // `_routing` from source), not from a column — there is no+ // columnar equivalent to stay in sync with.+ return None;+ }+ Some(Pred::Exists {+ field: field.to_owned(),+ })+ }_ => None,}}@@ -5322,6 +5503,9 @@ enum SegPred<'a> {/// lexicographically-sorted dictionary. Last bool = column has no nulls.KwRange(&'a KeywordColumn, u32, u32, bool),Num(&'a NumericColumn, f64, bool, f64, bool, bool),+ /// `exists` — the row carries a non-null keyword / numeric value.+ KwExists(&'a KeywordColumn),+ NumExists(&'a NumericColumn),/// Conjunction — every sub-predicate must match the row.And(Vec<SegPred<'a>>),}@@ -5440,6 +5624,11 @@ fn resolve_pred<'a>(Some(Column::Keyword(_)) => return None,None => miss_is_genuinely_empty(field, segs, mapped_fields)?,},+ Pred::Exists { field } => match dv_col(cols, field) {+ Some(Column::Keyword(k)) => SegPred::KwExists(k),+ Some(Column::Numeric(n)) => SegPred::NumExists(n),+ None => miss_is_genuinely_empty(field, segs, mapped_fields)?,+ },Pred::And(subs) => {let mut resolved: Vec<SegPred<'a>> = Vec::with_capacity(subs.len());for s in subs {@@ -5497,6 +5686,8 @@ fn seg_pred_matches(sp: &SegPred<'_>, row: u32) -> bool {let hi_ok = if *hi_incl { v <= *hi } else { v < *hi };lo_ok && hi_ok}+ SegPred::KwExists(k) => k.ord_for(row).is_some(),+ SegPred::NumExists(n) => !n.null_bitmap.contains(row),SegPred::And(subs) => subs.iter().all(|s| seg_pred_matches(s, row)),}}@@ -5517,6 +5708,12 @@ fn seg_pred_count(sp: &SegPred<'_>, docs: u32) -> u64 {.map(|s| s.iter().map(|c| *c as u64).sum()).unwrap_or(0),SegPred::Num(n, lo, lo_incl, hi, hi_incl, _) => n.range_count(*lo, *hi, *lo_incl, *hi_incl),+ // Non-null rows: with multi-valued fields column-suppressed, each row+ // carries at most one ord, so the per-ordinal histogram sums to the+ // non-null row count (same form as `KwIn` above). `live_count` is+ // the numeric column's own precomputed non-null count.+ SegPred::KwExists(k) => k.per_ord_count.iter().map(|c| *c as u64).sum(),+ SegPred::NumExists(n) => n.live_count,// Conjunction has no O(1) form — count matching rows directly. Only// reached from the top-level filter count (compile_pred, used by the// filter/filters executors, never yields `And`).diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 9fa99abcd..a61f96e5b 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -8014,6 +8014,13 @@ fn query_node_to_agg_filter(node: &QueryNode) -> Option<Value> {}Some(serde_json::json!({ "terms": { field: Value::Array(strs) } }))}+ // #1260: `exists` is columnarizable (a non-null column row). Before+ // this arm the node fell to the catch-all `None`, which dropped the+ // whole filtered-agg fast path for ANY query containing an exists+ // leaf — the finalize-verify window shape (`bool.filter [terms …,+ // exists …]` + terms agg) ran the brute `_source` path. Meta+ // fields (`_id`, …) still bail downstream in `compile_pred`.+ QueryNode::Exists { field } => Some(serde_json::json!({ "exists": { "field": field } })),// Numeric **or** date/keyword-string range. Every present bound must// be a JSON number, or every present bound must be a string — a mixed// pair has no single columnar form and stays on the brute path.diff --git a/engine/crates/xerj-engine/tests/fast_aggs_exists_and_deletes.rs b/engine/crates/xerj-engine/tests/fast_aggs_exists_and_deletes.rsnew file mode 100644index 000000000..e0bdf27db--- /dev/null+++ b/engine/crates/xerj-engine/tests/fast_aggs_exists_and_deletes.rs@@ -0,0 +1,378 @@+//! #1260 — two walls between the finalize-verify query shape and the+//! columnar fast path, both measured live on the 402,814-doc+//! autoindex-catalog:+//!+//! 1. `exists` had no arm in `compile_pred`, so the verify window+//! (`bool.filter [terms …, exists text]` + a terms agg) fell off the+//! fast path to the brute `_source` path (15.9 s vs 63 ms cold for the+//! exists-free twin).+//! 2. The `deletes_present` bail keyed on the MONOTONIC `ghost_events`+//! counter, so an index that has EVER seen an overwrite — the catalog+//! is rewritten by every finalize-catalog — never re-qualified, even+//! after merges compacted every ghost away. Admission is now+//! per-segment via the ghost-position bitmap: empty bitmaps proceed+//! (live == physical), dirty ones still bail.+//!+//! The invariant under test is fast-path/brute-path agreement, plus the+//! served/bailed signal from `aggs::fast_path_aggs_served` for the cases+//! where which executor answered IS the regression.++use serde_json::json;+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::Schema;+use xerj_engine::aggs::fast_path_aggs_served;+use xerj_engine::{Engine, Index};+use xerj_query::parse_request;++fn make_engine(dir: &TempDir) -> Engine {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ Engine::new(config).expect("engine::new")+}++async fn run(idx: &std::sync::Arc<Index>, body: serde_json::Value) -> serde_json::Value {+ let req = parse_request(&body).unwrap();+ let res = idx.search(&req).await.unwrap();+ json!({+ "total": res.total.value,+ "aggs": res.aggs.clone().unwrap_or(json!(null)),+ })+}++/// 12,000 flushed docs — past `FAST_AGG_MIN_DOCS` (10,000) — cycling the+/// `text` field through present / JSON-null / absent / empty-string, so a+/// single segment's keyword column carries non-null rows, null rows for+/// both missing shapes, and the ES-visible `""` (which counts as present).+async fn seed_exists_shapes(idx: &std::sync::Arc<Index>) {+ for i in 0..12_000u32 {+ let text = match i % 4 {+ 0 => json!("present"), // column row, value ""+ 1 => json!(null), // column row = null+ 2 => json!(null), // key omitted entirely below+ _ => json!(""), // column row, empty string — PRESENT+ };+ let mut doc = json!({ "extension": if i % 3 == 0 { "css" } else { "gz" }, "i": i });+ if i % 4 != 2 {+ doc["text"] = text;+ }+ idx.index_document(Some(i.to_string()), doc).await.unwrap();+ }+ idx.flush().await.unwrap();+}++fn exists_terms_query() -> serde_json::Value {+ // The finalize-verify window shape: a terms-set filter conjoined with+ // exists, answering a terms agg. Before #1260 the exists leaf alone+ // pushed this whole request to the brute path.+ json!({+ "query": {+ "bool": {+ "filter": [+ { "terms": { "extension": ["css", "gz"] } },+ { "exists": { "field": "text" } }+ ]+ }+ },+ "size": 0,+ "aggs": { "by_ext": { "terms": { "field": "extension" } } }+ })+}++#[tokio::test]+async fn exists_in_top_filter_matches_brute() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("existsq", Schema::empty()).unwrap();+ let idx = engine.get_index("existsq").unwrap();+ seed_exists_shapes(&idx).await;++ let before = fast_path_aggs_served();+ let fast = run(&idx, exists_terms_query()).await;+ let served = fast_path_aggs_served() - before;+ assert_eq!(+ served, 1,+ "the terms+exists conjunction must serve columnarly"+ );++ // ES semantics pinned on the reference too: `""` is present, JSON null+ // and absent are not — 2 of the 4 cycle positions match (3,000 + 3,000).+ // css among them: i%4 ∈ {0,3} ∧ i%3 == 0 → 2 per period-12 → 2,000;+ // gz gets the other 4,000.+ assert_eq!(fast["total"], 6_000);+ assert_eq!(fast["aggs"]["by_ext"]["buckets"][0]["key"], "gz");+ assert_eq!(fast["aggs"]["by_ext"]["buckets"][0]["doc_count"], 4_000);+ assert_eq!(fast["aggs"]["by_ext"]["buckets"][1]["key"], "css");+ assert_eq!(fast["aggs"]["by_ext"]["buckets"][1]["doc_count"], 2_000);++ // Brute reference via an overwrite (records a ghost, trips admission).+ idx.index_document(+ Some("0".to_string()),+ json!({ "extension": "css", "i": 0, "text": "present" }),+ )+ .await+ .unwrap();+ let brute = run(&idx, exists_terms_query()).await;+ assert_eq!(+ fast, brute,+ "columnar exists disagrees with the brute reference"+ );+}++/// `exists` over a NUMERIC column (the `NumExists` arm) — parity with+/// `value_present` on the brute path.+#[tokio::test]+async fn exists_on_numeric_field_matches_brute() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("existsn", Schema::empty()).unwrap();+ let idx = engine.get_index("existsn").unwrap();+ for i in 0..12_000u32 {+ let mut doc = json!({ "group": if i % 2 == 0 { "a" } else { "b" } });+ if i % 3 != 0 {+ doc["v"] = serde_json::Value::from(i as f64); // absent for every third doc+ }+ idx.index_document(Some(i.to_string()), doc).await.unwrap();+ }+ idx.flush().await.unwrap();++ let q = json!({+ "query": { "exists": { "field": "v" } },+ "size": 0,+ "aggs": {+ "n": { "value_count": { "field": "v" } },+ "by_group": { "terms": { "field": "group" } }+ }+ });+ let before = fast_path_aggs_served();+ let fast = run(&idx, q.clone()).await;+ assert_eq!(fast_path_aggs_served() - before, 1);+ assert_eq!(fast["total"], 8_000);+ assert_eq!(fast["aggs"]["n"]["value"], 8_000);++ // Byte-identical overwrite of id 0 — whose `v` is ABSENT (0 % 3 == 0),+ // so the body must omit it too, or the reference corpus changes.+ idx.index_document(Some("0".to_string()), json!({ "group": "a" }))+ .await+ .unwrap();+ let brute = run(&idx, q).await;+ assert_eq!(+ fast, brute,+ "numeric exists disagrees with the brute reference"+ );+}++/// Meta-field `exists` has no columnar form (brute answers it from+/// bookkeeping) — the fast path must BAIL, not answer it empty.+#[tokio::test]+async fn exists_on_meta_field_bails_to_brute() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("existsmeta", Schema::empty()).unwrap();+ let idx = engine.get_index("existsmeta").unwrap();+ for i in 0..12_000u32 {+ idx.index_document(Some(i.to_string()), json!({ "i": i }))+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let q = json!({+ "query": { "exists": { "field": "_id" } },+ "size": 0,+ "aggs": { "n": { "value_count": { "field": "i" } } }+ });+ let before = fast_path_aggs_served();+ let out = run(&idx, q).await;+ assert_eq!(+ fast_path_aggs_served() - before,+ 0,+ "meta-field exists must bail"+ );+ assert_eq!(out["total"], 12_000, "every doc has an _id");+}++/// The admission gate's safety half: an overwrite whose superseded row is+/// still resident (no merge yet) keeps the fast path OFF, and the live+/// corpus answer is unchanged by a byte-identical overwrite.+#[tokio::test]+async fn unmerged_ghosts_still_bail() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("ghosts", Schema::empty()).unwrap();+ let idx = engine.get_index("ghosts").unwrap();+ for i in 0..12_000u32 {+ idx.index_document(+ Some(i.to_string()),+ json!({ "group": if i % 2 == 0 { "a" } else { "b" }, "v": i as f64 }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let q = json!({+ "query": { "term": { "group": "a" } },+ "size": 0,+ "aggs": { "total_v": { "sum": { "field": "v" } } }+ });+ let clean = run(&idx, q.clone()).await;+ let served_clean = fast_path_aggs_served();++ // Overwrite + delete WITHOUT merging: the flushed segment still holds+ // the superseded rows — bitmaps are dirty.+ idx.index_document(Some("0".to_string()), json!({ "group": "a", "v": 0.0 }))+ .await+ .unwrap();+ idx.delete_document("2").await.unwrap();++ let dirty = run(&idx, q).await;+ assert_eq!(+ fast_path_aggs_served(),+ served_clean,+ "a segment with resident ghosts must not serve columnarly"+ );+ // Live corpus: doc 0 byte-identical, doc 2 deleted (was group a, v=2).+ assert_eq!(clean["total"], 6_000);+ assert_eq!(dirty["total"], 5_999);+ assert_eq!(+ clean["aggs"]["total_v"]["value"].as_f64().unwrap()+ - dirty["aggs"]["total_v"]["value"].as_f64().unwrap(),+ 2.0+ );+}++/// The #1260 headline: after merges compact the ghosts away the index+/// RE-QUALIFIES for the fast path even though `ghost_events` (monotonic)+/// never resets — with a live memtable on top, the production shape of the+/// autoindex-catalog (rewritten continuously, merged in the background).+#[tokio::test]+async fn merged_delete_history_re_qualifies_for_fast_path() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("readmit", Schema::empty()).unwrap();+ let idx = engine.get_index("readmit").unwrap();+ for i in 0..12_000u32 {+ idx.index_document(+ Some(i.to_string()),+ json!({ "extension": if i % 3 == 0 { "css" } else { "gz" }, "i": i }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ // Delete history: 100 overwrites (changed bodies) + 50 deletes.+ for i in 0..100u32 {+ idx.index_document(+ Some(i.to_string()),+ json!({ "extension": "css", "i": i, "rewritten": true }),+ )+ .await+ .unwrap();+ }+ for i in 100..150u32 {+ idx.delete_document(&i.to_string()).await.unwrap();+ }+ idx.flush().await.unwrap();+ idx.force_merge(1).await.unwrap();++ // A live memtable on top of the merged index (the catalog's steady+ // state): fresh ids only, so every entry is in-memory-live.+ for i in 12_000..12_200u32 {+ idx.index_document(Some(i.to_string()), json!({ "extension": "css", "i": i }))+ .await+ .unwrap();+ }++ let q = json!({+ "query": {+ "bool": {+ "filter": [+ { "term": { "extension": "css" } },+ { "exists": { "field": "i" } }+ ]+ }+ },+ "size": 0,+ "aggs": { "by_ext": { "terms": { "field": "extension" } } }+ });+ let before = fast_path_aggs_served();+ let fast = run(&idx, q.clone()).await;+ assert_eq!(+ fast_path_aggs_served() - before,+ 1,+ "a merged index with clean bitmaps must serve columnarly despite \+ its monotonic ghost history"+ );++ // Brute reference: overwrite one merged doc byte-identically (trips+ // admission without changing the live corpus).+ idx.index_document(+ Some("0".to_string()),+ json!({ "extension": "css", "i": 0, "rewritten": true }),+ )+ .await+ .unwrap();+ let brute = run(&idx, q).await;+ assert_eq!(fast, brute, "admitted fast path disagrees with brute");++ // Arithmetic: originals css = |{i < 12_000 : i % 3 == 0}| = 4_000;+ // overwrites 0..99 moved ALL 100 to css, of which 34 were css before+ // (i%3==0 for i<100) → 4_000 + 100 − 34 = 4_066; deletes 100..149+ // removed 16 css (multiples of 3 in [100,150): 102..147) → 4_050;+ // memtable +200 css → 4_250.+ assert_eq!(fast["total"], 4_250);+}++/// A memtable doc whose value for the exists field is a JSON OBJECT (the+/// field is scalar in every segment) — `value_present` says present on the+/// brute query path; `doc_matches_filter` flattened objects to `[]` and+/// disagreed. The alignment is pinned here.+#[tokio::test]+async fn object_valued_memtable_doc_counts_as_exists() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("objmem", Schema::empty()).unwrap();+ let idx = engine.get_index("objmem").unwrap();+ for i in 0..12_000u32 {+ idx.index_document(+ Some(i.to_string()),+ json!({ "extension": "seg", "text": "scalar" }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ // Buffered (un-flushed) docs with an object under the columned field.+ for i in 12_000..12_100u32 {+ idx.index_document(+ Some(i.to_string()),+ json!({ "extension": "mem", "text": { "nested": true } }),+ )+ .await+ .unwrap();+ }++ let q = json!({+ "query": { "exists": { "field": "text" } },+ "size": 0,+ "aggs": { "by_ext": { "terms": { "field": "extension" } } }+ });+ let before = fast_path_aggs_served();+ let fast = run(&idx, q.clone()).await;+ assert_eq!(fast_path_aggs_served() - before, 1);+ assert_eq!(+ fast["total"], 12_100,+ "objects count as present on both paths"+ );++ idx.index_document(+ Some("0".to_string()),+ json!({ "extension": "seg", "text": "scalar" }),+ )+ .await+ .unwrap();+ let brute = run(&idx, q).await;+ assert_eq!(fast, brute, "memtable object exists disagrees with brute");+}