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(autoindex): measure the mapping refusal, and stop conflating two junk counters
xerj-org96db1d26b701
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8765fc7ce..c9a942b68 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -221,9 +221,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0rather than an invocation-local counter that read `0` after a no-op resume.Existing catalogs whose historical `started` field was dynamically mappedas text remain usable: the additive mapping upgrade no longer attempts an- incompatible text-to-date type change.+ incompatible text-to-date type change. Concretely, this is catalogs written+ by **v1.0.0-rc.4** — the one release that had `autoindex` but not yet+ dynamic ISO-date inference (added in rc.5). Measured against a live engine,+ adding `started` as `date` to such a catalog is refused 400+ `mapper_parsing_exception` (*"field [started] already exists as [text],+ cannot add [date]"*), which aborts the invocation before any document work.+ Catalogs written by rc.5 or later already inferred `started` as `date` and+ were never affected.- Two consequences worth knowing before you upgrade:+ Three consequences worth knowing before you upgrade:- **`bytes` is redefined.** It used to be the bytes the latest invocationprocessed, credited to the first dataset a file was assigned to. It is now@@ -241,6 +248,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0resume after upgrading, and only regains it once one of its files isreprocessed. Re-run with `--fresh` if the note matters more than therescan.+ - **`junk_records_total` is narrower than the number it replaces**, and one+ class of failure has left it. It used to be an invocation counter that+ also folded in records the *backend* refused per bulk item; it is now+ parser junk only, so `xerj autoindex map`'s header counts exactly what the+ per-dataset `junk_records` values count. No signal is lost in practice: a+ single per-item rejection already aborts the run with+ `autoindex stopped with bulk/backend failures`, before any run document or+ map is written, so the folded-in number was never observable in a map.+ That abort message now also states how many records were refused, which+ the first-five error sample could not convey.- **The installer is now fail-closed on checksum *verification*, not just onchecksum *download*.** `landing/get` printeddiff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex 9c5ac3e88..2b4653130 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -11,23 +11,42 @@ pub const CATALOG_INDEX: &str = "autoindex-catalog";/// Explicit mapping for a **freshly created** catalog index.////// Tripwire — `started` is bimodal across installs, on purpose. This function-/// declares it `date`, but the additive upgrade in `run_index_report`-/// deliberately omits it: catalogs created before this mapping existed have a-/// dynamically inferred `text` `started`, and asking the engine to change an-/// existing `text` field to `date` is refused with a 400-/// `illegal_argument_exception` (`xerj-api/src/es_compat.rs:1792`) and aborts-/// the whole invocation. So a catalog created from here sorts `started`-/// server-side, and an upgraded legacy catalog does not.+/// declares it `date`; the additive upgrade in `run_index_report` deliberately+/// omits it. No release before this one declared `started` at all, so every+/// existing catalog got it from dynamic inference, and which type that produced+/// depends on which release wrote the catalog:///-/// Nothing may rely on `started` being a `date`: `run_map` sorts runs-/// client-side, which is what keeps the split benign. Any future server-side-/// range query, `sort`, or date aggregation on `started` must first migrate-/// legacy catalogs by reindexing them — not by adding `started` to the-/// additive upgrade, which is exactly the abort described above.+/// - **v1.0.0-rc.4** — the only release with `autoindex` (0f3ef60d, 2026-07-09)+/// but without dynamic ISO-date inference (a0f872ac, 2026-07-25, first in+/// rc.5). Its catalogs inferred `started` as **`text`**. Adding `started` as+/// `date` to those is refused **400 `mapper_parsing_exception`** — *"field+/// [started] already exists as [text], cannot add [date]"* — from the+/// `idx.schema()` guard in `xerj-api/src/es_compat.rs` (the+/// `XerjError::invalid_mapping` arm; `InvalidMapping` maps to+/// `mapper_parsing_exception` in `xerj-api/src/error.rs`). `es.update_mapping`+/// surfaces that as an `Err`, which aborts the invocation before any document+/// work.+/// - **v1.0.0-rc.5 and later** — inference already produced `date`, so the same+/// upgrade would simply be acknowledged 200.+///+/// It is specifically NOT the `illegal_argument_exception` *"mapper [started]+/// cannot be changed from type [text] to [date]"* guard earlier in the same+/// handler. That one reads `state.engine.index_mappings`, which holds only+/// *declared* mappings, and `started` was never declared — so for a legacy+/// catalog it cannot fire. (Measured against a live engine, v1.0.0-rc.13: text+/// inferred → `mapper_parsing_exception`; text declared →+/// `illegal_argument_exception`; date inferred → 200 acknowledged.)+///+/// So a catalog created from here sorts `started` server-side, an rc.4 catalog+/// does not, and nothing may rely on `started` being a `date`: `run_map` sorts+/// runs client-side, which is what keeps the split benign. Any future+/// server-side range query, `sort`, or date aggregation on `started` must first+/// migrate legacy catalogs by reindexing them — not by adding `started` to the+/// additive upgrade, which is exactly the abort above.pub fn catalog_mapping() -> Value {- // The three run-metadata fields are inserted after the literal rather than- // written inside it: `serde_json::json!` recurses once per key, and at 40- // properties the macro exceeds the default `recursion_limit = 128` and+ // The trailing run-metadata fields are inserted after the literal rather+ // than written inside it: `serde_json::json!` recurses once per key, and at+ // 40 properties the macro exceeds the default `recursion_limit = 128` and// fails to compile. Adding another field here must use this same tail, not// the literal.let mut mapping = json!({@@ -88,6 +107,7 @@ pub fn catalog_mapping() -> Value {"invocation_telemetry_scope".into(),json!({"type": "keyword"}),);+ properties.insert("junk_records_this_run".into(), json!({"type": "long"}));mapping}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex f252ed189..919cd7c25 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -31,6 +31,12 @@ struct MockState {catalog_preexists: bool,catalog_mapping_upgraded: bool,catalog_bulk_before_upgrade: bool,+ /// Set if the additive mapping upgrade ever asks for `started`. This is+ /// the executable half of `catalog::catalog_mapping`'s tripwire: against a+ /// legacy (v1.0.0-rc.4) catalog that request is refused 400 and aborts the+ /// run, so the product must never send it. Asserted false rather than left+ /// to the 400 branch below, which a correct product never reaches.+ started_mapping_requested: bool,/// Catalog bulk actions the fixture does not model. Recorded rather than/// panicked on: this runs inside the server thread while the state guard/// is held, so a panic here would poison the `Mutex` and turn@@ -46,6 +52,12 @@ struct MockState {/// Accept every data bulk (`errors: false`) but persist nothing — the/// shape of any rejection path the client-side classifier misses.swallow_data_bulks: bool,+ /// Refuse the FIRST document of every data bulk with a per-item 400 and+ /// apply the rest. This is the one bulk shape that produces an+ /// `item_error` without a `server_error`: status is neither 429 nor 5xx+ /// and the type is not a block, so the run continues and must still+ /// report the rejection.+ reject_first_data_item: bool,}struct MockEndpoint {@@ -170,18 +182,31 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {.is_some()});let mut locked = state.lock().unwrap();+ locked.started_mapping_requested |= started_requested;if locked.catalog_preexists && started_requested {- // The literal shape `PUT /_mapping` returns for an incompatible- // type change (`xerj-api/src/es_compat.rs`): 400- // `illegal_argument_exception`, not `mapper_parsing_exception`,- // which is reserved for a malformed mapping body.- let reason = "mapper [started] cannot be changed from type [text] to [date]";+ // The shape a real engine returns when the additive upgrade asks+ // for `started` on a legacy (v1.0.0-rc.4) catalog, where `started`+ // was dynamically inferred as `text`. Measured against a live+ // v1.0.0-rc.13 engine, not read off the handler: the request falls+ // past the `illegal_argument_exception` guard — that one only sees+ // *declared* mappings, and `started` was never declared — and is+ // refused by the `idx.schema()` guard, which returns+ // `XerjError::invalid_mapping` and therefore a 400+ // `mapper_parsing_exception`.+ //+ // A correct product never reaches this branch (see+ // `started_mapping_requested`, asserted false in+ // `existing_catalog_is_upgraded_before_new_run_metadata_is_written`).+ // It is kept, and kept accurate, so that adding `started` to the+ // additive upgrade fails here with the message the operator would+ // really see rather than passing silently.+ let reason = "field [started] already exists as [text], cannot add [date]";(400,json!({"error": {- "root_cause": [{"type": "illegal_argument_exception", "reason": reason}],- "type": "illegal_argument_exception",+ "root_cause": [{"type": "mapper_parsing_exception", "reason": reason}],+ "type": "mapper_parsing_exception","reason": reason,},"status": 400,@@ -310,6 +335,27 @@ fn bulk_response(body: &[u8], state: &Arc<Mutex<MockState>>) -> Value {if locked.swallow_data_bulks {return json!({"errors": false, "items": []});}+ if locked.reject_first_data_item {+ let mut items = Vec::new();+ for (nth, pair) in lines.chunks_exact(2).enumerate() {+ if nth == 0 {+ items.push(json!({"index": {+ "status": 400,+ "error": {+ "type": "document_parsing_exception",+ "reason": "refused: value could not be parsed"+ }+ }}));+ continue;+ }+ let action: Value = serde_json::from_slice(pair[0]).unwrap();+ let doc: Value = serde_json::from_slice(pair[1]).unwrap();+ let id = action.pointer("/index/_id").unwrap().as_str().unwrap();+ locked.docs.insert(id.to_owned(), doc);+ items.push(json!({"index": {"status": 201}}));+ }+ return json!({"errors": true, "items": 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() };@@ -683,6 +729,13 @@ fn existing_catalog_is_upgraded_before_new_run_metadata_is_written() {);let state = endpoint.state.lock().unwrap();assert!(state.catalog_mapping_upgraded);+ assert!(+ !state.started_mapping_requested,+ "the additive upgrade asked a legacy catalog for `started`; a real v1.0.0-rc.4 catalog \+ answers that with 400 mapper_parsing_exception (\"field [started] already exists as \+ [text], cannot add [date]\") and the run aborts before any document work — see the \+ tripwire on catalog::catalog_mapping"+ );assert!(!state.catalog_bulk_before_upgrade,"new run metadata must not reach a legacy catalog before its additive mapping upgrade"@@ -1445,6 +1498,66 @@ fn write_block_rejections_are_backend_fatal_and_the_file_stays_pending() {assert_eq!(endpoint.state.lock().unwrap().docs.len(), 2);}+/// Pins WHY the run document carries no backend-rejection count, so nobody+/// "restores" one that could only ever read 0.+///+/// Making `junk_records_total` durable narrowed it: it no longer folds in the+/// per-item rejections that `record_bulk_outcome` counts. That looks like a+/// lost signal, and it would be one — except that a single per-item rejection+/// also lands in `bulk_errors`, which aborts the run before the run document,+/// the map, the summary line and the exit code exist at all. So the narrowed+/// number was unreachable in any published map either way.+///+/// The rejection count is therefore reported in the one place a rejected run+/// ever reaches: the abort message, where it supplies the scale that+/// `bulk_errors`' first-five sample cannot.+#[test]+fn backend_rejected_records_abort_the_run_before_any_map_is_written() {+ 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,kept\n1,kept\n2,kept\n",+ )+ .unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ endpoint.state.lock().unwrap().reject_first_data_item = true;+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);++ // A per-item 400 is NOT a server error (not 429, not 5xx, not a block), so+ // it is the weakest rejection the classifier recognises — and even it is+ // fatal.+ let error = format!("{:#}", run_index_report(config).unwrap_err());+ assert!(+ error.contains("document_parsing_exception"),+ "the refusal itself must be quoted: {error}"+ );+ assert!(+ error.contains("The backend refused 1 record(s)."),+ "the abort must state how many records were refused, not just sample the errors: {error}"+ );++ // Measured, and deliberately pinned even though it is NOT what the abort+ // message implies: `record_bulk_outcome` treats a per-item rejection as+ // non-fatal to the worker (only `server_errors` set `send_err`), so the+ // file is journaled COMPLETE and the run aborts only at the end. A rerun+ // therefore resumes past this file and never retries the refused record,+ // while the message says failed sources "were not journaled complete".+ //+ // That divergence predates this branch — it is `main`'s behaviour for the+ // item-error class — and fixing it means changing when a worker treats a+ // rejection as fatal, which is a resume-semantics change with nothing to+ // do with map metadata. Recorded here so the next reader finds the fact+ // rather than the assumption; tracked in the PR body as a known gap.+ assert_eq!(+ file_done_count(state_dir.path()),+ 1,+ "pre-existing: a per-item rejection still journals the source complete"+ );+}+/// #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 recordsdiff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 1f782cbdf..700221e01 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -93,10 +93,23 @@ fn replacement_failpoint(_boundary: u8) -> Result<()> {Ok(())}+/// Send one bulk body and fold its per-item rejections into+/// `rejected_records`.+///+/// This counter is deliberately NOT the parser-junk counter. A record the+/// *backend* refused and a record the *parser* could not read are different+/// failures with different lifetimes: parser junk is durable (journaled per+/// file and replayed on every resume), a backend rejection is not (no+/// `FileDone` records a document that was never accepted). Adding both to one+/// number is what let `junk_records_total` mean two things at once.+///+/// Note where this number can and cannot surface. Any non-zero value here also+/// puts an entry in `bulk_errors`, which aborts the run before the run+/// document exists — so it is reported in the abort message and nowhere else.fn record_bulk_outcome(es: &Es,body: Vec<u8>,- junk_records: &AtomicU64,+ rejected_records: &AtomicU64,bulk_errors: &Mutex<Vec<String>>,send_err: &mut Option<String>,) -> bool {@@ -115,7 +128,7 @@ fn record_bulk_outcome(return true;}if outcome.item_errors > 0 {- junk_records.fetch_add(outcome.item_errors, Ordering::Relaxed);+ rejected_records.fetch_add(outcome.item_errors, Ordering::Relaxed);if let Some(error) = outcome.first_error {let mut errors = bulk_errors.lock().unwrap();if errors.len() < 5 {@@ -1346,14 +1359,19 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {catalog::CATALOG_INDEX,&json!({"properties": {"duplicate_of": {"type": "keyword"},- // `started` intentionally stays out of this additive upgrade.- // Older catalogs dynamically mapped it as text, and asking the- // engine to change that existing field to date aborts every run.- // `catalog::catalog_mapping` declares it `date` for a fresh- // catalog, so the field is permanently bimodal across installs;- // its doc comment carries the full tripwire.+ // `started` intentionally stays out of this additive upgrade. A+ // catalog written by v1.0.0-rc.4 has a dynamically inferred TEXT+ // `started`, and asking the engine to add it as `date` is refused+ // 400 — which `es.update_mapping` turns into an `Err`, aborting+ // the run before any document work. `catalog::catalog_mapping`+ // declares it `date` for a fresh catalog, so the field is+ // permanently bimodal across installs; its doc comment carries the+ // full tripwire and the measured refusal."summary_generated_at": {"type": "date", "format": "strict_date_optional_time||epoch_millis"},- "invocation_telemetry_scope": {"type": "keyword"}+ "invocation_telemetry_scope": {"type": "keyword"},+ // Safe to add here, unlike `started`: no release ever wrote this+ // field, so no existing catalog has a conflicting inferred type.+ "junk_records_this_run": {"type": "long"}}}),).context("upgrade autoindex catalog mapping")?;@@ -1479,7 +1497,12 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// replacement invalidation can only ever see prior-generation edges —// running it later would invalidate this run's own fresh edges.let bulk_cut = cfg.bulk_mb << 20;+ // Parser junk this invocation read out of source files (durable: it is+ // journaled per file and replayed on resume).let junk_records = AtomicU64::new(0);+ // Records the backend refused in a bulk response (invocation-local: no+ // journal record exists for a document that was never accepted).+ let rejected_records = AtomicU64::new(0);let bulk_errors = Mutex::new(Vec::<String>::new());let graph: Option<GraphRt> = if cfg.no_graph {None@@ -1582,7 +1605,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&& record_bulk_outcome(&es,std::mem::take(&mut buf),- &junk_records,+ &rejected_records,&bulk_errors,&mut send_err,)@@ -1591,7 +1614,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}}if send_err.is_none() && !buf.is_empty() {- record_bulk_outcome(&es, buf, &junk_records, &bulk_errors, &mut send_err);+ record_bulk_outcome(&es, buf, &rejected_records, &bulk_errors, &mut send_err);}if let Some(e) = send_err {anyhow::bail!("write structural graph edges to {edges_index}: {e}");@@ -1985,7 +2008,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&& record_bulk_outcome(&es,std::mem::take(&mut buf),- &junk_records,+ &rejected_records,&bulk_errors,&mut send_err,)@@ -2001,7 +2024,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {record_bulk_outcome(&es,buf,- &junk_records,+ &rejected_records,&bulk_errors,&mut send_err,);@@ -2026,7 +2049,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&& record_bulk_outcome(&es,std::mem::take(&mut ebuf),- &junk_records,+ &rejected_records,&bulk_errors,&mut send_err,)@@ -2038,7 +2061,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {record_bulk_outcome(&es,ebuf,- &junk_records,+ &rejected_records,&bulk_errors,&mut send_err,);@@ -2133,7 +2156,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&& record_bulk_outcome(&es,std::mem::take(&mut buf),- &junk_records,+ &rejected_records,&bulk_errors,&mut send_err,)@@ -2142,7 +2165,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}}if send_err.is_none() && !buf.is_empty() {- record_bulk_outcome(&es, buf, &junk_records, &bulk_errors, &mut send_err);+ record_bulk_outcome(&es, buf, &rejected_records, &bulk_errors, &mut send_err);}match send_err {Some(e) => bulk_errors@@ -2162,11 +2185,24 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {let bulk_errs = bulk_errors.into_inner().unwrap();if !bulk_errs.is_empty() {+ // `bulk_errors` keeps only the first five distinct errors, so without+ // the counter the operator cannot tell one refused document from ten+ // thousand. That is the whole reason backend rejections are counted+ // apart from parser junk: this is the only place the number is ever+ // reported, because a run that gets here writes no run document and+ // no map.+ let rejected = rejected_records.load(Ordering::Relaxed);+ let scale = if rejected > 0 {+ format!(" The backend refused {rejected} record(s).")+ } else {+ String::new()+ };anyhow::bail!(- "autoindex stopped with bulk/backend failures: {}. Failed source files were not \+ "autoindex stopped with bulk/backend failures: {}.{} Failed source files were not \journaled complete; fix the reported server or embedding configuration and rerun \the same command to resume safely",- bulk_errs.join(" | ")+ bulk_errs.join(" | "),+ scale);}@@ -2571,9 +2607,26 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {"duplicate_files": plan.duplicate_files.len(),"files_junk": junk_file_count,"records_total": total_records,- // Durable corpus descriptor, same definition as every dataset doc's- // `junk_records`; `junk_records_this_run` below is the invocation- // counter, which also includes records the backend itself rejected.+ // Two numbers, one definition each, neither of them overlapping.+ //+ // `junk_records_total` is the durable corpus descriptor: the same+ // definition as every dataset doc's `junk_records`, summed over every+ // `FileDone` in the journal. It survives a no-op resume.+ //+ // `junk_records_this_run` is the same *kind* of failure narrowed to+ // the files this invocation actually parsed. It is the NARROWER of the+ // two, not the wider: every file counted here also committed a+ // `FileDone` that the total sums. On an unchanged resume it reads 0+ // while the total stays non-zero — which is the whole defect this+ // change exists to fix, seen from the other side.+ //+ // Backend rejections are deliberately absent. They are a different+ // failure, and they can never be reported here anyway: a per-item+ // rejection populates `bulk_errors`, which aborts the run above,+ // before this document exists. Publishing a+ // `records_rejected_by_backend` field would ship a number that is+ // provably always 0 — see `record_bulk_outcome` and+ // `backend_rejected_records_abort_the_run_before_any_map_is_written`."junk_records_total": durable_junk_records,"junk_records_this_run": junk_records_by_run,// This-run submission accounting (#195): what THIS invocation sent@@ -2704,6 +2757,11 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {cfg.url, cfg.prefix);}+ // Exit 3 means "completed, some input was unusable". Backend rejections+ // are not consulted and must not be: a rejected item aborts the run with+ // an error long before this line, so `rejected_records` is provably 0+ // here. Splitting them out of `junk_total_records` therefore changes no+ // exit code.let code = if junk_total_records > 0 || junk_file_count > 0 {3} else {