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(bulk): reject one lone-surrogate doc per-item, not the whole batch

xerj-orge7430a787c62
diff --git a/engine/crates/xerj-engine/src/bulk.rs b/engine/crates/xerj-engine/src/bulk.rs
index 06e92a063..6cb9439b4 100644
--- a/engine/crates/xerj-engine/src/bulk.rs
+++ b/engine/crates/xerj-engine/src/bulk.rs
@@ -154,6 +154,131 @@ fn malformed_document_reason(
)
}
+/// Per-item 400 reason for a document carrying an unpaired UTF-16 surrogate.
+/// Mirrors the shape of [`malformed_document_reason`] so the HTTP response
+/// reads the same way, and names the fix the issue reporter already adopted.
+fn lone_surrogate_document_reason(
+ document_id: Option<&str>,
+ item_index: usize,
+ detail: &str,
+) -> String {
+ let document_id = document_id.unwrap_or("<auto-generated>");
+ format!(
+ "invalid document JSON for document ID {document_id:?} at bulk item position {}: \
+ parser error: {detail}; a JSON string escape (\\uXXXX) encoded an unpaired UTF-16 \
+ surrogate — half of an astral code point (e.g. an emoji cut in two by a fixed-width \
+ chunker). Fix: replace the unpaired surrogate with U+FFFD, or re-encode the field as \
+ valid UTF-8, before indexing. \
+ Related help: xerj index --help and https://xerj.org/llms.txt",
+ item_index + 1,
+ )
+}
+
+/// Scan a structurally-valid JSON document for an unpaired UTF-16 surrogate in
+/// a `\uXXXX` string escape, returning a short reason when one is found.
+///
+/// Why this exists: the `index` turbo path validates each source line with
+/// `serde_json::IgnoredAny`, which walks the JSON *without decoding* string
+/// contents, so it ACCEPTS an escape such as `"a\ud83db"`. The auto-id docs
+/// are then grouped and parsed as one batch into `serde_json::Value`s
+/// (`index_batch_turbo_raw` → `parse_validated_raw_batch`), and that parse
+/// DOES decode escapes and rejects the unpaired surrogate — but it fails the
+/// whole batch with a single error, so one bad chunk sank all 127 of its
+/// neighbours (issue #1304). ES reports such a document per-item and indexes
+/// the rest; this check restores that contract by catching the one gap
+/// between `IgnoredAny` acceptance and `Value` rejection here, per-item,
+/// before the document can enter a batch.
+///
+/// It runs only after `IgnoredAny` has already accepted the bytes, so every
+/// string is terminated and every `\u` is followed by four hex digits; the
+/// scan therefore only has to check surrogate *pairing*. Equivalence with
+/// serde_json's own accept/reject decision is pinned by a unit test. Unpaired
+/// surrogates are the sole semantic string check `Value` makes that
+/// `IgnoredAny` skips (nesting depth is already capped identically upstream
+/// in `validate_raw_json_nesting`), so this closes the gap completely.
+fn lone_surrogate_escape_reason(bytes: &[u8]) -> Option<&'static str> {
+ // Decode four ASCII hex digits at `i` into a u16. The structural pass
+ // guarantees they are present and valid; `None` here would mean that
+ // invariant broke, in which case we defer to the downstream parser.
+ fn hex4(bytes: &[u8], i: usize) -> Option<u16> {
+ let mut value: u16 = 0;
+ for offset in 0..4 {
+ let digit = *bytes.get(i + offset)?;
+ let nibble = match digit {
+ b'0'..=b'9' => digit - b'0',
+ b'a'..=b'f' => digit - b'a' + 10,
+ b'A'..=b'F' => digit - b'A' + 10,
+ _ => return None,
+ };
+ value = (value << 4) | nibble as u16;
+ }
+ Some(value)
+ }
+
+ // Fast path: a `\uXXXX` escape requires a backslash, so a document with
+ // no backslash at all cannot carry an unpaired surrogate. `contains` is a
+ // single memchr pass, which keeps the common ingest doc (no escapes) off
+ // the byte-by-byte state machine below and preserves the turbo win.
+ if !bytes.contains(&b'\\') {
+ return None;
+ }
+
+ let mut i = 0;
+ let mut in_string = false;
+ while i < bytes.len() {
+ let byte = bytes[i];
+ if !in_string {
+ if byte == b'"' {
+ in_string = true;
+ }
+ i += 1;
+ continue;
+ }
+ match byte {
+ b'"' => {
+ in_string = false;
+ i += 1;
+ }
+ b'\\' => {
+ // The byte after a backslash is the escape kind. An escaped
+ // backslash (`\\`) consumes both bytes here, so a following
+ // `u` is a literal `u`, never the start of a `\u` escape.
+ match bytes.get(i + 1).copied() {
+ Some(b'u') => {
+ // `None` can only mean the structural invariant broke;
+ // fall through to the downstream parser via `?`.
+ let code_unit = hex4(bytes, i + 2)?;
+ if (0xDC00..=0xDFFF).contains(&code_unit) {
+ // A low surrogate with no preceding high surrogate.
+ return Some("lone trailing surrogate in hex escape");
+ }
+ if (0xD800..=0xDBFF).contains(&code_unit) {
+ // A high surrogate must be followed immediately by
+ // a `\u` escape encoding a low surrogate.
+ let paired = bytes.get(i + 6) == Some(&b'\\')
+ && bytes.get(i + 7) == Some(&b'u')
+ && hex4(bytes, i + 8)
+ .is_some_and(|low| (0xDC00..=0xDFFF).contains(&low));
+ if !paired {
+ return Some("lone leading surrogate in hex escape");
+ }
+ // Consume the whole valid pair: `\uXXXX\uYYYY`.
+ i += 12;
+ continue;
+ }
+ // A well-formed non-surrogate `\uXXXX` escape.
+ i += 6;
+ }
+ Some(_) => i += 2, // `\"`, `\\`, `\n`, `\t`, …
+ None => i += 1,
+ }
+ }
+ _ => i += 1,
+ }
+ }
+ None
+}
+
/// The one place a bulk item's per-item `status` is derived from an engine
/// error. Every `Err` arm in this module routes through here.
///
@@ -848,6 +973,31 @@ pub async fn process_bulk_with_opts(
*item_index,
);
}
+ // `IgnoredAny` above does not decode string escapes,
+ // so an unpaired UTF-16 surrogate (`"a\ud83db"`) slips
+ // through here but is rejected by the batch `Value`
+ // parse on the turbo-raw ingest path — failing every
+ // other document grouped with it (issue #1304). Reject
+ // it per-item now so ES's bulk contract holds: the one
+ // bad document errors and its neighbours still index.
+ if let Some(detail) = lone_surrogate_escape_reason(dl.as_bytes()) {
+ return ParseOutcome::Err(
+ BulkItemResult {
+ action: action_type.to_string(),
+ index: target_index,
+ id: doc_id.clone().unwrap_or_default(),
+ status: 400,
+ result: None,
+ error: Some(lone_surrogate_document_reason(
+ doc_id.as_deref(),
+ *item_index,
+ detail,
+ )),
+ get_source: None,
+ },
+ *item_index,
+ );
+ }
let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(dl.as_bytes());
(None, bytes)
} else {
@@ -3425,3 +3575,168 @@ mod semantic_lifecycle_tests {
assert_eq!(crate::ingest_memory::LEDGER.accounting_errors(), 0);
}
}
+
+#[cfg(test)]
+mod lone_surrogate_tests {
+ use super::*;
+ use tempfile::TempDir;
+ use xerj_common::config::Config;
+ use xerj_common::types::Schema;
+
+ fn plain_engine(name: &str) -> (TempDir, Engine) {
+ let dir = TempDir::new().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = Engine::new(config).unwrap();
+ engine.create_index(name, Schema::empty()).unwrap();
+ (dir, engine)
+ }
+
+ /// The per-item scan must reject exactly the documents serde_json's own
+ /// `Value` parse rejects for surrogate escapes — no more, no less. If it
+ /// were stricter it would drop valid documents; if it were laxer the bad
+ /// document would still reach the batch `Value` parse and sink its
+ /// neighbours, which is the bug. Every case below first passes
+ /// `IgnoredAny` (the fast path the scan runs after), so the comparison is
+ /// apples-to-apples.
+ #[test]
+ fn surrogate_scan_matches_serde_value_decision() {
+ // Build every `\uXXXX` escape from a runtime backslash (code point 92)
+ // so the test source carries no literal escape sequences that a tool
+ // or editor might normalise — the bytes under test are exactly these.
+ let bs = char::from_u32(92).unwrap();
+ let u = |hex: &str| format!("{bs}u{hex}");
+ let body = |inner: String| format!(r#"{{"body":"{inner}"}}"#).into_bytes();
+ let key = |inner: String| format!(r#"{{"{inner}":"v"}}"#).into_bytes();
+
+ let cases: Vec<Vec<u8>> = vec![
+ body("plain ascii".to_string()),
+ body(format!("emoji {}{} ok", u("d83d"), u("de00"))), // valid pair
+ body(format!("clef {}{}", u("d834"), u("dd1e"))), // valid astral pair
+ body(format!("a{}b", u("d83d"))), // lone high (issue #1304)
+ body(u("d83d")), // lone high at string end
+ body(format!("{} low", u("dc00"))), // lone low surrogate
+ body(format!("{}{}", u("d83d"), u("0041"))), // high then a non-low escape
+ body(format!("{}text", u("d83d"))), // high then plain text
+ body(format!("{}{}", u("dc00"), u("d83d"))), // low before high (both wrong)
+ body(format!("escaped {}{}u1234 literal", bs, bs)), // `\\u1234` is not an escape
+ body(format!("{}t {}n {}{} tame", bs, bs, bs, bs)), // ordinary escapes only
+ body(format!("bom {} null {}", u("feff"), u("0000"))), // valid non-surrogate escapes
+ key(format!("{}{}", u("d83d"), u("de00"))), // valid pair in an object key
+ key(u("d83d")), // lone surrogate in a key
+ ];
+ for raw in &cases {
+ let readable = String::from_utf8_lossy(raw);
+ assert!(
+ serde_json::from_slice::<serde::de::IgnoredAny>(raw).is_ok(),
+ "precondition: IgnoredAny should accept {readable:?}",
+ );
+ let scan_rejects = lone_surrogate_escape_reason(raw).is_some();
+ let value_rejects = serde_json::from_slice::<serde_json::Value>(raw).is_err();
+ assert_eq!(
+ scan_rejects, value_rejects,
+ "scan and serde_json::Value disagree on {readable:?}",
+ );
+ }
+ }
+
+ /// Issue #1304: a single auto-id document carrying an unpaired UTF-16
+ /// surrogate must fail per-item while its 127 well-formed neighbours
+ /// index. Before the fix the whole batch failed with a single
+ /// `lone leading surrogate in hex escape` and nothing was indexed.
+ #[tokio::test]
+ async fn one_lone_surrogate_does_not_sink_its_bulk_batch() {
+ let name = "issue-1304";
+ let (_dir, engine) = plain_engine(name);
+
+ const TOTAL: usize = 128;
+ const BAD_POS: usize = 42;
+ let mut body = String::new();
+ for i in 0..TOTAL {
+ // Auto-id: no `_id`, so every doc is grouped into one turbo batch.
+ body.push_str(&format!("{{\"index\":{{\"_index\":\"{name}\"}}}}\n"));
+ if i == BAD_POS {
+ // `"a" + String.fromCharCode(0xd83d) + "b"` -> `"a\ud83db"`.
+ body.push_str("{\"body\":\"a\\ud83db\"}\n");
+ } else {
+ body.push_str(&format!("{{\"body\":\"chunk {i} is well formed\"}}\n"));
+ }
+ }
+
+ let result = process_bulk(&engine, None, &body).await;
+
+ assert!(
+ result.errors,
+ "a batch containing one bad document must report errors=true",
+ );
+ assert_eq!(result.items.len(), TOTAL);
+
+ let failed: Vec<usize> = result
+ .items
+ .iter()
+ .enumerate()
+ .filter(|(_, item)| item.status != 201)
+ .map(|(i, _)| i)
+ .collect();
+ assert_eq!(
+ failed,
+ vec![BAD_POS],
+ "exactly the one unpaired-surrogate document must fail, not its neighbours",
+ );
+
+ let bad = &result.items[BAD_POS];
+ assert_eq!(bad.status, 400, "the bad document is a 400, not a 500");
+ assert!(
+ bad.error
+ .as_deref()
+ .unwrap_or_default()
+ .contains("surrogate"),
+ "the per-item error should name the surrogate: {:?}",
+ bad.error,
+ );
+
+ // The 127 good documents are actually indexed, not merely acked.
+ let index = engine.get_index(name).unwrap();
+ index.refresh().await.unwrap();
+ assert_eq!(
+ index.live_doc_count(),
+ (TOTAL - 1) as u64,
+ "every well-formed document in the batch must be indexed",
+ );
+ }
+
+ /// Two bad documents in the same batch each fail on their own; the rest
+ /// still index. Guards against an off-by-one in the per-item routing.
+ #[tokio::test]
+ async fn multiple_bad_surrogates_each_fail_individually() {
+ let name = "issue-1304-multi";
+ let (_dir, engine) = plain_engine(name);
+
+ const TOTAL: usize = 64;
+ let bad_positions = [7usize, 50];
+ let mut body = String::new();
+ for i in 0..TOTAL {
+ body.push_str(&format!("{{\"index\":{{\"_index\":\"{name}\"}}}}\n"));
+ if bad_positions.contains(&i) {
+ body.push_str("{\"body\":\"\\udc00 trailing\"}\n");
+ } else {
+ body.push_str(&format!("{{\"body\":\"doc {i}\"}}\n"));
+ }
+ }
+
+ let result = process_bulk(&engine, None, &body).await;
+ assert!(result.errors);
+ let failed: Vec<usize> = result
+ .items
+ .iter()
+ .enumerate()
+ .filter(|(_, item)| item.status != 201)
+ .map(|(i, _)| i)
+ .collect();
+ assert_eq!(failed, bad_positions.to_vec());
+
+ let index = engine.get_index(name).unwrap();
+ index.refresh().await.unwrap();
+ assert_eq!(index.live_doc_count(), (TOTAL - bad_positions.len()) as u64);
+ }
+}