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(engine): admit _bulk against the memory limiter before its parse (#2427) (#2440)

xerj-orgc470f1f45a6f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 901b8d0ee..1bc26037f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -87,6 +87,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
indexing worker now retries with a short backoff when thread creation is
refused, and the replay finishes on the calling thread if no worker can be
started, so a refusal is no longer fatal (#2428).
+- `_bulk` now checks the memory limiter before it parses the request, not
+ only when each index's batch is written. A bulk that arrived while the memory
+ or memtable breaker was engaged still split and copied its whole body first.
+ Several concurrent bulks between two RSS samples were each admitted on the
+ same old sample, which could carry the node past its memory cap. Each
+ request now counts its body against live RSS plus every other in-flight
+ reservation until its parse ends, and is answered with one HTTP 429 per action (top-level 429,
+ `Retry-After: 1`) when that would reach the watermark or a breaker is
+ engaged, so clients back off and re-offer every record (part of #2427).
- `xerj autoindex` no longer runs out of memory while planning a large folder.
It used to keep the sampled values of every file in memory at once before
grouping them into datasets, and kept them all until the end of the run;
diff --git a/engine/crates/xerj-engine/src/bulk.rs b/engine/crates/xerj-engine/src/bulk.rs
index 222363914..fcaf4d17a 100644
--- a/engine/crates/xerj-engine/src/bulk.rs
+++ b/engine/crates/xerj-engine/src/bulk.rs
@@ -402,6 +402,50 @@ pub struct BulkOpts {
pub default_pipeline: Option<String>,
}
+/// The action named by the first key of a bulk action line, without parsing
+/// the line. Anything unrecognised reads as `index`, the renderer's default.
+fn action_line_kind(line: &str) -> &'static str {
+ let rest = line.trim_start_matches([' ', '\t']);
+ let Some(rest) = rest.strip_prefix('{') else {
+ return "index";
+ };
+ let rest = rest.trim_start_matches([' ', '\t']);
+ let Some(rest) = rest.strip_prefix('"') else {
+ return "index";
+ };
+ match rest.split('"').next() {
+ Some("create") => "create",
+ Some("update") => "update",
+ Some("delete") => "delete",
+ _ => "index",
+ }
+}
+
+/// One refusal item per paired action, in body order (#2427). Used when the
+/// whole request is refused before its parse: a single summary item would
+/// not match the body's action count, and the autoindex client (like any
+/// client re-offering 429 items by position) could not map it back.
+fn refuse_every_action(
+ pairs: &[(usize, &str, Option<&str>, usize)],
+ default_index: Option<&str>,
+ error: &EngineError,
+) -> Vec<BulkItemResult> {
+ let status = engine_error_http_status(error);
+ let reason = error.to_string();
+ pairs
+ .iter()
+ .map(|(_, action_line, _, _)| BulkItemResult {
+ action: action_line_kind(action_line).to_string(),
+ index: default_index.unwrap_or("").to_string(),
+ id: String::new(),
+ status,
+ result: None,
+ error: Some(reason.clone()),
+ get_source: None,
+ })
+ .collect()
+}
+
pub async fn process_bulk_with_opts(
engine: &Engine,
default_index: Option<&str>,
@@ -549,6 +593,31 @@ pub async fn process_bulk_with_opts(
i += advance;
}
+ // #2427: memory admission for the whole request BEFORE the parse.
+ // The write paths below check the breaker only after the parse has built
+ // a document copy (and, for update/create, a parsed `Value`) per action,
+ // so a bulk admitted on a stale sample, or while a latch was engaged,
+ // allocated all of that first. `lines` and `pairs` borrow the body and
+ // cost a few words per action. Refuse here with one 429 per action (the
+ // client re-offers 429 items by position, so the count must match the
+ // body), or count the body against live RSS until the parse ends.
+ let parse_reservation = match crate::governor::global() {
+ Some(g) => match g.admit_bulk_parse(body.len() as u64) {
+ Ok(reservation) => Some(reservation),
+ Err(e) => {
+ // The refusal frees nothing by itself; ask for the drain on
+ // this 429 like `Index::governor_write_gate` (#2321).
+ crate::engine::request_memory_pressure_drain();
+ return BulkResult {
+ took_ms: started.elapsed().as_millis() as u64,
+ errors: true,
+ items: refuse_every_action(&pairs, default_index, &EngineError::Common(e)),
+ };
+ }
+ },
+ None => None,
+ };
+
// Step 2: parallel parse. Each tuple yields either a
// `ParsedAction` or an `ErrItem`. The order of the output
// vector matches the input order so `item_index` still
@@ -1119,6 +1188,9 @@ pub async fn process_bulk_with_opts(
});
let parse_ms = t_parse.elapsed().as_millis() as u64;
+ // The parse buffers now exist and are visible to the RSS sampler; each
+ // write path takes its own analyze reservation for the token spike.
+ drop(parse_reservation);
let t_group = std::time::Instant::now();
let mut parsed: Vec<ParsedAction> = Vec::with_capacity(parse_results.len());
for outcome in parse_results {
@@ -3759,3 +3831,43 @@ mod lone_surrogate_tests {
assert_eq!(index.live_doc_count(), (TOTAL - bad_positions.len()) as u64);
}
}
+
+#[cfg(test)]
+mod parse_admission_tests {
+ use super::*;
+
+ #[test]
+ fn action_line_kind_reads_the_first_key_without_parsing() {
+ assert_eq!(action_line_kind(r#"{"index":{"_index":"a"}}"#), "index");
+ assert_eq!(action_line_kind(r#" { "create":{}}"#), "create");
+ assert_eq!(action_line_kind(r#"{"update":{"_id":"1"}}"#), "update");
+ assert_eq!(action_line_kind(r#"{"delete":{"_id":"1"}}"#), "delete");
+ assert_eq!(action_line_kind("not json"), "index");
+ }
+
+ /// #2427: a request refused before its parse answers one 429 per action,
+ /// in body order, so a client re-offering 429 items by position can map
+ /// every item back onto the body it sent.
+ #[test]
+ fn a_refused_bulk_answers_one_429_per_action() {
+ let pairs: Vec<(usize, &str, Option<&str>, usize)> = vec![
+ (0, r#"{"index":{}}"#, Some(r#"{"a":1}"#), 0),
+ (2, r#"{"delete":{"_id":"x"}}"#, None, 1),
+ (3, r#"{"update":{"_id":"y"}}"#, Some(r#"{"doc":{}}"#), 2),
+ ];
+ let error = EngineError::Common(xerj_common::XerjError::circuit_breaking(
+ "[parent] real memory circuit breaker tripped",
+ ));
+ let items = refuse_every_action(&pairs, Some("logs"), &error);
+ assert_eq!(items.len(), 3);
+ assert_eq!(
+ items.iter().map(|i| i.action.as_str()).collect::<Vec<_>>(),
+ ["index", "delete", "update"]
+ );
+ for item in &items {
+ assert_eq!(item.status, 429);
+ assert_eq!(item.index, "logs");
+ assert!(item.error.as_deref().unwrap().contains("circuit breaker"));
+ }
+ }
+}
diff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rs
index a593642f0..ee07fa2e8 100644
--- a/engine/crates/xerj-engine/src/governor.rs
+++ b/engine/crates/xerj-engine/src/governor.rs
@@ -387,6 +387,26 @@ impl ResourceGovernor {
Err(self.analyze_reservation_refused(bytes))
}
+ /// Admit one `_bulk` request before its body is split and parsed (#2427).
+ ///
+ /// Every write path checks the breaker, but only after the bulk parse
+ /// has already built its per-action line, pair and document-copy vectors.
+ /// A request that arrives while a breaker is latched still did all of that
+ /// work, and concurrent bulks between two sampler ticks were admitted
+ /// on a sample that predates each other's parse buffers. This refuses the
+ /// request with the same 429 when either latch is engaged, and otherwise
+ /// reserves `body_bytes` against live RSS plus every other in-flight
+ /// reservation, so parse buffers are counted before they are allocated.
+ /// The caller drops the reservation when the parse ends; the per-index
+ /// write path then takes its own analyze reservation for the tokens.
+ pub(crate) fn admit_bulk_parse(
+ &self,
+ body_bytes: u64,
+ ) -> Result<AnalyzeReservation, XerjError> {
+ self.check_ingest_admission()?;
+ self.reserve_analyze(body_bytes)
+ }
+
fn observed_process_memory(&self) -> u64 {
self.rss_bytes
.load(Ordering::Relaxed)
@@ -2053,6 +2073,62 @@ mod tests {
/// The guard is a thin wrapper around [`analyze_reservation_fits`]. The
/// watermark sits above a live probe so the test does not depend on this
/// process's RSS, and a second reserve sees the first until it is dropped.
+ /// #2427: a bulk that arrives while a breaker is latched is refused
+ /// before its parse, and reserves nothing.
+ #[test]
+ fn bulk_parse_admission_refuses_while_a_breaker_is_latched() {
+ let mut cfg = Config::default();
+ cfg.limits.max_total_memtable_mb = 0;
+ let governor = build(&cfg);
+ let live = governor.observed_process_memory();
+ governor
+ .memory_watermark_bytes
+ .store(live.saturating_add(512 * 1024 * 1024), Ordering::Relaxed);
+ governor.rss_bytes.store(live, Ordering::Relaxed);
+
+ governor.memory_tripped.store(true, Ordering::Relaxed);
+ let refused = governor.admit_bulk_parse(1024).unwrap_err();
+ assert_eq!(refused.http_status(), 429, "{refused}");
+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);
+ governor.memory_tripped.store(false, Ordering::Relaxed);
+
+ governor.memtable_tripped.store(true, Ordering::Relaxed);
+ let refused = governor.admit_bulk_parse(1024).unwrap_err();
+ assert_eq!(refused.http_status(), 429, "{refused}");
+ assert!(refused.to_string().contains("memtable"), "{refused}");
+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);
+ }
+
+ /// #2427: an admitted bulk's body is counted against the watermark until
+ /// its parse ends, so concurrent bulks cannot each be admitted on the
+ /// same stale sample and together cross the cap.
+ #[test]
+ fn bulk_parse_admission_counts_concurrent_bodies_against_the_watermark() {
+ const MIB: u64 = 1024 * 1024;
+ let mut cfg = Config::default();
+ cfg.limits.max_total_memtable_mb = 0;
+ let governor = build(&cfg);
+ let live = governor.observed_process_memory();
+ governor
+ .memory_watermark_bytes
+ .store(live.saturating_add(1024 * MIB), Ordering::Relaxed);
+ governor.rss_bytes.store(live, Ordering::Relaxed);
+
+ let first = governor.admit_bulk_parse(400 * MIB).unwrap();
+ let second = governor.admit_bulk_parse(400 * MIB).unwrap();
+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 800 * MIB);
+ // A third body would reach the watermark: backpressure, not admission.
+ let refused = governor.admit_bulk_parse(400 * MIB).unwrap_err();
+ assert_eq!(refused.http_status(), 429, "{refused}");
+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 800 * MIB);
+
+ drop(first);
+ let third = governor.admit_bulk_parse(400 * MIB).unwrap();
+ drop(second);
+ drop(third);
+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);
+ }
+
#[test]
fn analyze_reservation_releases_and_sees_a_prior_reserve() {
let governor = build(&Config::default());