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(reindex): page >10k docs via true search_after keyset pagination

xerj-org4a6ec82b4292
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index b9bc8c3d9..8fcd80c7f 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -13128,28 +13128,46 @@ pub async fn reindex(
Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),
};
+ // Flush the source memtable to segments before paging. `_id`-sorted
+ // `search_after` keyset pagination is correct over on-disk segments, but
+ // the in-memory memtable's field-sort path does NOT order by `_id`
+ // reliably, so un-flushed recent writes would be skipped or duplicated
+ // across pages. Reindex is a snapshot-style bulk op, so a single flush up
+ // front is an acceptable cost and makes the whole source keyset-pageable.
+ let _ = source_idx.flush().await;
+
let query_val = body
.source
.query
.clone()
.unwrap_or(json!({ "match_all": {} }));
let page_size = body.source.size.min(10_000); // cap per-batch at 10k
- let max_total = 100_000usize; // safety cap for reindex total
+ // Safety backstop only. With TRUE keyset (`search_after`) paging below,
+ // every page is a fresh top-N strictly below `max_result_window`, so we
+ // never hit the deep-paging wall — this cap just prevents a runaway loop
+ // on a pathologically large source, well above any realistic reindex.
+ let max_total = 10_000_000usize;
let mut total_fetched = 0usize;
let mut created = 0usize;
let mut updated = 0usize;
let mut failures: Vec<Value> = Vec::new();
let mut batches = 0usize;
- let mut from = 0usize;
+ // Keyset cursor: `[last_id]` of the previous page (the sole sort key is
+ // `_id: asc`). `None` on the first page. This replaces `from`-offset
+ // paging, which silently truncated at `max_result_window` (~10k) once
+ // `from` exceeded the deep-paging limit.
+ let mut search_after: Option<Value> = None;
loop {
- let search_body_val = json!({
+ let mut search_body_val = json!({
"query": query_val,
"size": page_size,
- "from": from,
"sort": [{ "_id": "asc" }],
});
+ if let Some(ref sa) = search_after {
+ search_body_val["search_after"] = sa.clone();
+ }
let search_req = match xerj_query::parse_request(&search_body_val)
.map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))
@@ -13171,6 +13189,9 @@ pub async fn reindex(
batches += 1;
total_fetched += batch_size;
+ // Capture the keyset cursor before the `for` loop consumes `results.hits`.
+ let last_id = results.hits.last().map(|h| h.id.clone());
+
for hit in results.hits {
if !hit.source.is_null() {
// Check if doc already exists in dest to track created vs updated.
@@ -13201,10 +13222,11 @@ pub async fn reindex(
}
}
- from += batch_size;
+ // Advance the keyset cursor to the last `_id` of this page.
+ search_after = last_id.map(|id| json!([id]));
- // Stop if we've reached the safety cap or fetched fewer docs than requested
- // (meaning we hit the end of the source).
+ // Stop if we've reached the safety backstop or fetched fewer docs than
+ // requested (meaning we hit the end of the source).
if batch_size < page_size || total_fetched >= max_total {
break;
}
@@ -25020,3 +25042,84 @@ mod ml_anomaly_tests {
assert_eq!(ml_anomaly_score(5.0, 0.0), 0.0);
}
}
+
+#[cfg(test)]
+mod reindex_keyset_tests {
+ use super::*;
+ use xerj_common::{
+ config::{Config, WalSync},
+ metrics::Metrics,
+ };
+ use xerj_engine::Engine;
+
+ fn test_state() -> AppState {
+ let dir = tempfile::tempdir().expect("tempdir");
+ // Leak the tempdir so the data directory outlives the Engine.
+ let path = dir.keep();
+ let mut config = Config::default();
+ config.server.data_dir = path.to_str().unwrap().to_string();
+ // Never fsync — this test indexes >10k docs and only cares about
+ // correctness of paging, not durability.
+ config.storage.wal_sync = WalSync::Async;
+ let metrics = Metrics::new().expect("metrics");
+ let engine = Engine::new(config.clone()).expect("engine");
+ AppState::new(config, engine, metrics)
+ }
+
+ /// Reindexing a source larger than `max_result_window` (~10k) must carry
+ /// every document. A `from`-offset pager truncates once `from` crosses the
+ /// deep-paging wall; true `search_after` keyset paging does not.
+ #[tokio::test]
+ async fn reindex_pages_past_10k_via_keyset() {
+ let state = test_state();
+ let n = 10_050usize;
+
+ // Index N docs with distinct _ids into `src` via the batched turbo
+ // path (one WAL append) so the test isn't dominated by per-doc fsyncs.
+ let src = state.engine.get_or_create_index("src").expect("src index");
+ let mut batch: Vec<(String, Value, std::sync::Arc<[u8]>)> = Vec::with_capacity(n);
+ for i in 0..n {
+ let id = format!("doc-{i:06}");
+ let v = json!({ "n": i });
+ let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(serde_json::to_vec(&v).unwrap());
+ batch.push((id, v, bytes));
+ }
+ src.index_batch_turbo(batch, true, false)
+ .await
+ .expect("bulk index src");
+ assert_eq!(
+ src.live_doc_count(),
+ n as u64,
+ "sanity: all source docs indexed"
+ );
+
+ // Reindex src -> dst with a 1000-doc page size (forces >10 pages,
+ // crossing the 10k window that a from-offset pager cannot).
+ let body = ReindexBody {
+ source: ReindexSource {
+ index: "src".into(),
+ query: None,
+ size: 1000,
+ },
+ dest: ReindexDest {
+ index: "dst".into(),
+ },
+ };
+ let resp = reindex(State(state.clone()), Json(body))
+ .await
+ .into_response();
+ assert!(
+ resp.status().is_success(),
+ "reindex returned {}",
+ resp.status()
+ );
+
+ // Independent count via the destination's version map.
+ let dst = state.engine.get_index("dst").expect("dst index");
+ assert_eq!(
+ dst.live_doc_count(),
+ n as u64,
+ "every source doc must be reindexed (a from-offset pager truncates at ~10k)"
+ );
+ }
+}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c8596aa98..a0b564b60 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -15613,7 +15613,13 @@ fn compute_sort_values(
Value::Number(
serde_json::Number::from_f64(score as f64).unwrap_or(serde_json::Number::from(0)),
)
- } else if sf.is_doc_order() {
+ } else if sf.is_doc_order() || sf.field == "_id" {
+ // `_id` (and `_doc`) is doc metadata, NOT part of `_source`, so a
+ // plain `get_field_value` returns Null — which breaks `_id`-sorted
+ // `search_after` cursors (the cursor `[id]` has nothing to compare
+ // against). Project the doc id as the sort value so `sort: [_id]`
+ // ordering and `search_after: [last_id]` keyset paging (used by
+ // reindex) compare correctly. Matches ES, which echoes the id.
Value::String(id.to_string())
} else {
let raw = get_field_value(source, &sf.field).unwrap_or(Value::Null);
diff --git a/engine/tests/es-compat-yaml/src/main.rs b/engine/tests/es-compat-yaml/src/main.rs
index 2ab158855..1ba3a1023 100644
--- a/engine/tests/es-compat-yaml/src/main.rs
+++ b/engine/tests/es-compat-yaml/src/main.rs
@@ -1163,6 +1163,7 @@ fn resolve_action(action: &str, params: &serde_yaml::Mapping) -> (String, String
}
("POST".into(), path, body)
}
+ "reindex" => ("POST".into(), "/_reindex".into(), body),
"scroll" => {
let mut path = "/_search/scroll".to_string();
let mut qp = Vec::new();
diff --git a/engine/tests/es-compat-yaml/yaml/reindex/20_keyset_multipage.yml b/engine/tests/es-compat-yaml/yaml/reindex/20_keyset_multipage.yml
new file mode 100644
index 000000000..3bc15df5a
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/reindex/20_keyset_multipage.yml
@@ -0,0 +1,44 @@
+---
+"reindex pages every doc via search_after keyset (multi-page)":
+ # Seed 7 docs into src with distinct _ids.
+ - do:
+ index: { index: rk_src, id: "1", body: { n: 1 } }
+ - do:
+ index: { index: rk_src, id: "2", body: { n: 2 } }
+ - do:
+ index: { index: rk_src, id: "3", body: { n: 3 } }
+ - do:
+ index: { index: rk_src, id: "4", body: { n: 4 } }
+ - do:
+ index: { index: rk_src, id: "5", body: { n: 5 } }
+ - do:
+ index: { index: rk_src, id: "6", body: { n: 6 } }
+ - do:
+ index: { index: rk_src, id: "7", refresh: true, body: { n: 7 } }
+
+ # size:2 forces >3 keyset pages, exercising multi-page cursor advancement.
+ - do:
+ reindex:
+ body:
+ source: { index: rk_src, size: 2 }
+ dest: { index: rk_dst }
+
+ - do:
+ indices.refresh:
+ index: rk_dst
+
+ # Every doc must arrive — no gaps, no dupes, no early truncation.
+ - do:
+ search:
+ index: rk_dst
+ body:
+ query: { match_all: {} }
+ size: 0
+ - match: { hits.total.value: 7 }
+
+ # Spot-check a doc from a later page is present with its source intact.
+ - do:
+ get:
+ index: rk_dst
+ id: "7"
+ - match: { _source.n: 7 }