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(#1022): _update_by_query pages the match set; exact sig-text/enrich counts

xerj-org427e2f47d4f2
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 615cf888d..1cd47bf48 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -14835,8 +14835,15 @@ async fn search_impl(
// significant_text profiler debug (total_buckets / values_fetched /
// chars_fetched / extract_count / collect_analyzed_count) can only be
// computed from the analyzed source docs. When the request profiles a
- // significant_text agg, fetch the foreground (query-matched) docs and
- // precompute the per-agg debug block keyed by agg name.
+ // significant_text agg, fold the foreground (query-matched) docs
+ // through per-agg accumulators and precompute the debug block keyed by
+ // agg name. #1022: this used to materialise ONE `size: 10_000` search
+ // per index into a `Vec<Value>` — past one page of matches every
+ // counter silently under-reported (this is an exact-statistics
+ // surface), and the materialisation itself was an up-to-10k-source
+ // RSS transient. `fold_match_sources` walks each index once and holds
+ // ONE doc at a time; the counters are order-independent folds, so the
+ // values are mathematically unchanged below the truncation threshold.
let agg_req_for_sig = search_req
.aggs
.as_ref()
@@ -14852,25 +14859,28 @@ async fn search_impl(
.query
.clone()
.unwrap_or_else(|| json!({"match_all": {}}));
- let mut fg_docs: Vec<Value> = Vec::new();
- if let Ok(fg_req) =
- xerj_query::parse_request(&json!({"query": fg_query, "size": 10000, "from": 0}))
- {
+ if let Ok(fg_req) = xerj_query::parse_request(&json!({"query": fg_query})) {
+ let mut accs: Vec<SigTextAccumulator> =
+ specs.iter().map(SigTextAccumulator::new).collect();
+ // All specs share ONE walk per index, and the accumulators
+ // span the whole index_names loop so cross-index totals
+ // stay pooled exactly the way the old `fg_docs` vec pooled
+ // them. Failures stay tolerated (a missing index or an
+ // unreadable segment contributes nothing), matching the
+ // old `if let Ok` swallowing.
for idx_name in &index_names {
if let Ok(idx) = state.engine.get_index(idx_name) {
- if let Ok(result) = idx.search(&fg_req).await {
- for hit in result.hits {
- if !hit.source.is_null() {
- fg_docs.push(hit.source);
- }
+ idx.fold_match_sources(&fg_req.query, &mut |doc: &Value| {
+ for acc in &mut accs {
+ acc.fold_doc(doc);
}
- }
+ })
+ .await;
}
}
- }
- for spec in &specs {
- sig_text_debug
- .insert(spec.name.clone(), compute_sig_text_debug(spec, &fg_docs));
+ for acc in &accs {
+ sig_text_debug.insert(acc.spec.name.clone(), acc.finish());
+ }
}
}
}
@@ -24875,38 +24885,56 @@ fn sig_text_token_set(s: &str) -> std::collections::HashSet<String> {
set
}
-/// Compute the ES `significant_text` profiler debug block for one agg from
-/// the foreground source docs. `total_buckets` is the sum, over each owning
-/// (parent) bucket, of the distinct analyzed terms in that bucket's docs —
-/// matching ES's per-ordinal bucket allocation.
-fn compute_sig_text_debug(spec: &SigTextSpec, fg_docs: &[Value]) -> Value {
- let mut values_fetched: u64 = 0;
- let mut chars_fetched: u64 = 0;
- let mut extract_count: u64 = 0;
- let mut collect_analyzed_count: u64 = 0;
+/// Incremental form of the `significant_text` profiler debug block (#1022).
+///
+/// The block's counters are order-independent folds (sums and per-group
+/// unions), so they can be accumulated doc-by-doc across a single-pass engine
+/// walk (`Index::fold_match_sources`) instead of being computed from a
+/// materialised foreground-doc `Vec` — which truncated at 10 000 docs per
+/// index and held that many full `Value` trees at once. `fold_doc`'s body is
+/// the exact former loop body of `compute_sig_text_debug`; `finish` emits the
+/// identical `json!` block (key order included — the YAML suite pins it).
+struct SigTextAccumulator<'a> {
+ spec: &'a SigTextSpec,
+ values_fetched: u64,
+ chars_fetched: u64,
+ extract_count: u64,
+ collect_analyzed_count: u64,
// owning bucket key -> union of analyzed terms across its docs
- let mut per_group: std::collections::HashMap<String, std::collections::HashSet<String>> =
- std::collections::HashMap::new();
+ per_group: std::collections::HashMap<String, std::collections::HashSet<String>>,
+}
+
+impl<'a> SigTextAccumulator<'a> {
+ fn new(spec: &'a SigTextSpec) -> Self {
+ Self {
+ spec,
+ values_fetched: 0,
+ chars_fetched: 0,
+ extract_count: 0,
+ collect_analyzed_count: 0,
+ per_group: std::collections::HashMap::new(),
+ }
+ }
- for doc in fg_docs {
- let vals = extract_field_values_from_source(doc, &spec.field);
+ fn fold_doc(&mut self, doc: &Value) {
+ let vals = extract_field_values_from_source(doc, &self.spec.field);
if vals.is_empty() {
- continue;
+ return;
}
- extract_count += 1;
+ self.extract_count += 1;
let mut doc_tokens: std::collections::HashSet<String> = std::collections::HashSet::new();
for v in &vals {
if let Some(s) = v.as_str() {
- values_fetched += 1;
- chars_fetched += s.chars().count() as u64;
+ self.values_fetched += 1;
+ self.chars_fetched += s.chars().count() as u64;
for t in sig_text_token_set(s) {
doc_tokens.insert(t);
}
}
}
- collect_analyzed_count += doc_tokens.len() as u64;
+ self.collect_analyzed_count += doc_tokens.len() as u64;
// Group by the owning bucket field value (or a single global group).
- let group_key = match spec.parent_field.as_deref() {
+ let group_key = match self.spec.parent_field.as_deref() {
Some(pf) => extract_field_values_from_source(doc, pf)
.first()
.map(|v| match v {
@@ -24916,20 +24944,26 @@ fn compute_sig_text_debug(spec: &SigTextSpec, fg_docs: &[Value]) -> Value {
.unwrap_or_default(),
None => String::new(),
};
- per_group.entry(group_key).or_default().extend(doc_tokens);
+ self.per_group
+ .entry(group_key)
+ .or_default()
+ .extend(doc_tokens);
+ }
+
+ fn finish(&self) -> Value {
+ let total_buckets: u64 = self.per_group.values().map(|s| s.len() as u64).sum();
+ json!({
+ "collection_strategy": "analyze text from _source",
+ "result_strategy": "significant_terms",
+ "total_buckets": total_buckets,
+ "values_fetched": self.values_fetched,
+ "chars_fetched": self.chars_fetched,
+ "extract_ns": 1u64,
+ "extract_count": self.extract_count,
+ "collect_analyzed_ns": 1u64,
+ "collect_analyzed_count": self.collect_analyzed_count,
+ })
}
- let total_buckets: u64 = per_group.values().map(|s| s.len() as u64).sum();
- json!({
- "collection_strategy": "analyze text from _source",
- "result_strategy": "significant_terms",
- "total_buckets": total_buckets,
- "values_fetched": values_fetched,
- "chars_fetched": chars_fetched,
- "extract_ns": 1u64,
- "extract_count": extract_count,
- "collect_analyzed_ns": 1u64,
- "collect_analyzed_count": collect_analyzed_count,
- })
}
fn build_aggregation_profile_full(
@@ -26533,8 +26567,16 @@ async fn run_delete_by_query(
#[derive(Debug, Deserialize)]
pub struct UpdateByQueryBody {
pub query: Option<Value>,
- /// Script block (accepted but not executed — docs are re-indexed as-is).
+ /// Script block (`ctx._source.*` mutations applied per matched doc).
pub script: Option<Value>,
+ /// ES `max_docs`: "Maximum number of documents to process. Defaults to
+ /// all documents." `total` then reports the processed count.
+ #[serde(default)]
+ pub max_docs: Option<u64>,
+ /// ES `scroll_size`: "Size of the scroll request that powers the
+ /// operation. Defaults to 1000."
+ #[serde(default)]
+ pub scroll_size: Option<u64>,
}
pub async fn update_by_query(
@@ -26551,13 +26593,24 @@ pub async fn update_by_query(
Ok(t) => t,
Err(e) => return ApiError::new(e).into_response(),
};
- let search_body_val = json!({ "query": effective_query, "size": 10000, "from": 0 });
- let search_req = match xerj_query::parse_request(&search_body_val)
- .map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))
- {
- Ok(r) => r,
- Err(e) => return ApiError::new(e).into_response(),
- };
+
+ // Validate the (alias-filter-ANDed) query once, up front, so a malformed
+ // body is an immediate 400 before a task is registered or any member is
+ // touched — the runner below re-parses per batch as the cursor advances
+ // (#1022: same shape as `_delete_by_query`).
+ let scroll_size = body
+ .scroll_size
+ .unwrap_or(DEFAULT_BY_QUERY_SCROLL_SIZE)
+ .clamp(1, 10_000) as usize;
+ let validation_body = json!({
+ "query": effective_query,
+ "size": scroll_size,
+ "from": 0,
+ "sort": [{ "_id": "asc" }],
+ });
+ if let Err(e) = xerj_query::parse_request(&validation_body) {
+ return ApiError::new(xerj_common::XerjError::invalid_query(e.to_string())).into_response();
+ }
// Optional painless script — when present, each matched hit's source is
// mutated by the script and re-indexed under its EXISTING `_id`, so the
@@ -26612,13 +26665,23 @@ pub async fn update_by_query(
let task_key = handle.key().to_string();
let spawned_key = task_key.clone();
let tasks = state.tasks.clone();
+ let task_query = effective_query.clone();
+ let task_max_docs = body.max_docs;
// Same reasoning as the `_delete_by_query` spawn above: the task owns
// the already-authorized `Index` handles and can reach no other index.
tokio::spawn(async move {
let mut results = Vec::with_capacity(indices.len());
for idx in &indices {
results.push(
- run_update_by_query(idx, &search_req, script.clone(), pipeline.clone()).await,
+ run_update_by_query(
+ idx,
+ &task_query,
+ task_max_docs,
+ scroll_size,
+ script.clone(),
+ pipeline.clone(),
+ )
+ .await,
);
}
tasks.complete(&spawned_key, aggregate_by_query_results(results, "updated"));
@@ -26629,7 +26692,17 @@ pub async fn update_by_query(
let mut results = Vec::with_capacity(indices.len());
for idx in &indices {
- results.push(run_update_by_query(idx, &search_req, script.clone(), pipeline.clone()).await);
+ results.push(
+ run_update_by_query(
+ idx,
+ &effective_query,
+ body.max_docs,
+ scroll_size,
+ script.clone(),
+ pipeline.clone(),
+ )
+ .await,
+ );
}
drop(handle);
by_query_response(aggregate_by_query_results(results, "updated"))
@@ -26678,124 +26751,346 @@ fn apply_pipeline_or_fail(
}
}
+/// One member's paginated `_update_by_query` run (#1022).
+///
+/// Shaped like `run_delete_by_query` (#1019), with one extra hazard delete
+/// did not have: the updates themselves repopulate the memtable, and a later
+/// page's search must never page over unflushed state — the memtable's
+/// field-sort path does not order by `_id` reliably, so a rewritten doc with
+/// `_id <= cursor` could resurface on a later page and get the script applied
+/// TWICE (silent corruption, versus delete's idempotent duplicate). The paged
+/// arm therefore flushes after every batch that mutated at least one doc
+/// (mirroring ES's per-batch refresh), keeping each page search over on-disk
+/// segments where the immutable-segment scan + cursor decline are proven.
+///
+/// Two arms, same counters:
+///
+/// * script mode over a `match_all` / `ids` selector takes the #1019
+/// single-pass id collection (`Index::matching_ids_sorted`) and transforms
+/// per id in `scroll_size` batches — NO hydration search at all: the
+/// per-id serialized transform (`transform_document_serialized`) re-reads
+/// and holds ONE doc at a time, which is a strictly tighter bound than any
+/// page size. No per-batch flush is needed because this arm never
+/// re-searches (the id set is fixed at the snapshot, ES's documented
+/// start-of-run collection semantics).
+///
+/// * everything else takes the `_id`-keyset paged loop. Script-mode pages run
+/// with the INTERNAL ids-only projection (`SearchRequest::ids_only`, never
+/// deserialisable from the wire) — the transform re-reads each source
+/// itself. No-script pages keep sources attached, bounded at one
+/// `scroll_size` page of `Value` trees — the same bound one ES scroll batch
+/// materialises.
+///
+/// ES semantics matched (#1019's rule set, the same transport contract):
+/// `total` is the exact match count when unlimited (page 1's `hits.total`,
+/// the pre-mutation snapshot — later pages run over a mutated index) or the
+/// processed count under `max_docs`; `batches` is the real batch count;
+/// `version_conflicts` stays 0 (the transform is serialized per id and the
+/// no-script write is blind — XERJ cannot produce a version conflict);
+/// `noops` stays 0 (the mini-painless tolerates `ctx.*` statements without
+/// skipping the write).
async fn run_update_by_query(
- idx: &xerj_engine::Index,
- search_req: &xerj_query::SearchRequest,
+ idx: &std::sync::Arc<xerj_engine::Index>,
+ query: &Value,
+ max_docs: Option<u64>,
+ scroll_size: usize,
script: Option<(String, Value)>,
pipeline: Option<(std::sync::Arc<xerj_engine::Engine>, String)>,
) -> Value {
let started = Instant::now();
- let results = match idx.search(search_req).await {
- Ok(r) => r,
- Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_value(),
- };
- // Same reasoning as `run_delete_by_query`: a fail-closed script selection
- // would update an arbitrary subset and call it a complete run.
- if let Some(reason) = &results.script_failure {
- return script_limit_error_value(reason);
+ // Flush precondition (see doc comment): the keyset paging below is only
+ // correct over on-disk segments, and the single-pass id collection reads
+ // the flushed segments' id maps. Propagated, not swallowed, for the same
+ // reason as `reindex` and `run_delete_by_query`: the flush is a
+ // precondition of the run being complete, so a failed flush must not be
+ // followed by an update that reports a `total` over an index it could not
+ // read consistently.
+ if let Err(e) = idx.flush().await {
+ return ApiError::new(xerj_common::XerjError::internal(format!(
+ "update_by_query was not attempted: flushing the index failed ({e}); the update \
+ needs a flushed index to page over it without skipping or duplicating documents"
+ )))
+ .into_value();
}
- let total = results.hits.len() as u64;
+ // Parse once for the single-pass eligibility check below. The handler
+ // already validated the (page-1-shaped) query, so this cannot fail for a
+ // request that got here; the paged arm re-parses per page only because it
+ // rebuilds the body to attach `search_after`.
+ let parsed_query = match xerj_query::parse_request(&json!({ "query": query })) {
+ Ok(r) => r.query,
+ Err(e) => {
+ return ApiError::new(xerj_common::XerjError::invalid_query(e.to_string())).into_value()
+ }
+ };
- // One budget for the whole request, the way `_search` already gets one.
- // Every `;`-separated statement builds its own `PainlessCtx`, and with no
- // deadline in scope each one falls back to its own ~500 ms slice — so a
- // script's cost multiplied by its statement count and again by the hit
- // count (up to 10k), with `wait_for_completion=false` detaching the whole
- // thing onto the runtime. Publishing a single deadline bounds the request
- // however it is spelled, and the fault sink turns a resource-limit trip
- // into one honest error instead of the same failure recorded ten thousand
- // times.
+ // One budget for the whole request, the way `_search` already gets one —
+ // and it now spans the page searches too, since the search phases are part
+ // of the request it bounds. Publishing a single deadline bounds the
+ // request however it is spelled, and the fault sink turns a resource-limit
+ // trip into one honest error instead of the same failure recorded once per
+ // batch.
let deadline = Instant::now() + Duration::from_millis(SCRIPTED_UPDATE_BUDGET_MS);
- let hits = results.hits;
- let ((updated, failures, timed_out), fault) = xerj_engine::painless::with_script_fault_capture(
- xerj_engine::painless::with_script_deadline(deadline, async move {
- let mut updated = 0u64;
- let mut failures: Vec<Value> = Vec::new();
- let mut timed_out = false;
-
- for hit in hits {
- // The deadline bounds each evaluation, but not the loop: the
- // per-evaluation slice is clamped to a floor even once the
- // request deadline has passed — so an ordinary script is not
- // cut off just because a slow search overran — and that floor
- // times ten thousand hits is still ~1000 s of CPU from one
- // request. The loop has to stop on its own, and say that it
- // did rather than reporting `timed_out: false` over a run that
- // was cut short.
- if Instant::now() >= deadline {
- timed_out = true;
- break;
- }
- if hit.source.is_null() {
- continue;
+ // `Box::pin`: the loop body below is a large async state machine, and the
+ // deadline/fault wrappers store their future INLINE (`F: Future`, not
+ // `Pin<Box<dyn Future>>`), so unboxed the whole nested machine lands on
+ // the tokio worker's 2 MiB stack — measured as a stack overflow in debug
+ // builds. Boxing moves it to the heap; the per-iteration cost is one
+ // indirection.
+ let (outcome, fault) = xerj_engine::painless::with_script_fault_capture(
+ xerj_engine::painless::with_script_deadline(
+ deadline,
+ Box::pin(async move {
+ // ── Single-pass arm: script mode, match_all / ids selectors ──────
+ //
+ // The whole live match set is collected once from the cached
+ // per-segment `_id` maps (#950), then transformed per id in
+ // `scroll_size` batches — one O(N) id materialisation, no
+ // per-page stored-section re-scan, no `_source` hydration outside
+ // the per-id transform.
+ if script.is_some() {
+ if let Some(mut ids) = idx.matching_ids_sorted(&parsed_query) {
+ // ES `max_docs`: stop after N documents; `total` then
+ // reports the processed count (the same rule the paged
+ // arm applies).
+ let matched = ids.len() as u64;
+ if let Some(cap) = max_docs {
+ ids.truncate(cap as usize);
+ }
+ let mut processed: u64 = 0;
+ let mut updated: u64 = 0;
+ let mut batches: u64 = 0;
+ let mut failures: Vec<Value> = Vec::new();
+ let mut timed_out = false;
+ 'single: for chunk in ids.chunks(scroll_size) {
+ batches += 1;
+ for id in chunk {
+ // The deadline bounds each evaluation, but not the
+ // loop (see the paged arm's per-hit check for the
+ // reasoning) — the loop stops on its own and says
+ // that it did.
+ if Instant::now() >= deadline {
+ timed_out = true;
+ break 'single;
+ }
+ processed += 1;
+ if let Some(f) = transform_one(idx, id, &script, &pipeline).await {
+ match f {
+ Ok(()) => updated += 1,
+ Err(reason) => failures.push(json!({
+ "id": id,
+ "cause": { "reason": reason },
+ })),
+ }
+ }
+ // `None` = the doc vanished mid-run: skip silently,
+ // no counter — the same outcome the pre-fix
+ // `hit.source.is_null()` guard produced.
+ }
+ }
+ let total = if max_docs.is_none() {
+ matched.max(updated)
+ } else {
+ processed
+ };
+ return Ok((total, updated, batches, failures, timed_out));
+ }
}
- if let Some((src, params)) = script.as_ref() {
- if src.is_empty() {
- failures.push(json!({
- "id": hit.id,
- "cause": { "reason": "script source is required" },
- }));
- continue;
+
+ // ── Paged arm: every other shape ─────────────────────────────────
+ let mut total: u64 = 0;
+ let mut processed: u64 = 0;
+ let mut updated: u64 = 0;
+ let mut batches: u64 = 0;
+ let mut failures: Vec<Value> = Vec::new();
+ let mut timed_out = false;
+ // Keyset cursor: the last id of the previous page (the sole sort
+ // key is `_id: asc`). `None` on the first page.
+ let mut search_after: Option<String> = None;
+ // Safety backstop only, mirroring reindex's `max_total`.
+ let max_total: u64 = 10_000_000;
+
+ loop {
+ let page = match max_docs {
+ Some(cap) => {
+ (scroll_size as u64).min(cap.saturating_sub(processed)) as usize
+ }
+ None => scroll_size,
+ };
+ if page == 0 {
+ break; // max_docs reached
+ }
+
+ let mut search_body_val = json!({
+ "query": query,
+ "size": page,
+ "sort": [{ "_id": "asc" }],
+ // Belt only — under the ids-only projection this is not
+ // even consulted for the source cut; on the no-script
+ // arm it is overridden below because that arm NEEDS its
+ // page's sources.
+ "_source": false,
+ });
+ if script.is_none() {
+ // No-script re-index-in-place: the page search itself
+ // hydrates JUST this page's sources (bounded by
+ // `scroll_size` — the same bound one ES scroll batch
+ // materialises; no second ids-then-hydrate query needed).
+ search_body_val["_source"] = json!(true);
+ }
+ if let Some(ref cursor) = search_after {
+ search_body_val["search_after"] = json!([cursor]);
+ }
+ let mut search_req = match xerj_query::parse_request(&search_body_val)
+ .map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))
+ {
+ Ok(r) => r,
+ Err(e) => return Err(ApiError::new(e).into_value()),
+ };
+ // Internal-only projection hint for script-mode pages: the
+ // per-id transform re-reads the source itself, so the page
+ // carries nothing but ids. `parse_request` can never set it.
+ if script.is_some() {
+ search_req.ids_only = true;
}
- let result = idx
- .transform_document_serialized(&hit.id, None, |mut current| {
- apply_painless_update(&mut current, src, params)?;
- // ES runs `?pipeline=` on the result of the script,
- // and so do we — inside the same serialized
- // transform, so the pipeline sees exactly the
- // document that is about to be written.
- if let Some((engine, name)) = pipeline.as_ref() {
- current = apply_pipeline_or_fail(engine, name, &hit.id, current)?;
- }
- Ok::<_, String>(current)
- })
- .await;
- match result {
- Ok(Ok(Some(_))) => updated += 1,
- Ok(Ok(None)) => {}
- Ok(Err(error)) => failures.push(json!({
- "id": hit.id,
- "cause": { "reason": error },
- })),
- Err(error) => failures.push(json!({
- "id": hit.id,
- "cause": { "reason": error.to_string() },
- })),
+
+ let results = match idx.search(&search_req).await {
+ Ok(r) => r,
+ Err(e) => {
+ return Err(ApiError::new(xerj_common::XerjError::from(e)).into_value())
+ }
+ };
+ // A script resource limit makes matching fail-closed, so the
+ // selection is a subset of what the caller asked to update —
+ // checked PER BATCH, before a single doc of the page is
+ // touched. Updating that subset and reporting success is both
+ // destructive and wrong; refuse instead.
+ if let Some(reason) = &results.script_failure {
+ return Err(script_limit_error_value(reason));
}
- } else {
- // No script: preserve the historical re-index-in-place
- // behavior, with `?pipeline=` applied when one was named.
- let doc = match pipeline.as_ref() {
- None => hit.source,
- Some((engine, name)) => {
- match apply_pipeline_or_fail(engine, name, &hit.id, hit.source) {
- Ok(d) => d,
- Err(reason) => {
- failures.push(json!({
+
+ if results.hits.is_empty() {
+ break;
+ }
+ batches += 1;
+ // Page 1's `hits.total` is the EXACT pre-mutation match count
+ // (later pages run over an already-mutated index). Under
+ // `max_docs` ES reports the processed count instead.
+ if max_docs.is_none() && total == 0 {
+ total = results.total.value;
+ }
+
+ // Capture the cursor before the loop consumes `results.hits`.
+ let last_id = results.hits.last().map(|h| h.id.clone());
+ let mut mutated_in_batch: u64 = 0;
+ for hit in results.hits {
+ // The deadline bounds each evaluation, but not the loop:
+ // the per-evaluation slice is clamped to a floor even once
+ // the request deadline has passed — so an ordinary script
+ // is not cut off just because a slow search overran — and
+ // that floor times a whole index is unbounded CPU from one
+ // request. The loop has to stop on its own, and say that
+ // it did rather than reporting `timed_out: false` over a
+ // run that was cut short.
+ if Instant::now() >= deadline {
+ timed_out = true;
+ break;
+ }
+ processed += 1;
+ if script.is_some() {
+ // ids-only hits carry `source: Null` BY CONSTRUCTION —
+ // the old `hit.source.is_null()` skip must NOT run
+ // here or every hit would be skipped; liveness is
+ // delegated to the transform's `Ok(Ok(None))` (the
+ // doc vanished mid-run).
+ if let Some(f) = transform_one(idx, &hit.id, &script, &pipeline).await {
+ match f {
+ Ok(()) => {
+ updated += 1;
+ mutated_in_batch += 1;
+ }
+ Err(reason) => failures.push(json!({
"id": hit.id,
"cause": { "reason": reason },
+ })),
+ }
+ }
+ } else {
+ // No script: preserve the historical re-index-in-place
+ // behavior, with `?pipeline=` applied when one was
+ // named.
+ if hit.source.is_null() {
+ continue;
+ }
+ let doc = match pipeline.as_ref() {
+ None => hit.source,
+ Some((engine, name)) => {
+ match apply_pipeline_or_fail(engine, name, &hit.id, hit.source)
+ {
+ Ok(d) => d,
+ Err(reason) => {
+ failures.push(json!({
+ "id": hit.id,
+ "cause": { "reason": reason },
+ }));
+ continue;
+ }
+ }
+ }
+ };
+ match idx.index_document(Some(hit.id.clone()), doc).await {
+ Ok(_) => {
+ updated += 1;
+ mutated_in_batch += 1;
+ }
+ Err(e) => {
+ failures.push(json!({
+ "id": hit.id,
+ "cause": { "reason": e.to_string() },
}));
- continue;
}
}
}
- };
- match idx.index_document(Some(hit.id.clone()), doc).await {
- Ok(_) => updated += 1,
- Err(e) => {
- failures.push(json!({
- "id": hit.id,
- "cause": { "reason": e.to_string() },
- }));
+ }
+
+ // MID-RUN REWRITE HAZARD (see doc comment): this batch's
+ // writes are memtable-resident, and the next page's search
+ // must not page over unflushed state. Flush before searching
+ // again — the updated docs carry `_id <= cursor`, so the next
+ // page's cursor decline skips them in one compare. A failed
+ // flush aborts the run rather than letting the next page
+ // search unflushed state.
+ if mutated_in_batch > 0 {
+ if let Err(e) = idx.flush().await {
+ return Err(ApiError::new(xerj_common::XerjError::internal(format!(
+ "update_by_query aborted mid-run: flushing a batch failed ({e}); \
+ paging on without the flush could apply the script twice"
+ )))
+ .into_value());
}
}
+
+ match last_id {
+ Some(id) => search_after = Some(id),
+ None => break,
+ }
+ if processed >= max_total {
+ break;
+ }
}
- }
- (updated, failures, timed_out)
- }),
+ if max_docs.is_none() {
+ // Never under-report if a concurrent writer extended the match
+ // set past page 1's snapshot count mid-run.
+ total = total.max(processed);
+ } else {
+ total = processed;
+ }
+
+ Ok((total, updated, batches, failures, timed_out))
+ }),
+ ),
)
.await;
// A trip is a property of the request, not of the document that happened
@@ -26804,6 +27099,10 @@ async fn run_update_by_query(
if let Some(reason) = fault {
return script_limit_error_value(&reason);
}
+ let (total, updated, batches, failures, timed_out) = match outcome {
+ Ok(t) => t,
+ Err(e) => return e,
+ };
let took = started.elapsed().as_millis() as u64;
json!({
@@ -26812,7 +27111,7 @@ async fn run_update_by_query(
"total": total,
"updated": updated,
"deleted": 0,
- "batches": 1,
+ "batches": batches,
"version_conflicts": 0,
"noops": 0,
"failures": failures,
@@ -26822,6 +27121,44 @@ async fn run_update_by_query(
})
}
+/// Apply one `_update_by_query` hit: the scripted transform (with the optional
+/// pipeline inside the same serialized publication bracket), shared by the
+/// single-pass and paged arms.
+///
+/// `None` = the document vanished mid-run (`Ok(Ok(None))` from the engine):
+/// there is nothing to update and no failure to report. `Some(Err(reason))`
+/// is a per-document failure (script/pipeline error or write error).
+#[allow(clippy::type_complexity)]
+async fn transform_one(
+ idx: &std::sync::Arc<xerj_engine::Index>,
+ id: &str,
+ script: &Option<(String, Value)>,
+ pipeline: &Option<(std::sync::Arc<xerj_engine::Engine>, String)>,
+) -> Option<std::result::Result<(), String>> {
+ let (src, params) = script.as_ref()?;
+ if src.is_empty() {
+ return Some(Err("script source is required".to_string()));
+ }
+ let result = idx
+ .transform_document_serialized(id, None, |mut current| {
+ apply_painless_update(&mut current, src, params)?;
+ // ES runs `?pipeline=` on the result of the script, and so do we —
+ // inside the same serialized transform, so the pipeline sees
+ // exactly the document that is about to be written.
+ if let Some((engine, name)) = pipeline.as_ref() {
+ current = apply_pipeline_or_fail(engine, name, id, current)?;
+ }
+ Ok::<_, String>(current)
+ })
+ .await;
+ match result {
+ Ok(Ok(Some(_))) => Some(Ok(())),
+ Ok(Ok(None)) => None,
+ Ok(Err(error)) => Some(Err(error)),
+ Err(error) => Some(Err(error.to_string())),
+ }
+}
+
#[cfg(test)]
mod scripted_update_publication_tests {
use super::*;
@@ -26903,7 +27240,9 @@ mod scripted_update_publication_tests {
start.wait().await;
run_update_by_query(
&idx,
- &xerj_query::SearchRequest::default(),
+ &json!({ "match_all": {} }),
+ None,
+ DEFAULT_BY_QUERY_SCROLL_SIZE as usize,
Some(("ctx._source.n += 1".into(), json!({}))),
None,
)
@@ -31994,22 +32333,19 @@ pub async fn execute_enrich_policy(
}
};
- // Pull every source doc (match_all, large page) and copy it into the
- // enrich index, preserving doc ids.
- let req = match parse_request(&json!({
- "query": { "match_all": {} },
- "size": 10000,
- // Enrich policies materialise source documents into a lookup index, so
- // they must read the COMPLETE `_source` rather than inheriting the
- // search default which hides engine-generated embedding companions.
- "_source": true,
- })) {
- Ok(r) => r,
- Err(e) => {
- return ApiError::new(xerj_common::XerjError::invalid_query(e.to_string()))
- .into_response();
- }
- };
+ // Materialise EVERY source doc into the enrich index via `_id`-keyset
+ // `search_after` paging — reindex's exact loop shape (#1022). The old
+ // single-shot `{"query": {"match_all": {}}, "size": 10000}` search
+ // silently dropped every doc past the first page, so keys past one page
+ // never materialised and every later enrich lookup against them silently
+ // missed (enrich correctness is keyed on completeness of the copy), with
+ // `records` under-reporting. Internal page size only — ES `_execute` has
+ // no max_docs/scroll_size wire parameters, and none are invented here.
+ const ENRICH_COPY_PAGE: usize = 1_000;
+ // Safety backstop only, mirroring reindex's `max_total`: with keyset
+ // paging every page is a fresh top-N far below `max_result_window`, so
+ // this just bounds a runaway loop.
+ let max_total: usize = 10_000_000;
let mut materialised: u64 = 0;
for src_name in &source_indices {
@@ -32019,17 +32355,77 @@ pub async fn execute_enrich_policy(
Ok(i) => i,
Err(_) => continue,
};
- let result = match src.search(&req).await {
- Ok(r) => r,
- Err(e) => {
- return ApiError::new(xerj_common::XerjError::from(e)).into_response();
+ // Degenerate self-reference belt: a policy naming its own
+ // `.enrich-<name>` among its sources would page over its own
+ // writes. The destination is otherwise a different index, so the
+ // walk never sees its own output.
+ if src_name == &enrich_index {
+ continue;
+ }
+ // Flush precondition (reindex's rule, same wording): `_id`-keyset
+ // paging is only correct over on-disk segments — the memtable's
+ // field-sort path does not order by `_id` reliably, so unflushed docs
+ // could be skipped or duplicated across pages. Propagated, not
+ // swallowed: a failed flush must not be followed by a copy that
+ // reports `records: N` over a source it could not read consistently.
+ if let Err(e) = src.flush().await {
+ return ApiError::new(xerj_common::XerjError::internal(format!(
+ "enrich policy [{name}] was not executed against source [{src_name}]: flushing \
+ the source failed ({e}); the copy needs a flushed source to page over it \
+ without skipping or duplicating documents"
+ )))
+ .into_response();
+ }
+ // Keyset cursor: `[last_id]` of the previous page (the sole sort key
+ // is `_id: asc`). `None` on the first page.
+ let mut search_after: Option<Value> = None;
+ let mut fetched: usize = 0;
+ loop {
+ let mut search_body = json!({
+ "query": { "match_all": {} },
+ "size": ENRICH_COPY_PAGE,
+ "sort": [{ "_id": "asc" }],
+ // Enrich policies materialise source documents into a lookup
+ // index, so they must read the COMPLETE `_source` rather than
+ // inheriting the search default which hides engine-generated
+ // embedding companions. Per-page hydration: at most
+ // ENRICH_COPY_PAGE `Value` trees are alive at once — the same
+ // bound one ES scroll batch materialises.
+ "_source": true,
+ });
+ if let Some(ref sa) = search_after {
+ search_body["search_after"] = sa.clone();
}
- };
- for hit in result.hits {
- if let Err(e) = dest.index_document(Some(hit.id.clone()), hit.source).await {
- return ApiError::new(xerj_common::XerjError::from(e)).into_response();
+ let req = match parse_request(&search_body) {
+ Ok(r) => r,
+ Err(e) => {
+ return ApiError::new(xerj_common::XerjError::invalid_query(e.to_string()))
+ .into_response();
+ }
+ };
+ let result = match src.search(&req).await {
+ Ok(r) => r,
+ Err(e) => {
+ return ApiError::new(xerj_common::XerjError::from(e)).into_response();
+ }
+ };
+ let batch = result.hits.len();
+ if batch == 0 {
+ break;
+ }
+ // Capture the keyset cursor before the `for` loop consumes the hits.
+ let last_id = result.hits.last().map(|h| json!([h.id]));
+ for hit in result.hits {
+ if let Err(e) = dest.index_document(Some(hit.id.clone()), hit.source).await {
+ return ApiError::new(xerj_common::XerjError::from(e)).into_response();
+ }
+ materialised += 1;
+ }
+ fetched += batch;
+ search_after = last_id;
+ if batch < ENRICH_COPY_PAGE || fetched >= max_total {
+ break;
}
- materialised += 1;
}
}
diff --git a/engine/crates/xerj-api/tests/enrich_execute_copies_entire_index.rs b/engine/crates/xerj-api/tests/enrich_execute_copies_entire_index.rs
new file mode 100644
index 000000000..a911e9959
--- /dev/null
+++ b/engine/crates/xerj-api/tests/enrich_execute_copies_entire_index.rs
@@ -0,0 +1,207 @@
+//! Issue #1022: `POST /_enrich/policy/{name}/_execute` truncates its source
+//! copy at 10 000 documents per source index.
+//!
+//! The executor ran ONE search per source index — `{"query":{"match_all":{}},
+//! "size":10000,"_source":true}` — and copied whatever came back into the
+//! system index `.enrich-<name>`. With more than 10 000 docs in a source
+//! index the documents past the first page were silently never materialised,
+//! so every later enrich lookup against those keys silently misses (enrich
+//! correctness is keyed on completeness of the copy), and `records`
+//! under-reports.
+//!
+//! This endpoint is a reindex into a system index, so the fix adopts
+//! reindex's exact `_id`-keyset `search_after` loop. ES `_execute` has no
+//! `max_docs`/`scroll_size` wire parameters — none are invented here.
+//!
+//! Fails before the fix at `records` == 10 000 with the `.enrich-` index
+//! holding 10 000 of 10 500 documents.
+
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::{json, Value};
+use tower::ServiceExt;
+
+async fn app() -> (axum::Router, tempfile::TempDir) {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ (xerj_api::router::build_es_compat_router(state), dir)
+}
+
+async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(path);
+ let body = if body.is_null() {
+ Body::empty()
+ } else {
+ req = req.header("content-type", "application/json");
+ Body::from(body.to_string())
+ };
+ let response = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+}
+
+/// Seed `n` docs `{"k": "key-i", "payload": i}` with zero-padded ids so the
+/// `_id`-keyset copy pages deterministically.
+async fn seed_bulk(app: &axum::Router, index: &str, n: u64, offset: u64) {
+ let (st, _) = call(
+ app,
+ "PUT",
+ &format!("/{index}"),
+ json!({"mappings": {"properties": {
+ "k": {"type": "keyword"},
+ "payload": {"type": "long"},
+ }}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create {index}");
+
+ let width = (offset + n).to_string().len();
+ let chunk = 2_500u64;
+ let mut start = 0u64;
+ while start < n {
+ let end = (start + chunk).min(n);
+ let mut ndjson = String::new();
+ for i in start..end {
+ let gid = offset + i;
+ ndjson.push_str(&format!(
+ "{{\"index\":{{\"_id\":\"d{gid:0width$}\"}}}}\n{{\"k\":\"key-{gid}\",\"payload\":{gid}}}\n",
+ width = width
+ ));
+ }
+ let response = app
+ .clone()
+ .oneshot(
+ Request::post(format!("/{index}/_bulk"))
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(ndjson))
+ .unwrap(),
+ )
+ .await
+ .expect("bulk request");
+ assert_eq!(response.status(), StatusCode::OK, "bulk {start}..{end}");
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: Value = serde_json::from_slice(&bytes).expect("bulk body");
+ assert_eq!(body["errors"], json!(false), "bulk {start}..{end}: {body}");
+ start = end;
+ }
+ let (st, _) = call(app, "POST", &format!("/{index}/_refresh"), Value::Null).await;
+ assert_eq!(st, StatusCode::OK, "refresh {index}");
+}
+
+async fn count(app: &axum::Router, index: &str) -> u64 {
+ let (st, body) = call(
+ app,
+ "POST",
+ &format!("/{index}/_count"),
+ json!({"query": {"match_all": {}}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "_count {index}: {body}");
+ body["count"].as_u64().unwrap_or(u64::MAX)
+}
+
+/// Executing a policy over a 10 500-doc source must materialise ALL of them
+/// into `.enrich-<name>` — the copy is a lookup table, and a key missing from
+/// it is a lookup that silently misses forever. Fails before the fix at
+/// `records`/count == 10 000.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn enrich_execute_copies_past_ten_thousand() {
+ let (app, _dir) = app().await;
+ const N: u64 = 10_500;
+ seed_bulk(&app, "enrich-src", N, 0).await;
+
+ let (st, body) = call(
+ &app,
+ "PUT",
+ "/_enrich/policy/pol-big",
+ json!({"match": {
+ "indices": "enrich-src",
+ "match_field": "k",
+ "enrich_fields": ["payload"],
+ }}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/_enrich/policy/pol-big/_execute",
+ Value::Null,
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(
+ body["records"],
+ json!(N),
+ "records must be the exact source count, not the page length: {body}"
+ );
+
+ assert_eq!(
+ count(&app, ".enrich-pol-big").await,
+ N,
+ "the enrich index must hold every source document"
+ );
+ // Completeness is keyed: the LAST document of the _id order (the one the
+ // truncation dropped) must be present with its payload.
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/.enrich-pol-big/_search",
+ json!({"query": {"term": {"k": "key-10499"}}, "size": 1}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(
+ body["hits"]["hits"][0]["_source"]["payload"],
+ json!(10_499),
+ "the final source doc must be materialised with its fields"
+ );
+}
+
+/// A policy naming multiple source indices copies each one completely; a
+/// missing source index is skipped, not fatal (existing ES-tolerated
+/// behavior, pinned here so the paged rewrite keeps it).
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn enrich_execute_copies_every_source_index_and_skips_missing() {
+ let (app, _dir) = app().await;
+ seed_bulk(&app, "enrich-a", 300, 0).await;
+ seed_bulk(&app, "enrich-b", 200, 1_000).await;
+
+ let (st, body) = call(
+ &app,
+ "PUT",
+ "/_enrich/policy/pol-multi",
+ json!({"match": {
+ "indices": ["enrich-a", "enrich-b", "enrich-missing"],
+ "match_field": "k",
+ "enrich_fields": ["payload"],
+ }}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/_enrich/policy/pol-multi/_execute",
+ Value::Null,
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(body["records"], json!(500), "{body}");
+ assert_eq!(count(&app, ".enrich-pol-multi").await, 500);
+}
diff --git a/engine/crates/xerj-api/tests/significant_text_profile_counts_every_doc.rs b/engine/crates/xerj-api/tests/significant_text_profile_counts_every_doc.rs
new file mode 100644
index 000000000..3ddf2872b
--- /dev/null
+++ b/engine/crates/xerj-api/tests/significant_text_profile_counts_every_doc.rs
@@ -0,0 +1,249 @@
+//! Issue #1022: the `significant_text` profiler debug fast path truncates its
+//! foreground fetch at 10 000 documents per index.
+//!
+//! When a `profile: true` request carries a `significant_text` agg, the
+//! handler pre-fetches the query-matched (foreground) docs with ONE search —
+//! `{"query": …, "size": 10000, "from": 0}` — and folds their sources into
+//! ES's profiler debug block (total_buckets / values_fetched / chars_fetched
+//! / extract_count / collect_analyzed_count). With more than 10 000 matched
+//! docs every counter silently under-reports: the profiler debug block is an
+//! exact-statistics surface, and it reports made-up numbers.
+//!
+//! The counters are order-independent folds (sums and per-group unions), so
+//! the fix feeds every matched doc through an incremental accumulator in one
+//! engine walk — no materialisation, no paging order requirement.
+//!
+//! Fails before the fix at extract_count/values_fetched == 10 000 for a
+//! 10 500-doc corpus (chars_fetched 110 000 vs 115 500,
+//! collect_analyzed_count 20 000 vs 21 000).
+
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::{json, Value};
+use tower::ServiceExt;
+
+async fn app() -> (axum::Router, tempfile::TempDir) {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ (xerj_api::router::build_es_compat_router(state), dir)
+}
+
+async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(path);
+ let body = if body.is_null() {
+ Body::empty()
+ } else {
+ req = req.header("content-type", "application/json");
+ Body::from(body.to_string())
+ };
+ let response = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+}
+
+/// Seed `n` identical docs `{"t": "hello world"}` — 11 chars, 2 analyzed
+/// tokens per doc, token union of 2 — so every counter is a closed-form
+/// function of `n`.
+async fn seed_bulk(app: &axum::Router, index: &str, n: u64) {
+ let (st, _) = call(
+ app,
+ "PUT",
+ &format!("/{index}"),
+ json!({"mappings": {"properties": {"t": {"type": "text"}}}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create {index}");
+
+ let width = n.to_string().len();
+ let chunk = 2_500u64;
+ let mut start = 0u64;
+ while start < n {
+ let end = (start + chunk).min(n);
+ let mut ndjson = String::new();
+ for i in start..end {
+ ndjson.push_str(&format!(
+ "{{\"index\":{{\"_id\":\"d{i:0width$}\"}}}}\n{{\"t\":\"hello world\"}}\n",
+ width = width
+ ));
+ }
+ let response = app
+ .clone()
+ .oneshot(
+ Request::post(format!("/{index}/_bulk"))
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(ndjson))
+ .unwrap(),
+ )
+ .await
+ .expect("bulk request");
+ assert_eq!(response.status(), StatusCode::OK, "bulk {start}..{end}");
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: Value = serde_json::from_slice(&bytes).expect("bulk body");
+ assert_eq!(body["errors"], json!(false), "bulk {start}..{end}: {body}");
+ start = end;
+ }
+ let (st, _) = call(app, "POST", &format!("/{index}/_refresh"), Value::Null).await;
+ assert_eq!(st, StatusCode::OK, "refresh {index}");
+}
+
+fn sig_debug(body: &Value) -> &Value {
+ &body["profile"]["shards"][0]["aggregations"][0]["debug"]
+}
+
+/// Profiling a `significant_text` agg over 10 500 matched docs must count
+/// ALL of them: the debug block is an exact-statistics surface. Every doc is
+/// `{"t": "hello world"}` (1 string value, 11 chars, 2 distinct tokens), so
+/// the exact answers are closed-form in N.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn significant_text_profile_counts_past_ten_thousand() {
+ let (app, _dir) = app().await;
+ const N: u64 = 10_500;
+ seed_bulk(&app, "sig-big", N).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/sig-big/_search",
+ json!({
+ "size": 0,
+ "profile": true,
+ "query": {"match_all": {}},
+ "aggs": {"sig": {"significant_text": {"field": "t"}}},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ let debug = sig_debug(&body);
+ assert_eq!(
+ debug.get("collection_strategy").and_then(Value::as_str),
+ Some("analyze text from _source"),
+ "{debug}"
+ );
+ assert_eq!(
+ debug["extract_count"],
+ json!(N),
+ "extract_count must count every matched doc: {debug}"
+ );
+ assert_eq!(
+ debug["values_fetched"],
+ json!(N),
+ "one string value per doc: {debug}"
+ );
+ assert_eq!(
+ debug["chars_fetched"],
+ json!(11 * N),
+ "11 chars per doc: {debug}"
+ );
+ assert_eq!(
+ debug["collect_analyzed_count"],
+ json!(2 * N),
+ "2 distinct tokens per doc: {debug}"
+ );
+ assert_eq!(
+ debug["total_buckets"],
+ json!(2),
+ "token union across the single (no parent bucket) group: {debug}"
+ );
+}
+
+/// The same walk must stay byte-identical on the small corpus the YAML suite
+/// pins (7-doc shape): 7 docs of 11 chars → the historical exact answers.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn significant_text_profile_small_corpus_unchanged() {
+ let (app, _dir) = app().await;
+ seed_bulk(&app, "sig-small", 7).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/sig-small/_search",
+ json!({
+ "size": 0,
+ "profile": true,
+ "query": {"match_all": {}},
+ "aggs": {"sig": {"significant_text": {"field": "t"}}},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ let debug = sig_debug(&body);
+ assert_eq!(debug["extract_count"], json!(7), "{debug}");
+ assert_eq!(debug["values_fetched"], json!(7), "{debug}");
+ assert_eq!(debug["chars_fetched"], json!(77), "{debug}");
+ assert_eq!(debug["collect_analyzed_count"], json!(14), "{debug}");
+ assert_eq!(debug["total_buckets"], json!(2), "{debug}");
+}
+
+/// A selective foreground query folds only the matched docs — the fold's
+/// membership must agree with the search path's.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn significant_text_profile_honors_foreground_query() {
+ let (app, _dir) = app().await;
+ // 20 docs; the query matches only ids d00xx with an even prefix digit —
+ // use a range on a numeric field for a portable selective query.
+ let (st, _) = call(
+ &app,
+ "PUT",
+ "/sig-sel",
+ json!({"mappings": {"properties": {
+ "t": {"type": "text"},
+ "v": {"type": "long"},
+ }}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK);
+ let mut ndjson = String::new();
+ for i in 0..20u64 {
+ ndjson.push_str(&format!(
+ "{{\"index\":{{\"_id\":\"d{i:02}\"}}}}\n{{\"t\":\"hello world\",\"v\":{i}}}\n"
+ ));
+ }
+ let response = app
+ .clone()
+ .oneshot(
+ Request::post("/sig-sel/_bulk")
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(ndjson))
+ .unwrap(),
+ )
+ .await
+ .expect("bulk");
+ assert_eq!(response.status(), StatusCode::OK);
+ call(&app, "POST", "/sig-sel/_refresh", Value::Null).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/sig-sel/_search",
+ json!({
+ "size": 0,
+ "profile": true,
+ "query": {"range": {"v": {"gte": 10}}},
+ "aggs": {"sig": {"significant_text": {"field": "t"}}},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ let debug = sig_debug(&body);
+ assert_eq!(
+ debug["extract_count"],
+ json!(10),
+ "only the matched 10: {debug}"
+ );
+ assert_eq!(debug["values_fetched"], json!(10), "{debug}");
+ assert_eq!(debug["chars_fetched"], json!(110), "{debug}");
+ assert_eq!(debug["collect_analyzed_count"], json!(20), "{debug}");
+}
diff --git a/engine/crates/xerj-api/tests/update_by_query_updates_entire_index.rs b/engine/crates/xerj-api/tests/update_by_query_updates_entire_index.rs
new file mode 100644
index 000000000..409a83802
--- /dev/null
+++ b/engine/crates/xerj-api/tests/update_by_query_updates_entire_index.rs
@@ -0,0 +1,372 @@
+//! Issue #1022: `_update_by_query` truncates at 10 000 documents per call.
+//!
+//! The handler built ONE search body — `{"query": …, "size": 10000, "from":
+//! 0}` — transformed whatever came back, and reported `total` as the page
+//! length with `batches` hardcoded to 1. Under the two real uses of the
+//! endpoint (mass scripted migration, mapping-change pickup via the no-script
+//! re-index-in-place) exactly the documents past the first page kept their
+//! stale values while the call reported success with `total == 10 000`.
+//!
+//! ES semantics (8.18 docs-update-by-query): no default document cap — the
+//! whole match set is processed in `scroll_size` batches (default 1 000)
+//! unless `max_docs` limits it; `total` is the exact match count (the
+//! snapshot the operation started from), `batches` the real number of scroll
+//! responses pulled back.
+//!
+//! These tests go through the real HTTP route. They fail before the fix at
+//! `total`/`updated` == 10 000 with docs 10 000..N left untouched.
+//!
+//! Elasticsearch is referenced for wire semantics only (approach-only per the
+//! licence rules); no ES code is reproduced here.
+
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::{json, Value};
+use tower::ServiceExt;
+
+async fn app() -> (axum::Router, tempfile::TempDir) {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ (xerj_api::router::build_es_compat_router(state), dir)
+}
+
+async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(path);
+ let body = if body.is_null() {
+ Body::empty()
+ } else {
+ req = req.header("content-type", "application/json");
+ Body::from(body.to_string())
+ };
+ let response = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+}
+
+/// Seed `n` docs `{"v": i, "n": 0}` into `index` via `_bulk` (chunked so no
+/// single request body is enormous). Ids are zero-padded so lexicographic
+/// `_id` order is deterministic — the paginated runner pages by `_id` keyset.
+async fn seed_bulk(app: &axum::Router, index: &str, n: u64) {
+ let (st, _) = call(
+ app,
+ "PUT",
+ &format!("/{index}"),
+ json!({"mappings": {"properties": {
+ "v": {"type": "long"},
+ "n": {"type": "long"},
+ "touched": {"type": "long"},
+ }}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create {index}");
+
+ let width = n.to_string().len();
+ let chunk = 2_500u64;
+ let mut start = 0u64;
+ while start < n {
+ let end = (start + chunk).min(n);
+ let mut ndjson = String::new();
+ for i in start..end {
+ ndjson.push_str(&format!(
+ "{{\"index\":{{\"_id\":\"d{i:0width$}\"}}}}\n{{\"v\":{i},\"n\":0}}\n",
+ width = width
+ ));
+ }
+ let response = app
+ .clone()
+ .oneshot(
+ Request::post(format!("/{index}/_bulk"))
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(ndjson))
+ .unwrap(),
+ )
+ .await
+ .expect("bulk request");
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "bulk chunk {start}..{end}"
+ );
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: Value = serde_json::from_slice(&bytes).expect("bulk body");
+ assert_eq!(
+ body["errors"],
+ json!(false),
+ "bulk chunk {start}..{end}: {body}"
+ );
+ start = end;
+ }
+ let (st, _) = call(app, "POST", &format!("/{index}/_refresh"), Value::Null).await;
+ assert_eq!(st, StatusCode::OK, "refresh {index}");
+}
+
+async fn count_query(app: &axum::Router, index: &str, query: Value) -> u64 {
+ let (st, body) = call(
+ app,
+ "POST",
+ &format!("/{index}/_count"),
+ json!({"query": query}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "_count {index}: {body}");
+ body["count"].as_u64().unwrap_or(u64::MAX)
+}
+
+/// One scripted `_update_by_query` over 25 000 matching docs must update ALL
+/// of them — no 10k truncation, `total` the exact match count, `batches` the
+/// real page count, and every document carrying the scripted mutation.
+/// Fails before the fix at total/updated == 10 000 with 15 000 docs left
+/// `touched`-less.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn update_by_query_scripts_past_ten_thousand_in_one_call() {
+ let (app, _dir) = app().await;
+ const N: u64 = 25_000;
+ seed_bulk(&app, "ubq-big", N).await;
+ assert_eq!(
+ count_query(&app, "ubq-big", json!({"match_all": {}})).await,
+ N,
+ "seeded"
+ );
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/ubq-big/_update_by_query",
+ json!({
+ "query": {"match_all": {}},
+ "script": {"source": "ctx._source.touched = 1"},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(
+ body["total"],
+ json!(N),
+ "total must be the exact match count, not the page length: {body}"
+ );
+ assert_eq!(
+ body["updated"],
+ json!(N),
+ "every matching doc updated by ONE call: {body}"
+ );
+ let batches = body["batches"].as_u64().expect("batches");
+ assert!(
+ batches >= 3,
+ "a 25k run at the default scroll_size of 1000 must pull real batches, got {batches}: {body}"
+ );
+ assert_eq!(body["failures"], json!([]), "{body}");
+
+ assert_eq!(
+ count_query(&app, "ubq-big", json!({"term": {"touched": 1}})).await,
+ N,
+ "every document must carry the scripted mutation"
+ );
+}
+
+/// The no-script form (re-index-in-place, the pick-up-mapping-changes use)
+/// must equally cover the whole match set — it pages with per-page source
+/// hydration instead of the ids-only projection, and the exactness contract
+/// is the same. Fails before the fix at total/updated == 10 000.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn update_by_query_reindexes_past_ten_thousand_in_one_call() {
+ let (app, _dir) = app().await;
+ const N: u64 = 25_000;
+ seed_bulk(&app, "ubq-noscript", N).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/ubq-noscript/_update_by_query",
+ json!({"query": {"match_all": {}}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(body["total"], json!(N), "{body}");
+ assert_eq!(body["updated"], json!(N), "{body}");
+ let batches = body["batches"].as_u64().expect("batches");
+ assert!(batches >= 3, "real batch count, got {batches}: {body}");
+ assert_eq!(body["failures"], json!([]), "{body}");
+
+ assert_eq!(
+ count_query(&app, "ubq-noscript", json!({"match_all": {}})).await,
+ N,
+ "re-index-in-place must not lose documents"
+ );
+ // The re-index preserves the source: a term from the original docs still
+ // matches exactly N documents.
+ assert_eq!(
+ count_query(&app, "ubq-noscript", json!({"range": {"v": {"gte": 0}}})).await,
+ N,
+ "re-index-in-place must preserve field values"
+ );
+}
+
+/// ES `max_docs`: "Maximum number of documents to process. Defaults to all
+/// documents." Exactly `max_docs` documents are updated, `total` reports the
+/// processed count, and a `max_docs <= scroll_size` run is a single batch
+/// (the documented no-scroll fast path).
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn update_by_query_honors_max_docs() {
+ let (app, _dir) = app().await;
+ seed_bulk(&app, "ubq-max", 20).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/ubq-max/_update_by_query",
+ json!({
+ "query": {"match_all": {}},
+ "max_docs": 7,
+ "script": {"source": "ctx._source.touched = 1"},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(
+ body["total"],
+ json!(7),
+ "with max_docs set, total is the processed count: {body}"
+ );
+ assert_eq!(body["updated"], json!(7), "{body}");
+ assert_eq!(
+ body["batches"],
+ json!(1),
+ "max_docs <= scroll_size is a single batch: {body}"
+ );
+
+ assert_eq!(
+ count_query(&app, "ubq-max", json!({"term": {"touched": 1}})).await,
+ 7,
+ "exactly max_docs documents updated"
+ );
+}
+
+/// ES `scroll_size` (default 1 000): the size of the batch that powers the
+/// operation — `batches` is the number of batches actually pulled.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn update_by_query_reports_real_batch_count() {
+ let (app, _dir) = app().await;
+ seed_bulk(&app, "ubq-scroll", 10).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/ubq-scroll/_update_by_query",
+ json!({
+ "query": {"match_all": {}},
+ "scroll_size": 3,
+ "script": {"source": "ctx._source.touched = 1"},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(body["total"], json!(10), "{body}");
+ assert_eq!(body["updated"], json!(10), "{body}");
+ assert_eq!(
+ body["batches"],
+ json!(4),
+ "10 docs at scroll_size 3 = 4 batches: {body}"
+ );
+ assert_eq!(
+ count_query(&app, "ubq-scroll", json!({"term": {"touched": 1}})).await,
+ 10,
+ );
+}
+
+/// A selective query must page exactly like match_all: every matching doc
+/// updated, non-matching untouched, `total` the exact match count.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn update_by_query_paginates_selective_queries() {
+ let (app, _dir) = app().await;
+ seed_bulk(&app, "ubq-sel", 30).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/ubq-sel/_update_by_query",
+ json!({
+ "query": {"range": {"v": {"gte": 10}}},
+ "scroll_size": 4,
+ "script": {"source": "ctx._source.touched = 1"},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(body["total"], json!(20), "docs with v >= 10: {body}");
+ assert_eq!(body["updated"], json!(20), "{body}");
+ assert_eq!(
+ body["batches"],
+ json!(5),
+ "20 matches at scroll_size 4 = 5 batches: {body}"
+ );
+
+ assert_eq!(
+ count_query(&app, "ubq-sel", json!({"term": {"touched": 1}})).await,
+ 20,
+ "exactly the matched docs updated"
+ );
+}
+
+/// MID-RUN REWRITE HAZARD (the one thing `_update_by_query` has that
+/// `_delete_by_query` did not): the updates themselves repopulate the
+/// memtable, and a later page's search must not page over unflushed state —
+/// a rewritten doc with `_id <= cursor` resurfacing on a later page would
+/// apply the script TWICE (silent corruption, versus delete's idempotent
+/// duplicate). A counter script over a paged run must increment each doc
+/// exactly once.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn update_by_query_applies_script_exactly_once_per_doc_when_paged() {
+ let (app, _dir) = app().await;
+ const N: u64 = 2_500;
+ seed_bulk(&app, "ubq-once", N).await;
+
+ let (st, body) = call(
+ &app,
+ "POST",
+ "/ubq-once/_update_by_query",
+ json!({
+ "query": {"match_all": {}},
+ "scroll_size": 100,
+ "script": {"source": "ctx._source.n += 1"},
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "{body}");
+ assert_eq!(body["total"], json!(N), "{body}");
+ assert_eq!(body["updated"], json!(N), "{body}");
+ assert_eq!(
+ body["batches"],
+ json!(25),
+ "2500 docs at scroll_size 100 = 25 batches: {body}"
+ );
+ assert_eq!(body["failures"], json!([]), "{body}");
+
+ assert_eq!(
+ count_query(&app, "ubq-once", json!({"term": {"n": 1}})).await,
+ N,
+ "every doc incremented exactly once"
+ );
+ assert_eq!(
+ count_query(&app, "ubq-once", json!({"term": {"n": 0}})).await,
+ 0,
+ "no doc left un-incremented"
+ );
+ assert_eq!(
+ count_query(&app, "ubq-once", json!({"range": {"n": {"gte": 2}}})).await,
+ 0,
+ "no doc double-applied"
+ );
+}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c24bbd605..c5b8567b7 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -17854,6 +17854,305 @@ impl Index {
Some(ids)
}
+ /// Single-pass `_source` fold over the whole live match set (#1022).
+ ///
+ /// Calls `f` with the `_source` of every live document matching `query`,
+ /// holding ONE parsed doc at a time. This is the read-side analogue of
+ /// `matching_ids_sorted`: the significant_text profiler fast path used to
+ /// issue ONE `size: 10_000` search and fold the materialised hits, so on
+ /// a corpus past one page it silently under-counted every exact-statistics
+ /// counter — and it materialised up to 10 k full `Value` trees per index
+ /// to do it (the #950 RSS-transient class). The fold is exact at any
+ /// corpus size and never holds more than one source.
+ ///
+ /// Why a fold and not keyset paging: the consumers of this walk need
+ /// completeness and duplicate-freedom, not page ORDER (their counters are
+ /// order-independent folds). That is exactly the property `_id`-keyset
+ /// `search_after` paging cannot give without a flush — the memtable's
+ /// field-sort path does not order by `_id` reliably, and a read endpoint
+ /// (`_search`) must not flush. One walk needs neither.
+ ///
+ /// Membership agrees with the search path's: the query is resolved
+ /// through the same pipeline `search_inner` applies (alias rewrite,
+ /// keyword→term, lexically-typeless lowering, single-clause bool unwrap)
+ /// and then matched per doc with the same typed matcher the memtable scan
+ /// arm uses (`doc_matches_query_typed`); liveness is the same rule the
+ /// scan arms apply (version-map tombstone skip, superseded-copy skip, one
+ /// id per walk, memtable copy preferred over a stale segment copy).
+ ///
+ /// Consistency under a concurrent publication: the segment snapshot holds
+ /// its read lease for the whole walk (retired segment files persist), so
+ /// a mid-walk flush or merge can neither orphan a byte range nor feed an
+ /// id twice — a drained-then-flushed doc is either still in this
+ /// snapshot's memtable capture or in one of its segments, never both
+ /// (dedup by id) and never neither (the lease keeps the old segment
+ /// readable). Docs written after the walk started may or may not be seen;
+ /// that is the same window any single search has.
+ pub async fn fold_match_sources<F: FnMut(&Value)>(&self, query: &QueryNode, f: &mut F) {
+ // Resolve the query exactly as `search_inner` does (two guard takes,
+ // same as that function's `dmq_schema` then `schema.read()` pair).
+ let dmq_schema = self.schema().await;
+ let resolved_query = {
+ let schema = self.schema.read().await;
+ let resolved = rewrite_keyword_full_text_to_term(
+ &rewrite_query_aliases(query, &schema.schema),
+ &schema.schema,
+ );
+ let typeless = crate::memtable::lexically_typeless_fields(&schema.schema);
+ let lowered = if typeless.is_empty() {
+ resolved
+ } else {
+ lower_lexically_typeless_clauses(&resolved, &typeless)
+ };
+ unwrap_single_clause_bool(lowered)
+ };
+ let is_match_all = matches!(resolved_query, QueryNode::MatchAll);
+ let needs_id_injection = query_needs_id_injection(&resolved_query);
+ let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
+
+ // ── Memtable: one Arc-shared snapshot, matched per doc ──────────────
+ // Deletes remove from the memtable, so `docs` is live by construction;
+ // the ghost-window check (below) only guards the window where the
+ // live copy of an id moved to a segment between snapshot and now —
+ // the segment walk covers that id instead.
+ let ghost_filter = self.store.version_map.ghost_events() > 0;
+ for (_seq_no, doc_id, source) in self.memtable.all_docs_with_seq_arc() {
+ if ghost_filter {
+ if let Some(ver) = self.store.version_map.get(&doc_id) {
+ if ver.deleted
+ || ver.segment_id.as_ref()
+ != xerj_storage::version_map::IN_MEMORY_SEGMENT_ID
+ {
+ continue;
+ }
+ }
+ }
+ if !seen.insert(doc_id.clone()) {
+ continue;
+ }
+ let matched = if is_match_all {
+ true
+ } else if let QueryNode::Ids { values } = &resolved_query {
+ values.iter().any(|v| v == doc_id.as_str())
+ } else if !needs_id_injection || source.get("_id").is_some() {
+ doc_matches_query_typed(&resolved_query, &source, &dmq_schema)
+ } else {
+ // Inject `_id` so deeply-nested Ids queries can resolve it
+ // (same fallback as the memtable scan arm).
+ let source_with_id = if let Some(obj) = source.as_object() {
+ let mut o = obj.clone();
+ o.insert("_id".to_string(), Value::String(doc_id.clone()));
+ Value::Object(o)
+ } else {
+ (*source).clone()
+ };
+ doc_matches_query_typed(&resolved_query, &source_with_id, &dmq_schema)
+ };
+ if matched && !source.is_null() {
+ f(&source);
+ }
+ }
+
+ // ── Segments: one stored-section walk per segment, one doc parsed
+ // at a time. The scan arms' brace-walk, reduced to its bones.
+ let snap = self.store.snapshot();
+ for meta in snap.segments.iter() {
+ let seg_id = meta.id.clone();
+ // Same cache discipline as the unsorted search path: reuse the
+ // retained decompressed section when present, else cold-decode
+ // (under the segment's single-flight lock, so concurrent cold
+ // walkers decode once) and publish it back for the next query.
+ let cached_bytes: Option<Vec<u8>> = self
+ .decoded_stored_cache
+ .get(seg_id.as_str())
+ .map(|e| e.value().value().clone())
+ .or_else(|| {
+ self.stored_slices_cache
+ .get(seg_id.as_str())
+ .map(|e| e.value().bytes.clone())
+ });
+ let stored_bytes = match cached_bytes {
+ Some(bytes) => bytes,
+ None => {
+ let flight = {
+ let entry = self
+ .stored_slices_build_locks
+ .entry(seg_id.clone())
+ .or_default();
+ std::sync::Arc::clone(entry.value())
+ };
+ let _flight_guard = flight.lock().ok();
+ // Re-check under the flight lock — another thread may
+ // have decoded and published while we waited.
+ let rechecked: Option<Vec<u8>> = self
+ .decoded_stored_cache
+ .get(seg_id.as_str())
+ .map(|e| e.value().value().clone())
+ .or_else(|| {
+ self.stored_slices_cache
+ .get(seg_id.as_str())
+ .map(|e| e.value().bytes.clone())
+ });
+ match rechecked {
+ Some(bytes) => bytes,
+ None => {
+ let decoded: Option<Vec<u8>> =
+ match self.store.open_segment_arc(&seg_id) {
+ Ok(reader) => match reader.section(SectionType::Stored) {
+ Ok(Some(raw)) => {
+ xerj_storage::stored_codec::decode_stored(raw).ok()
+ }
+ _ => None,
+ },
+ Err(_) => None,
+ };
+ match decoded {
+ Some(bytes) => {
+ let est = crate::segment_cache_estimates::decoded_stored_bytes(
+ &seg_id,
+ std::mem::size_of::<CacheResident<Vec<u8>>>(),
+ bytes.capacity(),
+ );
+ let _ = self.publish_current(
+ &self.decoded_stored_cache,
+ &seg_id,
+ seg_id.clone(),
+ SegmentCacheCategory::DecodedStored,
+ est,
+ bytes.clone(),
+ );
+ bytes
+ }
+ // Unreadable/undecodable section: the search
+ // path fails the whole query here; a fold has
+ // no error channel, so skip the segment and
+ // let the caller's own tolerance stand (the
+ // pre-fold fast path swallowed search errors
+ // the same way).
+ None => continue,
+ }
+ }
+ }
+ }
+ };
+
+ // Brace-walk the section: `[{...}, {...}, ...]` — find each
+ // top-level object's byte range by balanced-brace counting and
+ // parse only that slice (the same per-doc allocation discipline
+ // as `scan_stored_section_into`).
+ let bytes: &[u8] = &stored_bytes;
+ let n = bytes.len();
+ let mut i = 0usize;
+ while i < n && (bytes[i].is_ascii_whitespace() || bytes[i] == b'[') {
+ i += 1;
+ }
+ loop {
+ while i < n && (bytes[i].is_ascii_whitespace() || bytes[i] == b',') {
+ i += 1;
+ }
+ if i >= n || bytes[i] == b']' {
+ break;
+ }
+ if bytes[i] != b'{' {
+ break; // unexpected byte — stop this section gracefully
+ }
+ let start = i;
+ let mut depth = 0i32;
+ let mut in_str = false;
+ let mut escape = false;
+ while i < n {
+ let b = bytes[i];
+ if in_str {
+ if escape {
+ escape = false;
+ } else if b == b'\\' {
+ escape = true;
+ } else if b == b'"' {
+ in_str = false;
+ }
+ } else {
+ match b {
+ b'"' => in_str = true,
+ b'{' => depth += 1,
+ b'}' => {
+ depth -= 1;
+ if depth == 0 {
+ i += 1;
+ break;
+ }
+ }
+ _ => {}
+ }
+ }
+ i += 1;
+ }
+ if depth != 0 {
+ break; // malformed tail — stop this section gracefully
+ }
+ let slice = &bytes[start..i];
+
+ // Id first, borrowed where the layout allows (the #1019
+ // trick), falling back to the parsed doc's `_id`.
+ let borrowed_id = extract_stored_id_str(slice).map(str::to_string);
+ let mut doc_buf = slice.to_vec();
+ let doc: Value = match simd_json::serde::from_slice(&mut doc_buf) {
+ Ok(v) => v,
+ Err(_) => continue,
+ };
+ let id_owned = borrowed_id
+ .or_else(|| doc.get("_id").and_then(Value::as_str).map(str::to_string));
+ let id_ref: &str = match id_owned.as_deref() {
+ Some(id) => id,
+ None => continue,
+ };
+ if !seen.insert(id_ref.to_string()) {
+ continue;
+ }
+ // Version-map liveness + superseded-copy skip (the scan arm's
+ // exact predicate, including the raw-source-without-`_seq_no`
+ // pass-through).
+ if let Some(ver) = self.store.version_map.get(id_ref) {
+ if ver.deleted {
+ continue;
+ }
+ if let Some(doc_seq) = doc.get("_seq_no").and_then(Value::as_u64) {
+ if doc_seq < ver.seq_no {
+ continue;
+ }
+ }
+ }
+ let matched = if is_match_all {
+ true
+ } else if let QueryNode::Ids { values } = &resolved_query {
+ values.iter().any(|v| v == id_ref)
+ } else {
+ let source_ref = doc.get("_source").unwrap_or(&doc);
+ if needs_id_injection && source_ref.get("_id").is_none() {
+ let source_with_id = if let Some(obj) = source_ref.as_object() {
+ let mut o = obj.clone();
+ o.insert("_id".to_string(), Value::String(id_ref.to_string()));
+ Value::Object(o)
+ } else {
+ source_ref.clone()
+ };
+ doc_matches_query_typed(&resolved_query, &source_with_id, &dmq_schema)
+ } else {
+ doc_matches_query_typed(&resolved_query, source_ref, &dmq_schema)
+ }
+ };
+ if !matched {
+ continue;
+ }
+ // Same source rule as a hydrated hit: the envelope's
+ // `_source`, or the whole doc for raw-source layouts.
+ let source_ref = doc.get("_source").unwrap_or(&doc);
+ if !source_ref.is_null() {
+ f(source_ref);
+ }
+ }
+ }
+ }
+
/// Delete all documents matching the given query.
///
/// Collects the whole match set in one pass (`matching_ids_sorted`) and
diff --git a/engine/tests/es-compat-yaml/src/main.rs b/engine/tests/es-compat-yaml/src/main.rs
index 0cfaf2a9d..f5406526a 100644
--- a/engine/tests/es-compat-yaml/src/main.rs
+++ b/engine/tests/es-compat-yaml/src/main.rs
@@ -1173,6 +1173,9 @@ fn resolve_action(action: &str, params: &serde_yaml::Mapping) -> (String, String
// #1019 — pins the paginated delete-by-query contract (exact total,
// real batch count, max_docs).
"delete_by_query" => ("POST".into(), format!("/{}/_delete_by_query", index), body),
+ // #1022 — pins the paginated update-by-query contract (exact total,
+ // real batch count, max_docs, script applied to every matched doc).
+ "update_by_query" => ("POST".into(), format!("/{}/_update_by_query", index), body),
"scroll" => {
let mut path = "/_search/scroll".to_string();
let mut qp = Vec::new();
diff --git a/engine/tests/es-compat-yaml/yaml/update_by_query/10_multipage_update.yml b/engine/tests/es-compat-yaml/yaml/update_by_query/10_multipage_update.yml
new file mode 100644
index 000000000..cf0012340
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/update_by_query/10_multipage_update.yml
@@ -0,0 +1,88 @@
+---
+"update_by_query pages through the whole index in batches":
+ # Seed 6 docs; scroll_size 2 forces 3 batches, so the run must advance a
+ # keyset cursor across pages instead of stopping at the first batch
+ # (#1022: the runner used to fire ONE size=10000 search and truncate, and
+ # hardcoded batches: 1). The script must reach every matched doc.
+ - do:
+ indices.create:
+ index: ubq_src
+ body:
+ mappings:
+ properties:
+ n: { type: long }
+ touched: { type: long }
+ - do:
+ index: { index: ubq_src, id: "1", body: { n: 1 } }
+ - do:
+ index: { index: ubq_src, id: "2", body: { n: 2 } }
+ - do:
+ index: { index: ubq_src, id: "3", body: { n: 3 } }
+ - do:
+ index: { index: ubq_src, id: "4", body: { n: 4 } }
+ - do:
+ index: { index: ubq_src, id: "5", body: { n: 5 } }
+ - do:
+ index: { index: ubq_src, id: "6", refresh: true, body: { n: 6 } }
+
+ - do:
+ update_by_query:
+ index: ubq_src
+ body:
+ query: { match_all: {} }
+ scroll_size: 2
+ script: { source: "ctx._source.touched = 1" }
+
+ # total is the exact match count (not the first page's length), every
+ # matched doc updated, batches the real page count.
+ - match: { total: 6 }
+ - match: { updated: 6 }
+ - match: { batches: 3 }
+ - match: { failures: [] }
+
+ # Every doc carries the scripted mutation — none skipped past page one.
+ - do:
+ count:
+ index: ubq_src
+ body:
+ query: { term: { touched: 1 } }
+ - match: { count: 6 }
+
+---
+"update_by_query honors max_docs":
+ - do:
+ indices.create:
+ index: ubq_max
+ body:
+ mappings:
+ properties:
+ n: { type: long }
+ touched: { type: long }
+ - do:
+ index: { index: ubq_max, id: "1", body: { n: 1 } }
+ - do:
+ index: { index: ubq_max, id: "2", body: { n: 2 } }
+ - do:
+ index: { index: ubq_max, id: "3", refresh: true, body: { n: 3 } }
+
+ # ES: max_docs <= scroll_size means a single batch, no scroll; total then
+ # reports the processed count.
+ - do:
+ update_by_query:
+ index: ubq_max
+ body:
+ query: { match_all: {} }
+ max_docs: 2
+ script: { source: "ctx._source.touched = 1" }
+
+ - match: { total: 2 }
+ - match: { updated: 2 }
+ - match: { batches: 1 }
+ - match: { failures: [] }
+
+ - do:
+ count:
+ index: ubq_max
+ body:
+ query: { term: { touched: 1 } }
+ - match: { count: 2 }