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(#1023): complete matching_ids_sorted with a memtable leg (runner-only lost increments)

xerj-orga750983f6290
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 07d936f6d..5b5c513ef 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -17811,8 +17811,10 @@ impl Index {
/// over the corpus — the dominant cost of a default-size purge once the
/// per-page `_source` hydration was gone).
///
- /// Caller MUST flush first (same precondition as the paged loop): the
- /// memtable is not represented in any segment's id map.
+ /// Caller SHOULD flush first (same precondition as the paged loop): the
+ /// memtable leg below keeps the enumeration COMPLETE without it, but the
+ /// paged fallback arm the caller eventually runs for other query shapes
+ /// pages `_id`-keyset over on-disk segments only.
///
/// `None` = this query shape (or a segment without a complete id index)
/// is not served here — the caller falls back to the paged keyset loop,
@@ -17835,6 +17837,25 @@ impl Index {
/// enumeration cannot land inside that window. On `Poisoned` the answer
/// is `None` — the caller's paged arm runs `search()`, which surfaces the
/// poison as a real error instead of a silent no-op.
+ ///
+ /// COMPLETE, not just consistent (the runner-only #1023 residual):
+ /// admission alone made every capture consistent but left it INCOMPLETE —
+ /// the segment id maps say nothing about a doc whose live copy is still
+ /// memtable-only, so at any validated instant before the first drain (or
+ /// after a failed finalize restored a drained doc) the enumeration
+ /// answered `Some([])`, a perfectly consistent EMPTY match set, and the
+ /// by-query arms no-opped silently (`total:0 / failures:[]`). On CI's
+ /// 4-vCPU / `--test-threads=2` / slow-fsync runners sixteen concurrent
+ /// `_update_by_query` calls still lost fourteen of sixteen increments
+ /// (`left:2`) after the admission fix, while every local shape (40+
+ /// isolated, full-suite, `RUST_TEST_THREADS=2` on pinned cores) held the
+ /// entry-flush precondition that made the memtable-only instant
+ /// unreachable. The memtable leg removes the dependence on that
+ /// precondition entirely: the FTS memtable's live ids are captured inside
+ /// the SAME validated bracket (`fold_match_sources`'s capture shape), so
+ /// a doc is enumerated from its memtable copy until a flush's publish
+ /// bracket commits, and from its segment's id map from then on — never
+ /// from neither.
pub async fn matching_ids_sorted(&self, query: &QueryNode) -> Option<Vec<String>> {
use crate::collection_publication::ReadAdmission;
@@ -17861,9 +17882,40 @@ impl Index {
ReadAdmission::WriterActive => notified.await,
}
};
+ // BOTH legs captured inside ONE bracket (`fold_match_sources`'s
+ // capture shape): the memtable's live ids and the segment
+ // snapshot. A drain happens only inside a publication bracket
+ // whose commit follows the snapshot publish, so a validated pair
+ // cannot straddle a drain→publish window — every live doc is in
+ // exactly one leg (the sort+dedup below collapses an id that a
+ // concurrent update left in both).
+ let mem_ids = self.memtable.all_doc_ids();
let snap = self.store.snapshot();
- let mut ids: Vec<String> =
- Vec::with_capacity(snap.segments.iter().map(|m| m.doc_count as usize).sum());
+ let mut ids: Vec<String> = Vec::with_capacity(
+ mem_ids.len()
+ + snap
+ .segments
+ .iter()
+ .map(|m| m.doc_count as usize)
+ .sum::<usize>(),
+ );
+ // ── Memtable leg: a doc lives here from its write until a flush
+ // publish commits it into a segment. Deletes remove from the
+ // memtable, so the only liveness rule needed on top is the same
+ // version-map tombstone skip the segment leg applies.
+ for id in mem_ids {
+ if let Some(set) = &values {
+ if !set.contains(id.as_str()) {
+ continue;
+ }
+ }
+ if let Some(ver) = self.store.version_map.get(&id) {
+ if ver.deleted {
+ continue;
+ }
+ }
+ ids.push(id);
+ }
let mut unsupported = false;
for meta in snap.segments.iter() {
let map = match self.id_pos_map_for(meta.id.as_str(), meta.doc_count) {
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index 2850b3b16..c43616c0b 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -2734,6 +2734,66 @@ async fn test_matching_ids_sorted_linearized_against_concurrent_flush() {
}
}
+/// #1023 completeness twin (deterministic, no race): admission made every
+/// `matching_ids_sorted` capture CONSISTENT but left it INCOMPLETE — the
+/// segment id maps say nothing about a doc whose live copy is still
+/// memtable-only, so before the memtable leg the enumeration answered
+/// `Some([])` for a never-flushed doc: a perfectly consistent EMPTY match
+/// set that the by-query arms turn into a silent no-op
+/// (`total:0 / failures:[]`). This is the runner-only residual loss shape
+/// (CI lost 14 of 16 increments, `left:2`, after the admission fix alone);
+/// fails before the memtable leg with `ids == []`.
+#[tokio::test]
+async fn test_matching_ids_sorted_enumerates_memtable_only_documents() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ engine
+ .create_index("mis-memtable", Schema::empty())
+ .unwrap();
+ let idx = engine.get_index("mis-memtable").unwrap();
+
+ idx.index_document(Some("counter".into()), json!({"n": 0}))
+ .await
+ .unwrap();
+ // Deliberately NO flush: the doc's live copy is memtable-only and no
+ // segment id map mentions it.
+ let ids = idx
+ .matching_ids_sorted(&QueryNode::MatchAll)
+ .await
+ .expect("match_all is a supported shape");
+ assert_eq!(
+ ids,
+ vec!["counter".to_string()],
+ "a memtable-only doc is part of the live match set"
+ );
+
+ let ids = idx
+ .matching_ids_sorted(&QueryNode::Ids {
+ values: vec!["counter".to_string()],
+ })
+ .await
+ .expect("ids is a supported shape");
+ assert_eq!(
+ ids,
+ vec!["counter".to_string()],
+ "the ids selector resolves membership against the memtable leg too"
+ );
+
+ // And the same enumeration after a flush: the doc moves to the segment
+ // leg without ever being double-listed.
+ idx.flush().await.unwrap();
+ let ids = idx
+ .matching_ids_sorted(&QueryNode::MatchAll)
+ .await
+ .expect("match_all is a supported shape");
+ assert_eq!(
+ ids,
+ vec!["counter".to_string()],
+ "the flushed doc is enumerated exactly once from its segment"
+ );
+}
+
/// #1023: the flush-vs-collector race above, answered through the engine's
/// own `delete_by_query` (flush + collect + delete). Guards that the
/// admission change cannot make a concurrent purge storm deadlock, error, or
@@ -2765,12 +2825,25 @@ async fn test_concurrent_delete_by_query_purges_the_document() {
}));
}
let mut seen: u64 = 0;
+ let mut deleted_sum: u64 = 0;
for task in tasks {
let (total, deleted) = task.await.unwrap().unwrap();
- assert_eq!(deleted, total, "no partial purges");
+ // NOT `deleted == total`: a runner that collected the doc can still
+ // delete nothing when another runner's delete of the same id landed
+ // between its collection and its `delete_document` — the loser's
+ // delete is a clean no-op there, ES charges it to version
+ // conflicts, and no work is lost (the final get below proves the
+ // purge happened). `delete_by_query` itself already reports
+ // `total.max(deleted)`, so `total` is allowed to exceed `deleted`.
+ assert!(deleted <= total, "deleted cannot exceed the collected set");
seen += total;
+ deleted_sum += deleted;
}
assert!(seen >= 1, "at least one runner must have matched the doc");
+ assert!(
+ deleted_sum >= 1,
+ "at least one runner must have actually deleted the doc"
+ );
assert_eq!(
idx.get_document("counter").await.unwrap(),