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(brain): classify the zero-live verification instead of propagating it

xerj-org541d7233578f
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 421d0682d..e2a8e3c34 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -1183,6 +1183,43 @@ impl RefusalTargets {
}
}
+/// The #195 zero-live verification failure, as a type rather than a string.
+///
+/// The journal claims records were made visible; the destination answers with
+/// none. That is always a failure, but not always the *same* failure: for a
+/// composing caller like `xerj brain` a resume journal that outlived a wiped
+/// data directory has a specific, executable recovery (`--fresh` in place),
+/// while a write-blocked or unreachable server does not. Only a typed error
+/// lets the caller tell them apart — `anyhow::bail!` forces it to either
+/// string-match the prose or reprint it verbatim.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ZeroLiveVerificationError {
+ /// Records the resume journal says were published.
+ pub journal_records: u64,
+ /// Completed files those records came from.
+ pub files_done_journaled: usize,
+ /// Dataset indices that answered with zero live documents.
+ pub dataset_indices: usize,
+}
+
+impl std::fmt::Display for ZeroLiveVerificationError {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ formatter,
+ "autoindex verification failed: the resume journal records {} \
+ record(s) from {} 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",
+ self.journal_records, self.files_done_journaled, self.dataset_indices
+ )
+ }
+}
+
+impl std::error::Error for ZeroLiveVerificationError {}
+
#[derive(Debug)]
struct UnsupportedInventoryDeltaError {
delta: UnsupportedInventoryDelta,
@@ -2940,16 +2977,21 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
};
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()
- );
+ // Typed, not `bail!`: a caller that composes this pipeline can only
+ // tell "the journal outlived its destination" from "the server
+ // rejected our writes" if the condition carries a type. `xerj brain`
+ // downcasts it (brain.rs) to offer the in-place rebuild instead of
+ // printing this text raw. Peer precedent for classifying a
+ // recoverable condition rather than folding it into a generic error:
+ // redb's `Database::do_repair` returns `DatabaseError::RepairAborted`
+ // as its own variant (redb/src/db.rs:994, Apache-2.0/MIT) so the
+ // caller can distinguish it from ordinary corruption.
+ return Err(ZeroLiveVerificationError {
+ journal_records,
+ files_done_journaled,
+ dataset_indices: plan.datasets.len(),
+ }
+ .into());
}
// correlations
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 594870e32..6def96b9b 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -269,7 +269,29 @@ fn run(cfg: BrainCfg) -> Result<i32> {
// ── index: the autoindex pipeline, graph detection on ────────────────
let (code, run_doc) =
- xerj_autoindex::run_index_report(index_cfg(&cfg, &brain, api_key.clone()))?;
+ match xerj_autoindex::run_index_report(index_cfg(&cfg, &brain, api_key.clone())) {
+ Ok(report) => report,
+ // #195's zero-live verification fires INSIDE `run_index_report`,
+ // before the probe below ever runs. A resume journal that outlived
+ // a wiped data directory reaches it first — the run resumes, skips
+ // every already-done file, and finds nothing live — so propagating
+ // it unchanged hands the operator raw verification prose for
+ // exactly the case `journal_server_disagreement()` was written to
+ // explain, with no `xerj brain --fresh` recovery in it. Classify it
+ // here instead. Every other failure keeps its own message, and so
+ // does this one when the probe fails or contradicts it: a probe
+ // that cannot answer is not evidence of a wiped destination.
+ Err(error) => {
+ if error.is::<xerj_autoindex::ZeroLiveVerificationError>() {
+ if let Ok(live_nodes) = live_node_docs(&es, &brain) {
+ if zero_live_is_journal_server_disagreement(&error, live_nodes, cfg.fresh) {
+ bail!("{}", journal_server_disagreement(&cfg, &brain));
+ }
+ }
+ }
+ return Err(error);
+ }
+ };
let run_u64 = |doc: &Option<Value>, key: &str| {
doc.as_ref()
@@ -450,6 +472,24 @@ fn journal_server_disagrees(files_indexed: u64, live_nodes: Option<u64>, fresh:
files_indexed > 0 && matches!(live_nodes, None | Some(0)) && !fresh
}
+/// A failed indexing run is the wiped-destination case only when the failure
+/// is autoindex's own zero-live verification (#195) *and* the live-node probe
+/// agrees that nothing is there. The journal's completed-file count is the
+/// claim being contradicted, so it is what the disagreement test reads —
+/// the run summary that would normally carry `files_indexed` is never
+/// produced when the pipeline fails.
+fn zero_live_is_journal_server_disagreement(
+ error: &anyhow::Error,
+ live_nodes: Option<u64>,
+ fresh: bool,
+) -> bool {
+ error
+ .downcast_ref::<xerj_autoindex::ZeroLiveVerificationError>()
+ .is_some_and(|zero_live| {
+ journal_server_disagrees(zero_live.files_done_journaled as u64, live_nodes, fresh)
+ })
+}
+
fn needs_live_node_probe(records_total: u64) -> bool {
records_total == 0
}
@@ -745,6 +785,65 @@ mod tests {
assert!(!journal_server_disagrees(1, Some(0), true));
}
+ /// The wiped-data-dir case never reaches the probe above on its own: the
+ /// pipeline's own zero-live verification fails first. Unless that failure
+ /// is classified, the operator reads verification prose instead of the
+ /// recovery, which is what CI's use-case smoke phase 5 caught.
+ #[test]
+ fn a_zero_live_verification_failure_is_read_as_the_wiped_destination() {
+ let zero_live: anyhow::Error = xerj_autoindex::ZeroLiveVerificationError {
+ journal_records: 42,
+ files_done_journaled: 7,
+ dataset_indices: 2,
+ }
+ .into();
+ assert!(zero_live_is_journal_server_disagreement(
+ &zero_live, None, false
+ ));
+ assert!(zero_live_is_journal_server_disagreement(
+ &zero_live,
+ Some(0),
+ false
+ ));
+ // Server truth contradicts the verification: keep the original error.
+ assert!(!zero_live_is_journal_server_disagreement(
+ &zero_live,
+ Some(9),
+ false
+ ));
+ // `--fresh` republishes in place, so a zero-live failure under it is
+ // a real write problem, not a stale journal.
+ assert!(!zero_live_is_journal_server_disagreement(
+ &zero_live, None, true
+ ));
+ // Every other failure keeps its own message.
+ assert!(!zero_live_is_journal_server_disagreement(
+ &anyhow::anyhow!("server at http://localhost:9200 stopped answering"),
+ None,
+ false
+ ));
+ }
+
+ /// The classified message must still be the recovery text, not the
+ /// verification text — the two are distinguishable by their first clause.
+ #[test]
+ fn zero_live_verification_prose_is_not_the_recovery_prose() {
+ let verification = xerj_autoindex::ZeroLiveVerificationError {
+ journal_records: 3,
+ files_done_journaled: 1,
+ dataset_indices: 1,
+ }
+ .to_string();
+ assert!(
+ verification.contains("0 documents are live"),
+ "{verification}"
+ );
+ assert!(
+ !verification.contains("resume journal and server disagree"),
+ "{verification}"
+ );
+ }
+
#[test]
fn setup_link_is_scraped_from_bordered_and_bare_banner_lines() {
let dir = std::env::temp_dir().join(format!("xerj-brain-test-{}", std::process::id()));