Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(search): bound the delete-present FTS scan to O(cap) (#179)

xerj-org7e577050bc82
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 92bc19c12..2d635a515 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -14458,13 +14458,44 @@ impl Index {
// 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 {
+ let fts_cap = if count_only || sort_topk.is_some() {
usize::MAX
} else {
+ // #179 — `deletes_present` no longer forces the
+ // unbounded scan. The heap is bounded to
+ // `materialisation_limit`; LIVE matches are counted by
+ // an observer over the full (still-scanned) match set
+ // below, and only a segment that truncates a ghost
+ // re-expands (rare). See `search_bounded_observed`.
materialisation_limit
};
if fts_has_field {
- let bounded = searcher.search_bounded(&fq, fts_cap, false);
+ // #179 — under deletes, build the segment ghost bitmap
+ // up front and count dead matches with an observer while
+ // the (bounded) scan visits every posting, so the heap
+ // stays O(cap) yet the live count stays exact (b7 DEFECT
+ // 1c). On the no-delete hot path we call the plain
+ // `search_bounded` (byte-identical to before).
+ let ghost_bm: Option<Arc<Vec<u64>>> = if deletes_present {
+ self.ghost_positions_for(seg_id.as_str(), meta.doc_count)
+ } else {
+ None
+ };
+ let mut dead_matches: u64 = 0;
+ let bounded = if deletes_present {
+ let bm = ghost_bm.as_deref();
+ searcher.search_bounded_observed(&fq, fts_cap, false, |doc_id| {
+ if let Some(bm) = bm {
+ let w =
+ bm.get((doc_id / 64) as usize).copied().unwrap_or(0);
+ if (w >> (doc_id % 64)) & 1 == 1 {
+ dead_matches += 1;
+ }
+ }
+ })
+ } else {
+ searcher.search_bounded(&fq, fts_cap, false)
+ };
// Record a deadline trip regardless of Ok/Err —
// the expansion may have stopped early either
// way (RC4 blocker 12).
@@ -14483,35 +14514,54 @@ impl Index {
// that wrote tombstones/overwrites and the merge
// that purges them it counts deleted docs and
// superseded old versions (live-observed 40 vs
- // ES 26). With ghosts present the hit list is
- // complete (`fts_cap == usize::MAX` above), so
- // tally only positions that are LIVE per the
- // version map, via the per-(segment, ghost-epoch)
- // cached bitmap. Physical-count fallback only if
- // the stored section can't be indexed (legacy
- // behaviour, matching the materialisation
- // fallback's failure mode).
- if deletes_present {
- match self.ghost_positions_for(seg_id.as_str(), meta.doc_count)
- {
- Some(ghosts) => {
- let live = seg_hits
+ // ES 26). #179 — the LIVE total is
+ // `seg_total - dead_matches`, where `dead_matches`
+ // was tallied by the observer above over the FULL
+ // match set (the scan visits every posting even when
+ // the heap is bounded to the page cap), so this is
+ // exact WITHOUT forcing `fts_cap == usize::MAX` to
+ // hold the complete hit list. `dead_matches` is 0
+ // unless `deletes_present` and the ghost bitmap was
+ // built — matching the old physical-count fallback.
+ total_count += seg_total.saturating_sub(dead_matches);
+ // #179 — materialisation correctness under deletes.
+ // `seg_hits` is the top-`cap` by SCORE and the walk
+ // below skips ghosts inline. Underfill is possible
+ // ONLY when this segment truncated its match set
+ // (`seg_total > cap`) AND a ghost sits INSIDE the
+ // kept top-`cap`: that ghost holds a slot a lower-
+ // scored live hit (now stranded past the bound) would
+ // have taken. A ghost that scored below the cap was
+ // never kept and displaces nothing, so we test the
+ // returned slice, not the whole match set — an
+ // index with an old low-scoring delete keeps the
+ // bounded fast path. When it can underfill, re-expand
+ // THIS segment uncapped so the walk sees every live
+ // candidate (rare). The exact live count above used
+ // `dead_matches` over the FULL set and is untouched.
+ let mut seg_hits = seg_hits;
+ if deletes_present && fts_cap != usize::MAX && seg_total > fts_cap as u64
+ {
+ let dead_in_top = ghost_bm
+ .as_deref()
+ .map(|bm| {
+ seg_hits
.iter()
.filter(|sh| {
- ghosts
- .get((sh.doc_id / 64) as usize)
- .is_none_or(|w| {
- (w >> (sh.doc_id % 64)) & 1 == 0
- })
+ bm.get((sh.doc_id / 64) as usize).is_some_and(
+ |w| (w >> (sh.doc_id % 64)) & 1 == 1,
+ )
})
.count()
- as u64;
- total_count += live;
+ })
+ .unwrap_or(0);
+ if dead_in_top > 0 {
+ if let Ok((full, _)) =
+ searcher.search_bounded(&fq, usize::MAX, false)
+ {
+ seg_hits = full;
}
- None => total_count += seg_total,
}
- } else {
- total_count += seg_total;
}
// Field-sorted FTS (e.g. bool/match under the
// implicit `@timestamp desc` index sort): the
@@ -14592,10 +14642,30 @@ impl Index {
// defined only once the collector is at its cap
// (below the cap nothing has to be displaced). A
// segment is opened when it can beat that, and its
- // descending run is walked until it can't; the
- // overflow is trimmed back to the cap by score
- // right after. Bounded by 2×cap in the worst case.
- let page_worst: Option<f32> = if sort_topk.is_none()
+ // descending run is walked until it can't.
+ //
+ // #179 — `page_worst` is maintained INCREMENTALLY
+ // inside the walk (see the push site below), not
+ // only recomputed once per segment here, and the
+ // overflow is trimmed back to the cap the moment
+ // `all_hits` exceeds 2×cap — not just after the
+ // whole segment run. That is what actually holds
+ // the admission walk to O(cap) work and a 2×cap
+ // peak, and it does so EVEN under `deletes_present`,
+ // where `fts_cap == usize::MAX` (above) hands this
+ // loop a `seg_hits` spanning every physical match.
+ // Before #179 that combination broke the bound: the
+ // fill-up segment left `page_worst == None` for its
+ // whole run, so it hydrated `_source` for every one
+ // of the O(matches) hits and grew `all_hits` to
+ // O(matches) before the end-of-run trim — an ~8×
+ // read regression on any index that had ever seen a
+ // delete/overwrite (`ghost_events()` is monotonic
+ // and global, so that branch is permanent). (The
+ // O(matches) score-sort *inside* `search_bounded`
+ // is a separate cost governed by `fts_cap`, not by
+ // this admission walk, and is out of scope here.)
+ let mut page_worst: Option<f32> = if sort_topk.is_none()
&& !count_only
&& all_hits.len() >= materialisation_limit
{
@@ -14611,6 +14681,23 @@ impl Index {
} else {
None
};
+ // The `sort_topk.is_some()` disjunct keeps the
+ // segment unconditionally enterable on the
+ // field-sort path. That is deliberate and settled
+ // (#179): the sorted path NEVER pushes to
+ // `all_hits` — every admission routes through
+ // `topk.offer()` (see the push site below and the
+ // sorted admission macros), so `all_hits.len()`
+ // stays 0 and the second disjunct (`0 < cap`) is
+ // ALREADY unconditionally true for it. The explicit
+ // `sort_topk.is_some()` therefore changes no
+ // decision today; it makes the invariant visible and
+ // future-proofs it, since were `all_hits` ever
+ // pre-seeded past the cap by an earlier stage the
+ // bare length gate would wrongly begin skipping later
+ // segments and drop global sort candidates. The
+ // bounded `SortTopK` heap — not this cap — bounds the
+ // sorted path's memory.
let seg_can_enter = sort_topk.is_some()
|| all_hits.len() < materialisation_limit
|| seg_hits
@@ -14698,25 +14785,68 @@ impl Index {
.and_then(|d| d.get(pos as usize).cloned())
}
};
+ // #179 — reduce `all_hits` to the best
+ // `materialisation_limit` hits seen so far
+ // by the SAME comparator the final page sort
+ // uses (score DESC, seq_no ASC, `_id` ASC),
+ // and return the surviving worst score (the
+ // new cap-th score, = the min of the kept
+ // set). Shared by the in-walk 2×cap eager
+ // trim and the end-of-run trim so admission
+ // and final ordering always agree.
+ let trim_to_cap = |hits: Vec<Hit>| -> (Vec<Hit>, Option<f32>) {
+ let mut decorated: Vec<(u64, Hit)> = hits
+ .into_iter()
+ .map(|h| {
+ (
+ self.lookup_seq_no(&h.id)
+ .unwrap_or(u64::MAX),
+ h,
+ )
+ })
+ .collect();
+ decorated.sort_by(|a, b| {
+ b.1.score
+ .partial_cmp(&a.1.score)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then_with(|| a.0.cmp(&b.0))
+ .then_with(|| a.1.id.cmp(&b.1.id))
+ });
+ decorated.truncate(materialisation_limit);
+ let worst = decorated.last().map(|(_, h)| h.score);
+ let kept =
+ decorated.into_iter().map(|(_, h)| h).collect();
+ (kept, worst)
+ };
for sh in &seg_hits {
// `seg_hits` descends by score, so once
- // a hit cannot displace the worst kept
- // one neither can any hit after it —
+ // a hit's score is STRICTLY below the
+ // worst kept score, neither it nor any
+ // hit after it can displace a kept hit —
// the rest are already counted in
// `total_count`, so stop decoding
- // sources. While the collector is
- // still below its cap `page_worst` is
- // `None` and everything this segment
- // offers is taken (at most one cap's
- // worth; the trim below restores the
- // bound). 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.
+ // sources. #179 — `page_worst` is now
+ // maintained incrementally at the push
+ // site below, so this early-out fires
+ // WITHIN the fill-up segment too (once
+ // the collector first reaches its cap),
+ // not only in later segments; that is
+ // what bounds the walk under
+ // `deletes_present`. The comparison is
+ // STRICT (`<`): a hit that TIES the
+ // worst kept score is still hydrated so
+ // the trim's comparator (seq_no/`_id`)
+ // can rank it — a `<=` here would drop
+ // the tie-winners of a boundary or
+ // all-equal top cluster and move the
+ // page. 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()
- && page_worst.is_some_and(|worst| sh.score <= worst)
+ && page_worst.is_some_and(|worst| sh.score < worst)
{
break;
}
@@ -14776,6 +14906,41 @@ impl Index {
topk.offer(hit, seq);
} else {
all_hits.push(hit);
+ // #179 — hold the collector at
+ // O(cap). Once it first reaches the
+ // cap, establish `page_worst` so the
+ // STRICT early-out above can stop the
+ // walk within this very segment; once
+ // it exceeds 2×cap, trim back to the
+ // best cap by the final comparator
+ // and refresh `page_worst` to the new
+ // cap-th score. Between cap and 2×cap
+ // no recompute is needed: every hit
+ // pushed since the last (re)establish
+ // scored `>= page_worst` (it did not
+ // break), so the running min — and
+ // hence `page_worst` — is unchanged.
+ if all_hits.len() >= materialisation_limit {
+ if all_hits.len()
+ > materialisation_limit.saturating_mul(2)
+ {
+ let (kept, worst) = trim_to_cap(
+ std::mem::take(&mut all_hits),
+ );
+ all_hits = kept;
+ page_worst = worst;
+ } else if page_worst.is_none() {
+ page_worst = all_hits
+ .iter()
+ .map(|h| h.score)
+ .fold(None, |acc: Option<f32>, s| {
+ Some(match acc {
+ Some(a) if a <= s => a,
+ _ => s,
+ })
+ });
+ }
+ }
}
}
// #177 — trim the overflow back to the cap
@@ -14788,31 +14953,20 @@ impl Index {
// agree and the page is stable under any
// cap: `size:1` and `size:200` return the
// same top hit, and adding `highlight`
- // returns the same page.
+ // returns the same page. #179 — the in-walk
+ // eager trim already caps `all_hits` at
+ // 2×cap during the segment; this end-of-run
+ // trim is the final normalisation back to
+ // exactly the cap before the next segment.
if sort_topk.is_none()
&& all_hits.len() > materialisation_limit
{
- let mut decorated: Vec<(u64, Hit)> =
- std::mem::take(&mut all_hits)
- .into_iter()
- .map(|h| {
- (
- self.lookup_seq_no(&h.id)
- .unwrap_or(u64::MAX),
- h,
- )
- })
- .collect();
- decorated.sort_by(|a, b| {
- b.1.score
- .partial_cmp(&a.1.score)
- .unwrap_or(std::cmp::Ordering::Equal)
- .then_with(|| a.0.cmp(&b.0))
- .then_with(|| a.1.id.cmp(&b.1.id))
- });
- decorated.truncate(materialisation_limit);
- all_hits =
- decorated.into_iter().map(|(_, h)| h).collect();
+ // `page_worst` is recomputed fresh at the
+ // next segment's entry, so the trimmed
+ // worst is not needed past here.
+ let (kept, _worst) =
+ trim_to_cap(std::mem::take(&mut all_hits));
+ all_hits = kept;
}
}
}
diff --git a/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs b/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs
new file mode 100644
index 000000000..369293dae
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs
@@ -0,0 +1,326 @@
+//! Regression test for #179 — a scored FTS search over an index that has
+//! ghosts (a delete or an overwrite anywhere in its history) must still
+//! return the true global top-k, and the bounded hit collector must stay
+//! O(cap) while doing it.
+//!
+//! ## What #179 was
+//!
+//! `deletes_present` (any flushed tombstone, or `ghost_events() > 0`) forces
+//! the per-segment FTS cap to `usize::MAX`, so `search_bounded` hands the
+//! merge a `seg_hits` list spanning EVERY physical match — the cap can no
+//! longer bound it, because with ghosts a top-`cap`-by-score slice could be
+//! partly tombstoned and underfill the page. `ghost_events()` is monotonic
+//! and index-global, so after a single delete/overwrite ANYWHERE this branch
+//! is permanent for every later query.
+//!
+//! Before the fix the cross-segment merge only bounded itself when the cap
+//! bounded `seg_hits`: the fill-up segment left `page_worst == None` for its
+//! whole run, so it hydrated `_source` for every one of the O(matches) hits
+//! and grew `all_hits` to O(matches) before the end-of-run trim. On any
+//! mature index (one that had ever seen a delete) a `size:5` scored query
+//! therefore paid O(total_matches) source parses and memory — the ~8×
+//! read regression this test guards against.
+//!
+//! ## What this test can and cannot see
+//!
+//! The public API exposes no "documents hydrated" counter, so the O(cap)
+//! bound itself is not directly observable here (documented limitation).
+//! What IS observable, and what the pre-fix path would only satisfy at
+//! O(matches) cost, is the *contract* the bound must preserve while it trims:
+//! on a deliberately large match set (well above the 256-doc cap) with ghosts
+//! present, a small `size` must still return the exact global top-k by score,
+//! must exclude deleted/superseded ghosts, and must not move when a
+//! `highlight` block is added (#177) or when the page size changes. The bound
+//! itself is enforced structurally in `index.rs` by the incremental
+//! `page_worst` early-out plus the 2×cap eager trim; these assertions pin the
+//! behaviour that bound must not break.
+
+use serde_json::json;
+use std::sync::Arc;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::Schema;
+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")
+}
+
+/// A weak (low-BM25) body: a single buried occurrence of the term in a long
+/// field. The field GROWS with `i`, so BM25 length-normalisation gives every
+/// weak doc a DISTINCT, strictly decreasing score — all far below the short
+/// strong docs. The distinct scores matter: they are what let the collector's
+/// strict early-out fire at the cap instead of hydrating the whole match set.
+fn weak_body(i: usize) -> String {
+ let pad = "pad ".repeat(40 + i * 3);
+ format!("{pad} quicklist {pad}")
+}
+
+fn match_body(size: usize, highlight: bool) -> xerj_query::ast::SearchRequest {
+ let mut b = json!({
+ "size": size,
+ "query": {"match": {"body": "quicklist"}}
+ });
+ if highlight {
+ b.as_object_mut()
+ .unwrap()
+ .insert("highlight".into(), json!({"fields": {"body": {}}}));
+ }
+ parse_request(&b).expect("parse_request")
+}
+
+/// `(id, score)` page fingerprint.
+fn page(hits: &[xerj_query::Hit]) -> Vec<(String, f32)> {
+ hits.iter().map(|h| (h.id.clone(), h.score)).collect()
+}
+
+/// Build the corpus: a big low-scoring segment (`weak` docs, distinct
+/// decreasing scores) plus a small high-scoring segment (5 `strong` docs whose
+/// members are the true, tie-free top-5). `weak` is chosen > 256 by callers so
+/// the match set exceeds the collector cap.
+async fn build_corpus(idx: &Arc<Index>, weak: usize) {
+ // ── Segment 0: many weak matches, distinct decreasing scores ─────────
+ for i in 0..weak {
+ idx.index_document(Some(format!("weak{i:03}")), json!({"body": weak_body(i)}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+
+ // ── Segment 1: 5 strong, strictly-decreasing-score matches ───────────
+ // Short field + repeated term → high BM25. Strictly decreasing term
+ // frequency keeps the top-5 tie-free, so it has exactly one right answer.
+ for i in 0..5 {
+ let body = "quicklist ".repeat(10 - i) + &"filler ".repeat(i * 4);
+ idx.index_document(Some(format!("strong{i}")), json!({"body": body}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+}
+
+/// The core #179 guard: a large match set (> cap) with ghosts present,
+/// `size:5` must return the exact global top-5, exclude the ghosts, and stay
+/// #177-stable.
+#[tokio::test]
+async fn size5_returns_global_top5_under_ghosts_on_large_matchset() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("g1", Schema::empty()).unwrap();
+ let idx = engine.get_index("g1").unwrap();
+
+ // 360 weak + 5 strong = 365 physical matches — comfortably over the 256
+ // collector cap that `deletes_present` pins the query to.
+ build_corpus(&idx, 360).await;
+
+ // ── Introduce ghosts ─────────────────────────────────────────────────
+ // A DELETE (tombstone) and an OVERWRITE (superseded old version) — both
+ // land in already-flushed segment 0, so their stale copies are ghosts the
+ // scan must skip, and either one alone flips `deletes_present` (hence
+ // `fts_cap == usize::MAX`) permanently for every query below.
+ assert!(
+ idx.delete_document("weak000").await.unwrap(),
+ "weak000 should have existed to delete"
+ );
+ // Overwrite weak001: its live version moves to the memtable, its segment-0
+ // copy becomes a superseded ghost that the scan must not double-count.
+ idx.index_document(Some("weak001".into()), json!({"body": weak_body(1)}))
+ .await
+ .unwrap();
+
+ // Live matches: 360 weak - 1 deleted = 359 (weak001 overwritten, still
+ // matches) + 5 strong = 364.
+ let expected_total: u64 = 364;
+
+ // ── Ground truth: full materialisation, then the top 5 ───────────────
+ let full = idx.search(&match_body(500, false)).await.unwrap();
+ assert_eq!(
+ full.total.value, expected_total,
+ "live total wrong under ghosts (deleted/superseded copies leaked into the count)"
+ );
+ let mut truth = page(&full.hits);
+ truth.truncate(5);
+ assert!(
+ truth.iter().all(|(id, _)| id.starts_with("strong")),
+ "sanity: the 5 short docs must be the global top-5, got {truth:?}"
+ );
+ assert!(
+ full.hits.iter().all(|h| h.id != "weak000"),
+ "deleted doc weak000 leaked into results"
+ );
+ assert!(
+ full.hits.iter().filter(|h| h.id == "weak001").count() <= 1,
+ "overwritten doc weak001 returned as a duplicate (stale ghost not skipped)"
+ );
+
+ // ── The #179 assertion: the bounded `size:5` page == the true top-5 ──
+ // On the pre-fix code this same answer required hydrating all 364 live
+ // matches; the bound must produce it while trimming to O(cap).
+ let small = idx.search(&match_body(5, false)).await.unwrap();
+ assert_eq!(
+ small.total.value, expected_total,
+ "size:5 reported a different total than the full run under ghosts"
+ );
+ assert_eq!(
+ page(&small.hits),
+ truth,
+ "size:5 page is not the global top-5 under ghosts"
+ );
+
+ // ── #177 must still hold on the deletes-present path ─────────────────
+ let lit = idx.search(&match_body(5, true)).await.unwrap();
+ assert_eq!(
+ page(&small.hits),
+ page(&lit.hits),
+ "adding `highlight` changed the page under ghosts: without={:?} with={:?}",
+ page(&small.hits),
+ page(&lit.hits)
+ );
+ for h in &lit.hits {
+ let frags = h
+ .highlight
+ .as_ref()
+ .and_then(|m| m.get("body"))
+ .unwrap_or_else(|| panic!("hit {} has no `body` highlight", h.id));
+ assert!(
+ frags.iter().any(|f| f.contains("<em>quicklist</em>")),
+ "hit {} fragments do not mark the matched term: {frags:?}",
+ h.id
+ );
+ }
+}
+
+/// The #179 re-expand path, exercised end to end: a page that reaches PAST the
+/// strong docs and INTO the big, truncated, ghost-bearing segment. Under the
+/// observer fix that segment is scanned bounded (heap = cap) but re-expands
+/// uncapped because it truncated (`seg_total > cap`) AND holds ghosts
+/// (`dead_matches > 0`), so the walk still sees every live candidate. Without
+/// the re-expand the top-`cap`-by-score slice — whose highest members here are
+/// the very docs that were deleted/overwritten — would drop live hits and the
+/// page would be wrong. Asserted black-box against a full-materialisation
+/// ground truth, so it holds whatever the exact BM25 order turns out to be.
+#[tokio::test]
+async fn page_reaching_into_truncated_ghost_segment_is_exact() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("g3", Schema::empty()).unwrap();
+ let idx = engine.get_index("g3").unwrap();
+
+ // 360 weak (distinct DECREASING scores: weak000 is the highest-scoring
+ // weak doc) + 5 strong. Match set 365 > 256 cap.
+ build_corpus(&idx, 360).await;
+
+ // Ghost the TWO highest-scoring weak docs — exactly the ones a bounded
+ // top-cap slice keeps first, so a broken bound would surface them.
+ assert!(idx.delete_document("weak000").await.unwrap());
+ idx.index_document(Some("weak001".into()), json!({"body": weak_body(1)}))
+ .await
+ .unwrap();
+
+ let expected_total: u64 = 364;
+
+ // Ground truth: full materialisation.
+ let full = idx.search(&match_body(500, false)).await.unwrap();
+ assert_eq!(full.total.value, expected_total, "live total wrong under ghosts");
+
+ // Pages that reach well into the weak segment must equal the ground-truth
+ // prefix — this is the assertion the re-expand exists to satisfy.
+ for size in [10usize, 25, 50, 100] {
+ let mut truth = page(&full.hits);
+ truth.truncate(size);
+ let r = idx.search(&match_body(size, false)).await.unwrap();
+ assert_eq!(r.total.value, expected_total, "size:{size} total drifted under ghosts");
+ assert_eq!(
+ page(&r.hits),
+ truth,
+ "size:{size} page reaching into the truncated ghost segment != global order"
+ );
+ assert!(
+ r.hits.iter().all(|h| h.id != "weak000"),
+ "size:{size}: deleted weak000 leaked into the page"
+ );
+ assert!(
+ r.hits.iter().filter(|h| h.id == "weak001").count() <= 1,
+ "size:{size}: overwritten weak001 returned as a duplicate (stale ghost not skipped)"
+ );
+ }
+}
+
+/// Cap-independence must hold on the `deletes_present` path too: the top hit of
+/// a `size:1` request is the top hit of a `size:200` request, unchanged by the
+/// presence of ghosts. This is the incremental `page_worst` doing its job — a
+/// worst-kept score frozen at segment entry would let the fill-up segment's
+/// arrival order leak into small pages.
+#[tokio::test]
+async fn top_hit_stable_across_page_sizes_under_ghosts() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("g2", Schema::empty()).unwrap();
+ let idx = engine.get_index("g2").unwrap();
+
+ build_corpus(&idx, 300).await;
+
+ // One delete → `deletes_present` is now permanently true.
+ assert!(idx.delete_document("weak100").await.unwrap());
+
+ let deep = idx.search(&match_body(400, false)).await.unwrap();
+ let expected_top = (deep.hits[0].id.clone(), deep.hits[0].score);
+ assert_eq!(
+ expected_top.0, "strong0",
+ "sanity: strong0 is the global top hit"
+ );
+
+ for size in [1usize, 2, 5, 10, 50, 100] {
+ let r = idx.search(&match_body(size, false)).await.unwrap();
+ let got = (r.hits[0].id.clone(), r.hits[0].score);
+ assert_eq!(
+ got, expected_top,
+ "size:{size} returned a different top hit under ghosts (bounded merge lost the global top-k)"
+ );
+ }
+}
+
+/// Stress guard for the re-expand fallback at scale: a big single segment
+/// (well over the cap) whose HIGHEST-scoring doc is a ghost, so every page that
+/// reaches the top must skip it via an uncapped re-expand and still return the
+/// exact global order. This is the large-match-set analogue of
+/// `page_reaching_into_truncated_ghost_segment_is_exact`; it exists because the
+/// bounded scan sheds the pre-#179 full-set sort/allocation here — the win that
+/// grows with the match-set size — and this pins the correctness that shedding
+/// must preserve.
+#[tokio::test]
+async fn large_single_segment_with_top_ghost_returns_exact_order() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("g4", Schema::empty()).unwrap();
+ let idx = engine.get_index("g4").unwrap();
+
+ // 1500 distinct-scoring matches in ONE segment; weak0000 is the top.
+ let n = 1500usize;
+ for i in 0..n {
+ idx.index_document(Some(format!("weak{i:04}")), json!({"body": weak_body(i)}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+
+ // Delete the top-scorer (inside the kept top-cap → forces the re-expand)
+ // and overwrite the runner-up (superseded ghost).
+ assert!(idx.delete_document("weak0000").await.unwrap());
+ idx.index_document(Some("weak0001".into()), json!({"body": weak_body(1)}))
+ .await
+ .unwrap();
+
+ let full = idx.search(&match_body(500, false)).await.unwrap();
+ assert_eq!(full.total.value, (n as u64) - 1, "live total wrong under a top ghost");
+ for size in [10usize, 50, 200] {
+ let mut truth = page(&full.hits);
+ truth.truncate(size);
+ let r = idx.search(&match_body(size, false)).await.unwrap();
+ assert_eq!(page(&r.hits), truth, "size:{size} order wrong with a top-scoring ghost");
+ assert!(r.hits.iter().all(|h| h.id != "weak0000"), "deleted top-scorer leaked");
+ }
+}
diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rs
index 7415d8648..b7069bff7 100644
--- a/engine/crates/xerj-fts/src/search.rs
+++ b/engine/crates/xerj-fts/src/search.rs
@@ -505,10 +505,38 @@ impl FtsSearcher {
query: &Query,
cap: usize,
explain: bool,
+ ) -> Result<(Vec<ScoredHit>, u64)> {
+ // The no-op observer monomorphises away, so this stays byte-identical to
+ // the pre-#179 bounded search on the hot (no-delete) path.
+ self.search_bounded_observed(query, cap, explain, |_| {})
+ }
+
+ /// Like [`Self::search_bounded`], but invokes `observe(doc_id)` once for
+ /// EVERY match in the full match set — before the `cap` is applied — so a
+ /// caller can derive an exact per-match statistic without materialising the
+ /// whole hit list. The returned total is the exact physical match count
+ /// regardless of `cap` ([`TopN`] counts every push).
+ ///
+ /// #179: the delete-present read path uses this to tally LIVE matches (via
+ /// the segment ghost bitmap) during a BOUNDED scan, instead of forcing
+ /// `cap == usize::MAX` purely to hold the complete hit list for the count.
+ /// The scan already visits every posting on the bounded path, so the
+ /// observer is free; the win is shedding the full-set sort and the
+ /// O(matches) `Vec` that the unbounded path built on any index that had ever
+ /// seen a delete.
+ pub fn search_bounded_observed<F: FnMut(u32)>(
+ &self,
+ query: &Query,
+ cap: usize,
+ explain: bool,
+ mut observe: F,
) -> Result<(Vec<ScoredHit>, u64)> {
if cap == usize::MAX {
let mut hits = self.execute(query, explain)?;
let total = hits.len() as u64;
+ for h in &hits {
+ observe(h.doc_id);
+ }
hits.sort_unstable();
return Ok((hits, total));
}
@@ -516,11 +544,15 @@ impl FtsSearcher {
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)?,
+ Query::Term(tq) => self.scan_term(tq, explain, |h| {
+ observe(h.doc_id);
+ top.push(h);
+ })?,
// 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)? {
+ observe(hit.doc_id);
top.push(hit);
}
}
@@ -550,17 +582,12 @@ impl FtsSearcher {
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.
+ /// Shared scoring scan used by both [`Self::execute_term`] (Vec) and the
+ /// bounded [`Self::search_bounded_observed`] path (which offers each scored
+ /// posting 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). Emits one `ScoredHit` per matching posting in ascending
+ /// doc_id order.
fn scan_term<F: FnMut(ScoredHit)>(
&self,
tq: &TermQuery,