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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(engine): bound large-JSON ingest before the node aborts (#1122) (#2302)
xerj-orgf7b8e87134fc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d9d877801..61d6f4892 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `xerj autoindex` no longer aborts the node on one large JSON file (#1122).+ A bulk whose analysis would cross the memory watermark is rejected with+ HTTP 429 before the documents are parsed, so several in-flight bulks cannot+ allocate their token strings together. Uncompressed JSON larger than 64 MiB+ is read one value at a time; a value over the fixed 8 MiB document ceiling+ is skipped with a note that names the file, its size, and that+ `--max-file-mb` and `limits.max_process_memory_mb` do not raise that+ ceiling. A file over the scan cap names its size and `--max-file-mb`.+- `POST /{index}/_refresh` makes recent writes searchable without waiting fora background segment merge to finish, and a multi-index or wildcard refreshis not serialized behind one busy index. The route used to call thediff --git a/engine/crates/xerj-autoindex/src/extract/json.rs b/engine/crates/xerj-autoindex/src/extract/json.rsindex 2db9cf50f..617b94142 100644--- a/engine/crates/xerj-autoindex/src/extract/json.rs+++ b/engine/crates/xerj-autoindex/src/extract/json.rs@@ -18,6 +18,11 @@//! one element, over that ceiling is skipped and named — it is not indexed//! (#1122). Files at or under the ceiling keep the DOM path so existing//! locators stay byte-identical.+//!+//! An uncompressed file larger than [`MAX_WHOLE_FILE`] is not loaded at all.+//! A cursor walks it from disk and keeps at most one document-sized value.+//! Gzip stays on the in-memory cap: the uncompressed length is not known+//! until the bytes are inflated.use super::{emit_document_with_fields, ensure_text_passage, flatten_object, ExtractStats, FieldOrigin,@@ -29,9 +34,17 @@ use serde_json::value::RawValue;use serde_json::{Map, Value};use std::collections::{HashMap, HashSet};use std::fmt;+use std::io::{Read, Seek, SeekFrom};use std::ops::Range;use std::path::Path;+/// Sentence appended to a skip that the 8 MiB document ceiling caused.+///+/// `--max-file-mb` is the scan cap (default 2 GiB). `limits.max_process_memory_mb`+/// is the process watermark. Neither raises this ceiling.+const FIXED_DOCUMENT_CEILING: &str =+ "This ceiling is fixed and is not raised by --max-file-mb or limits.max_process_memory_mb";+pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {extract_limited(path,@@ -42,13 +55,33 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {}fn extract_limited(path: &Path, gzip: bool, sink: Sink, limit: usize) -> Result<ExtractStats> {+ extract_with_whole_file_cap(path, gzip, sink, limit, MAX_WHOLE_FILE)+}++fn extract_with_whole_file_cap(+ path: &Path,+ gzip: bool,+ sink: Sink,+ limit: usize,+ whole_file_cap: u64,+) -> Result<ExtractStats> {+ // Uncompressed JSON past the in-memory cap is walked from disk. The+ // 8–64 MiB window stays on `stream_large` so its locators stay the ones+ // the DOM path produced.+ if !gzip {+ if let Ok(meta) = std::fs::metadata(path) {+ if meta.is_file() && meta.len() > whole_file_cap {+ return stream_uncompressed_over_cap(path, meta.len(), limit, sink);+ }+ }+ }let mut stats = ExtractStats::default();- let Some(bytes) = super::read_whole(path, gzip, MAX_WHOLE_FILE)? else {+ let Some(bytes) = super::read_whole(path, gzip, whole_file_cap)? else {stats.junk += 1;stats.refusal = Some(format!(- "{} is larger than {} bytes; a JSON file over that size is not read. Split it into smaller files",+ "{} is larger than {whole_file_cap} bytes; a JSON file over that size is not read. \+ Split it into smaller files. {FIXED_DOCUMENT_CEILING}",file_label(path),- MAX_WHOLE_FILE));return Ok(stats);};@@ -477,9 +510,13 @@ fn file_label(path: &Path) -> String {}fn finish_empty_refusal(path: &Path, nbytes: usize, limit: usize, stats: &mut ExtractStats) {+ finish_empty_refusal_len(path, nbytes as u64, limit, stats);+}++fn finish_empty_refusal_len(path: &Path, nbytes: u64, limit: usize, stats: &mut ExtractStats) {if stats.records == 0 && stats.oversize_values > 0 && stats.refusal.is_none() {stats.refusal = Some(format!(- "{} is {nbytes} bytes; {} JSON value(s) were not indexed (over the {limit}-byte limit for one document). Split the file into smaller documents",+ "{} is {nbytes} bytes; {} JSON value(s) were not indexed (over the {limit}-byte limit for one document). Split the file into smaller documents. {FIXED_DOCUMENT_CEILING}",file_label(path),stats.oversize_values,));@@ -752,7 +789,7 @@ fn emit_single_object(if (skipped > 0 && kept.is_empty()) || sum > limit {stats.oversize_values += 1 + skipped;stats.refusal = Some(format!(- "{} is {} bytes; a JSON document over {limit} bytes is not indexed. Split the file into smaller documents",+ "{} is {} bytes; a JSON document over {limit} bytes is not indexed. Split the file into smaller documents. {FIXED_DOCUMENT_CEILING}",file_label(path),bytes.len(),));@@ -924,6 +961,793 @@ fn emit(v: Value, locator: &str, sink: Sink, stats: &mut ExtractStats) -> bool {})}+// Peak bytes retained from one JSON value. Tests assert this stays within the+// per-document cap while a larger sibling value is skipped.+#[cfg(test)]+thread_local! {+ static JSON_SCAN_STORED_PEAK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}++fn note_stored(capacity: usize) {+ #[cfg(test)]+ {+ JSON_SCAN_STORED_PEAK.with(|peak| {+ if capacity > peak.get() {+ peak.set(capacity);+ }+ });+ }+ #[cfg(not(test))]+ {+ let _ = capacity;+ }+}++#[derive(Debug)]+struct ScanError(String);++impl ScanError {+ fn new(message: impl Into<String>) -> Self {+ Self(message.into())+ }+}++impl fmt::Display for ScanError {+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {+ formatter.write_str(&self.0)+ }+}++impl std::error::Error for ScanError {}++impl From<std::io::Error> for ScanError {+ fn from(error: std::io::Error) -> Self {+ Self(error.to_string())+ }+}++enum ScanOutcome {+ Fits(Vec<u8>),+ Oversize,+}++struct Recorder {+ cap: usize,+ stored: Vec<u8>,+ over: bool,+}++impl Recorder {+ fn new(cap: usize) -> Self {+ Self {+ cap,+ stored: Vec::new(),+ over: false,+ }+ }++ fn push(&mut self, byte: u8) {+ if self.over {+ return;+ }+ if self.cap == 0 || self.stored.len() >= self.cap {+ self.over = true;+ self.stored = Vec::new();+ return;+ }+ if self.stored.len() == self.stored.capacity() {+ let room = self.cap - self.stored.len();+ let grow = room.min(self.stored.capacity().max(64).saturating_mul(2));+ if grow == 0 {+ self.over = true;+ self.stored = Vec::new();+ return;+ }+ self.stored.reserve_exact(grow);+ }+ self.stored.push(byte);+ note_stored(self.stored.len());+ }++ fn finish(self) -> ScanOutcome {+ if self.over {+ ScanOutcome::Oversize+ } else {+ ScanOutcome::Fits(self.stored)+ }+ }+}++struct JsonSrc {+ inner: std::fs::File,+ buf: Vec<u8>,+ buf_start: u64,+ pos: usize,+ filled: usize,+}++impl JsonSrc {+ fn new(inner: std::fs::File) -> Self {+ Self {+ inner,+ buf: vec![0; 64 * 1024],+ buf_start: 0,+ pos: 0,+ filled: 0,+ }+ }++ fn position(&self) -> u64 {+ self.buf_start + self.pos as u64+ }++ fn fill(&mut self) -> Result<(), ScanError> {+ if self.pos < self.filled {+ return Ok(());+ }+ let at = self.position();+ self.inner.seek(SeekFrom::Start(at))?;+ let n = self.inner.read(&mut self.buf)?;+ self.buf_start = at;+ self.pos = 0;+ self.filled = n;+ Ok(())+ }++ fn peek(&mut self) -> Result<Option<u8>, ScanError> {+ self.fill()?;+ if self.pos >= self.filled {+ return Ok(None);+ }+ Ok(Some(self.buf[self.pos]))+ }++ fn bump(&mut self) -> Result<Option<u8>, ScanError> {+ let byte = self.peek()?;+ if byte.is_some() {+ self.pos += 1;+ }+ Ok(byte)+ }++ fn skip_ws(&mut self) -> Result<(), ScanError> {+ while let Some(byte) = self.peek()? {+ if matches!(byte, b' ' | b'\t' | b'\n' | b'\r') {+ self.bump()?;+ } else {+ break;+ }+ }+ Ok(())+ }++ fn seek_to(&mut self, at: u64) -> Result<(), ScanError> {+ if at >= self.buf_start && (at - self.buf_start) < self.filled as u64 {+ self.pos = (at - self.buf_start) as usize;+ return Ok(());+ }+ self.inner.seek(SeekFrom::Start(at))?;+ self.buf_start = at;+ self.pos = 0;+ self.filled = 0;+ Ok(())+ }++ fn read_range(&mut self, start: u64, end: u64) -> Result<Vec<u8>, ScanError> {+ if end < start {+ return Err(ScanError::new("invalid JSON span"));+ }+ let len = usize::try_from(end - start)+ .map_err(|_| ScanError::new("JSON value does not fit in memory"))?;+ let mut out = vec![0; len];+ self.inner.seek(SeekFrom::Start(start))?;+ self.inner.read_exact(&mut out)?;+ self.buf_start = end;+ self.pos = 0;+ self.filled = 0;+ Ok(out)+ }+}++fn expect_byte(src: &mut JsonSrc, want: u8) -> Result<(), ScanError> {+ match src.bump()? {+ Some(byte) if byte == want => Ok(()),+ Some(byte) => Err(ScanError::new(format!(+ "expected '{}', found byte {byte}",+ want as char+ ))),+ None => Err(ScanError::new("truncated JSON")),+ }+}++const JSON_NEST_MAX: usize = 128;++fn scan_value(src: &mut JsonSrc, cap: usize) -> Result<ScanOutcome, ScanError> {+ let mut rec = Recorder::new(cap);+ let byte = src+ .bump()?+ .ok_or_else(|| ScanError::new("truncated JSON value"))?;+ rec.push(byte);+ match byte {+ b'"' => scan_string_body(src, &mut rec)?,+ b'{' => scan_nest(src, &mut rec, b'}')?,+ b'[' => scan_nest(src, &mut rec, b']')?,+ b't' => scan_exact(src, &mut rec, b"rue")?,+ b'f' => scan_exact(src, &mut rec, b"alse")?,+ b'n' => scan_exact(src, &mut rec, b"ull")?,+ b'-' | b'0'..=b'9' => scan_number_rest(src, &mut rec)?,+ _ => return Err(ScanError::new("invalid JSON value")),+ }+ Ok(rec.finish())+}++fn scan_exact(src: &mut JsonSrc, rec: &mut Recorder, rest: &[u8]) -> Result<(), ScanError> {+ for &expected in rest {+ match src.bump()? {+ Some(byte) if byte == expected => rec.push(byte),+ _ => return Err(ScanError::new("invalid JSON literal")),+ }+ }+ Ok(())+}++fn scan_number_rest(src: &mut JsonSrc, rec: &mut Recorder) -> Result<(), ScanError> {+ loop {+ match src.peek()? {+ Some(byte)+ if byte.is_ascii_digit() || matches!(byte, b'+' | b'-' | b'.' | b'e' | b'E') =>+ {+ let Some(byte) = src.bump()? else {+ return Ok(());+ };+ rec.push(byte);+ }+ _ => return Ok(()),+ }+ }+}++fn scan_string_body(src: &mut JsonSrc, rec: &mut Recorder) -> Result<(), ScanError> {+ loop {+ let byte = src+ .bump()?+ .ok_or_else(|| ScanError::new("truncated JSON string"))?;+ rec.push(byte);+ if byte == b'\\' {+ let escaped = src+ .bump()?+ .ok_or_else(|| ScanError::new("truncated JSON string"))?;+ rec.push(escaped);+ if escaped == b'u' {+ for _ in 0..4 {+ let hex = src+ .bump()?+ .ok_or_else(|| ScanError::new("truncated JSON string"))?;+ if !hex.is_ascii_hexdigit() {+ return Err(ScanError::new("invalid JSON unicode escape"));+ }+ rec.push(hex);+ }+ }+ continue;+ }+ if byte == b'"' {+ return Ok(());+ }+ }+}++fn scan_nest(src: &mut JsonSrc, rec: &mut Recorder, closer: u8) -> Result<(), ScanError> {+ let mut stack = Vec::with_capacity(8);+ stack.push(closer);+ let mut in_string = false;+ let mut escape = false;+ while !stack.is_empty() {+ let byte = src+ .bump()?+ .ok_or_else(|| ScanError::new("truncated JSON value"))?;+ rec.push(byte);+ if in_string {+ if escape {+ escape = false;+ continue;+ }+ if byte == b'\\' {+ escape = true;+ continue;+ }+ if byte == b'"' {+ in_string = false;+ }+ continue;+ }+ match byte {+ b'"' => in_string = true,+ b'{' | b'[' => {+ if stack.len() >= JSON_NEST_MAX {+ return Err(ScanError::new("JSON nesting exceeds 128"));+ }+ stack.push(if byte == b'{' { b'}' } else { b']' });+ }+ b'}' | b']' if stack.pop() != Some(byte) => {+ return Err(ScanError::new("mismatched JSON bracket"));+ }+ b'}' | b']' => {}+ _ => {}+ }+ }+ Ok(())+}++fn read_object_key(src: &mut JsonSrc) -> Result<String, ScanError> {+ let ScanOutcome::Fits(bytes) = scan_value(src, 1 << 20)? else {+ return Err(ScanError::new("JSON object key is too long"));+ };+ serde_json::from_slice(&bytes).map_err(|error| ScanError::new(error.to_string()))+}++struct DiskField {+ key: String,+ start: u64,+ end: u64,+ record_len: Option<u64>,+}++struct ArrayMeasure {+ end: u64,+ record_len: Option<u64>,+}++fn after_value(src: &mut JsonSrc, end: u8) -> Result<(), ScanError> {+ src.skip_ws()?;+ match src.peek()? {+ Some(b',') => {+ src.bump()?;+ src.skip_ws()?;+ if matches!(src.peek()?, Some(byte) if byte == end) || src.peek()?.is_none() {+ return Err(ScanError::new("trailing comma in JSON"));+ }+ Ok(())+ }+ Some(byte) if byte == end => Ok(()),+ _ => Err(ScanError::new("expected comma or end of JSON value")),+ }+}++fn measure_array(src: &mut JsonSrc) -> Result<ArrayMeasure, ScanError> {+ expect_byte(src, b'[')?;+ let mut objects = 0u64;+ let mut others = 0u64;+ loop {+ src.skip_ws()?;+ match src.peek()? {+ None => return Err(ScanError::new("truncated JSON array")),+ Some(b']') => {+ src.bump()?;+ break;+ }+ Some(byte) => {+ if byte == b'{' {+ objects += 1;+ } else {+ others += 1;+ }+ let _ = scan_value(src, 0)?;+ after_value(src, b']')?;+ }+ }+ }+ let record_len = if others == 0 && objects >= 2 {+ Some(objects)+ } else {+ None+ };+ Ok(ArrayMeasure {+ end: src.position(),+ record_len,+ })+}++fn scan_object_fields(src: &mut JsonSrc) -> Result<Vec<DiskField>, ScanError> {+ expect_byte(src, b'{')?;+ let mut fields = Vec::new();+ let mut at: HashMap<String, usize> = HashMap::new();+ loop {+ src.skip_ws()?;+ match src.peek()? {+ None => return Err(ScanError::new("truncated JSON object")),+ Some(b'}') => {+ src.bump()?;+ break;+ }+ Some(b'"') => {+ let key = read_object_key(src)?;+ src.skip_ws()?;+ expect_byte(src, b':')?;+ src.skip_ws()?;+ let start = src.position();+ let (end, record_len) = if src.peek()? == Some(b'[') {+ let measured = measure_array(src)?;+ (measured.end, measured.record_len)+ } else {+ let _ = scan_value(src, 0)?;+ (src.position(), None)+ };+ let field = DiskField {+ key: key.clone(),+ start,+ end,+ record_len,+ };+ if let Some(slot) = at.get(&key).copied() {+ fields[slot] = field;+ } else {+ at.insert(key, fields.len());+ fields.push(field);+ }+ after_value(src, b'}')?;+ }+ _ => return Err(ScanError::new("expected object key")),+ }+ }+ Ok(fields)+}++fn field_raw_len(field: &DiskField) -> Option<usize> {+ usize::try_from(field.end.saturating_sub(field.start)).ok()+}++fn read_field_value(+ src: &mut JsonSrc,+ field: &DiskField,+ limit: usize,+) -> Result<Option<Value>, ScanError> {+ let Some(len) = field_raw_len(field) else {+ return Ok(None);+ };+ if len > limit {+ return Ok(None);+ }+ let bytes = src.read_range(field.start, field.end)?;+ let value =+ serde_json::from_slice(&bytes).map_err(|error| ScanError::new(error.to_string()))?;+ Ok(Some(value))+}++type SharedSplit = (Map<String, Value>, Vec<(String, Value)>);++fn shared_from_disk(+ src: &mut JsonSrc,+ fields: &[DiskField],+ skip: &HashSet<&str>,+ limit: usize,+ stats: &mut ExtractStats,+) -> Result<SharedSplit, ScanError> {+ let mut obj = Map::new();+ for field in fields {+ if skip.contains(field.key.as_str()) {+ continue;+ }+ match read_field_value(src, field, limit)? {+ None => stats.oversize_values += 1,+ Some(value) => {+ obj.insert(field.key.clone(), value);+ }+ }+ }+ Ok(partition_shared(obj))+}++fn emit_disk_array(+ src: &mut JsonSrc,+ field: &DiskField,+ group: Option<String>,+ shared: &Map<String, Value>,+ limit: usize,+ sink: Sink,+ stats: &mut ExtractStats,+) -> Result<(), ScanError> {+ let key = field.key.as_str();+ src.seek_to(field.start)?;+ expect_byte(src, b'[')?;+ let mut live = true;+ let mut index = 0u64;+ loop {+ src.skip_ws()?;+ match src.peek()? {+ None => return Err(ScanError::new("truncated JSON array")),+ Some(b']') => {+ src.bump()?;+ break;+ }+ Some(_) => {+ let cap = if live { limit } else { 0 };+ let outcome = scan_value(src, cap)?;+ let i = index;+ index += 1;+ if live {+ match outcome {+ ScanOutcome::Oversize => stats.oversize_values += 1,+ ScanOutcome::Fits(bytes) => match serde_json::from_slice::<Value>(&bytes) {+ Ok(Value::Object(element)) => {+ let fields = merge_shared(shared, element);+ if !emit_fields(+ fields,+ format!("{key}:e{i}"),+ group.clone(),+ sink,+ stats,+ ) {+ live = false;+ }+ }+ Ok(_) => {}+ Err(_) => stats.junk += 1,+ },+ }+ }+ after_value(src, b']')?;+ }+ }+ }+ Ok(())+}++fn emit_disk_single_object(+ src: &mut JsonSrc,+ path: &Path,+ file_len: u64,+ fields: &[DiskField],+ limit: usize,+ sink: Sink,+ stats: &mut ExtractStats,+) -> Result<(), ScanError> {+ let mut skipped = 0u64;+ let mut kept = Vec::new();+ let mut sum = 2usize;+ for field in fields {+ let Some(raw_len) = field_raw_len(field) else {+ skipped += 1;+ continue;+ };+ if raw_len > limit {+ skipped += 1;+ continue;+ }+ sum = sum.saturating_add(field.key.len() + raw_len + 4);+ kept.push(field);+ }+ if (skipped > 0 && kept.is_empty()) || sum > limit {+ stats.oversize_values += 1 + skipped;+ stats.refusal = Some(format!(+ "{} is {file_len} bytes; a JSON document over {limit} bytes is not indexed. \+ Split the file into smaller documents. {FIXED_DOCUMENT_CEILING}",+ file_label(path),+ ));+ return Ok(());+ }+ stats.oversize_values += skipped;+ let mut obj = Map::new();+ for field in kept {+ let Some(value) = read_field_value(src, field, limit)? else {+ return Err(ScanError::new("JSON field exceeded the document limit"));+ };+ obj.insert(field.key.clone(), value);+ }+ emit(Value::Object(obj), "doc", sink, stats);+ Ok(())+}++fn emit_scanned_object(+ src: &mut JsonSrc,+ path: &Path,+ file_len: u64,+ fields: &[DiskField],+ limit: usize,+ sink: Sink,+ stats: &mut ExtractStats,+) -> Result<(), ScanError> {+ let mut arrays: Vec<usize> = (0..fields.len())+ .filter(|&index| fields[index].record_len.is_some())+ .collect();+ arrays.sort_by(|&left, &right| {+ let left_len = fields[left].record_len.unwrap_or(0);+ let right_len = fields[right].record_len.unwrap_or(0);+ right_len+ .cmp(&left_len)+ .then_with(|| fields[left].key.cmp(&fields[right].key))+ });+ if arrays.len() >= 2+ && fields[arrays[0]].record_len.unwrap_or(0) >= MULTI_ARRAY_SPLIT_MIN as u64+ {+ let skip: HashSet<&str> = arrays+ .iter()+ .map(|&index| fields[index].key.as_str())+ .collect();+ let (small, sidecars) = shared_from_disk(src, fields, &skip, limit, stats)?;+ for (idx, field_i) in arrays.iter().copied().enumerate() {+ let group = if idx == 0 {+ None+ } else {+ Some(fields[field_i].key.clone())+ };+ let len = fields[field_i].record_len.unwrap_or(0);+ stats.populations.push((group.clone(), len));+ emit_disk_array(src, &fields[field_i], group, &small, limit, sink, stats)?;+ }+ emit_sidecars_bounded(sidecars, limit, sink, stats);+ } else if let Some(field_i) = arrays.into_iter().next() {+ let key = fields[field_i].key.clone();+ let len = fields[field_i].record_len.unwrap_or(0);+ let mut skip = HashSet::new();+ skip.insert(key.as_str());+ let (small, sidecars) = shared_from_disk(src, fields, &skip, limit, stats)?;+ stats.populations.push((None, len));+ emit_disk_array(src, &fields[field_i], None, &small, limit, sink, stats)?;+ emit_sidecars_bounded(sidecars, limit, sink, stats);+ } else {+ emit_disk_single_object(src, path, file_len, fields, limit, sink, stats)?;+ }+ Ok(())+}++fn stream_disk_top_array(+ src: &mut JsonSrc,+ limit: usize,+ sink: Sink,+ stats: &mut ExtractStats,+) -> Result<(), ScanError> {+ expect_byte(src, b'[')?;+ let mut count = 0u64;+ let mut live = true;+ let result = (|| -> Result<(), ScanError> {+ loop {+ src.skip_ws()?;+ match src.peek()? {+ None => return Err(ScanError::new("truncated JSON array")),+ Some(b']') => {+ src.bump()?;+ break;+ }+ Some(_) => {+ let cap = if live { limit } else { 0 };+ let outcome = scan_value(src, cap)?;+ let index = count;+ count += 1;+ if live {+ match outcome {+ ScanOutcome::Oversize => stats.oversize_values += 1,+ ScanOutcome::Fits(bytes) => {+ match serde_json::from_slice::<Value>(&bytes) {+ Ok(value) => {+ if !emit(value, &format!("e{index}"), sink, stats) {+ live = false;+ }+ }+ Err(_) => stats.junk += 1,+ }+ }+ }+ }+ after_value(src, b']')?;+ }+ }+ }+ src.skip_ws()?;+ if src.peek()?.is_some() {+ return Err(ScanError::new("trailing data after JSON array"));+ }+ Ok(())+ })();+ if count > 0 {+ stats.populations.push((None, count));+ }+ result+}++fn stream_disk_top_object(+ src: &mut JsonSrc,+ path: &Path,+ file_len: u64,+ limit: usize,+ sink: Sink,+ stats: &mut ExtractStats,+) -> Result<(), ScanError> {+ let fields = scan_object_fields(src)?;+ src.skip_ws()?;+ if src.peek()?.is_some() {+ return Err(ScanError::new("trailing data after JSON object"));+ }+ emit_scanned_object(src, path, file_len, &fields, limit, sink, stats)+}++fn nothing_emitted(stats: &ExtractStats) -> bool {+ stats.records == 0 && stats.oversize_values == 0 && stats.junk == 0+}++fn stream_uncompressed_over_cap(+ path: &Path,+ file_len: u64,+ limit: usize,+ sink: Sink,+) -> Result<ExtractStats> {+ let mut stats = ExtractStats::default();+ let file = std::fs::File::open(path)?;+ let mut src = JsonSrc::new(file);+ let kind = src.skip_ws().and_then(|_| src.peek());+ match kind {+ Ok(Some(b'[')) => {+ if let Err(error) = stream_disk_top_array(&mut src, limit, sink, &mut stats) {+ if nothing_emitted(&stats) {+ return jsonl_from_disk(path, file_len, limit, sink);+ }+ stats.junk += 1;+ let _ = error;+ }+ }+ Ok(Some(b'{')) => {+ if let Err(error) =+ stream_disk_top_object(&mut src, path, file_len, limit, sink, &mut stats)+ {+ if nothing_emitted(&stats) {+ return jsonl_from_disk(path, file_len, limit, sink);+ }+ stats.junk += 1;+ let _ = error;+ }+ }+ _ => return jsonl_from_disk(path, file_len, limit, sink),+ }+ finish_empty_refusal_len(path, file_len, limit, &mut stats);+ Ok(stats)+}++fn jsonl_from_disk(path: &Path, file_len: u64, limit: usize, sink: Sink) -> Result<ExtractStats> {+ let mut reader = std::io::BufReader::new(std::fs::File::open(path)?);+ let mut stats = ExtractStats::default();+ let mut offset = 0u64;+ let mut line = Vec::new();+ loop {+ line.clear();+ let n = super::jsonl::read_capped_line(&mut reader, &mut line)?;+ if n == 0 {+ break;+ }+ let start = offset;+ offset += n as u64;+ let trimmed = super::jsonl::trim_ws(&line);+ if trimmed.is_empty() {+ continue;+ }+ if line.len() >= MAX_LINE {+ stats.junk += 1;+ continue;+ }+ if trimmed.len() > limit {+ stats.oversize_values += 1;+ continue;+ }+ match serde_json::from_slice::<Value>(trimmed) {+ Ok(Value::Object(map)) => {+ let mut fields = flatten_object(map);+ ensure_text_passage(&mut fields);+ stats.records += 1;+ if !sink(RawRecord {+ fields,+ locator: format!("b{start}"),+ group: None,+ origin: FieldOrigin::Data,+ }) {+ break;+ }+ }+ Ok(_) | Err(_) => stats.junk += 1,+ }+ }+ finish_empty_refusal_len(path, file_len, limit, &mut stats);+ Ok(stats)+}+#[cfg(test)]mod tests {use super::*;@@ -1588,4 +2412,157 @@ mod tests {.contains(&(None, MULTI_ARRAY_SPLIT_MIN as u64)));assert!(stats.populations.contains(&(Some("runs".into()), 3)));}++ fn run_with_caps(+ text: &str,+ limit: usize,+ whole_file_cap: u64,+ ) -> (ExtractStats, Vec<RawRecord>) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("t.json");+ std::fs::write(&path, text).unwrap();+ let mut recs = Vec::new();+ let stats = extract_with_whole_file_cap(+ &path,+ false,+ &mut |record| {+ recs.push(record);+ true+ },+ limit,+ whole_file_cap,+ )+ .unwrap();+ (stats, recs)+ }++ fn run_disk(text: &str, limit: usize) -> (ExtractStats, Vec<RawRecord>) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("t.json");+ std::fs::write(&path, text).unwrap();+ let mut recs = Vec::new();+ let stats = stream_uncompressed_over_cap(&path, text.len() as u64, limit, &mut |record| {+ recs.push(record);+ true+ })+ .unwrap();+ (stats, recs)+ }++ /// The disk walker is what runs once a file is past 64 MiB. It must emit+ /// the same records as the DOM path, including a multi-array split and a+ /// shared value that is too big to copy onto every row.+ #[test]+ fn a_file_read_from_disk_matches_the_dom_path() {+ let mut functions = Vec::new();+ for i in 0..MULTI_ARRAY_SPLIT_MIN {+ functions.push(format!(r#"{{"name":"f{i}","addr":{i}}}"#));+ }+ let split = format!(+ r#"{{"generated":"2026-01-01","functions":[{}],"runs":[{{"label":"boot","start":1}},{{"label":"loop","start":9}}]}}"#,+ functions.join(",")+ );+ let blob = "x".repeat(SHARED_REPLICATE_MAX + 8);+ let sidecar = format!(+ r#"{{"name":"n","items":[{{"id":1}},{{"id":2,"name":"row"}}],"blob":"{blob}"}}"#+ );+ let cases = [+ split.as_str(),+ sidecar.as_str(),+ r#"[{"id":1,"user":{"name":"ann"}},{"id":2}]"#,+ r#"{"generated":"2026-01-01","count":2,"items":[{"id":1},{"id":2,"generated":"per-item"}],"errors":[{"e":1}]}"#,+ "[1,2,3]",+ "[\n {\"id\": 1}, {\"id\": 2}\n]",+ r#"{"a":1,"note":"ok"}"#,+ ];+ for text in cases {+ let (dom_stats, dom) = run_limited(text, usize::MAX);+ let (disk_stats, disk) = run_disk(text, usize::MAX);+ assert_eq!(dom_stats.records, disk_stats.records, "{text}");+ assert_eq!(dom_stats.populations, disk_stats.populations, "{text}");+ assert_eq!(+ dom_stats.oversize_values, disk_stats.oversize_values,+ "{text}"+ );+ assert_same_records(&dom, &disk);+ }+ }++ /// Routing: a file past the whole-file cap is streamed, not refused.+ #[test]+ fn a_file_over_the_whole_file_cap_is_streamed_not_refused() {+ let text = r#"[{"id":1},{"id":2}]"#;+ let (stats, recs) = run_with_caps(text, usize::MAX, 4);+ assert!(stats.refusal.is_none(), "{:?}", stats.refusal);+ assert_eq!(stats.records, 2);+ assert_eq!(recs[0].locator, "e0");+ assert_eq!(recs[1].locator, "e1");+ assert_eq!(recs[1].fields["id"], serde_json::json!(2));+ }++ /// One element past the document ceiling is skipped. The bytes retained+ /// for that value stay within the ceiling; its siblings keep their indexes.+ #[test]+ fn a_disk_stream_skips_one_oversized_element_within_the_cap() {+ let blob = "y".repeat(200);+ let text = format!(r#"[{{"id":1}},{{"blob":"{blob}"}},{{"id":2}}]"#);+ super::JSON_SCAN_STORED_PEAK.with(|peak| peak.set(0));+ let (stats, recs) = run_with_caps(&text, 40, 8);+ let peak = super::JSON_SCAN_STORED_PEAK.with(|peak| peak.get());+ assert!(+ peak <= 40,+ "retained {peak} bytes of a value past the 40-byte cap"+ );+ assert_eq!(stats.oversize_values, 1);+ assert_eq!(recs.len(), 2);+ assert_eq!(recs[0].locator, "e0");+ assert_eq!(recs[1].locator, "e2");+ assert_eq!(recs[1].fields["id"], serde_json::json!(2));+ assert!(stats.refusal.is_none(), "the siblings were indexed");+ }++ #[test]+ fn a_single_oversized_document_on_disk_names_the_file_and_the_fixed_ceiling() {+ let blob = "x".repeat(80);+ let text = format!(r#"{{"blob":"{blob}"}}"#);+ let (stats, recs) = run_with_caps(&text, 32, 8);+ assert!(recs.is_empty());+ let reason = stats.refusal.expect("a refusal");+ assert!(reason.contains("t.json"), "{reason}");+ assert!(reason.contains(&text.len().to_string()), "{reason}");+ assert!(reason.contains("32"), "{reason}");+ assert!(reason.contains("not indexed"), "{reason}");+ assert!(reason.contains("--max-file-mb"), "{reason}");+ assert!(reason.contains("limits.max_process_memory_mb"), "{reason}");+ }++ /// A `.json` file whose first line is one object and whose next line is+ /// another is JSONL that sniffed as JSON once the first line outgrew the+ /// sniff prefix. Past the whole-file cap it must still index every line.+ #[test]+ fn a_jsonl_file_over_the_whole_file_cap_streams_every_line() {+ let text = "{\"id\":1}\n{\"id\":2}\n";+ let (stats, recs) = run_with_caps(text, usize::MAX, 4);+ assert_eq!(stats.records, 2, "{:?}", stats.refusal);+ assert_eq!(recs[0].locator, "b0");+ assert_eq!(recs[0].fields["id"], serde_json::json!(1));+ let second = text.find('\n').unwrap() + 1;+ assert_eq!(recs[1].locator, format!("b{second}"));+ assert_eq!(recs[1].fields["id"], serde_json::json!(2));+ }++ #[test]+ fn gzip_over_the_whole_file_cap_names_the_fixed_ceiling() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("t.json.gz");+ let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());+ std::io::Write::write_all(&mut encoder, br#"{"id":1,"name":"ann"}"#).unwrap();+ std::fs::write(&path, encoder.finish().unwrap()).unwrap();+ let stats = extract_with_whole_file_cap(&path, true, &mut |_| true, usize::MAX, 4).unwrap();+ let reason = stats.refusal.expect("gzip is not streamed past the cap");+ assert!(reason.contains("t.json.gz"), "{reason}");+ assert!(reason.contains("--max-file-mb"), "{reason}");+ assert!(reason.contains("limits.max_process_memory_mb"), "{reason}");+ assert_eq!(stats.records, 0);+ }}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 110ff55f8..f79ee3d8d 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -3266,6 +3266,18 @@ fn human_size(bytes: u64) -> String {}}+/// Scan-time skip for a whole-file family over `--max-file-bytes`.+///+/// Names the file's actual size and the flag that raises this cap. It does+/// not raise the 8 MiB per-document ceiling.+fn oversized_family_reason(family: &str, size: u64, max_file_bytes: u64) -> String {+ format!(+ "oversized for non-streaming family {family} ({} > {}); raise --max-file-mb",+ human_size(size),+ human_size(max_file_bytes),+ )+}+fn scan_file(path: &Path,size: u64,@@ -3327,11 +3339,7 @@ fn scan_file(if whole_file && size > max_file_bytes {out.junk = Some(("skipped".into(),- format!(- "oversized for non-streaming family {} (> {})",- sn.family.as_str(),- human_size(max_file_bytes),- ),+ oversized_family_reason(sn.family.as_str(), size, max_file_bytes),));out.sniffed = Some(sn);return out;@@ -9766,21 +9774,16 @@ fn run_index_report_inner(truncated_files.lock().unwrap().push(f.rel.clone());}if stats.oversize_values > 0 {- if stats.records > 0 {- pr.note(&format!(- "{}: {} JSON value(s) were not indexed (over the {}-byte limit for one document). The rest of the file was indexed.",- f.rel,- stats.oversize_values,- xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES,- ));+ let ceiling = xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES;+ let tail = if stats.records > 0 {+ "The rest of the file was indexed."} else {- pr.note(&format!(- "{}: {} JSON value(s) were not indexed (over the {}-byte limit for one document).",- f.rel,- stats.oversize_values,- xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES,- ));- }+ "Nothing else in the file was indexed."+ };+ pr.note(&format!(+ "{} ({} bytes): {} JSON value(s) were not indexed (over the {ceiling}-byte limit for one document). {tail} This ceiling is fixed and is not raised by --max-file-mb or limits.max_process_memory_mb; split the value into smaller documents.",+ f.rel, f.size, stats.oversize_values,+ ));}}Err(e) => {@@ -14546,6 +14549,14 @@ mod legacy_rebuild_argv_tests {assert_eq!(human_size(0), "0 bytes");}+ #[test]+ fn an_oversized_family_skip_names_the_file_size_and_the_flag() {+ assert_eq!(+ oversized_family_reason("json", 3 << 30, 2 << 30),+ "oversized for non-streaming family json (3 GB > 2 GB); raise --max-file-mb"+ );+ }+/// #1233 back-compat: an index built before sub-GB caps existed serialised/// its cap as the top-level `max_file_gb` integer. A whole-GB cap must still/// produce that exact key (so the prepared-records digest is unchanged anddiff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rsindex d763d4f7c..f96f63945 100644--- a/engine/crates/xerj-engine/src/governor.rs+++ b/engine/crates/xerj-engine/src/governor.rs@@ -12,7 +12,9 @@//! Crossing either rejects writes with HTTP 429//! `circuit_breaking_exception` (so a 429 beats the OOM-killer), and//! wires the hitherto-inert `max_query_memory_mb` into a per-query-//! allocation guard.+//! allocation guard. An analyze reservation charges in-flight token+//! spikes before the next RSS sample, so several bulks cannot all pass+//! one sample and allocate together (#1122).//! * **item 2** — a global search-concurrency pool sized from//! `max_concurrent_searches` (previously a hardcoded per-index//! `Semaphore::new(64)`, i.e. no global cap).@@ -45,6 +47,42 @@ static GOVERNOR: OnceLock<Arc<ResourceGovernor>> = OnceLock::new();/// tokio pool is saturated.pub const SAMPLE_INTERVAL_MS: u64 = 100;+/// Bytes of analyze-time reservation charged per raw JSON input byte (#1122).+///+/// `document_limit` measured about 56 bytes of RSS per token for a+/// `Vec<String>` of the word `word ` (2026-10-23, 8,388,605 input bytes).+/// The densest input that still produces one token per two bytes is `"a "`,+/// so 28 bytes of reservation per input byte covers that spike. One token+/// per byte is outside this factor; the 8 MiB document ceiling bounds that+/// input. Eight such bulks are admitted only while the sum of reservations+/// stays under the watermark.+pub const ANALYZE_RESERVE_PER_INPUT_BYTE: u64 = 28;++/// Reservation for a raw JSON batch of `raw_json_bytes`.+pub fn analyze_reserve_bytes(raw_json_bytes: u64) -> u64 {+ raw_json_bytes.saturating_mul(ANALYZE_RESERVE_PER_INPUT_BYTE)+}++/// `true` when `request` bytes of analyze reservation still fit.+///+/// A watermark of `0` is the disabled breaker: every request fits. Otherwise+/// the request fails when `observed + already_reserved + request` reaches+/// the watermark. The comparison is `>=`, matching RSS admission.+pub fn analyze_reservation_fits(+ watermark: u64,+ observed: u64,+ already_reserved: u64,+ request: u64,+) -> bool {+ if watermark == 0 {+ return true;+ }+ observed+ .saturating_add(already_reserved)+ .saturating_add(request)+ < watermark+}+/// Process-wide resource governor. See the module docs.pub struct ResourceGovernor {/// One admission authority shared by every index in this process.@@ -83,6 +121,10 @@ pub struct ResourceGovernor {memory_watermark_bytes: AtomicU64,/// Last sampled resident set size of this process.rss_bytes: AtomicU64,+ /// Bytes reserved for in-flight analysis spikes that the RSS sample has+ /// not observed yet (#1122). Released once those tokens exist, so the+ /// next admission sees them in live RSS instead of counting them twice.+ analyze_reserved: Arc<AtomicU64>,/// Latched: last sample crossed the RSS watermark.memory_tripped: AtomicBool,/// The effective watermark in force when the breaker last engaged (#1250).@@ -208,6 +250,69 @@ impl ResourceGovernor {Ok(())}+ /// Reserve `bytes` of upcoming analysis allocations (#1122).+ ///+ /// Callers pass [`analyze_reserve_bytes`] of the raw JSON, before the+ /// batch is parsed. The check uses the max of the sampled RSS and a live+ /// probe, plus reservations already held, and rechecks after the atomic+ /// add so two bulks cannot both pass the same snapshot. A watermark of+ /// `0`, or a zero request, reserves nothing. The guard releases on drop.+ pub(crate) fn reserve_analyze(&self, bytes: u64) -> Result<AnalyzeReservation, XerjError> {+ if bytes == 0 || self.memory_watermark_bytes.load(Ordering::Relaxed) == 0 {+ return Ok(AnalyzeReservation::none());+ }+ if self.memory_tripped.load(Ordering::Relaxed) {+ return Err(self.analyze_reservation_refused(bytes));+ }+ let watermark = self.memory_watermark_bytes.load(Ordering::Relaxed);+ let observed = self.observed_process_memory();+ let already = self.analyze_reserved.load(Ordering::Acquire);+ if !analyze_reservation_fits(watermark, observed, already, bytes) {+ return Err(self.analyze_reservation_refused(bytes));+ }+ let prev = self.analyze_reserved.fetch_add(bytes, Ordering::AcqRel);+ let watermark = self.memory_watermark_bytes.load(Ordering::Relaxed);+ if watermark == 0 {+ self.analyze_reserved.fetch_sub(bytes, Ordering::AcqRel);+ return Ok(AnalyzeReservation::none());+ }+ let observed = self.observed_process_memory();+ if analyze_reservation_fits(watermark, observed, prev, bytes) {+ return Ok(AnalyzeReservation {+ slot: Some(Arc::clone(&self.analyze_reserved)),+ bytes,+ });+ }+ self.analyze_reserved.fetch_sub(bytes, Ordering::AcqRel);+ Err(self.analyze_reservation_refused(bytes))+ }++ fn observed_process_memory(&self) -> u64 {+ self.rss_bytes+ .load(Ordering::Relaxed)+ .max(current_process_memory_bytes())+ }++ fn analyze_reservation_refused(&self, request: u64) -> XerjError {+ const MIB: u64 = 1024 * 1024;+ let observed = self.observed_process_memory();+ let reserved = self.analyze_reserved.load(Ordering::Relaxed);+ let watermark = self.memory_watermark_bytes.load(Ordering::Relaxed);+ XerjError::circuit_breaking(format!(+ "[parent] real memory circuit breaker tripped: rss={}MB plus {}MB already reserved \+ for analysis plus {}MB for this batch would reach watermark={}MB ({}% of \+ limit={}MB); writes rejected to prevent an out-of-memory kill (raise \+ limits.max_process_memory_mb or XERJ_MAX_PROCESS_MEMORY_MB, or live with \+ PUT _cluster/settings {{\"persistent\":{{\"indices.breaker.total.limit\":\"<N>gb\"}}}})",+ observed / MIB,+ reserved / MIB,+ request / MIB,+ watermark / MIB,+ pct_of(watermark, self.memory_limit_bytes),+ self.memory_limit_bytes / MIB,+ ))+ }+/// Whether the parent RSS memory breaker is currently engaged (issue/// #948). Admission (429) is only half of the contract: the resource/// sampler uses this flag, together with [`Self::memtable_breaker_engaged`],@@ -1151,6 +1256,7 @@ fn build(config: &Config) -> ResourceGovernor {} else {0}),+ analyze_reserved: Arc::new(AtomicU64::new(0)),memory_tripped: AtomicBool::new(startup_starved),memory_trip_watermark: AtomicU64::new(if startup_starved {memory_watermark_bytes@@ -1573,6 +1679,32 @@ fn parse_byte_size(s: &str) -> Option<u64> {// Small formatting helpers// ─────────────────────────────────────────────────────────────────────────+/// Releases an analyze reservation when the batch's tokens exist (#1122).+#[derive(Debug)]+pub(crate) struct AnalyzeReservation {+ slot: Option<Arc<AtomicU64>>,+ bytes: u64,+}++impl AnalyzeReservation {+ pub(crate) fn none() -> Self {+ Self {+ slot: None,+ bytes: 0,+ }+ }+}++impl Drop for AnalyzeReservation {+ fn drop(&mut self) {+ if let Some(slot) = self.slot.take() {+ if self.bytes > 0 {+ slot.fetch_sub(self.bytes, Ordering::AcqRel);+ }+ }+ }+}+fn pct_of(part: u64, whole: u64) -> u64 {if whole == 0 {0@@ -1670,6 +1802,53 @@ fn human_bytes(b: u64) -> String {mod tests {use super::*;+ #[test]+ fn analyze_reservation_fits_under_the_watermark_and_rejects_at_it() {+ assert!(analyze_reservation_fits(0, 100, 100, 100));+ assert!(analyze_reservation_fits(1_000, 100, 100, 799));+ assert!(!analyze_reservation_fits(1_000, 100, 100, 800));+ assert!(!analyze_reservation_fits(1_000, 900, 50, 50));+ assert_eq!(analyze_reserve_bytes(8 << 20), (8 << 20) * 28);+ }++ /// 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.+ #[test]+ fn analyze_reservation_releases_and_sees_a_prior_reserve() {+ let governor = build(&Config::default());+ let live = governor.observed_process_memory();+ let slack = 512 * 1024 * 1024;+ governor+ .memory_watermark_bytes+ .store(live.saturating_add(slack), Ordering::Relaxed);+ governor.rss_bytes.store(live, Ordering::Relaxed);+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);++ let first = governor.reserve_analyze(32 * 1024 * 1024).unwrap();+ assert_eq!(+ governor.analyze_reserved.load(Ordering::Relaxed),+ 32 * 1024 * 1024+ );+ let refused = governor.reserve_analyze(480 * 1024 * 1024 + 1).unwrap_err();+ let text = refused.to_string();+ assert!(text.contains("circuit breaker"), "{text}");+ assert!(text.contains("writes rejected"), "{text}");+ assert!(text.contains("limits.max_process_memory_mb"), "{text}");+ assert_eq!(refused.http_status(), 429);++ drop(first);+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);+ let second = governor.reserve_analyze(400 * 1024 * 1024).unwrap();+ drop(second);+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);++ governor.memory_watermark_bytes.store(0, Ordering::Relaxed);+ let disabled = governor.reserve_analyze(u64::MAX).unwrap();+ assert_eq!(governor.analyze_reserved.load(Ordering::Relaxed), 0);+ drop(disabled);+ }+#[test]fn segment_hydration_resolver_is_cgroup_proportional_and_explicit() {const GIB: u64 = 1024 * 1024 * 1024;diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex d74f71aad..09a3bf194 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -11877,6 +11877,10 @@ impl Index {}}+ // Charge the token spike before the batch is parsed. Eight bulks can+ // pass one RSS sample and then analyze together; the reservation+ // makes the second one 429 while the first is still allocating (#1122).+ let analyze_reservation = Self::reserve_batch_analyze(validated.docs())?;let dom_t = std::time::Instant::now();let validated = crate::ingest_pool().install(|| xerj_storage::IndexStore::parse_validated_raw_batch(validated))@@ -12112,6 +12116,9 @@ impl Index {p_insert_us = p_t.elapsed().as_micros();}}+ // Tokens are in the memtable. Drop the estimate so the next batch+ // is charged the live RSS of those tokens, not the estimate as well.+ drop(analyze_reservation);drop(publication_schema);if prof {@@ -12268,6 +12275,7 @@ impl Index {}}+ let analyze_reservation = Self::reserve_batch_analyze(validated.docs())?;let _hnsw_publication = has_vector_mapping.then(|| self.begin_hnsw_publication());let index_start = std::time::Instant::now();let wal_t = std::time::Instant::now();@@ -12459,6 +12467,7 @@ impl Index {}).collect()});+ drop(analyze_reservation);// Single batch-level atomic instead of one per doc. At 1.7 M/s// × 10 k batch = 170 batches/s this cuts ~17 M atomic ops/s of// cache-line bouncing on `doc_count`.@@ -27111,6 +27120,21 @@ impl Index {Ok(())}+ /// Reserve headroom for the token spike of `docs` before they are parsed+ /// (#1122). See [`crate::governor::analyze_reserve_bytes`]. No governor+ /// reserves nothing, so an `Index` built directly in a unit test is unchanged.+ fn reserve_batch_analyze(+ docs: &[xerj_storage::RawJsonDoc],+ ) -> Result<crate::governor::AnalyzeReservation> {+ let Some(governor) = crate::governor::global() else {+ return Ok(crate::governor::AnalyzeReservation::none());+ };+ let raw = docs.iter().map(|(_, bytes)| bytes.len() as u64).sum();+ governor+ .reserve_analyze(crate::governor::analyze_reserve_bytes(raw))+ .map_err(EngineError::Common)+ }+/// Every block name the `_block` API and `index.blocks.*` settings accept.pub const BLOCK_NAMES: [&'static str; 5] = ["read_only",