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): honour --dry-run on a generation, stop junk being fatal
xerj-org9ed5587eeff1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 18ab0da54..971eee863 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -409,6 +409,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`--snapshot-max-gb` (default 64) caps the logical staged payload; it is apayload budget, not a disk-space or peak-memory guarantee.+- **Junk keeps the contract it always had on the generated path: recorded,+ never fatal.** A file that cannot be read or recognised (`plan.junk_files`)+ and a record that no dataset assignment accepts (`stats.junk`) both used to+ abort a `--no-graph` run outright — the first with+ `plan has no assignment for <file>`, the second with+ `durable preparation of <file> produced N junk records`. A single zero-byte+ file was enough to make a whole folder unindexable. Both are now counted+ instead: the sealed prepared artifact carries its junk-record count, the+ manifest group carries it into the generation, and the catalog's per-file+ `junk` and run-level `junk_records_total` report it instead of a hardcoded+ zero. Such a run exits **3** ("completed with junk"), the same signal the+ legacy path publishes — the generated path previously returned a flat `0`+ and lost it.++- **`--dry-run` is honoured on an already-generated state directory.** It was+ evaluated only after the pending-replay and reconcile branches had already+ published and committed, so on any state directory past generation 1 the flag+ was accepted, silently ignored, and the destination mutated. It is now decided+ before either branch: it prints the plan a real run would act on — the+ projected reconcile plan, or the sealed plan of a pending generation — and+ returns without opening the journal for write, without snapshot GC, and+ without a single bulk request.+### Changed — `autoindex --fresh` is refused on a durable generation- **`--fresh` no longer silently destroys a committed corpus generation.**diff --git a/engine/crates/xerj-autoindex/src/generation_catalog.rs b/engine/crates/xerj-autoindex/src/generation_catalog.rsindex c3c5b4e61..c7e77a48b 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog.rs@@ -111,7 +111,7 @@ pub fn project_generation("indexed",None,group.expected_records,- 0,+ group.expected_junk_records,group.content_size,&metadata.generation_id,);@@ -145,7 +145,16 @@ pub fn project_generation(}let mut total_records = 0u64;- let mut total_junk_records = 0u64;+ // The run total comes from the manifest, not from summing the per-dataset+ // statistics. A junk record belongs to no dataset — the dataset docs+ // attribute it to one of the group's slugs so a multi-dataset file is not+ // counted twice, and a group with no dataset slug at all would otherwise+ // drop out of the total entirely. Summing the sealed per-group counts is+ // the only arithmetic that is exact in both cases.+ let total_junk_records = desired.groups.iter().try_fold(0u64, |sum, group| {+ sum.checked_add(group.expected_junk_records)+ .context("catalog total junk-record count overflow")+ })?;for dataset in &desired.plan.datasets {let stats = dataset_stats.get(&dataset.slug).with_context(|| {format!(@@ -156,9 +165,6 @@ pub fn project_generation(total_records = total_records.checked_add(stats.record_count).context("catalog total record count overflow")?;- total_junk_records = total_junk_records- .checked_add(stats.junk_records)- .context("catalog total junk-record count overflow")?;let mut formats = stats.formats.clone();formats.sort();formats.dedup();@@ -361,6 +367,7 @@ mod tests {expected_records: 2,expected_passages: 0,expected_vectors: 0,+ expected_junk_records: 0,}}diff --git a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rsindex 6cf055237..166bb0f86 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs@@ -114,6 +114,7 @@ fn group(key: &str, path: &str, aliases: &[&str]) -> ManifestGroup {expected_records: 2,expected_passages: 0,expected_vectors: 0,+ expected_junk_records: 0,}}diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 501b804c3..0e4970e9c 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -1015,3 +1015,169 @@ fn upsert_clears_a_survivor_under_the_desired_content_identity() {assert_eq!(paths(&endpoint.data_docs()), ["a.csv"]);assert_eq!(journal_events(state_dir.path(), "sync_commit"), 3);}++/// `--dry-run` used to be consulted only *after* the generated branches had+/// already published and committed, so on any already-generated state+/// directory the flag was accepted, ignored, and the destination mutated.+#[test]+fn dry_run_on_a_generated_state_directory_publishes_nothing() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap();+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ let committed_docs = endpoint.data_docs();+ let bulks = endpoint.data_bulk_requests();+ let journal_before = fs::read(state_dir.path().join("journal.ndjson")).unwrap();++ // A real change, so the dry run has something it would publish.+ fs::write(+ corpus.path().join("a.csv"),+ "id,value\n1,CHANGED\n2,added\n",+ )+ .unwrap();+ let mut dry = config.clone();+ dry.dry_run = true;+ let (code, summary) = run_index_report(dry.clone()).unwrap();+ assert_eq!(code, 0);+ assert!(+ summary.is_none(),+ "--dry-run must not report a committed run summary"+ );+ assert_eq!(+ endpoint.data_bulk_requests(),+ bulks,+ "--dry-run issued a data bulk"+ );+ assert_eq!(+ endpoint.data_docs(),+ committed_docs,+ "--dry-run mutated the destination"+ );+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);+ assert_eq!(+ fs::read(state_dir.path().join("journal.ndjson")).unwrap(),+ journal_before,+ "--dry-run appended to the durable journal"+ );++ // An unchanged folder takes the no-op arm of the same branch: still inert.+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();+ assert_eq!(run_index(dry).unwrap(), 0);+ assert_eq!(endpoint.data_bulk_requests(), bulks);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);++ // And the real run that follows still converges on the change.+ fs::write(+ corpus.path().join("a.csv"),+ "id,value\n1,CHANGED\n2,added\n",+ )+ .unwrap();+ assert_eq!(run_index(config).unwrap(), 0);+ assert_eq!(endpoint.data_docs().len(), 2);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);+}++/// A junk/skipped file has no `plan.files` entry by construction, so demanding+/// a prepared artifact for every inventory entry failed the whole run on any+/// folder containing one unreadable, empty or unrecognised file.+#[test]+fn a_junk_file_is_recorded_and_never_fatal() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap();+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n2,beta\n").unwrap();+ fs::write(corpus.path().join("empty.csv"), "").unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);++ let (code, summary) = run_index_report(config.clone()).unwrap();+ let summary = summary.expect("a corpus with one junk file still commits a generation");+ assert_eq!(+ code, 3,+ "a completed run that skipped a file exits 3, not 0 (cli.rs EXIT CODES)"+ );+ assert_eq!(summary["generation"], 1);+ assert_eq!(summary["files_junk"], 1);+ assert_eq!(summary["records_total"], 2);+ assert_eq!(paths(&endpoint.data_docs()), ["a.csv"]);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);+ let junk_docs: Vec<Value> = endpoint+ .state+ .lock()+ .unwrap()+ .docs+ .iter()+ .filter(|((index, _), doc)| {+ index == catalog::CATALOG_INDEX+ && doc.get("doc_kind").and_then(Value::as_str) == Some("file")+ && doc.get("path").and_then(Value::as_str) == Some("empty.csv")+ })+ .map(|(_, doc)| doc.clone())+ .collect();+ assert_eq!(+ junk_docs.len(),+ 1,+ "the skipped file must still get exactly one catalog entry"+ );++ // The generation reconciles normally afterwards, junk file and all.+ fs::write(corpus.path().join("b.csv"), "id,value\n3,gamma\n").unwrap();+ assert_eq!(run_index(config).unwrap(), 3);+ assert_eq!(paths(&endpoint.data_docs()), ["a.csv", "b.csv"]);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);+}++/// Junk *records* were fatal on the generated path+/// (`durable preparation of X produced N junk records`) while the legacy path+/// merely accumulated them — directly contradicting the documented contract+/// "3 completed-with-junk (junk recorded, never fatal)".+#[test]+fn a_junk_record_is_counted_into_the_generation_and_never_fatal() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap();+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let mut log = String::from("!!! rotated by logrotate, not a log line\n");+ for n in 1..=40 {+ log.push_str(&format!(+ "10.0.0.{n} - - [09/Aug/2026:10:00:{n:02} +0000] \"GET /p/{n} HTTP/1.1\" 200 {n}\n"+ ));+ }+ fs::write(corpus.path().join("access.log"), log).unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);++ let (code, summary) = run_index_report(config).unwrap();+ let summary = summary.expect("a corpus with one junk record still commits a generation");+ assert_eq!(code, 3, "completed-with-junk exits 3");+ assert_eq!(summary["generation"], 1);+ assert_eq!(summary["files_junk"], 0);+ assert_eq!(+ summary["junk_records_total"], 1,+ "the unparseable line must be counted, not hardcoded to zero"+ );+ assert_eq!(summary["records_total"], 40);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);++ // The same count reaches the per-file catalog document.+ let file_doc = endpoint+ .state+ .lock()+ .unwrap()+ .docs+ .iter()+ .find(|((index, _), doc)| {+ index == catalog::CATALOG_INDEX+ && doc.get("doc_kind").and_then(Value::as_str) == Some("file")+ && doc.get("path").and_then(Value::as_str) == Some("access.log")+ })+ .map(|(_, doc)| doc.clone())+ .expect("the indexed file has a catalog document");+ assert_eq!(file_doc["junk"], 1);+ assert_eq!(file_doc["records"], 40);+}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 22b6eca0b..414d62e00 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -150,6 +150,78 @@ pub(crate) fn ensure_generation_mappings(es: &Es, plan: &Plan) -> Result<()> {.context("install generation catalog mapping")}+/// Project the current inventory onto a committed plan.+///+/// Pure by design and deliberately shared: `--dry-run` prints exactly the plan+/// the real reconcile would act on, because it is produced by this same call+/// rather than by a parallel implementation that could drift away from it.+///+/// The scan itself obeys the same two policies the legacy phase A does. It runs+/// inside the run's own pool, because `--workers` has to bound the CPU-bound+/// phase for the knob to mean anything (#240 §2), and it opens a per-file+/// progress guard, because a file this route touches must not drop out of the+/// progress denominator (#241). Run-local PDF artifact reuse is deliberately+/// disabled here: the generated route publishes from its own sealed snapshot+/// and never reaches the legacy phase B, so a retained artifact could never be+/// replayed (#248).+fn project_reconcile_plan(+ inventory: &content::Inventory,+ base_plan: &Plan,+ cfg: &IndexCfg,+ state_dir: &Path,+ pr: &Progress,+) -> Result<Plan> {+ let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);+ let ctx = PhaseAContext {+ state_dir,+ budget: &budget,+ capacity_warning: None,+ progress: pr,+ };+ pr.phase(+ "scan",+ inventory.files.len() as u64,+ inventory.files.iter().map(|file| file.size).sum(),+ );+ let scans: Vec<FileScan> = crate::pool::install(|| {+ use rayon::prelude::*;+ inventory+ .files+ .par_iter()+ .zip(inventory.digests.par_iter())+ .map(|(file, digest)| {+ let _in_flight = pr.file(&file.rel, file.size);+ scan_file(+ &file.path,+ file.size,+ digest,+ &ctx,+ cfg.sample,+ cfg.max_file_gb,+ )+ })+ .collect()+ });+ reconcile_plan::reconcile_plan(inventory, base_plan, scans, cfg.sample)+}++/// Exit code for a run that committed (or confirmed) a corpus generation.+///+/// `3` is "completed with junk — recorded, never fatal", the same contract the+/// legacy path publishes (`cli.rs` EXIT CODES, and CLAUDE.md's own indexing+/// workflow treats 3 as success). The generated path returned a flat `0`, which+/// silently downgraded that signal for `--no-graph`. Both inputs come from the+/// committed generation's own run document, so a no-op re-run over a corpus+/// that still contains junk reports 3 again instead of flapping to 0.+fn generated_exit_code(summary: &Value) -> i32 {+ let count = |field: &str| summary.get(field).and_then(Value::as_u64).unwrap_or(0);+ if count("junk_records_total") > 0 || count("files_junk") > 0 {+ 3+ } else {+ 0+ }+}+fn begin_non_graph_generation(es: &Es,journal: &mut state::Journal,@@ -273,6 +345,7 @@ fn begin_non_graph_generation(expected_records: 0,expected_passages: 0,expected_vectors: 0,+ expected_junk_records: 0,});}let mut groups = sync::reconcile_groups(&base.groups, candidates)?;@@ -1799,6 +1872,26 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}.into());}+ // `--dry-run` has to be decided *before* the generated branches, not after+ // them. Both of those branches publish and commit, and both return before+ // control ever reaches the legacy `cfg.dry_run` check further down — so on+ // any already-generated state directory the flag was accepted, ignored, and+ // the destination mutated anyway. A projection-only flag that writes is+ // worse than one that errors, so this branch is placed where nothing has+ // been opened for write yet: the journal is still only preflighted, and+ // `gc_snapshots` (which deletes unprotected snapshot directories) has not+ // run.+ if cfg.dry_run {+ if let Some(pending) = &preflight.pending_sync {+ println!("{}", serde_json::to_string_pretty(&pending.desired.plan)?);+ eprintln!(+ "(dry run — nothing indexed; corpus generation {} is already sealed and pending \+ replay from its own durable snapshot. Re-run without --dry-run to finish it.)",+ pending.desired.generation+ );+ return Ok((0, None));+ }+ }// A durable sync_begin owns the desired generation. Never rediscover and// replan from a mutable source tree while that transaction is pending.// Operation handlers are deliberately not enabled by this foundation@@ -1828,7 +1921,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// `--progress json` stays one parseable stream (#241).pr.note("autoindex: resumed and committed pending corpus generation from durable source");let summary = finish_generated_run(&es, &mut journal, &cfg)?;- return Ok((0, Some(summary)));+ return Ok((generated_exit_code(&summary), Some(summary)));}// Totals are unknown until the walk returns, so this phase honestly// reports `pct=unknown` and proves liveness with the clock alone.@@ -1858,6 +1951,39 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {pr.phase("hash", discovered_files.len() as u64, discovered_bytes);let mut inventory = content::resolve_reporting(discovered_files, &|bytes| pr.item_done(bytes))?;if cfg.no_graph && preflight.committed_manifest.is_some() && !genesis_recovery {+ if cfg.dry_run {+ let base = preflight+ .committed_manifest+ .as_ref()+ .context("branch guard proved a committed manifest")?;+ let plan = project_reconcile_plan(&inventory, &base.plan, &cfg, &state_dir, &pr)?;+ let unchanged = serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)?;+ println!("{}", serde_json::to_string_pretty(&plan)?);+ // stdout is the RESULT, stderr is PROGRESS: the projection above is+ // the result, this explanation is progress and goes out through the+ // surface that `--progress none` silences (#241).+ pr.note(&format!(+ "(dry run — nothing indexed; {})",+ if unchanged {+ format!(+ "committed generation {} already describes this folder",+ base.generation+ )+ } else {+ format!(+ "this is the plan a real run would commit as generation {}",+ base.generation + 1+ )+ }+ ));+ pr.finish(+ true,+ 0,+ "dry-run",+ &[("files", inventory.files.len() as u64)],+ );+ return Ok((0, None));+ }let mut journal = state::Journal::open_after_preflight(preflight,&root_str,@@ -1872,46 +1998,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.as_ref().context("generated journal lost its committed manifest")?.clone();-<<<<<<< HEAD- // Phase A's scan runs in the run's own pool and reports every file it- // touches, exactly as the legacy route does: `--workers` has to bound- // the CPU-bound phase for the knob to mean anything (#240 §2), and no- // file may drop out of the progress denominator (#241). Run-local PDF- // artifact reuse is disabled here on purpose — this route publishes- // from its own durable snapshot and never reaches the legacy phase B,- // so a retained artifact could never be replayed (#248).- let reconcile_budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);- let reconcile_ctx = PhaseAContext {- state_dir: &state_dir,- budget: &reconcile_budget,- capacity_warning: None,- progress: &pr,- };- pr.phase(- "scan",- inventory.files.len() as u64,- inventory.files.iter().map(|file| file.size).sum(),- );- let scans: Vec<FileScan> = crate::pool::install(|| {- use rayon::prelude::*;- inventory- .files- .par_iter()- .zip(inventory.digests.par_iter())- .map(|(file, digest)| {- let _in_flight = pr.file(&file.rel, file.size);- scan_file(- &file.path,- file.size,- digest,- &reconcile_ctx,- cfg.sample,- cfg.max_file_gb,- )- })- .collect()- });- let plan = reconcile_plan::reconcile_plan(&inventory, &base.plan, scans, cfg.sample)?;+ let plan = project_reconcile_plan(&inventory, &base.plan, &cfg, &state_dir, &pr)?;if serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)? {if let Some(expected) = &base.execution {let (schema_identity, index_identity) = generation_contract_identities(&plan)?;@@ -1949,7 +2036,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}}let summary = finish_generated_run(&es, &mut journal, &cfg)?;- return Ok((0, Some(summary)));+ return Ok((generated_exit_code(&summary), Some(summary)));}begin_non_graph_generation(&es,@@ -1963,7 +2050,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {let mut backend = sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20);sync_executor::replay_pending_operations(&state_dir, &mut journal, &mut backend)?;let summary = finish_generated_run(&es, &mut journal, &cfg)?;- return Ok((0, Some(summary)));+ return Ok((generated_exit_code(&summary), Some(summary)));}if cfg.no_graph && preflight.plan.is_some() && !genesis_recovery {let replacement_state = state_dir.with_extension("generation-v1");@@ -2304,7 +2391,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {let mut backend = sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20);sync_executor::replay_pending_operations(&state_dir, &mut journal, &mut backend)?;let summary = finish_generated_run(&es, &mut journal, &cfg)?;- return Ok((0, Some(summary)));+ return Ok((generated_exit_code(&summary), Some(summary)));}if plandiff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex 71e6ebe4e..a089c101c 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -1370,6 +1370,7 @@ mod sync_journal_tests {expected_records: 1,expected_passages: 1,expected_vectors: 1,+ expected_junk_records: 0,}],},)diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rsindex 6d32de31b..5be46c375 100644--- a/engine/crates/xerj-autoindex/src/sync.rs+++ b/engine/crates/xerj-autoindex/src/sync.rs@@ -47,6 +47,13 @@ pub struct ManifestGroup {pub expected_records: u64,pub expected_passages: u64,pub expected_vectors: u64,+ /// Records this content produced that no dataset could accept. They are+ /// *not* published, so no read-back count can recover them — the sealed+ /// preparation is the only place the number exists, and the generation has+ /// to carry it or the catalog's `junk_records_total` is a permanent zero.+ /// Junk is recorded, never fatal (`cli.rs` EXIT CODES).+ #[serde(default)]+ pub expected_junk_records: u64,}impl ManifestGroup {@@ -549,6 +556,7 @@ pub struct DesiredContentGroup {pub expected_records: u64,pub expected_passages: u64,pub expected_vectors: u64,+ pub expected_junk_records: u64,}/// Content identity is collision-safe and byte-verified by the inventory@@ -631,6 +639,7 @@ pub fn reconcile_groups(expected_records: candidate.expected_records,expected_passages: candidate.expected_passages,expected_vectors: candidate.expected_vectors,+ expected_junk_records: candidate.expected_junk_records,});}result.sort_by(|left, right| left.group_id.cmp(&right.group_id));@@ -1112,6 +1121,7 @@ mod tests {expected_records: 1,expected_passages: 1,expected_vectors: 1,+ expected_junk_records: 0,}}@@ -1125,6 +1135,7 @@ mod tests {expected_records: 1,expected_passages: 1,expected_vectors: 1,+ expected_junk_records: 0,}}diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex 465b18a07..2ee8f6543 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -52,6 +52,11 @@ pub struct PreparedArtifact {pub records: u64,pub passages: u64,pub vectors: u64,+ /// Records the extractor produced that no dataset assignment could accept.+ /// Sealed here because nothing downstream can recover the number: junk is+ /// never published, so no read-back count sees it.+ #[serde(default)]+ pub junk: u64,pub bytes: u64,pub digest: String,}@@ -424,6 +429,20 @@ impl<'a> EsSyncBackend<'a> {sum.checked_add(group.content_size).context("dataset source byte count overflow")})?;+ // Junk is a property of the *file*, not of a dataset: a record that+ // no assignment accepted belongs to no dataset by definition. A+ // group that feeds several datasets therefore charges its junk to+ // exactly one of them — the first of its sorted slugs — so the+ // run-level `junk_records_total` (a sum over datasets) stays exact+ // instead of multiplying by fan-out. The legacy path attributes it+ // the same way, to `fa.assignments.first()` (lib.rs).+ let junk_records = groups+ .iter()+ .filter(|group| group.dataset_slugs.first() == Some(&dataset.slug))+ .try_fold(0u64, |sum, group| {+ sum.checked_add(group.expected_junk_records)+ .context("dataset junk-record count overflow")+ })?;let time = |name: &str| {response.pointer(&format!("/aggregations/{name}/value_as_string"))@@ -434,7 +453,7 @@ impl<'a> EsSyncBackend<'a> {dataset.slug.clone(),crate::generation_catalog::DatasetCatalogStats {record_count,- junk_records: 0,+ junk_records,bytes,formats,time_min: time("time_min"),@@ -1062,6 +1081,7 @@ pub fn groups_from_inventory(expected_records: prior.map_or(0, |group| group.expected_records),expected_passages: prior.map_or(0, |group| group.expected_passages),expected_vectors: prior.map_or(0, |group| group.expected_vectors),+ expected_junk_records: prior.map_or(0, |group| group.expected_junk_records),})}).collect::<Result<Vec<_>>>()?;@@ -1098,6 +1118,7 @@ pub fn bind_prepared_counts(group.expected_records = prepared.records;group.expected_passages = prepared.passages;group.expected_vectors = prepared.vectors;+ group.expected_junk_records = prepared.junk;}Ok(())}@@ -1235,20 +1256,26 @@ fn create_snapshot_inner(crate::content::verify(&destination, source.size, content_digest)?;#[cfg(test)]apply_post_seal_source_replacement(&source.path)?;- let prepared = plan- .map(|plan| {- prepare_artifact(- &staging,- ordinal,- tx_id,- source,- content_id,- &destination,- plan,- &mut budget,- )- })- .transpose()?;+ // A junk/skipped file has no `plan.files` entry *by construction* — it+ // lives in `plan.junk_files` and is never indexed — so demanding one+ // here made `--no-graph` fail outright on any folder holding a single+ // unreadable, empty or unrecognised file. Its bytes still belong in the+ // sealed snapshot (a resume replays from the snapshot, not from the+ // mutable tree, and the inventory it is verified against lists the+ // file), but there is nothing to prepare for it: `prepared: None`.+ let prepared = match plan {+ Some(plan) if plan.files.contains_key(content_id.as_str()) => Some(prepare_artifact(+ &staging,+ ordinal,+ tx_id,+ source,+ content_id,+ &destination,+ plan,+ &mut budget,+ )?),+ _ => None,+ };files.push(SnapshotFile {content_id: content_id.clone(),content_digest: content_digest.clone(),@@ -1493,14 +1520,14 @@ fn prepare_artifact(}true};+ // Junk records are recorded, never fatal — that is the documented contract+ // (`cli.rs` EXIT CODES: "3 completed-with-junk (junk recorded, never+ // fatal)") and what the legacy path has always done. Aborting the whole+ // generation because one line of one log file did not parse would make a+ // realistic corpus unindexable. The count is sealed into the artifact so+ // the generation, and then the catalog, can report it.let stats = crate::extract::extract(snapshot_blob, &sniffed, None, &mut sink).with_context(|| format!("extract {} into durable preparation", source.rel))?;- anyhow::ensure!(- stats.junk == 0,- "durable preparation of {} produced {} junk records",- source.rel,- stats.junk- );if let Some(error) = sink_error {return Err(error);}@@ -1513,6 +1540,7 @@ fn prepare_artifact(records,passages,vectors,+ junk: stats.junk,bytes,digest: stream_digest(&path, "axp1")?,})