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(#950): id-position maps from the __id projection; stream the stored reassembly

xerj-orgd1e80569e2a9
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 1fb4f395b..975fa29ea 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -1511,6 +1511,85 @@ mod flush_publication_recovery_tests {
assert_eq!(idx.search(&request).await.unwrap().hits[0].id, "survivor");
}
+ /// #950: building the id→position map must NOT materialise the full
+ /// stored section. Before the fix, `id_pos_map_for` ran the complete
+ /// `stored_slices_for` decode — every column of every stored document
+ /// as a `serde_json::Value` tree (~10-20x the JSON text) — to read one
+ /// string per row; a delete-by-query storm over that path was the
+ /// dominant RSS transient on the 5,369-index corpus server
+ /// (heap-profiled: 6.1 of 11.1 GiB sampled live). After the fix the
+ /// map comes from the `__id` column projection alone and the
+ /// stored-slices cache stays COLD — the observable contract pinned
+ /// here. Fails-before: the legacy path publishes a `StoredSlices`
+ /// entry for the segment as a side effect of building the map.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn id_pos_map_builds_from_projection_without_warming_stored_slices() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config).unwrap();
+ engine
+ .create_index("idpos-projection", slash_field_schema())
+ .unwrap();
+ let idx = engine.get_index("idpos-projection").unwrap();
+ idx.abort_background_tasks();
+ // Enough docs that every memtable shard flushes a segment above
+ // V2_MIN_DOCS (128), so the stored section is columnar ZBS2 and the
+ // projection path applies (smaller segments stay legacy LZ4 and
+ // correctly fall back to the full decode).
+ for i in 0..4096u64 {
+ idx.index_document(Some(format!("doc-{i}")), json!({"bad/field": "needle"}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+ // The flush's publish-time warm populates the stored caches, so a
+ // warm-cache assertion right after flush proves nothing. Restart
+ // cold (this is also the shape the #950 profile came from: a booted
+ // server, cold stored caches, a delete-by-query storm) and probe.
+ drop(idx);
+ drop(engine);
+ let mut config2 = Config::default();
+ config2.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config2).unwrap();
+ let idx = engine.get_index("idpos-projection").unwrap();
+ idx.abort_background_tasks();
+ let snapshot = idx.store.snapshot();
+ let segs: Vec<_> = snapshot.segments.clone();
+ drop(snapshot);
+ assert!(!segs.is_empty());
+ for seg in &segs {
+ assert!(
+ idx.stored_slices_cache.get(&seg.id).is_none(),
+ "precondition: segment {} must be cold after restart",
+ seg.id
+ );
+ }
+ // Every flushed shard segment must answer its id map from the
+ // projection alone.
+ for seg in &segs {
+ let map = idx
+ .id_pos_map_for(&seg.id, seg.doc_count)
+ .expect("id map must build from the __id projection");
+ assert_eq!(map.len() as u64, seg.doc_count);
+ assert!(
+ idx.stored_slices_cache.get(&seg.id).is_none(),
+ "#950: id_pos must not warm the full stored decode (StoredSlices cache cold)"
+ );
+ }
+ // And the maps actually resolve ids across all shards.
+ let total: usize = segs
+ .iter()
+ .filter_map(|seg| idx.id_pos_cache.get(&seg.id).map(|e| e.value().len()))
+ .sum();
+ assert_eq!(
+ total, 4096,
+ "every indexed doc must resolve across the shard maps"
+ );
+ drop(idx);
+ drop(engine);
+ }
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn slash_field_flush_publishes_and_restarts_searchable() {
let _fault_test = FLUSH_FAULT_TEST_LOCK.lock().await;
@@ -28467,6 +28546,33 @@ impl Index {
if let Some(entry) = self.id_pos_cache.get(seg_id) {
return Some(Arc::clone(entry.value()));
}
+ // #950: build the map from the `_id` column ALONE before touching
+ // the full stored decode. `stored_slices_for` materialises every
+ // column of every stored document as a `serde_json::Value` tree
+ // (~10-20x the JSON text) where this map needs one string per row;
+ // a delete-by-query storm over that path was the dominant RSS
+ // transient on the #950 corpus server (heap-profiled: 6.1 GiB of
+ // 11.1 GiB sampled live). Same id-resolution shape as meilisearch,
+ // which answers id lookups from `external_documents_ids()` and
+ // never from the document store. Deliberately lock-free: the
+ // `_id` column decode is a dict-bitpacked microsecond read, so a
+ // concurrent-miss race only duplicates trivial work.
+ if let Some(map) = self.id_pos_map_from_projection(seg_id, expect_docs) {
+ let key = seg_id.to_string();
+ let bytes = cache_estimates::id_positions_bytes(
+ &key,
+ std::mem::size_of::<CacheResident<std::collections::HashMap<String, u32>>>(),
+ &map,
+ );
+ return Some(self.publish_current(
+ &self.id_pos_cache,
+ seg_id,
+ key,
+ SegmentCacheCategory::IdPositions,
+ bytes,
+ map,
+ ));
+ }
let slices = self.stored_slices_for(seg_id, expect_docs)?;
let mut map: std::collections::HashMap<String, u32> =
std::collections::HashMap::with_capacity(slices.offsets.len());
@@ -28511,6 +28617,41 @@ impl Index {
))
}
+ /// `_id`-only map build over the stored projection (#950): decodes the
+ /// `_id` column without materialising any other column. `None` falls
+ /// back to the full slice walk below — legacy LZ4/raw sections, a missing
+ /// `_id` column, a row count that disagrees with the segment metadata, a
+ /// non-string id, or duplicate ids (the same completeness guard the slice
+ /// walk applies, so a doc without a usable stored `_id` still defers to
+ /// the scan and no match is ever lost).
+ fn id_pos_map_from_projection(
+ &self,
+ seg_id: &str,
+ expect_docs: u64,
+ ) -> Option<std::collections::HashMap<String, u32>> {
+ use xerj_storage::stored_codec::{decode_stored_projection, StoredV2ProjectionResult};
+ let reader = self.store.open_segment_arc(seg_id).ok()?;
+ let raw = reader.section(SectionType::Stored).ok()??;
+ let projected = decode_stored_projection(raw, &["__id"]).ok()?;
+ let StoredV2ProjectionResult::Projected(projection) = projected else {
+ return None;
+ };
+ let ids = projection.columns.get("__id")?;
+ if ids.len() as u64 != expect_docs {
+ return None;
+ }
+ let mut map: std::collections::HashMap<String, u32> =
+ std::collections::HashMap::with_capacity(ids.len());
+ for (pos, id) in ids.iter().enumerate() {
+ let id = id.as_str()?;
+ map.insert(id.to_string(), pos as u32);
+ }
+ if map.len() as u64 != expect_docs {
+ return None;
+ }
+ Some(map)
+ }
+
/// Lazily-built, cached `stored-position → seq_no` array for a segment
/// (see `row_seq_cache`). Returns `None` when the segment has no complete
/// id index or an id is missing from the version map entirely.
diff --git a/engine/crates/xerj-storage/src/stored_codec.rs b/engine/crates/xerj-storage/src/stored_codec.rs
index 5d2e9c55f..8dd4743be 100644
--- a/engine/crates/xerj-storage/src/stored_codec.rs
+++ b/engine/crates/xerj-storage/src/stored_codec.rs
@@ -725,6 +725,25 @@ pub fn decode_stored(bytes: &[u8]) -> Result<Vec<u8>> {
Ok(bytes.to_vec())
}
+/// Column-projected decode over any supported stored payload (#950).
+///
+/// Same dispatch as `decode_stored` (V3-wrapped or bare V2), but decodes
+/// ONLY the requested columns instead of materialising the whole segment.
+/// The engine's id-position map needs one string per row; running the full
+/// decoder for it cost a transient `serde_json::Value` universe per segment
+/// (~10-20x the JSON text). Legacy LZ4/raw sections return `NotV2` so the
+/// caller can fall back to the compatibility decoder.
+pub fn decode_stored_projection(
+ bytes: &[u8],
+ requested: &[&str],
+) -> Result<StoredV2ProjectionResult> {
+ if bytes.len() >= 4 && &bytes[..4] == STORED_V3_MAGIC {
+ let (_present_nulls, inner) = split_stored_v3(bytes)?;
+ return decode_stored_v2_projection(inner, requested);
+ }
+ decode_stored_v2_projection(bytes, requested)
+}
+
/// Conservative retained-size bound for the canonical stored bytes plus the
/// `(start, end)` row-offset table used by the engine's `StoredSlices`.
///
@@ -1917,13 +1936,30 @@ fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>
let id_col_ix = col_name_to_ix.get("__id").copied().unwrap_or(0);
let seq_col_ix = col_name_to_ix.get("__seq_no").copied().unwrap_or(1);
- let mut out_docs: Vec<serde_json::Value> = Vec::new();
- out_docs.try_reserve_exact(num_docs).map_err(|error| {
- StorageError::Other(anyhow::anyhow!(
- "cannot reserve {num_docs} decoded stored rows: {error}"
- ))
- })?;
+ // #950: serialise one document at a time straight into the output
+ // buffer. The previous shape accumulated ALL rows as a second full
+ // `Value` universe (`out_docs: Vec<Value>` built by `.cloned()` out of
+ // `col_data`) only to hand it to `serde_json::to_vec` and drop it — a
+ // transient the size of the whole column materialisation AGAIN, sitting
+ // on every stored warm/fetch path (heap-profiled at 6.1 GiB live on the
+ // #950 corpus server). Per-row serialisation keeps the peak at
+ // `col_data` + one document and is byte-identical: same compact
+ // formatter, same `[doc,doc,...]` array framing as `to_vec(&Vec<Value>)`.
+ // The reserve is a floor, not the final size — it exists so a corrupt
+ // `num_docs` fails as an error instead of an abort, like the row reserve
+ // it replaces.
+ let mut out: Vec<u8> = Vec::new();
+ out.try_reserve_exact(num_docs.saturating_mul(16).saturating_add(2))
+ .map_err(|error| {
+ StorageError::Other(anyhow::anyhow!(
+ "cannot reserve {num_docs} decoded stored rows: {error}"
+ ))
+ })?;
+ out.push(b'[');
for d in 0..num_docs {
+ if d > 0 {
+ out.push(b',');
+ }
let mut source_map = serde_json::Map::new();
for (cix, name) in col_names.iter().enumerate() {
if cix == id_col_ix || cix == seq_col_ix {
@@ -1957,11 +1993,11 @@ fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>
.unwrap_or(serde_json::Value::Null),
);
doc.insert("_source".into(), serde_json::Value::Object(source_map));
- out_docs.push(serde_json::Value::Object(doc));
+ serde_json::to_writer(&mut out, &serde_json::Value::Object(doc))
+ .map_err(|e| StorageError::Other(anyhow::anyhow!("v2 reassemble: {e}")))?;
}
-
- serde_json::to_vec(&out_docs)
- .map_err(|e| StorageError::Other(anyhow::anyhow!("v2 reassemble: {e}")))
+ out.push(b']');
+ Ok(out)
}
// ── Column-level helpers ─────────────────────────────────────────────────
@@ -2763,6 +2799,111 @@ mod tests {
assert!(got[1]["_source"].get("z").is_none());
}
+ /// #950 (fix part 2): the reassembly serialises one document at a time
+ /// instead of accumulating a second full `Value` universe. Downstream
+ /// consumers (`brace_walk_offsets`, `extract_stored_id`) walk the output
+ /// bytes blind, so the output must stay EXACTLY the canonical JSON array —
+ /// framing intact and every document fully equal (not spot-checked),
+ /// including escapes, unicode, control characters, nested structures,
+ /// floats, and present-null keys.
+ #[test]
+ fn v2_decode_streaming_output_is_canonical_for_nasty_docs() {
+ let mut docs: Vec<serde_json::Value> = Vec::new();
+ for i in 0..64u64 {
+ let mut source = json!({
+ "quote": format!("said \"hi\" {}", i),
+ "unicode": "héllo → 世界 ✓",
+ "backslash": "C:\\path\\to",
+ "control": "\u{0007}\n\t",
+ "nested": { "deep": [1, 2, { "deeper": true }] },
+ "float": 0.010127 + i as f64,
+ "empty_str": "",
+ });
+ if i % 3 == 0 {
+ source["opt"] = serde_json::Value::Null;
+ }
+ docs.push(json!({
+ "_id": format!("id-\"{}\"", i),
+ "_seq_no": i,
+ "_source": source,
+ }));
+ }
+ let raw = serde_json::to_vec(&docs).unwrap();
+ let encoded = encode_stored_v2(&raw);
+ let decoded = decode_stored(&encoded).unwrap();
+ // Array framing: downstream walks these bytes blind.
+ assert_eq!(decoded.first(), Some(&b'['), "output must open the array");
+ assert_eq!(decoded.last(), Some(&b']'), "output must close the array");
+ let got: Vec<serde_json::Value> = serde_json::from_slice(&decoded).unwrap();
+ assert_eq!(got.len(), docs.len());
+ for (g, w) in got.iter().zip(docs.iter()) {
+ assert_eq!(
+ g,
+ w,
+ "full-document mismatch in streamed output: {}",
+ String::from_utf8_lossy(&decoded)
+ );
+ }
+ }
+
+ /// #950 (fix part 1): the column-projected decoder must serve `_id`
+ /// from both ZBS2 and ZBS3 payloads, refuse legacy LZ4/v1 sections with
+ /// `NotV2` (so callers fall back to the compatibility decoder), and
+ /// never decode unrequested columns.
+ #[test]
+ fn stored_projection_serves_ids_from_v2_and_v3_and_refuses_legacy() {
+ let docs: Vec<serde_json::Value> = (0..400u64)
+ .map(|i| {
+ if i % 5 == 0 {
+ json!({ "_id": format!("d{}", i), "_seq_no": i, "_source": { "opt": null, "path": "/x" } })
+ } else {
+ json!({ "_id": format!("d{}", i), "_seq_no": i, "_source": { "path": "/x" } })
+ }
+ })
+ .collect();
+ let v3 = encode_stored_v2(&serde_json::to_vec(&docs).unwrap());
+ assert_eq!(&v3[..4], STORED_V3_MAGIC, "present nulls must wrap as ZBS3");
+ match decode_stored_projection(&v3, &["__id"]).unwrap() {
+ StoredV2ProjectionResult::Projected(p) => {
+ assert_eq!(p.num_docs, docs.len());
+ let ids = p.columns.get("__id").expect("`__id` column must project");
+ assert_eq!(ids.len(), docs.len());
+ for (i, id) in ids.iter().enumerate() {
+ assert_eq!(id.as_str(), Some(format!("d{}", i).as_str()), "row {i}");
+ }
+ assert!(
+ !p.columns.contains_key("path"),
+ "unrequested columns must not be decoded"
+ );
+ }
+ StoredV2ProjectionResult::NotV2 => panic!("ZBS3 payload must project"),
+ }
+
+ let null_free: Vec<serde_json::Value> = (0..400u64)
+ .map(|i| json!({ "_id": format!("d{}", i), "_seq_no": i, "_source": { "path": "/x" } }))
+ .collect();
+ let v2 = encode_stored_v2(&serde_json::to_vec(&null_free).unwrap());
+ assert_eq!(&v2[..4], STORED_V2_MAGIC, "null-free stays ZBS2");
+ match decode_stored_projection(&v2, &["__id"]).unwrap() {
+ StoredV2ProjectionResult::Projected(p) => {
+ let ids = p.columns.get("__id").expect("`__id` column must project");
+ assert_eq!(ids.len(), null_free.len());
+ assert_eq!(ids[399].as_str(), Some("d399"));
+ }
+ StoredV2ProjectionResult::NotV2 => panic!("ZBS2 payload must project"),
+ }
+
+ // A legacy (non-columnar) section reports NotV2 so the engine falls
+ // back to the full compatibility decoder instead of failing.
+ let raw_legacy = br#"[{"_id":"a","_seq_no":1,"_source":{"m":"x"}}]"#;
+ match decode_stored_projection(raw_legacy, &["__id"]).unwrap() {
+ StoredV2ProjectionResult::NotV2 => {}
+ StoredV2ProjectionResult::Projected(_) => {
+ panic!("legacy section must not claim to project")
+ }
+ }
+ }
+
#[test]
fn v3_retained_bound_routes_through_inner_zbs2_estimator() {
// #538: a null-bearing segment is ZBS3. Its retained upper bound must be