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(autoindex,engine): refuse or stream one oversized JSON document (#1122) (#2256)

xerj-org61c9c70b96f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4607a93e1..396ddb42e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -61,6 +61,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
field on a semantic query. Chunks are not wrapped in `<em>` tags. A
lexical `match` on the same field still highlights query terms.
+- A single JSON document over 8 MiB is not indexed, so one file of 50 MB
+ or more cannot abort the node during autoindex or `_bulk` (#1122).
+ Autoindex streams a top-level array, or a top-level array of records
+ inside a larger object, one element at a time and skips only the values
+ that exceed the limit. The skip names the file. A bulk item over the
+ limit is HTTP 413 and its neighbours still index. The ceiling is fixed,
+ not a new setting. Files over 64 MiB are still not read; the skip now
+ says so.
+
+- Opening an index whose snapshot names a segment file that is already
+ gone drops that segment instead of failing every later `_search` with
+ `Segment … not found`. A sibling segment that is still on disk stays
+ readable, and sequence numbers from the missing segment are not reused.
+ Object-store mode is unchanged: a catalogue whose bundle is missing
+ still refuses to open. This is what let `xerj brain --fresh` finish
+ its catalog read-back after a data directory was only partly removed.
+
- A best-effort helper thread that cannot be created no longer aborts the
process. On Unix those threads are started with `pthread_create` and do not
map an alternate signal stack, so the allocation failure that used to panic
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 2bba1e0e0..917ebe79c 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -3828,6 +3828,12 @@ pub async fn index_doc_auto(
Query(params): Query<IndexDocAutoParams>,
body: bytes::Bytes,
) -> impl IntoResponse {
+ if xerj_common::document_limit::indexed_document_too_large(body.len()) {
+ return ApiError::new(xerj_common::XerjError::invalid_document_json(
+ xerj_common::document_limit::indexed_document_refusal(body.len()),
+ ))
+ .into_response();
+ }
// Parse the raw body directly — avoids the axum Json extractor's extra
// content-type enforcement and serde_json::from_str double-pass.
let doc: Value = match serde_json::from_slice(&body) {
diff --git a/engine/crates/xerj-autoindex/src/extract/json.rs b/engine/crates/xerj-autoindex/src/extract/json.rs
index 971e294c4..2db9cf50f 100644
--- a/engine/crates/xerj-autoindex/src/extract/json.rs
+++ b/engine/crates/xerj-autoindex/src/extract/json.rs
@@ -11,21 +11,50 @@
//! - a Google Keep note (Takeout `Keep/*.json`) → a DOCUMENT: `title`/`body`
//! plus labels and dates — see [`keep_note`]
//! - anything else → a single record
+//!
+//! A file larger than [`xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES`]
+//! (and still within [`MAX_WHOLE_FILE`]) is not parsed into one `Value`.
+//! Record arrays are streamed one element at a time. A single document, or
+//! 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.
use super::{
emit_document_with_fields, ensure_text_passage, flatten_object, ExtractStats, FieldOrigin,
RawRecord, Sink, MAX_LINE, MAX_WHOLE_FILE,
};
use anyhow::Result;
+use serde::de::{Deserializer, MapAccess, SeqAccess, Visitor};
+use serde_json::value::RawValue;
use serde_json::{Map, Value};
+use std::collections::{HashMap, HashSet};
+use std::fmt;
+use std::ops::Range;
use std::path::Path;
pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
+ extract_limited(
+ path,
+ gzip,
+ sink,
+ xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES,
+ )
+}
+
+fn extract_limited(path: &Path, gzip: bool, sink: Sink, limit: usize) -> Result<ExtractStats> {
let mut stats = ExtractStats::default();
let Some(bytes) = super::read_whole(path, gzip, MAX_WHOLE_FILE)? 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",
+ file_label(path),
+ MAX_WHOLE_FILE
+ ));
return Ok(stats);
};
+ if bytes.len() > limit {
+ return stream_large(&bytes, path, limit, sink);
+ }
let v: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => {
@@ -41,7 +70,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
// a success. A file that is neither one JSON value nor a
// sequence of JSON lines junks exactly as before — every
// line fails the per-line parse too.
- return jsonl_fallback(&bytes, sink);
+ return jsonl_fallback(&bytes, limit, path, sink);
}
};
match v {
@@ -398,7 +427,7 @@ fn emit_fields(
/// byte-offset locator, anything else junks. No `limit_bytes` exists here
/// (the family reads the whole file), so there is no truncated-tail
/// exemption to carry over.
-fn jsonl_fallback(bytes: &[u8], sink: Sink) -> Result<ExtractStats> {
+fn jsonl_fallback(bytes: &[u8], limit: usize, path: &Path, sink: Sink) -> Result<ExtractStats> {
let mut stats = ExtractStats::default();
let mut offset: u64 = 0;
for line in bytes.split(|&b| b == b'\n') {
@@ -412,6 +441,12 @@ fn jsonl_fallback(bytes: &[u8], sink: Sink) -> Result<ExtractStats> {
stats.junk += 1;
continue;
}
+ // The 8–16 MiB gap under MAX_LINE used to be parsed and tokenized
+ // as one document (#1122).
+ if trimmed.len() > limit {
+ stats.oversize_values += 1;
+ continue;
+ }
match serde_json::from_slice::<Value>(trimmed) {
Ok(Value::Object(m)) => {
let mut fields = flatten_object(m);
@@ -431,9 +466,445 @@ fn jsonl_fallback(bytes: &[u8], sink: Sink) -> Result<ExtractStats> {
}
}
}
+ finish_empty_refusal(path, bytes.len(), limit, &mut stats);
+ Ok(stats)
+}
+
+fn file_label(path: &Path) -> String {
+ path.file_name()
+ .map(|s| s.to_string_lossy().into_owned())
+ .unwrap_or_else(|| path.display().to_string())
+}
+
+fn finish_empty_refusal(path: &Path, nbytes: usize, 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",
+ file_label(path),
+ stats.oversize_values,
+ ));
+ }
+}
+
+fn stream_large(bytes: &[u8], path: &Path, limit: usize, sink: Sink) -> Result<ExtractStats> {
+ let mut stats = ExtractStats::default();
+ match first_significant(bytes) {
+ Some(b'[') => {
+ if let Err(error) = stream_top_array(bytes, limit, sink, &mut stats) {
+ if stats.records == 0 && stats.oversize_values == 0 && stats.junk == 0 {
+ return jsonl_fallback(bytes, limit, path, sink);
+ }
+ stats.junk += 1;
+ let _ = error;
+ }
+ }
+ Some(b'{') => {
+ if let Err(error) = stream_top_object(bytes, path, limit, sink, &mut stats) {
+ if stats.records == 0 && stats.oversize_values == 0 && stats.junk == 0 {
+ return jsonl_fallback(bytes, limit, path, sink);
+ }
+ stats.junk += 1;
+ let _ = error;
+ }
+ }
+ _ => return jsonl_fallback(bytes, limit, path, sink),
+ }
+ finish_empty_refusal(path, bytes.len(), limit, &mut stats);
Ok(stats)
}
+fn first_significant(bytes: &[u8]) -> Option<u8> {
+ bytes
+ .iter()
+ .copied()
+ .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
+}
+
+/// Byte range of `raw` inside `input`.
+///
+/// `serde_json`'s `&RawValue`, deserialized from a slice, borrows that slice.
+/// The pointer difference is only used after a byte-for-byte check that the
+/// range really is `raw`. A mismatch copies nothing and fails the value, so a
+/// future serde that copies `RawValue` cannot silently read the wrong bytes.
+fn raw_span(input: &[u8], raw: &str) -> Option<Range<usize>> {
+ let raw_bytes = raw.as_bytes();
+ let input_addr = input.as_ptr() as usize;
+ let raw_addr = raw_bytes.as_ptr() as usize;
+ if raw_addr < input_addr {
+ return None;
+ }
+ let start = raw_addr - input_addr;
+ let end = start.checked_add(raw_bytes.len())?;
+ if end > input.len() || input.get(start..end) != Some(raw_bytes) {
+ return None;
+ }
+ Some(start..end)
+}
+
+fn object_spans(input: &[u8]) -> Result<Vec<(String, Range<usize>)>, serde_json::Error> {
+ struct SpanVisitor<'a> {
+ input: &'a [u8],
+ }
+ impl<'de> Visitor<'de> for SpanVisitor<'de> {
+ type Value = Vec<(String, Range<usize>)>;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a JSON object")
+ }
+ fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
+ let mut spans: Vec<(String, Range<usize>)> = Vec::new();
+ let mut at: HashMap<String, usize> = HashMap::new();
+ while let Some(key) = map.next_key::<String>()? {
+ let raw = map.next_value::<&RawValue>()?;
+ let range = raw_span(self.input, raw.get()).ok_or_else(|| {
+ serde::de::Error::custom("JSON value is not a slice of the input")
+ })?;
+ if let Some(slot) = at.get(&key).copied() {
+ spans[slot].1 = range;
+ } else {
+ at.insert(key.clone(), spans.len());
+ spans.push((key, range));
+ }
+ }
+ Ok(spans)
+ }
+ }
+ let mut de = serde_json::Deserializer::from_slice(input);
+ let spans = de.deserialize_any(SpanVisitor { input })?;
+ de.end()?;
+ Ok(spans)
+}
+
+fn looks_like_array(bytes: &[u8]) -> bool {
+ first_significant(bytes) == Some(b'[')
+}
+
+/// `Some(len)` when `input` is an array of at least two objects.
+fn record_array_len(input: &[u8]) -> Result<Option<u64>, serde_json::Error> {
+ struct ShapeVisitor;
+ impl<'de> Visitor<'de> for ShapeVisitor {
+ type Value = Option<u64>;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a JSON array")
+ }
+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
+ let mut count = 0u64;
+ let mut objects = true;
+ while let Some(raw) = seq.next_element::<&RawValue>()? {
+ count += 1;
+ if objects && !raw.get().trim_start().starts_with('{') {
+ objects = false;
+ }
+ }
+ Ok(if objects && count >= 2 {
+ Some(count)
+ } else {
+ None
+ })
+ }
+ }
+ let mut de = serde_json::Deserializer::from_slice(input);
+ let len = de.deserialize_any(ShapeVisitor)?;
+ de.end()?;
+ Ok(len)
+}
+
+struct Field {
+ key: String,
+ range: Range<usize>,
+ record_len: Option<u64>,
+}
+
+fn stream_top_object(
+ bytes: &[u8],
+ path: &Path,
+ limit: usize,
+ sink: Sink,
+ stats: &mut ExtractStats,
+) -> Result<(), serde_json::Error> {
+ let spans = object_spans(bytes)?;
+ let mut fields = Vec::with_capacity(spans.len());
+ for (key, range) in spans {
+ let record_len = if looks_like_array(&bytes[range.clone()]) {
+ record_array_len(&bytes[range.clone()])?
+ } else {
+ None
+ };
+ fields.push(Field {
+ key,
+ range,
+ record_len,
+ });
+ }
+ let mut arrays: Vec<usize> = (0..fields.len())
+ .filter(|&i| fields[i].record_len.is_some())
+ .collect();
+ arrays.sort_by(|&a, &b| {
+ let la = fields[a].record_len.unwrap_or(0);
+ let lb = fields[b].record_len.unwrap_or(0);
+ lb.cmp(&la).then_with(|| fields[a].key.cmp(&fields[b].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(|&i| fields[i].key.as_str()).collect();
+ let shared = parse_shared_fields(bytes, &fields, &skip, limit, stats)?;
+ let (small, sidecars) = partition_shared(shared);
+ 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_record_array(
+ &bytes[fields[field_i].range.clone()],
+ &fields[field_i].key,
+ 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 range = fields[field_i].range.clone();
+ let len = fields[field_i].record_len.unwrap_or(0);
+ let mut skip = HashSet::new();
+ skip.insert(key.as_str());
+ let shared = parse_shared_fields(bytes, &fields, &skip, limit, stats)?;
+ let (small, sidecars) = partition_shared(shared);
+ stats.populations.push((None, len));
+ emit_record_array(&bytes[range], &key, None, &small, limit, sink, stats)?;
+ emit_sidecars_bounded(sidecars, limit, sink, stats);
+ } else {
+ emit_single_object(bytes, path, &fields, limit, sink, stats)?;
+ }
+ Ok(())
+}
+
+fn parse_shared_fields(
+ bytes: &[u8],
+ fields: &[Field],
+ skip: &HashSet<&str>,
+ limit: usize,
+ stats: &mut ExtractStats,
+) -> Result<Map<String, Value>, serde_json::Error> {
+ let mut obj = Map::new();
+ for field in fields {
+ if skip.contains(field.key.as_str()) {
+ continue;
+ }
+ if field.range.len() > limit {
+ stats.oversize_values += 1;
+ continue;
+ }
+ let value: Value = serde_json::from_slice(&bytes[field.range.clone()])?;
+ obj.insert(field.key.clone(), value);
+ }
+ Ok(obj)
+}
+
+fn emit_sidecars_bounded(
+ sidecars: Vec<(String, Value)>,
+ limit: usize,
+ sink: Sink,
+ stats: &mut ExtractStats,
+) {
+ let mut kept = Vec::new();
+ for (key, value) in sidecars {
+ let raw_len = match &value {
+ Value::String(text) => text.len(),
+ other => serde_json::to_string(other)
+ .map(|text| text.len())
+ .unwrap_or(usize::MAX),
+ };
+ if raw_len.saturating_add(key.len()).saturating_add(8) > limit {
+ stats.oversize_values += 1;
+ continue;
+ }
+ kept.push((key, value));
+ }
+ emit_sidecars(kept, sink, stats);
+}
+
+fn emit_single_object(
+ bytes: &[u8],
+ path: &Path,
+ fields: &[Field],
+ limit: usize,
+ sink: Sink,
+ stats: &mut ExtractStats,
+) -> Result<(), serde_json::Error> {
+ let mut skipped = 0u64;
+ let mut kept = Vec::new();
+ let mut sum = 2usize;
+ for field in fields {
+ if field.range.len() > limit {
+ skipped += 1;
+ continue;
+ }
+ sum = sum.saturating_add(field.key.len() + field.range.len() + 4);
+ kept.push(field);
+ }
+ 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",
+ file_label(path),
+ bytes.len(),
+ ));
+ return Ok(());
+ }
+ stats.oversize_values += skipped;
+ let mut obj = Map::new();
+ for field in kept {
+ let value: Value = serde_json::from_slice(&bytes[field.range.clone()])?;
+ obj.insert(field.key.clone(), value);
+ }
+ emit(Value::Object(obj), "doc", sink, stats);
+ Ok(())
+}
+
+fn stream_top_array(
+ bytes: &[u8],
+ limit: usize,
+ sink: Sink,
+ stats: &mut ExtractStats,
+) -> Result<(), serde_json::Error> {
+ struct TopVisitor<'a> {
+ limit: usize,
+ sink: Sink<'a>,
+ stats: &'a mut ExtractStats,
+ }
+ impl<'de> Visitor<'de> for TopVisitor<'_> {
+ type Value = ();
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a JSON array")
+ }
+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
+ let TopVisitor { limit, sink, stats } = self;
+ let mut count = 0u64;
+ let mut live = true;
+ loop {
+ let raw = match seq.next_element::<&RawValue>() {
+ Ok(Some(raw)) => raw,
+ Ok(None) => break,
+ Err(error) => {
+ if count > 0 {
+ stats.populations.push((None, count));
+ }
+ return Err(error);
+ }
+ };
+ let i = count;
+ count += 1;
+ if raw.get().len() > limit {
+ stats.oversize_values += 1;
+ continue;
+ }
+ if !live {
+ continue;
+ }
+ let value: Value = match serde_json::from_str(raw.get()) {
+ Ok(value) => value,
+ Err(_) => {
+ stats.junk += 1;
+ continue;
+ }
+ };
+ if !emit(value, &format!("e{i}"), sink, stats) {
+ live = false;
+ }
+ }
+ if count > 0 {
+ stats.populations.push((None, count));
+ }
+ Ok(())
+ }
+ }
+ let mut de = serde_json::Deserializer::from_slice(bytes);
+ de.deserialize_any(TopVisitor { limit, sink, stats })?;
+ de.end()?;
+ Ok(())
+}
+
+fn emit_record_array<'a>(
+ input: &'a [u8],
+ key: &'a str,
+ group: Option<String>,
+ shared: &'a Map<String, Value>,
+ limit: usize,
+ sink: Sink<'a>,
+ stats: &'a mut ExtractStats,
+) -> Result<(), serde_json::Error> {
+ struct RecVisitor<'a> {
+ key: &'a str,
+ group: Option<String>,
+ shared: &'a Map<String, Value>,
+ limit: usize,
+ sink: Sink<'a>,
+ stats: &'a mut ExtractStats,
+ }
+ impl<'de> Visitor<'de> for RecVisitor<'_> {
+ type Value = ();
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a JSON array of objects")
+ }
+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
+ let RecVisitor {
+ key,
+ group,
+ shared,
+ limit,
+ sink,
+ stats,
+ } = self;
+ let mut live = true;
+ let mut index = 0u64;
+ while let Some(raw) = seq.next_element::<&RawValue>()? {
+ let i = index;
+ index += 1;
+ if raw.get().len() > limit {
+ stats.oversize_values += 1;
+ continue;
+ }
+ if !live {
+ continue;
+ }
+ let value: Value = match serde_json::from_str(raw.get()) {
+ Ok(value) => value,
+ Err(_) => {
+ stats.junk += 1;
+ continue;
+ }
+ };
+ let Value::Object(element) = value else {
+ continue;
+ };
+ let fields = merge_shared(shared, element);
+ if !emit_fields(fields, format!("{key}:e{i}"), group.clone(), sink, stats) {
+ live = false;
+ }
+ }
+ Ok(())
+ }
+ }
+ let mut de = serde_json::Deserializer::from_slice(input);
+ de.deserialize_any(RecVisitor {
+ key,
+ group,
+ shared,
+ limit,
+ sink,
+ stats,
+ })?;
+ de.end()?;
+ Ok(())
+}
+
fn emit(v: Value, locator: &str, sink: Sink, stats: &mut ExtractStats) -> bool {
let mut fields = match v {
Value::Object(m) => flatten_object(m),
@@ -959,4 +1430,162 @@ mod tests {
.contains(&(None, MULTI_ARRAY_SPLIT_MIN as u64)));
assert!(stats.populations.contains(&(Some("runs".into()), 3)));
}
+
+ fn run_limited(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 = extract_limited(
+ &path,
+ false,
+ &mut |r| {
+ recs.push(r);
+ true
+ },
+ limit,
+ )
+ .unwrap();
+ (stats, recs)
+ }
+
+ fn assert_same_records(dom: &[RawRecord], streamed: &[RawRecord]) {
+ assert_eq!(dom.len(), streamed.len());
+ for (left, right) in dom.iter().zip(streamed) {
+ assert_eq!(left.locator, right.locator);
+ assert_eq!(left.group, right.group);
+ assert_eq!(left.origin, right.origin);
+ assert_eq!(left.fields, right.fields);
+ }
+ }
+
+ /// A file past the per-document ceiling must emit the same locators as the
+ /// DOM path when every element itself fits. This is the 50 MB array of
+ /// small objects: the DOM path is what shipped, the stream is what runs
+ /// once the file is larger than the ceiling.
+ #[test]
+ fn a_file_over_the_document_limit_streams_the_same_records() {
+ 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 array = r#"[{"id":1,"user":{"name":"ann"}},{"id":2}]"#;
+ let wrapper = r#"{"generated":"2026-01-01","count":2,"items":[{"id":1},{"id":2,"generated":"per-item"}],"errors":[{"e":1}]}"#;
+ // Each limit is under the file and over every element, so the stream
+ // emits the same records the DOM path would.
+ for (text, limit) in [
+ (split.as_str(), 256usize),
+ (array, 36),
+ (wrapper, 80),
+ ("[1,2,3]", 4),
+ ] {
+ assert!(
+ text.len() > limit,
+ "the fixture must take the streaming path ({})",
+ text.len()
+ );
+ let (dom_stats, dom) = run_limited(text, usize::MAX);
+ let (stream_stats, streamed) = run_limited(text, limit);
+ assert_eq!(dom_stats.records, stream_stats.records, "{text}");
+ assert_eq!(dom_stats.populations, stream_stats.populations, "{text}");
+ assert_same_records(&dom, &streamed);
+ assert_eq!(stream_stats.oversize_values, 0, "{text}");
+ }
+ }
+
+ #[test]
+ fn a_single_object_over_the_document_limit_names_the_file_and_is_not_indexed() {
+ let blob = "x".repeat(80);
+ let text = format!(r#"{{"blob":"{blob}"}}"#);
+ let (stats, recs) = run_limited(&text, 32);
+ assert!(recs.is_empty());
+ assert_eq!(stats.records, 0);
+ assert!(stats.oversize_values >= 1);
+ let reason = stats.refusal.expect("a refusal naming the file");
+ assert!(reason.contains("t.json"), "{reason}");
+ assert!(reason.contains("32"), "{reason}");
+ assert!(reason.contains("not indexed"), "{reason}");
+ assert!(!stats.truncated, "this is not the section cap");
+ }
+
+ #[test]
+ fn a_huge_shared_string_is_skipped_and_the_record_array_is_indexed() {
+ let blob = "x".repeat(80);
+ let text = format!(r#"{{"name":"n","items":[{{"id":1}},{{"id":2}}],"blob":"{blob}"}}"#);
+ let (stats, recs) = run_limited(&text, 40);
+ assert_eq!(recs.len(), 2);
+ assert_eq!(recs[0].locator, "items:e0");
+ assert_eq!(recs[1].locator, "items:e1");
+ assert!(recs.iter().all(|r| r.fields.get("blob").is_none()));
+ assert_eq!(recs[0].fields["name"], serde_json::json!("n"));
+ assert!(stats.oversize_values >= 1);
+ assert!(stats.refusal.is_none(), "the records were indexed");
+ }
+
+ #[test]
+ fn an_oversized_array_element_keeps_its_siblings_and_its_index() {
+ let blob = "y".repeat(80);
+ let text = format!(r#"[{{"id":1}},{{"blob":"{blob}"}},{{"id":2}}]"#);
+ let (stats, recs) = run_limited(&text, 40);
+ assert_eq!(recs.len(), 2);
+ assert_eq!(recs[0].locator, "e0");
+ assert_eq!(recs[1].locator, "e2", "the skipped element keeps its index");
+ assert_eq!(recs[1].fields["id"], serde_json::json!(2));
+ assert_eq!(stats.oversize_values, 1);
+ assert_eq!(
+ stats.populations,
+ vec![(None, 3)],
+ "the population is the whole array, including the skipped element"
+ );
+ }
+
+ #[test]
+ fn a_jsonl_line_over_the_document_limit_is_not_indexed() {
+ let blob = "z".repeat(80);
+ let text = format!("{{\"id\":\"small\"}}\n{{\"blob\":\"{blob}\"}}\n");
+ let (stats, recs) = run_limited(&text, 40);
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs[0].fields["id"], serde_json::json!("small"));
+ assert_eq!(stats.oversize_values, 1);
+ assert_eq!(stats.junk, 0);
+ assert!(stats.refusal.is_none());
+ }
+
+ #[test]
+ fn stopping_a_streamed_array_keeps_its_population_and_the_sibling() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("t.json");
+ let mut functions = Vec::new();
+ for i in 0..MULTI_ARRAY_SPLIT_MIN {
+ functions.push(format!(r#"{{"name":"f{i}"}}"#));
+ }
+ let text = format!(
+ r#"{{"functions":[{}],"runs":[{{"label":"a"}},{{"label":"b"}},{{"label":"c"}}]}}"#,
+ functions.join(",")
+ );
+ assert!(text.len() > 64);
+ std::fs::write(&path, &text).unwrap();
+ let mut seen = std::collections::HashMap::<Option<String>, usize>::new();
+ let stats = extract_limited(
+ &path,
+ false,
+ &mut |r| {
+ let n = seen.entry(r.group.clone()).or_insert(0);
+ *n += 1;
+ *n < 2
+ },
+ 64,
+ )
+ .unwrap();
+ assert_eq!(seen.get(&None).copied(), Some(2));
+ assert_eq!(seen.get(&Some("runs".into())).copied(), Some(2));
+ assert!(stats
+ .populations
+ .contains(&(None, MULTI_ARRAY_SPLIT_MIN as u64)));
+ assert!(stats.populations.contains(&(Some("runs".into()), 3)));
+ }
}
diff --git a/engine/crates/xerj-autoindex/src/extract/jsonl.rs b/engine/crates/xerj-autoindex/src/extract/jsonl.rs
index 3b76dc407..5503f2dfd 100644
--- a/engine/crates/xerj-autoindex/src/extract/jsonl.rs
+++ b/engine/crates/xerj-autoindex/src/extract/jsonl.rs
@@ -12,6 +12,22 @@ pub fn extract(
gzip: bool,
limit_bytes: Option<u64>,
sink: Sink,
+) -> Result<ExtractStats> {
+ extract_limited(
+ path,
+ gzip,
+ limit_bytes,
+ sink,
+ xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES,
+ )
+}
+
+fn extract_limited(
+ path: &Path,
+ gzip: bool,
+ limit_bytes: Option<u64>,
+ sink: Sink,
+ doc_limit: usize,
) -> Result<ExtractStats> {
let mut r = super::open_reader(path, gzip, limit_bytes)?;
let mut stats = ExtractStats::default();
@@ -33,6 +49,12 @@ pub fn extract(
stats.junk += 1;
continue;
}
+ // A line under the 16 MB read cap can still be one document large
+ // enough to blow the node when it is tokenized (#1122).
+ if trimmed.len() > doc_limit {
+ stats.oversize_values += 1;
+ continue;
+ }
match serde_json::from_slice::<Value>(trimmed) {
Ok(Value::Object(m)) => {
let mut fields = flatten_object(m);
@@ -56,6 +78,16 @@ pub fn extract(
}
}
}
+ if stats.records == 0 && stats.oversize_values > 0 && stats.refusal.is_none() {
+ let name = path
+ .file_name()
+ .map(|s| s.to_string_lossy().into_owned())
+ .unwrap_or_else(|| path.display().to_string());
+ stats.refusal = Some(format!(
+ "{name} is over the {doc_limit}-byte limit for one JSON document; {} JSON value(s) were not indexed. Split the file into smaller documents",
+ stats.oversize_values,
+ ));
+ }
Ok(stats)
}
@@ -106,14 +138,32 @@ mod tests {
use super::*;
fn run(bytes: &[u8], limit: Option<u64>) -> (ExtractStats, Vec<RawRecord>) {
+ run_capped(
+ bytes,
+ limit,
+ xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES,
+ )
+ }
+
+ fn run_capped(
+ bytes: &[u8],
+ limit: Option<u64>,
+ doc_limit: usize,
+ ) -> (ExtractStats, Vec<RawRecord>) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("t.jsonl");
std::fs::write(&path, bytes).unwrap();
let mut recs = Vec::new();
- let stats = extract(&path, false, limit, &mut |r| {
- recs.push(r);
- true
- })
+ let stats = extract_limited(
+ &path,
+ false,
+ limit,
+ &mut |r| {
+ recs.push(r);
+ true
+ },
+ doc_limit,
+ )
.unwrap();
(stats, recs)
}
@@ -202,6 +252,29 @@ mod tests {
assert_eq!(recs[0].fields["id"], serde_json::json!(2));
}
+ /// A line between the per-document ceiling and the 16 MB read cap used to
+ /// be parsed and indexed (#1122).
+ #[test]
+ fn a_line_over_the_document_limit_is_not_indexed() {
+ let blob = "q".repeat(80);
+ let data = format!("{{\"id\":1}}\n{{\"blob\":\"{blob}\"}}\n");
+ let (stats, recs) = run_capped(data.as_bytes(), None, 40);
+ assert_eq!(stats.records, 1);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(stats.oversize_values, 1);
+ assert_eq!(recs[0].fields["id"], serde_json::json!(1));
+ assert!(stats.refusal.is_none(), "the small line was indexed");
+
+ let only = format!("{{\"blob\":\"{blob}\"}}\n");
+ let (stats, recs) = run_capped(only.as_bytes(), None, 40);
+ assert!(recs.is_empty());
+ assert_eq!(stats.oversize_values, 1);
+ let reason = stats.refusal.expect("names the file");
+ assert!(reason.contains("t.jsonl"), "{reason}");
+ assert!(reason.contains("40"), "{reason}");
+ assert!(reason.contains("not indexed"), "{reason}");
+ }
+
/// #1158: a JSONL record with no prose gains a `text` passage from its
/// own fields, same as the whole-file family — a `.jsonl` mirror is the
/// other raw-JSON corpus shape.
diff --git a/engine/crates/xerj-autoindex/src/extract/mod.rs b/engine/crates/xerj-autoindex/src/extract/mod.rs
index ef07b87ef..2ae4d0402 100644
--- a/engine/crates/xerj-autoindex/src/extract/mod.rs
+++ b/engine/crates/xerj-autoindex/src/extract/mod.rs
@@ -88,6 +88,15 @@ pub struct ExtractStats {
/// sampler stops, so a 100_000-row array sampled at 500 still reports
/// 100_000. Empty for families that do not know a length.
pub populations: Vec<(Option<String>, u64)>,
+ /// JSON values that were not indexed because one document would have
+ /// exceeded [`xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES`]
+ /// (#1122). Not a junk count: the rest of the file is still indexed.
+ pub oversize_values: u64,
+ /// Set when nothing from this file was indexed because of that ceiling,
+ /// or because the file is larger than [`MAX_WHOLE_FILE`]. Phase A prints
+ /// this instead of the generic "no records" line. `None` when the file
+ /// produced records (an oversize value is then only counted above).
+ pub refusal: Option<String>,
}
/// Sink returns false to stop extraction early (sampling).
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 7fc9118cf..f6e9d44fb 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -3432,14 +3432,18 @@ fn scan_file(
Ok(stats) => {
populations = stats.populations;
if groups.is_empty() {
- out.junk = Some((
- "junk".into(),
- format!(
- "no records extracted ({} candidate family, {} junk lines)",
- sn.family.as_str(),
- stats.junk
- ),
- ));
+ if let Some(reason) = stats.refusal {
+ out.junk = Some(("skipped".into(), reason));
+ } else {
+ out.junk = Some((
+ "junk".into(),
+ format!(
+ "no records extracted ({} candidate family, {} junk lines)",
+ sn.family.as_str(),
+ stats.junk
+ ),
+ ));
+ }
}
}
Err(e) => {
@@ -9760,6 +9764,23 @@ fn run_index_report_inner(
if stats.truncated {
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,
+ ));
+ } 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,
+ ));
+ }
+ }
}
Err(e) => {
send_err = Some(format!("extract {}: {e}", f.rel));
diff --git a/engine/crates/xerj-common/src/document_limit.rs b/engine/crates/xerj-common/src/document_limit.rs
new file mode 100644
index 000000000..89700d3af
--- /dev/null
+++ b/engine/crates/xerj-common/src/document_limit.rs
@@ -0,0 +1,127 @@
+//! Per-document byte ceiling for indexed JSON (#1122).
+//!
+//! One bulk item and one `index_document` call tokenize the whole source
+//! before the process memory breaker can sample. The FTS `Token` owns a
+//! `String` per word. A standalone reproduction of that ownership (not a live
+//! `analyze_doc` run), measured 2026-10-23: 8,388,605 bytes of the word
+//! `word ` (1,677,721 tokens) grew a `Vec<String>` from 10,160 KB RSS to
+//! 101,912 KB RSS — 91,752 KB, about 56 bytes per token. It was not repeated
+//! at 50 MB.
+//!
+//! The ceiling is a fixed constant. `limits` is already 15 settings and the
+//! user-facing total is 137; a new knob would have to touch every settings
+//! census for a bound that must not be raised by a config edit.
+
+use serde_json::Value;
+
+/// Largest JSON document source that may be parsed and analyzed.
+///
+/// 8 MiB is under the 50 MB files that killed a node during autoindex, and
+/// above a normal record. A larger file is streamed into smaller records or
+/// skipped. A single value over this limit is not indexed.
+pub const MAX_INDEXED_DOCUMENT_BYTES: usize = 8 << 20;
+
+/// `true` when `len` is past [`MAX_INDEXED_DOCUMENT_BYTES`].
+pub fn indexed_document_too_large(len: usize) -> bool {
+ len > MAX_INDEXED_DOCUMENT_BYTES
+}
+
+/// Refusal text for a document whose raw JSON is `len` bytes.
+pub fn indexed_document_refusal(len: usize) -> String {
+ format!(
+ "document is {len} bytes, over the {MAX_INDEXED_DOCUMENT_BYTES} byte limit for one indexed JSON document; it was not indexed. Split it into smaller documents"
+ )
+}
+
+/// Refusal text when a walk of an already-parsed value stopped at `seen`.
+pub fn indexed_document_refusal_at_least(seen: usize) -> String {
+ format!(
+ "document is at least {seen} bytes, over the {MAX_INDEXED_DOCUMENT_BYTES} byte limit for one indexed JSON document; it was not indexed. Split it into smaller documents"
+ )
+}
+
+/// `Some(accounted)` when a walk of `value` passes the limit.
+///
+/// The walk stops at the first byte past the limit, so `accounted` can be
+/// smaller than the full value. Strings contribute their decoded length.
+/// Numbers contribute a fixed 8 bytes (serde_json stores them as `i64`,
+/// `u64`, or `f64` without `arbitrary_precision`). One byte is charged per
+/// array element so a giant array of nulls still trips.
+pub fn json_value_exceeds_indexed_document_limit(value: &Value) -> Option<usize> {
+ let mut accounted = 0usize;
+ if exceeds(value, &mut accounted) {
+ Some(accounted)
+ } else {
+ None
+ }
+}
+
+fn charge(accounted: &mut usize, n: usize) -> bool {
+ *accounted = accounted.saturating_add(n);
+ *accounted > MAX_INDEXED_DOCUMENT_BYTES
+}
+
+fn exceeds(value: &Value, accounted: &mut usize) -> bool {
+ match value {
+ Value::Null | Value::Bool(_) => charge(accounted, 4),
+ Value::Number(_) => charge(accounted, 8),
+ Value::String(text) => charge(accounted, text.len().saturating_add(2)),
+ Value::Array(items) => {
+ if charge(accounted, 2) {
+ return true;
+ }
+ for item in items {
+ if charge(accounted, 1) || exceeds(item, accounted) {
+ return true;
+ }
+ }
+ false
+ }
+ Value::Object(map) => {
+ if charge(accounted, 2) {
+ return true;
+ }
+ for (key, child) in map {
+ if charge(accounted, key.len().saturating_add(3)) || exceeds(child, accounted) {
+ return true;
+ }
+ }
+ false
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn the_ceiling_is_eight_mebibytes() {
+ assert_eq!(MAX_INDEXED_DOCUMENT_BYTES, 8 * 1024 * 1024);
+ assert!(!indexed_document_too_large(MAX_INDEXED_DOCUMENT_BYTES));
+ assert!(indexed_document_too_large(MAX_INDEXED_DOCUMENT_BYTES + 1));
+ }
+
+ #[test]
+ fn refusal_names_the_size_and_the_limit() {
+ let text = indexed_document_refusal(50 * 1024 * 1024);
+ assert!(text.contains("52428800"));
+ assert!(text.contains(&MAX_INDEXED_DOCUMENT_BYTES.to_string()));
+ assert!(text.contains("not indexed"));
+ let at_least = indexed_document_refusal_at_least(MAX_INDEXED_DOCUMENT_BYTES + 3);
+ assert!(at_least.contains("at least"));
+ assert!(at_least.contains("not indexed"));
+ }
+
+ #[test]
+ fn a_small_value_is_under_the_limit_and_a_long_string_is_not() {
+ assert!(json_value_exceeds_indexed_document_limit(&json!({"id": 1})).is_none());
+ let huge = "x".repeat(MAX_INDEXED_DOCUMENT_BYTES + 1);
+ let seen = json_value_exceeds_indexed_document_limit(&json!({"blob": huge}))
+ .expect("a string past the ceiling must trip");
+ assert!(seen > MAX_INDEXED_DOCUMENT_BYTES);
+ // The walk stops on that string. It must not report a second full copy.
+ assert!(seen < MAX_INDEXED_DOCUMENT_BYTES + 64);
+ }
+}
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index 922500907..5aa7aee58 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -32,6 +32,8 @@
//! same-machine CLI/MCP commands (`xerj mcp`, `xerj autoindex`, `xerj init`)
//! - [`xccode`] — the reference-coding semantics shared by `xerj code`,
//! `xerj corpus`, and the `xerj_code_search` MCP tool (issue #977)
+//! - [`document_limit`] — the fixed per-document byte ceiling that keeps one
+//! JSON value from being tokenized into an unbounded `String` per word (#1122)
//! - [`thread_spawn`] — spawning helper threads without aborting the node
//! on a failed spawn (#1122): Unix threads are created with `pthread_create`
//! so a signal-stack allocation failure is an error instead of a panic in
@@ -45,6 +47,7 @@ pub mod calibration;
pub mod code_query;
pub mod config;
pub mod corpus_feedback;
+pub mod document_limit;
pub mod error;
pub mod feedback;
pub mod field_coercion;
diff --git a/engine/crates/xerj-engine/src/bulk.rs b/engine/crates/xerj-engine/src/bulk.rs
index 6cb9439b4..6170046fe 100644
--- a/engine/crates/xerj-engine/src/bulk.rs
+++ b/engine/crates/xerj-engine/src/bulk.rs
@@ -906,6 +906,31 @@ pub async fn process_bulk_with_opts(
);
}
};
+ // One document over the fixed ceiling is refused before
+ // `IgnoredAny`, `Value`, or tokenization. `Token` owns a
+ // `String` per word, and `panic = "abort"` dies on that
+ // allocation before the RSS governor samples (#1122).
+ // 413, not 429:
+ // the item is settled. Neighbours in the same bulk still
+ // index. A lone 413 is not the whole-request action-count
+ // refusal (`is_whole_request_too_large` requires more than
+ // one sent action).
+ if xerj_common::document_limit::indexed_document_too_large(dl.len()) {
+ return ParseOutcome::Err(
+ BulkItemResult {
+ action: action_type.to_string(),
+ index: target_index,
+ id: doc_id.unwrap_or_default(),
+ status: 413,
+ result: None,
+ error: Some(xerj_common::document_limit::indexed_document_refusal(
+ dl.len(),
+ )),
+ get_source: None,
+ },
+ *item_index,
+ );
+ }
// M5.11 — SKIP the doc-body JSON parse for `index`
// actions. The turbo-raw ingest path accepts the raw
// NDJSON bytes and defers the parse to drain-for-flush
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 697e57f10..f628d47c6 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -10859,6 +10859,18 @@ impl Index {
// Process-wide admission: disk flood-stage block (item 3) + parent
// memory circuit breaker (item 1). Fires before any per-index work.
self.governor_write_gate()?;
+ // Already-parsed bodies (PUT `/_doc/{id}` builds a `Value` in the
+ // extractor) still have to be refused before semantic embedding and
+ // `analyze_doc`. Bulk NDJSON is refused on the raw bytes earlier.
+ if let Some(seen) =
+ xerj_common::document_limit::json_value_exceeds_indexed_document_limit(&source)
+ {
+ return Err(EngineError::Common(
+ xerj_common::XerjError::invalid_document_json(
+ xerj_common::document_limit::indexed_document_refusal_at_least(seen),
+ ),
+ ));
+ }
let index_start = std::time::Instant::now();
let doc_id = id.unwrap_or_else(|| Uuid::new_v4().to_string());
diff --git a/engine/crates/xerj-engine/tests/es_compat_tests.rs b/engine/crates/xerj-engine/tests/es_compat_tests.rs
index 606d39baa..17d1f4444 100644
--- a/engine/crates/xerj-engine/tests/es_compat_tests.rs
+++ b/engine/crates/xerj-engine/tests/es_compat_tests.rs
@@ -811,6 +811,71 @@ async fn test_es_bulk_index_multiple() {
);
}
+/// One JSON document over [`MAX_INDEXED_DOCUMENT_BYTES`] must not be parsed
+/// or tokenized. Its neighbour in the same bulk still indexes, and a later
+/// single-document write of the same shape is refused the same way (#1122).
+#[tokio::test]
+async fn oversized_json_document_is_refused_and_its_neighbour_is_indexed() {
+ use xerj_common::document_limit::{indexed_document_too_large, MAX_INDEXED_DOCUMENT_BYTES};
+
+ let (engine, _dir) = test_engine();
+ engine
+ .create_index("bulk_oversize", Schema::empty())
+ .unwrap();
+
+ let big = "x".repeat(MAX_INDEXED_DOCUMENT_BYTES + 1);
+ let big_line = format!(r#"{{"blob":"{big}"}}"#);
+ assert!(indexed_document_too_large(big_line.len()));
+ let ndjson = format!(
+ "{}\n{}\n{}\n{}\n{}\n{}\n",
+ r#"{"index":{"_index":"bulk_oversize","_id":"small"}}"#,
+ r#"{"name":"Ada"}"#,
+ r#"{"index":{"_index":"bulk_oversize","_id":"big"}}"#,
+ big_line,
+ r#"{"index":{"_index":"bulk_oversize"}}"#,
+ r#"{"name":"Grace"}"#,
+ );
+
+ let result = process_bulk(&engine, Some("bulk_oversize"), &ndjson).await;
+ assert!(result.errors, "the oversized item is an error");
+ assert_eq!(result.items.len(), 3);
+ assert_eq!(result.items[0].status, 201);
+ assert_eq!(result.items[0].id, "small");
+ assert_eq!(result.items[1].status, 413);
+ assert_eq!(result.items[1].id, "big");
+ let reason = result.items[1].error.as_deref().unwrap_or("");
+ assert!(
+ reason.contains(&MAX_INDEXED_DOCUMENT_BYTES.to_string()),
+ "{reason}"
+ );
+ assert!(reason.contains("not indexed"), "{reason}");
+ assert!(!reason.contains(&big), "the refusal must not echo the body");
+ assert_eq!(
+ result.items[2].status, 201,
+ "auto-id neighbour still indexes"
+ );
+
+ let idx = engine.get_index("bulk_oversize").unwrap();
+ let search = idx
+ .search(&search_req(
+ json!({ "query": { "match_all": {} }, "size": 10 }),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(search.total.value, 2, "only the two small documents");
+ assert!(idx.get_document("big").await.unwrap().is_none());
+ assert!(idx.get_document("small").await.unwrap().is_some());
+
+ let err = idx
+ .index_document(Some("big-put".into()), json!({ "blob": big }))
+ .await
+ .expect_err("a parsed value past the ceiling is refused before analysis");
+ let text = err.to_string();
+ assert!(text.contains("at least"), "{text}");
+ assert!(text.contains("not indexed"), "{text}");
+ assert!(idx.get_document("small").await.unwrap().is_some());
+}
+
/// ES YAML test: bulk/10_basic.yml — mixed index + delete in one bulk request
#[tokio::test]
async fn test_es_bulk_mixed_operations() {
diff --git a/engine/crates/xerj-storage/src/index_store.rs b/engine/crates/xerj-storage/src/index_store.rs
index 5b85f6e0b..737c31818 100644
--- a/engine/crates/xerj-storage/src/index_store.rs
+++ b/engine/crates/xerj-storage/src/index_store.rs
@@ -775,6 +775,19 @@ fn block_on_backend<T>(
}
/// The off-runtime driver described on [`block_on_backend`].
+/// `true` when opening `path` fails because it is not there.
+///
+/// Any other error (permission, I/O) leaves the snapshot entry in place
+/// so a later open reports that error instead of dropping a segment whose
+/// file may still exist.
+fn segment_file_missing(path: &Path) -> bool {
+ match std::fs::File::open(path) {
+ Ok(_) => false,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
+ Err(_) => false,
+ }
+}
+
fn object_io_runtime() -> &'static tokio::runtime::Runtime {
static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
RUNTIME.get_or_init(|| {
@@ -789,6 +802,24 @@ fn object_io_runtime() -> &'static tokio::runtime::Runtime {
const WAL_MAINTENANCE_INTERVAL_MS: u64 = 1_000;
+/// Refuse one raw document before `IgnoredAny` or `from_slice` builds a DOM
+/// (#1122). Bulk filters the same ceiling per item so a mixed batch does not
+/// reach here; this is the backstop for `index_batch_turbo_raw`.
+fn reject_oversized_indexed_document(
+ doc_id: &str,
+ position: usize,
+ source_bytes: &[u8],
+) -> Result<()> {
+ if xerj_common::document_limit::indexed_document_too_large(source_bytes.len()) {
+ return Err(StorageError::RawBatchValidation {
+ doc_id: doc_id.to_string(),
+ position,
+ reason: xerj_common::document_limit::indexed_document_refusal(source_bytes.len()),
+ });
+ }
+ Ok(())
+}
+
impl IndexStore {
/// Open (or create) an index at `data_dir`.
///
@@ -915,6 +946,12 @@ impl IndexStore {
// Rebuild version map from flushed segments first (so WAL replay can
// correctly override segment entries for recently re-indexed docs).
+ //
+ // Do this only after a missing local segment file has been taken
+ // out of the snapshot. A surviving `.ids` sidecar is enough for the
+ // rebuild to point live docs at that id, and the next `_search`
+ // then fails the whole query with `Segment … not found`.
+ store.drop_local_segments_missing_files()?;
store.rebuild_version_map_from_segments()?;
// V4 M4.5 — snapshot GC on open. Any file in the segments directory
@@ -1034,6 +1071,94 @@ impl IndexStore {
Ok(store)
}
+ /// Remove snapshot entries whose segment file is already gone.
+ ///
+ /// Orphan recovery covers the opposite hole: a `.seg` that exists but
+ /// was never named by `snapshot.json`. This is the hole a partial
+ /// delete leaves behind. `snapshot.json` still names the segment, and
+ /// often the `.ids` sidecar does too, but the `.seg` was unlinked.
+ /// The live case is `xerj brain --fresh` after the data directory was
+ /// wiped while the previous process was still creating files: `rm`
+ /// removes `autoindex-catalog/<id>.seg` and then fails with "Directory
+ /// not empty", the new process opens that directory, and the catalog
+ /// read-back searches a snapshot that still lists the missing id.
+ /// `open_segment_arc` maps the missing file to `SegmentNotFound`, and
+ /// the search path treats that as a query error so it does not
+ /// undercount. Retries cannot help — the id stays in the snapshot.
+ ///
+ /// The bytes are already gone. Keeping the id makes every search fail,
+ /// including one whose new rows sit in a segment that is present.
+ /// Drop the id before the version map is rebuilt, and persist the
+ /// repaired snapshot so the next open does not rediscover it. Local
+ /// mode only: object-store boot hydrates a missing family from the
+ /// bucket, and a catalogue whose bundle is gone refuses to open
+ /// rather than shrinking the view.
+ ///
+ /// `max_seq_no` is not lowered. Sequence numbers from the missing
+ /// segment stay reserved so a later write does not reuse them.
+ fn drop_local_segments_missing_files(&self) -> Result<usize> {
+ if self.is_object_store_mode() {
+ return Ok(0);
+ }
+ let snap = self.snapshot.load();
+ if snap.segments.is_empty() {
+ return Ok(0);
+ }
+ let segments_dir = self.data_dir.join("segments");
+ let missing: Vec<String> = snap
+ .segments
+ .iter()
+ .filter(|meta| segment_file_missing(&segments_dir.join(&meta.seg_path)))
+ .map(|meta| meta.id.clone())
+ .collect();
+ if missing.is_empty() {
+ return Ok(0);
+ }
+ let missing_set: std::collections::HashSet<&str> =
+ missing.iter().map(String::as_str).collect();
+ let segments: Vec<SegmentMeta> = snap
+ .segments
+ .iter()
+ .filter(|meta| !missing_set.contains(meta.id.as_str()))
+ .cloned()
+ .collect();
+ // Keep the previous high-water mark. The missing segment's seqs
+ // must not be handed out again.
+ let max_seq_no = segments
+ .iter()
+ .map(|meta| meta.max_seq_no)
+ .max()
+ .unwrap_or(0)
+ .max(snap.max_seq_no);
+ let removed = missing.len();
+ let generation = snap.generation.saturating_add(1);
+ drop(snap);
+ self.snapshot.store(Arc::new(IndexSnapshot {
+ segments,
+ generation,
+ max_seq_no,
+ }));
+ if let Err(error) = self.save_snapshot() {
+ // The in-memory view is already repaired. Failing open would
+ // refuse the index, which is the 500 this pass exists to
+ // avoid. The on-disk manifest is unchanged, so the next open
+ // runs the same pass again.
+ warn!(
+ error = %error,
+ removed,
+ segments = ?missing,
+ "dropped snapshot segments whose files are gone, but could not persist the repaired snapshot"
+ );
+ return Ok(removed);
+ }
+ warn!(
+ removed,
+ segments = ?missing,
+ "dropped snapshot segments whose files are gone; searches no longer fail closed on them"
+ );
+ Ok(removed)
+ }
+
/// Try to add orphan segment files back to the snapshot before
/// `cleanup_orphaned_segment_files` deletes them.
///
@@ -4850,6 +4975,7 @@ impl IndexStore {
docs.par_iter()
.enumerate()
.map(|(position, (doc_id, source_bytes))| {
+ reject_oversized_indexed_document(doc_id, position + 1, source_bytes)?;
validate_raw_json_nesting(source_bytes).map_err(|reason| {
StorageError::RawBatchValidation {
doc_id: doc_id.clone(),
@@ -4877,6 +5003,7 @@ impl IndexStore {
.par_iter()
.enumerate()
.map(|(position, (doc_id, source_bytes))| {
+ reject_oversized_indexed_document(doc_id, position + 1, source_bytes)?;
validate_raw_json_nesting(source_bytes).map_err(|reason| {
StorageError::RawBatchValidation {
doc_id: doc_id.clone(),
@@ -6660,6 +6787,90 @@ mod tests {
assert_eq!(snap.segments.len(), 1);
}
+ /// A partial delete of the index directory leaves `snapshot.json` naming
+ /// a segment whose `.seg` is gone and whose `.ids` sidecar survived.
+ /// Reopening used to rebuild the version map from that sidecar and then
+ /// fail every `_search` with `Segment … not found` — the `--fresh`
+ /// catalog read-back after a wiped brain data dir. The missing id is
+ /// dropped; a sibling segment that is still on disk stays readable.
+ #[test]
+ fn reopen_drops_a_snapshot_segment_whose_file_is_gone() {
+ let dir = tempfile::tempdir().unwrap();
+ let kept_id;
+ let missing_id;
+ {
+ let store = open_test_store(dir.path());
+ store.index("kept", serde_json::json!({"k": 1})).unwrap();
+ kept_id = store.flush().unwrap().unwrap().id;
+ store.index("gone", serde_json::json!({"k": 2})).unwrap();
+ let gone = store.flush().unwrap().unwrap();
+ missing_id = gone.id.clone();
+ store.force_wal_maintenance().unwrap();
+ let snap = store.snapshot();
+ assert!(
+ snap.segments.iter().any(|meta| meta.id == missing_id),
+ "the segment must be published before its file is removed"
+ );
+ let seg_path = dir.path().join("segments").join(&gone.seg_path);
+ std::fs::remove_file(&seg_path).unwrap();
+ assert!(
+ dir.path()
+ .join("segments")
+ .join(format!("{missing_id}.ids"))
+ .exists(),
+ "the sidecar that used to resurrect the dangling id must still be there"
+ );
+ }
+
+ let store = open_test_store(dir.path());
+ {
+ let snap = store.snapshot();
+ let ids: Vec<&str> = snap.segments.iter().map(|meta| meta.id.as_str()).collect();
+ assert!(
+ ids.iter().all(|id| *id != missing_id.as_str()),
+ "a missing segment file must not stay in the snapshot: {ids:?}"
+ );
+ assert!(
+ snap.segments.iter().any(|meta| meta.id == kept_id),
+ "a sibling segment whose file is present must stay"
+ );
+ }
+ let kept = store.version_map.get("kept").expect("kept doc");
+ assert_eq!(&*kept.segment_id, kept_id.as_str());
+ assert!(!kept.deleted, "the surviving document must still be live");
+ match store.version_map.get("gone") {
+ None => {}
+ Some(entry) => {
+ assert_ne!(
+ &*entry.segment_id,
+ missing_id.as_str(),
+ "the version map must not point at the missing segment"
+ );
+ }
+ }
+ store
+ .open_segment_arc(&kept_id)
+ .expect("the surviving segment file opens");
+ store.index("fresh", serde_json::json!({"k": 3})).unwrap();
+ let fresh = store.flush().unwrap().unwrap();
+ store
+ .open_segment_arc(&fresh.id)
+ .expect("a segment written after the repair opens");
+
+ drop(store);
+ let again = open_test_store(dir.path());
+ assert!(
+ again
+ .snapshot()
+ .segments
+ .iter()
+ .all(|meta| meta.id != missing_id),
+ "the repaired snapshot must stay repaired across a second open"
+ );
+ assert!(again.version_map.get("kept").is_some());
+ assert!(again.version_map.get("fresh").is_some());
+ }
+
#[test]
fn open_segment_reader() {
let dir = tempfile::tempdir().unwrap();