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): classify write-block bulk rejections by type; verify live docs vs journal (#195)

xerj-orge67c3182aad3
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index 43ad3daa9..99445abb9 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -18,13 +18,51 @@ pub struct Es {
pub struct BulkOutcome {
pub item_errors: u64,
- /// Per-item 5xx/429 failures are backend/admission failures, not bad source
- /// records. Callers must not journal the source file complete.
+ /// Per-item backend/admission failures — 5xx/429 statuses plus
+ /// cluster/index write blocks recognised by TYPE (see
+ /// [`is_index_block_error`]). These are not bad source records: the same
+ /// record indexes fine once the server-side condition clears. Callers
+ /// must not journal the source file complete.
pub server_errors: u64,
pub first_error: Option<String>,
pub first_server_error: Option<String>,
}
+/// Whether a per-item bulk `error` object reports a cluster/index write
+/// block (e.g. `read_only_allow_delete` at the disk flood-stage watermark,
+/// or an explicit `index.blocks.write`).
+///
+/// Blocks must be recognised by error TYPE and wording, never by HTTP
+/// status: Elasticsearch maps explicit/API blocks to 403 FORBIDDEN and only
+/// the flood-stage block to 429 (IndexMetadata block constants), and XERJ
+/// mirrors that split, so a status-only classifier files a 403 block under
+/// "bad source record". That is issue #195: every rejected document was
+/// counted as junk, the source file was journaled complete, and the
+/// instructed rerun then resumed past the journal and reported success over
+/// an empty index. ES itself carries retryability on the block, not the
+/// status (ClusterBlockException::retryable) — the type is the contract.
+///
+/// Matches (verified against live responses):
+/// - XERJ: `{"type":"engine_exception","reason":"index [x] is blocked
+/// for write operations","status":403}`
+/// - ES: `{"type":"cluster_block_exception","reason":"index [x]
+/// blocked by: [FORBIDDEN/8/index write (api)];"}`
+///
+/// A reason merely *containing* "blocked" could in principle be a
+/// field-value echo in a mapping error; misclassifying that direction is
+/// the safe one — the file is retried instead of silently dropped.
+fn is_index_block_error(error: &Value) -> bool {
+ let type_is_block = error
+ .get("type")
+ .and_then(Value::as_str)
+ .is_some_and(|t| t.contains("cluster_block") || t.contains("index_block"));
+ let reason_is_block = error
+ .get("reason")
+ .and_then(Value::as_str)
+ .is_some_and(|reason| reason.contains("blocked"));
+ type_is_block || reason_is_block
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmbeddingExecutionIdentity {
pub version: u32,
@@ -275,7 +313,10 @@ impl Es {
item_errors += 1;
let item_status =
op.get("status").and_then(Value::as_u64).unwrap_or(500);
- if item_status == 429 || item_status >= 500 {
+ if item_status == 429
+ || item_status >= 500
+ || is_index_block_error(&op["error"])
+ {
server_errors += 1;
if first_server_error.is_none() {
first_server_error = Some(
@@ -616,6 +657,58 @@ mod tests {
}
}
+ /// #195: cluster/index write blocks arrive with status 403 (only the
+ /// flood-stage block is 429), so they must be classified as backend
+ /// failures by error TYPE/wording — never counted as junk source
+ /// records. A genuine per-item 400 stays junk.
+ #[test]
+ fn per_item_write_block_errors_are_backend_failures_not_junk() {
+ for (body, expect_server_errors) in [
+ // XERJ shape: explicit write block via the semantic bulk path.
+ (
+ br#"{"errors":true,"items":[{"index":{"_index":"i","_id":"a","status":403,"error":{"type":"engine_exception","reason":"index [i] is blocked for write operations","status":403}}}]}"#.to_vec(),
+ 1u64,
+ ),
+ // ES shape: cluster_block_exception recognised by TYPE alone
+ // (reason deliberately free of the word "blocked").
+ (
+ br#"{"errors":true,"items":[{"index":{"_index":"i","_id":"a","status":403,"error":{"type":"cluster_block_exception","reason":"FORBIDDEN/8/index write (api)"}}}]}"#.to_vec(),
+ 1u64,
+ ),
+ // A real bad-record 400 must stay in the junk bucket.
+ (
+ br#"{"errors":true,"items":[{"index":{"_index":"i","_id":"a","status":400,"error":{"type":"document_parsing_exception","reason":"failed to parse field [ts] of type [date]"}}}]}"#.to_vec(),
+ 0u64,
+ ),
+ ] {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ let _ = read_request(&mut stream);
+ respond_json(&mut stream, &body);
+ });
+ let es = Es::new(&format!("http://{address}"), None).unwrap();
+ let outcome = es.bulk(b"{\"index\":{}}\n{}\n".to_vec()).unwrap();
+ assert_eq!(outcome.item_errors, 1);
+ assert_eq!(
+ outcome.server_errors, expect_server_errors,
+ "{:?}",
+ outcome.first_error
+ );
+ if expect_server_errors > 0 {
+ let reason = outcome.first_server_error.expect("server error recorded");
+ assert!(
+ reason.contains("block") || reason.contains("FORBIDDEN"),
+ "{reason}"
+ );
+ } else {
+ assert!(outcome.first_server_error.is_none());
+ }
+ server.join().unwrap();
+ }
+ }
+
#[test]
fn retry_path_recovers_after_one_bulk_timeout() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index c7d18289f..a4f8618ce 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -25,6 +25,13 @@ struct MockState {
delete_calls: usize,
stop: bool,
embedding_identity_sha256: String,
+ /// Reject every data-bulk item with a 403 explicit write-block error
+ /// (the status ES gives `index.blocks.write` / `read_only`; only the
+ /// flood-stage block is 429) without applying anything — the #195 shape.
+ block_writes: bool,
+ /// Accept every data bulk (`errors: false`) but persist nothing — the
+ /// shape of any rejection path the client-side classifier misses.
+ swallow_data_bulks: bool,
}
struct MockEndpoint {
@@ -130,7 +137,11 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {
} else if method == "GET" && path.ends_with("/_count") {
json!({"count": state.lock().unwrap().docs.len()})
} else if method == "POST" && path.ends_with("/_search") {
- json!({"hits":{"total":{"value":0},"hits":[]},"aggregations":{}})
+ // Report the REAL number of stored docs: `run_index` now verifies
+ // live counts against the journal (#195), so a mock that always
+ // answered 0 hits would (rightly) fail every successful run.
+ let total = state.lock().unwrap().docs.len();
+ json!({"hits":{"total":{"value":total},"hits":[]},"aggregations":{}})
} else {
// ping, index creation/mapping, refresh, and catalog operations
json!({"acknowledged": true})
@@ -162,6 +173,26 @@ fn bulk_response(body: &[u8], state: &Arc<Mutex<MockState>>) -> Value {
let mut locked = state.lock().unwrap();
locked.data_bulk_number += 1;
+ if locked.block_writes {
+ // Explicit write block: per-item 403 (never 429/5xx), nothing applied.
+ let items: Vec<Value> = lines
+ .chunks_exact(2)
+ .map(|_| {
+ json!({"index": {
+ "status": 403,
+ "error": {
+ "type": "cluster_block_exception",
+ "reason": "index [failure-test-csv] is blocked for write operations",
+ "status": 403
+ }
+ }})
+ })
+ .collect();
+ return json!({"errors": true, "items": items});
+ }
+ if locked.swallow_data_bulks {
+ return json!({"errors": false, "items": []});
+ }
let fail = !locked.failed_once && locked.data_bulk_number == locked.fail_data_bulk;
let pairs = lines.chunks_exact(2);
let visible = if fail { pairs.len() / 2 } else { pairs.len() };
@@ -878,3 +909,67 @@ fn partial_file_done_is_rolled_back_before_another_worker_commits() {
.is_some_and(|value| value.ends_with("-new"))
}));
}
+
+/// #195: an index write block rejects every bulk item with status 403 (the
+/// status ES assigns explicit/API blocks — only the flood-stage
+/// `read_only_allow_delete` block is 429). A status-based classifier filed
+/// those items under "junk source records", journaled the file COMPLETE, and
+/// the instructed rerun then resumed past the journal and reported success
+/// over an empty index. Blocks must be classified by error type: fatal,
+/// file left pending, and the rerun after the block lifts must really index.
+#[test]
+fn write_block_rejections_are_backend_fatal_and_the_file_stays_pending() {
+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ fs::write(
+ corpus.path().join("records.csv"),
+ "id,value\n0,blocked\n1,blocked\n",
+ )
+ .unwrap();
+ let endpoint = MockEndpoint::start(usize::MAX);
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
+
+ endpoint.state.lock().unwrap().block_writes = true;
+ let error = format!("{:#}", run_index(config.clone()).unwrap_err());
+ assert!(error.contains("blocked"), "{error}");
+ assert_eq!(
+ file_done_count(state_dir.path()),
+ 0,
+ "a write-blocked source file must stay pending in the journal"
+ );
+ assert!(endpoint.state.lock().unwrap().docs.is_empty());
+
+ // Block lifted: the SAME command must resume and actually index.
+ endpoint.state.lock().unwrap().block_writes = false;
+ assert_eq!(run_index(config).unwrap(), 0);
+ assert_eq!(file_done_count(state_dir.path()), 1);
+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), 2);
+}
+
+/// #195 last-resort gate: a backend that ACCEPTS every bulk but persists
+/// nothing (the shape of any rejection path the per-item classifier does
+/// not recognise) must not yield a success exit. The journal says records
+/// landed; the live count says zero; the run must fail and say how to
+/// recover.
+#[test]
+fn zero_live_documents_after_journaled_records_fails_the_run() {
+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ fs::write(
+ corpus.path().join("records.csv"),
+ "id,value\n0,ghost\n1,ghost\n",
+ )
+ .unwrap();
+ let endpoint = MockEndpoint::start(usize::MAX);
+ endpoint.state.lock().unwrap().swallow_data_bulks = true;
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
+
+ let error = format!("{:#}", run_index(config).unwrap_err());
+ assert!(error.contains("verification failed"), "{error}");
+ assert!(error.contains("0 documents are live"), "{error}");
+ assert!(error.contains("--fresh"), "{error}");
+}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index da8614e6f..d5ee54104 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -1748,6 +1748,37 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
}
}
+ // ── zero-live verification gate (#195) ───────────────────────────────
+ //
+ // The journal's completed files claim records were made visible; the
+ // live counts above are what the server actually answers with. When the
+ // journal says records landed but ZERO documents are live across every
+ // dataset index, the run must not report success: the user (or agent)
+ // would be left with green, mapped, empty indices and no way to tell
+ // "the corpus has no match" from "nothing was ever written". This is
+ // the last-resort catch for any rejection path the per-bulk
+ // classification does not recognise.
+ let (files_done_journaled, journal_records) = {
+ let journal = journal_mx.lock().unwrap();
+ (
+ journal.done.len(),
+ journal.done.values().map(|fd| fd.records).sum::<u64>(),
+ )
+ };
+ let live_records: u64 = ds_counts.values().sum();
+ if journal_records > 0 && live_records == 0 {
+ anyhow::bail!(
+ "autoindex verification failed: the resume journal records {journal_records} \
+ record(s) from {files_done_journaled} completed file(s), but 0 documents are \
+ live across the {} dataset index(es). The indices exist and look healthy but \
+ hold nothing — a server-side write rejection (e.g. a disk flood-stage or \
+ index write block), deleted indices, or an unreadable server can all cause \
+ this. Fix the server-side condition, then rerun with --fresh to re-index \
+ from scratch",
+ plan.datasets.len()
+ );
+ }
+
// correlations
let mut key_corrs: Vec<correlate::KeyCorr> = Vec::new();
if let Some(clusters) = &clusters_rt {
@@ -2010,6 +2041,12 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
"files_junk": all_junk.len(),
"records_total": total_records,
"junk_records_total": junk_records_by_run,
+ // This-run submission accounting (#195): what THIS invocation sent
+ // and had accepted, vs `records_total` above which is the live
+ // server-side count. A healthy run keeps these consistent; a
+ // mismatch is visible without reading a server log.
+ "files_submitted_this_run": files_done.load(Ordering::Relaxed),
+ "records_submitted_this_run": records_total.load(Ordering::Relaxed),
"wall_seconds": (wall * 10.0).round() / 10.0,
"workers": cfg.workers,
"semantic": !cfg.no_semantic,
@@ -2020,7 +2057,21 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
push_doc(&format!("run:{run_id}"), &run_doc, &mut cat_buf);
if !cat_buf.is_empty() {
- es.bulk(cat_buf).context("write catalog")?;
+ let outcome = es.bulk(cat_buf).context("write catalog")?;
+ // The catalog is the data map every later `map`/`status`/agent query
+ // reads; a rejected catalog bulk (e.g. a write block that engaged
+ // mid-run) must not be swallowed into a "success" exit (#195).
+ if outcome.server_errors > 0 {
+ anyhow::bail!(
+ "write catalog: bulk backend failed for {} item(s): {}. Fix the reported \
+ server condition and rerun the same command",
+ outcome.server_errors,
+ outcome
+ .first_server_error
+ .as_deref()
+ .unwrap_or("unknown server error")
+ );
+ }
}
es.refresh(catalog::CATALOG_INDEX).ok();
journal_mx.lock().unwrap().finish(&run_doc)?;
@@ -2032,6 +2083,18 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
} else if !cfg.quiet {
println!("\ndone in {wall:.1}s — {} datasets, {} records live, {} duplicate aliases, {} junk records, {} junk/skipped files",
plan.datasets.len(), total_records, plan.duplicate_files.len(), junk_total_records, all_junk.len());
+ // Indexed-vs-submitted honesty line (#195): the live count against
+ // what this run actually submitted, so a silent-rejection mismatch
+ // is visible in the client output alone. Units differ on purpose: a
+ // source record (e.g. one prose file) can expand to several section
+ // documents, but submitted records with ZERO live documents is
+ // always a defect (and fails above, before this line prints).
+ println!(
+ "indexed: {} documents live; this run submitted {} source records from {} files",
+ total_records,
+ records_total.load(Ordering::Relaxed),
+ files_done.load(Ordering::Relaxed),
+ );
let mut rows: Vec<(&String, u64)> = plan
.datasets
.iter()