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): scope the --fresh refusal, version the legacy migration, keep no-graph crash coverage
xerj-org21fad7eb0436
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 98cb1e89f..18ab0da54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -386,19 +386,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0prints the funnel on demand, including which repo-level numbers arecontaminated and why.-### Changed — fail-closed autoindex restart semantics--- **`autoindex --fresh` no longer discards a durable resume plan.** A durable- plan contains the alias, path, graph, and stale-record knowledge needed for- safe reconciliation. `--fresh` is accepted only when the selected state- directory has no durable plan and never cleans the destination. An- independent rebuild must use a new state directory, new prefix, and new brain- namespace when graph detection is enabled (or disable graph writes), be- validated, and only then replace the old reader target. The shared catalog- and old target require explicit, validated cleanup. Generated journals with- `--no-graph` reconcile additions, changes, deletions, renames, and no-op- reruns. Legacy journals and graph-enabled generations refuse membership- changes before remote mutation.+### Added — incremental `--no-graph` corpus reconciliation++- **`xerj autoindex --no-graph` now reconciles a changed folder instead of+ re-deriving it.** A `--no-graph` run commits a durable *corpus generation*: a+ manifest of content groups (stable group identity, content digest and byte+ length, canonical path plus aliases, dataset assignment, validated output+ counts) plus a sealed source snapshot of the prepared records. A later run+ projects the current inventory onto the committed manifest and publishes only+ the difference — additions, content changes, deletions, renames, junk+ transitions and duplicate-alias moves all converge, and a no-op re-run issues+ no data bulk and appends no new generation. A run interrupted mid-generation+ replays from its own sealed snapshot, so the result never depends on whether+ the source tree changed after the crash. Dataset and mapping identity is+ frozen at generation 1: a file that would need a *new* dataset or a mapping+ change is refused before any remote mutation rather than silently widening+ the schema.++ Scope, plainly: only `--no-graph`. Graph-enabled runs are unchanged, and each+ changed generation still copies and prepares the full corpus (O(N) staging) —+ the win is in what gets published and verified, not yet in what gets read.+ `--snapshot-max-gb` (default 64) caps the logical staged payload; it is a+ payload budget, not a disk-space or peak-memory guarantee.++### Changed — `autoindex --fresh` is refused on a durable generation++- **`--fresh` no longer silently destroys a committed corpus generation.**+ `--fresh` deletes the resume journal, and the snapshot GC that follows every+ journal open then sees an empty protected set and removes every sealed+ snapshot — so on a generated state directory `--fresh` would discard the+ committed manifest, the pending replay evidence, and the alias/path/+ stale-record knowledge, while cleaning nothing at the destination. It is now+ refused up front, naming the generation that blocks it, and pointing at the+ plain re-run (which reconciles the change) or at an isolated rebuild with a+ new `--state-dir` and `--prefix`.++ **Unchanged for everyone else.** On a legacy (non-generated) journal —+ including every graph-enabled corpus and anything `xerj brain` writes —+ `--fresh` behaves exactly as before: it ignores the journal and restarts,+ which is what `xerj brain`'s documented self-heal for a wiped data directory+ depends on.++### Migration — pre-generation `--no-graph` state directories must be rebuilt++- **A `--no-graph` state directory written before this release cannot be+ adopted as generation zero, and the first `--no-graph` run against it will+ refuse with a followable rebuild command.** This is a deliberate, versioned+ format boundary (`sync::GENERATION_FORMAT_VERSION = 1`), not a validation+ failure: a pre-generation resume plan records no stable group identity, no+ content byte length and no validated per-group output counts, so no amount of+ evidence in it could reconstruct a manifest group. The refusal prints the+ exact `xerj autoindex` argv for an isolated rebuild into a new `--state-dir`+ and `--prefix`; the old target and the shared `autoindex-catalog` are left+ alone and require explicit, validated cleanup once the new target is+ verified. Nothing is migrated in place and no destination data is touched by+ the refusal. Graph-enabled state directories are not affected.## [1.0.0-rc.13] - 2026-08-08diff --git a/demo/usecases/autoindex/RECIPE_DRAFT.md b/demo/usecases/autoindex/RECIPE_DRAFT.mdindex e24b4819b..a035aa865 100644--- a/demo/usecases/autoindex/RECIPE_DRAFT.md+++ b/demo/usecases/autoindex/RECIPE_DRAFT.md@@ -203,15 +203,16 @@ done in 0.1s — 3 datasets, 5801 records live, 0 junk records, 1 junk/skipped fjust polite re-runs: in the robustness evaluation, a `kill -9` at 18 s into a200 MB file followed by a re-run converged to **byte-identical counts acrossall 9 datasets** — no duplicates. `xerj autoindex status` shows the journal-and live index counts. `--fresh` starts without resume state only when the-selected state directory has no durable plan; it never removes stale-destination records. For an independent rebuild, use a new `--state-dir`, new-`--prefix`, and new `--brain` when graph detection is enabled (or add-`--no-graph`). Validate before switching readers. The shared-`autoindex-catalog` and old target require explicit, validated cleanup.-Generated journals with `--no-graph` reconcile additions, changes, deletions,-renames, and no-op reruns. Legacy journals and graph-enabled generations refuse-membership changes before remote mutation.+and live index counts. `--fresh` ignores the resume journal and restarts (ids stay idempotent). It+never removes stale records from the destination, and it is refused once the+state directory holds a durable corpus generation — re-run without it and the+generated `--no-graph` path reconciles additions, changes, deletions, renames+and no-op reruns incrementally. For an independent rebuild, use a new+`--state-dir` and a new `--prefix`, plus a new `--brain` when graph detection+is enabled (or add `--no-graph`). Validate before switching readers; the shared+`autoindex-catalog` and old target require explicit, validated cleanup. A+`--no-graph` state directory written before the generation format cannot be+adopted in place and must be rebuilt the same way.## Reproduce it yourselfdiff --git a/docs/recipes/zero-config-indexing.md b/docs/recipes/zero-config-indexing.mdindex 88b27917f..2a584d9d4 100644--- a/docs/recipes/zero-config-indexing.md+++ b/docs/recipes/zero-config-indexing.md@@ -228,14 +228,16 @@ live indices at http://localhost:9280:autoindex-catalog 9 docs```-`--fresh` starts without resume state only when the selected state directory-has no durable plan; it never removes stale destination records. For an-independent rebuild, use a new `--state-dir`, new `--prefix`, and new-`--brain` when graph detection is enabled (or add `--no-graph`). Validate-before switching readers. The shared `autoindex-catalog` and old target require-explicit, validated cleanup. Generated journals with `--no-graph` reconcile-additions, changes, deletions, renames, and no-op reruns. Legacy journals and-graph-enabled generations refuse membership changes before remote mutation.+`--fresh` ignores the resume journal and restarts (ids stay idempotent). It+never removes stale records from the destination, and it is refused once the+state directory holds a durable corpus generation — re-run without it and the+generated `--no-graph` path reconciles additions, changes, deletions, renames+and no-op reruns incrementally. For an independent rebuild, use a new+`--state-dir` and a new `--prefix`, plus a new `--brain` when graph detection+is enabled (or add `--no-graph`). Validate before switching readers; the shared+`autoindex-catalog` and old target require explicit, validated cleanup. A+`--no-graph` state directory written before the generation format cannot be+adopted in place and must be rebuilt the same way.## Reproduce it yourselfdiff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 6499a7f80..e662e2f01 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -74,11 +74,12 @@ pub enum Cmd {}const FRESH_HELP: &str =- "start without resume state only when the selected state directory has no \-durable plan; an existing plan is refused and destination records are never reset";+ "ignore an existing resume journal and restart (ids stay idempotent); refused when the \+state directory holds a durable corpus generation, and it never resets destination records";const RESUME_POLICY_HELP: &str ="generated --no-graph journals reconcile add, change, delete, rename, and no-op runs; \-legacy journals and graph-enabled generations refuse membership changes before remote mutation";+a --no-graph state directory written before the generation format must be rebuilt into a new \+--state-dir and --prefix; graph-enabled journals keep the existing crash-resume behaviour";pub fn print_help() {println!(@@ -185,14 +186,16 @@ pub fn print_help() {\n\RESUME POLICY:\n\{resume_policy_help}.\n\- If a legacy or graph-enabled journal refuses a change, do not use --fresh as\n\- cleanup. Restore its original destination, or rebuild with a new --state-dir and\n\- new --prefix plus a new --brain when graph is enabled (or use --no-graph).\n\+ --fresh is not cleanup and is not destination reconciliation: it never removes\n\+ stale records from the destination, and it is refused outright once a durable\n\+ corpus generation exists (re-run without it — the generated path reconciles the\n\+ change incrementally). For an independent rebuild use a new --state-dir and a\n\+ new --prefix, plus a new --brain when graph is enabled (or --no-graph).\n\Validate before switching readers; explicitly clean the shared\n\autoindex-catalog and old target only after validation.\n\\n\EXIT CODES: 0 complete; 3 completed-with-junk (junk recorded, never fatal);\n\- 2 usage; 1 endpoint/journal failure or unsupported corpus delta\n",+ 2 usage; 1 endpoint/journal failure or a refused unsafe state transition\n",fresh_help = FRESH_HELP,resume_policy_help = RESUME_POLICY_HELP);@@ -522,21 +525,21 @@ mod tests {}#[test]- fn fresh_help_warns_that_it_is_not_destination_reconciliation() {- assert!(super::FRESH_HELP.contains("no durable plan"));- assert!(super::FRESH_HELP.contains("existing plan is refused"));- assert!(super::FRESH_HELP.contains("destination records are never reset"));+ fn fresh_help_scopes_the_refusal_and_denies_being_cleanup() {+ let help = super::FRESH_HELP;+ assert!(help.contains("ignore an existing resume journal and restart"));+ assert!(help.contains("durable corpus generation"));+ assert!(help.contains("never resets destination records"));}#[test]- fn resume_policy_help_distinguishes_supported_and_refused_state() {+ fn resume_policy_help_distinguishes_generated_legacy_and_graph_state() {let help = super::RESUME_POLICY_HELP;for claim in ["generated --no-graph journals","add, change, delete, rename, and no-op",- "legacy journals",- "graph-enabled generations",- "before remote mutation",+ "written before the generation format must be rebuilt",+ "graph-enabled journals keep the existing crash-resume behaviour",] {assert!(help.contains(claim), "missing resume-policy claim: {claim}");}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex fb2b1285a..d67c161b5 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -519,6 +519,17 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {}}+/// Row documents only — the file-level graph node document this module's+/// graph-enabled config also publishes (`ax_locator: "file"`) is not part of+/// any replacement transaction's subject.+fn data_rows(state: &MockState) -> Vec<&Value> {+ state+ .docs+ .values()+ .filter(|doc| doc["ax_locator"].as_str() != Some("file"))+ .collect()+}+fn file_done_count(state_dir: &Path) -> usize {let journal = fs::read_to_string(state_dir.join("journal.ndjson")).unwrap();journal@@ -562,170 +573,6 @@ fn dataset_catalog_docs(endpoint: &MockEndpoint) -> Vec<Value> {docs}-fn assert_unsupported_delta_without_remote_mutation(- endpoint: &MockEndpoint,- config: IndexCfg,- expected_added: &[&str],- expected_vanished: &[&str],-) {- let request_start = endpoint.state.lock().unwrap().requests.len();- let journal_path = config.state_dir.as_ref().unwrap().join("journal.ndjson");- let journal_before = fs::read(&journal_path).unwrap();- let error = run_index(config).unwrap_err();- let attempted_requests = endpoint.state.lock().unwrap().requests[request_start..].to_vec();- assert_eq!(- attempted_requests,- [("GET".to_owned(), "/".to_owned())],- "a refused attempt may perform only the endpoint-readiness GET"- );- assert_eq!(- fs::read(journal_path).unwrap(),- journal_before,- "preflight refusal must not append a resume event or rewrite the journal"- );- let message = format!("{error:#}");- assert!(message.contains("made no remote mutations"), "{message}");- assert!(- message.contains("existing destination may already be partial or stale"),- "{message}"- );- assert!(- message.contains("`--fresh` is not recovery or destination reconciliation"),- "{message}"- );- assert!(- message.contains("new --state-dir, a new --prefix"),- "{message}"- );- assert!(message.contains("new --brain"), "{message}");- for path in expected_added {- assert!(- message.contains(path),- "missing added path {path}: {message}"- );- }- for path in expected_vanished {- assert!(- message.contains(path),- "missing vanished path {path}: {message}"- );- }-}--#[test]-fn completed_plan_rejects_added_content_group_before_remote_mutation() {- 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("first.csv"), "id,value\n1,first\n").unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 0);-- fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["second.csv"], &[]);-}--#[test]-fn completed_plan_rejects_vanished_content_group_before_remote_mutation() {- 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("first.csv"), "id,value\n1,first\n").unwrap();- fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 0);-- fs::remove_file(corpus.path().join("second.csv")).unwrap();- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["second.csv"]);-}--#[test]-fn completed_plan_rejects_mixed_membership_delta_in_stable_order() {- 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("b-old.csv"), "id,value\n1,b\n").unwrap();- fs::write(corpus.path().join("a-old.csv"), "id,value\n2,a\n").unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 0);-- fs::remove_file(corpus.path().join("b-old.csv")).unwrap();- fs::remove_file(corpus.path().join("a-old.csv")).unwrap();- fs::write(corpus.path().join("z-new.csv"), "id,value\n3,z\n").unwrap();- fs::write(corpus.path().join("m-new.csv"), "id,value\n4,m\n").unwrap();- config.json = true;- let request_start = endpoint.state.lock().unwrap().requests.len();- let error = run_index(config).unwrap_err();- assert_eq!(- endpoint.state.lock().unwrap().requests[request_start..],- [("GET".to_owned(), "/".to_owned())]- );-- let typed = error- .downcast_ref::<UnsupportedInventoryDeltaError>()- .unwrap();- let value = typed.to_json();- assert_eq!(value["schema"], "xerj.autoindex.unsupported_sync_delta.v1");- assert_eq!(value["status"], "error");- let added: Vec<&str> = value["added_content_groups"]- .as_array()- .unwrap()- .iter()- .map(|entry| entry["path"].as_str().unwrap())- .collect();- let vanished: Vec<&str> = value["vanished_content_groups"]- .as_array()- .unwrap()- .iter()- .map(|entry| entry["path"].as_str().unwrap())- .collect();- assert_eq!(added, ["m-new.csv", "z-new.csv"]);- assert_eq!(vanished, ["a-old.csv", "b-old.csv"]);-}--#[test]-fn nonempty_fresh_cannot_erase_plan_and_bypass_membership_gate() {- 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("old.csv"), "id,value\n1,old\n").unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 0);-- fs::remove_file(corpus.path().join("old.csv")).unwrap();- fs::write(corpus.path().join("new.csv"), "id,value\n2,new\n").unwrap();- config.fresh = true;- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["new.csv"], &["old.csv"]);-}--#[test]-fn fresh_rejects_same_content_canonical_promotion_even_when_group_key_matches() {- 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();- let bytes = "id,value\n1,same\n";- fs::write(corpus.path().join("a.csv"), bytes).unwrap();- fs::write(corpus.path().join("b.csv"), bytes).unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 0);-- // b.csv becomes canonical with the same content key. A key-only delta is- // empty, but fresh would discard the alias/path cleanup knowledge.- fs::remove_file(corpus.path().join("a.csv")).unwrap();- config.fresh = true;- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &[]);-}-#[test]fn unchanged_planned_junk_is_not_reported_as_added_content() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();@@ -748,44 +595,6 @@ fn unchanged_planned_junk_is_not_reported_as_added_content() {);}-#[test]-fn deleted_planned_junk_fails_closed_before_catalog_can_stay_stale() {- 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("rows.csv"), "id,value\n1,kept\n").unwrap();- fs::write(- corpus.path().join("opaque.bin"),- [0_u8, 159, 146, 150, 0, 255],- )- .unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 3);-- fs::remove_file(corpus.path().join("opaque.bin")).unwrap();- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["opaque.bin"]);-}--#[test]-fn completed_plan_rejects_empty_current_folder_before_remote_mutation() {- 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("only.csv"), "id,value\n1,only\n").unwrap();- let endpoint = MockEndpoint::start(usize::MAX);- let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);- assert_eq!(run_index(config.clone()).unwrap(), 0);-- fs::remove_file(corpus.path().join("only.csv")).unwrap();- // Even `--fresh` must not erase the only durable inventory evidence and- // then report success while the destination still contains the document.- config.fresh = true;- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["only.csv"]);-}-#[test]fn semantic_resume_rejects_embedding_identity_drift_before_another_bulk() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();@@ -815,6 +624,47 @@ fn semantic_resume_rejects_embedding_identity_drift_before_another_bulk() {);}+/// `--fresh` must keep working on a graph-enabled (legacy) journal.+///+/// `xerj brain` documents `--fresh` as "ignore the resume journal, re-walk+/// everything" (brain.rs), and its self-heal path depends on it: when the+/// resume journal says a folder is indexed but the server has none of it (a+/// wiped data dir), `brain` sets `fresh = true` and re-runs `run_index_report`+/// to converge. The durable-generation refusal added alongside incremental+/// `--no-graph` reconciliation is deliberately scoped so it cannot reach this+/// path — `brain` always runs graph-enabled, which never commits a generation.+#[test]+fn fresh_restarts_a_completed_graph_enabled_journal_the_way_brain_self_heal_needs() {+ 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,indexed\n1,indexed\n",+ )+ .unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ let plans_before = event_count(state_dir.path(), "plan");++ // The server lost everything; brain's recovery is exactly this.+ endpoint.state.lock().unwrap().docs.clear();+ config.fresh = true;+ assert_eq!(+ run_index(config).unwrap(),+ 0,+ "--fresh must not be refused on a legacy graph-enabled journal"+ );+ assert_eq!(+ event_count(state_dir.path(), "plan"),+ plans_before,+ "--fresh restarts from a discarded journal, so it writes exactly one fresh plan"+ );+ assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 2);+}+#[test]fn fresh_publication_skips_delete_and_noop_resume_does_not_append_plan() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();@@ -1628,16 +1478,21 @@ fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {).unwrap();fs::write(corpus.path().join("b.csv"), original).unwrap();- assert_unsupported_delta_without_remote_mutation(&endpoint, config.clone(), &["b.csv"], &[]);+ assert_eq!(run_index(config.clone()).unwrap(), 3);{let locked = endpoint.state.lock().unwrap();- assert_eq!(locked.docs.len(), 3);- assert!(locked.docs.values().all(|doc| {- doc["ax_path"].as_str() == Some("a.csv")- && doc- .get("value")- .is_none_or(|value| value.as_str() == Some("original"))+ // Graph detection is enabled in this module, so a.csv also carries a+ // file-level node document (`ax_locator: "file"`, no row fields). The+ // replacement transaction's subject is the row documents.+ let rows: Vec<&Value> = data_rows(&locked);+ assert_eq!(rows.len(), 2);+ assert!(rows.iter().all(|doc| {+ doc["ax_path"].as_str() == Some("a.csv") && doc["value"].as_str() == Some("rewritten")}));+ assert!(locked+ .docs+ .values()+ .all(|doc| doc["ax_path"].as_str() == Some("a.csv")));}let replay = state::Journal::open(state_dir.path(),@@ -1651,19 +1506,24 @@ fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {assert!(replay.pending_replacements.is_empty());assert_eq!(replay.done.len(), 1);let plan = replay.plan.clone().unwrap();- assert!(plan.junk_files.is_empty());+ assert_eq!(plan.junk_files.len(), 1);+ assert_eq!(plan.junk_files[0].rel, "b.csv");+ assert!(plan.junk_files[0]+ .reason+ .contains("key ownership exclusive"));drop(replay);- // The refusal is deterministic: an identical rerun keeps the old owner,- // appends no new plan, and changes no documents.+ // The divergence is durable and deterministic: an identical rerun keeps+ // the same owner, appends no new plan, and changes no documents.let plans_before = event_count(state_dir.path(), "plan");- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["b.csv"], &[]);+ assert_eq!(run_index(config).unwrap(), 3);assert_eq!(event_count(state_dir.path(), "plan"), plans_before);let locked = endpoint.state.lock().unwrap();- assert_eq!(locked.docs.len(), 3);- assert!(locked.docs.values().all(|doc| doc- .get("value")- .is_none_or(|value| value.as_str() == Some("original"))));+ let rows = data_rows(&locked);+ assert_eq!(rows.len(), 2);+ assert!(rows+ .iter()+ .all(|doc| doc["value"].as_str() == Some("rewritten")));}/// #238: a file added after the plan was frozen is skipped and reported in the@@ -1672,6 +1532,7 @@ fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {/// ever been written and no run could remove it. The catalog is the data map/// every `map`/`status`/agent query reads; it must not keep advertising a file/// that is gone.+#[test]fn an_added_then_deleted_file_leaves_no_immortal_catalog_entry() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();@@ -1784,12 +1645,7 @@ fn deleting_an_entire_duplicate_group_strands_no_pending_replacement() {fs::remove_file(corpus.path().join("dup-a.csv")).unwrap();fs::remove_file(corpus.path().join("dup-b.csv")).unwrap();for _ in 0..2 {- assert_unsupported_delta_without_remote_mutation(- &endpoint,- config.clone(),- &[],- &["dup-a.csv"],- );+ assert_eq!(run_index(config.clone()).unwrap(), 0);assert_eq!(event_count(state_dir.path(), "file_replace_start"),starts,@@ -1899,7 +1755,7 @@ fn write_block_rejections_are_backend_fatal_and_the_file_stays_pending() {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);+ assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 2);}/// Pins WHY the run document carries no backend-rejection count, so nobodydiff --git a/engine/crates/xerj-autoindex/src/generation_catalog.rs b/engine/crates/xerj-autoindex/src/generation_catalog.rsindex c78df338c..c3c5b4e61 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog.rs@@ -341,6 +341,7 @@ mod tests {gzip: false,content_digest: Some("digest".into()),assignments: vec![(None, "reports".into())],+ as_document: false,}}@@ -373,7 +374,7 @@ mod tests {chunker_identity: "prepared-records-v1".into(),embedding_identity_sha256: "a".repeat(64),embedding_backend: "lexical".into(),- embedding_dimension: 384,+ embedding_dimension: Some(384),embedding_semantic_contract: "semantic_text-derived-vector.v1".into(),embedding_resumable: true,graph_enabled: false,diff --git a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rsindex 82ae54453..6cf055237 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs@@ -87,6 +87,7 @@ fn assignment(path: &str) -> FileAssignment {gzip: false,content_digest: Some(format!("digest-{path}")),assignments: vec![(None, "reports".into())],+ as_document: false,}}@@ -137,7 +138,7 @@ fn execution(generation_id: &str) -> ExecutionIdentity {chunker_identity: "prepared-records-v1".into(),embedding_identity_sha256: "a".repeat(64),embedding_backend: "lexical".into(),- embedding_dimension: 384,+ embedding_dimension: Some(384),embedding_semantic_contract: "semantic_text-derived-vector.v1".into(),embedding_resumable: true,graph_enabled: false,diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex b8444ab5b..501b804c3 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -21,6 +21,12 @@ struct HttpState {requests: Vec<(String, String)>,data_bulk_requests: usize,fail_next_data_bulk: bool,+ /// Apply the first half of the next data bulk's items and *then* report+ /// `errors: true`. This is the dangerous backend shape the legacy+ /// replacement transaction was hardened against (visibility changed, but+ /// the durable record must not be): `no_graph` corpora take the generated+ /// executor now, so the shape has to be proven here too.+ partially_apply_next_data_bulk: bool,fail_embedding_identity: bool,stop: bool,embedding_identity_sha256: String,@@ -236,8 +242,17 @@ fn bulk_http(body: &[u8], state: &Arc<Mutex<HttpState>>) -> (u16, Value) {);}}+ // Half-applied bulk: apply the leading actions, then report failure.+ let applied_limit = if is_data && std::mem::take(&mut locked.partially_apply_next_data_bulk) {+ Some(lines.len() / 2)+ } else {+ None+ };let mut cursor = 0;while cursor < lines.len() {+ if applied_limit.is_some_and(|limit| cursor >= limit) {+ break;+ }let action: Value = serde_json::from_slice(lines[cursor]).unwrap();cursor += 1;if let Some(meta) = action.get("delete") {@@ -261,6 +276,21 @@ fn bulk_http(body: &[u8], state: &Arc<Mutex<HttpState>>) -> (u16, Value) {target.extend(patch.clone());}}+ if applied_limit.is_some() {+ return (+ 200,+ json!({+ "errors": true,+ "items": [{"index": {+ "status": 500,+ "error": {+ "type": "injected_failure",+ "reason": "partial bulk applied before failing"+ }+ }}]+ }),+ );+ }(200, json!({"errors": false, "items": []}))}@@ -584,6 +614,72 @@ fn pending_generation_replays_sealed_source_after_live_source_mutates() {assert!(!rendered.contains("mutated-after-sync-begin"), "{rendered}");}+/// Crash/resume with a *partially applied* data bulk, on `--no-graph`.+///+/// `failure_resume_http_tests` used to run its whole injected-failure matrix+/// with `no_graph: true`; since `--no-graph` now takes the generated executor,+/// that module keeps the legacy graph-enabled transaction and this test carries+/// the no-graph half of the coverage. The endpoint applies half of a bulk and+/// *then* reports failure — visibility has changed, so the generation must stay+/// uncommitted, and the retry must converge on exactly the new content with no+/// duplicate or stale document surviving the half-applied attempt.+#[test]+fn partially_applied_data_bulk_leaves_the_generation_pending_and_the_retry_converges() {+ 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 source = corpus.path().join("rows.csv");+ fs::write(&source, "id,value\n1,first\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);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);++ fs::write(+ &source,+ "id,value\n1,replaced\n2,second\n3,third\n4,fourth\n",+ )+ .unwrap();+ endpoint+ .state+ .lock()+ .unwrap()+ .partially_apply_next_data_bulk = true;+ assert!(+ run_index(config.clone()).is_err(),+ "a partially applied bulk must fail the run, not be absorbed"+ );+ assert_eq!(+ journal_events(state_dir.path(), "sync_begin"),+ 2,+ "the generation was begun"+ );+ assert_eq!(+ journal_events(state_dir.path(), "sync_commit"),+ 1,+ "a partially applied bulk must never commit the generation"+ );++ // Retry: the sealed source replays, and the destination converges exactly.+ assert_eq!(run_index(config).unwrap(), 0);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);+ let docs = endpoint.data_docs();+ assert_eq!(paths(&docs), ["rows.csv"]);+ assert_eq!(+ docs.len(),+ 4,+ "exactly the four new records survive — no half-applied duplicate, no stale first record"+ );+ let rendered = serde_json::to_string(&docs).unwrap();+ assert!(rendered.contains("replaced"), "{rendered}");+ assert!(rendered.contains("fourth"), "{rendered}");+ assert!(+ !rendered.contains("\"value\":\"first\""),+ "the replaced record must not survive: {rendered}"+ );+}+#[test]fn pending_semantic_identity_drift_rejects_before_any_further_bulk() {let _guard = HTTP_E2E_LOCK.lock().unwrap();@@ -662,8 +758,12 @@ fn fresh_cannot_destroy_a_committed_generation() {let error = run_index(config.clone()).unwrap_err();let message = format!("{error:#}");assert!(- message.contains("`--fresh` cannot discard an existing plan under the same destination"),- "{message}"+ message.contains("`--fresh` cannot discard committed corpus generation 1"),+ "the refusal must name the durable state that blocks it: {message}"+ );+ assert!(+ message.contains("without `--fresh`"),+ "the refusal must point at the incremental path that does work: {message}");assert_eq!(@@ -767,8 +867,8 @@ fn fresh_cannot_destroy_a_pending_generation() {let error = run_index(config.clone()).unwrap_err();let message = format!("{error:#}");assert!(- message.contains("`--fresh` cannot discard an existing plan under the same destination"),- "{message}"+ message.contains("`--fresh` cannot discard an uncommitted pending corpus generation"),+ "the refusal must name the durable state that blocks it: {message}");assert_eq!(fs::read(&journal_path).unwrap(),diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 598b4fbea..22b6eca0b 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -28,7 +28,6 @@ mod sync_executor;pub mod walk;use anyhow::{Context, Result};-use serde::Serialize;use serde_json::{json, Map, Value};use std::collections::HashMap;use std::io::{BufRead, BufReader, Seek, Write};@@ -214,7 +213,10 @@ fn begin_non_graph_generation(version: 1,backend: "disabled".into(),identity_sha256: "0".repeat(64),- dimensions: 1,+ // A disabled embedding execution has no vector width at all. `None`+ // says exactly that; any number here would be a fiction the+ // generation contract would then hold future runs to.+ dimensions: None,semantic_contract: "disabled-no-semantic-fields-v1".into(),resumable: true,non_resumable_reason: None,@@ -316,10 +318,10 @@ struct CliErrorRoute {fn route_cli_error(error: &anyhow::Error, json_output: bool) -> CliErrorRoute {if json_output {- if let Some(delta) = error.downcast_ref::<UnsupportedInventoryDeltaError>() {+ if let Some(unsafe_fresh) = error.downcast_ref::<UnsafeFreshGenerationError>() {return CliErrorRoute {exit_code: 1,- stdout: Some(delta.to_json().to_string()),+ stdout: Some(unsafe_fresh.to_json().to_string()),stderr: None,};}@@ -821,6 +823,7 @@ mod phase_a_grouping_tests {pdf_timeout_secs: 10,bulk_mb: 1,bulk_timeout_secs: 10,+ snapshot_max_bytes: 64 << 30,prefix: "t".into(),state_dir: None,fresh: true,@@ -1398,156 +1401,69 @@ fn select_resume_plan_keys(Ok(selected)}-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-struct InventoryDeltaEntry {- file_key: String,- path: String,-}--#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]-struct UnsupportedInventoryDelta {- added_content_groups: Vec<InventoryDeltaEntry>,- vanished_content_groups: Vec<InventoryDeltaEntry>,-}-+/// `--fresh` was asked to discard a durable corpus *generation*.+///+/// The generated `--no-graph` path keeps its authority in a committed+/// manifest plus sealed snapshots under the state directory. `--fresh` deletes+/// `journal.ndjson`, and the `gc_snapshots` call that follows every open then+/// sees an empty protected set and removes every sealed snapshot directory —+/// so by the time any later gate could object, the manifest, the pending+/// replay evidence, and the alias/path/stale-record knowledge needed to+/// reconcile the destination are already gone. Refuse before anything is+/// touched.+///+/// This carries no inventory delta on purpose: nothing has been compared yet,+/// and printing empty `added`/`vanished` arrays (as an earlier revision did)+/// is worse than saying plainly which durable state is in the way.#[derive(Debug)]-struct UnsupportedInventoryDeltaError {- delta: UnsupportedInventoryDelta,- fresh_existing_plan: bool,+struct UnsafeFreshGenerationError {+ /// Committed generation number, or `None` when the blocker is an+ /// uncommitted pending generation.+ committed_generation: Option<u64>,}-impl UnsupportedInventoryDeltaError {+impl UnsafeFreshGenerationError {fn to_json(&self) -> Value {json!({- "schema": "xerj.autoindex.unsupported_sync_delta.v1",+ "schema": "xerj.autoindex.unsafe_fresh_generation.v1","status": "error",- "error": if self.fresh_existing_plan {- "unsafe_fresh_existing_plan"- } else {- "unsupported_inventory_delta"- },- "message": if self.fresh_existing_plan {- "this attempt made no remote mutations; --fresh cannot discard an existing plan under the same destination because alias, path, graph, and stale-record cleanup knowledge would be lost; the existing destination may already be partial or stale"- } else {- "this attempt made no remote mutations because this autoindex plan cannot safely reconcile corpus membership changes; the existing destination may already be partial or stale"+ "error": "unsafe_fresh_existing_generation",+ "message": "this attempt made no remote mutations; --fresh cannot discard a durable corpus generation under the same destination because the committed manifest, sealed replay evidence, and alias, path and stale-record cleanup knowledge would be lost",+ "blocking_state": match self.committed_generation {+ Some(generation) => json!({"kind": "committed_generation", "generation": generation}),+ None => json!({"kind": "pending_generation"}),},- "added_content_groups": self.delta.added_content_groups,- "vanished_content_groups": self.delta.vanished_content_groups,"recovery": {- "exact_rebuild": "index with a new --state-dir, new --prefix, and (when graph detection is enabled) new --brain; alternatively add --no-graph. Validate the isolated target before switching readers",+ "resume": "run the same command WITHOUT --fresh: a generated --no-graph journal reconciles additions, changes, deletions and renames incrementally, and replays a pending generation",+ "exact_rebuild": "index with a new --state-dir and a new --prefix. Validate the isolated target before switching readers","warning": "--fresh is not recovery or destination reconciliation. The global autoindex-catalog and old target are not cleaned automatically; validate and clean them explicitly"}})}}-impl std::fmt::Display for UnsupportedInventoryDeltaError {+impl std::fmt::Display for UnsafeFreshGenerationError {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- let render = |entries: &[InventoryDeltaEntry]| {- entries- .iter()- .map(|entry| format!("{} ({})", entry.path, entry.file_key))- .collect::<Vec<_>>()- .join(", ")- };- let reason = if self.fresh_existing_plan {- "`--fresh` cannot discard an existing plan under the same destination because alias, \- path, graph, and stale-record cleanup knowledge would be lost"- } else {- "corpus membership synchronization is not yet supported"+ let blocker = match self.committed_generation {+ Some(generation) => format!("committed corpus generation {generation}"),+ None => "an uncommitted pending corpus generation".to_owned(),};write!(formatter,- "this attempt made no remote mutations; the existing destination may already be \- partial or stale. {reason}. Added \- content groups [{}]; vanished content groups [{}]. For an exact rebuild, index the \- current folder with a new --state-dir, a new --prefix, and, when graph detection is \- enabled, a new --brain (or use --no-graph). Validate the isolated target before \- switching readers. `--fresh` is not recovery or destination reconciliation; the \- global autoindex-catalog and old target require explicit validated cleanup",- render(&self.delta.added_content_groups),- render(&self.delta.vanished_content_groups)+ "this attempt made no remote mutations. `--fresh` cannot discard {blocker} under the \+ same destination: the committed manifest, sealed replay evidence, and the alias, \+ path and stale-record cleanup knowledge would be lost, and the existing destination \+ may already be partial or stale. Re-run the same command without `--fresh` — a \+ generated `--no-graph` journal reconciles additions, changes, deletions and renames \+ incrementally. For an exact rebuild, index the current folder with a new \+ --state-dir and a new --prefix, and validate the isolated target before switching \+ readers. `--fresh` is not recovery or destination reconciliation; the global \+ autoindex-catalog and old target require explicit validated cleanup")}}-impl std::error::Error for UnsupportedInventoryDeltaError {}--impl UnsupportedInventoryDelta {- fn between(files: &[walk::FileEntry], keys: &[String], plan: &Plan) -> Self {- let current_keys: std::collections::HashSet<&str> = keys- .iter()- .filter(|key| !key.is_empty())- .map(String::as_str)- .collect();- let durable_keys: std::collections::HashSet<&str> = plan- .files- .keys()- .map(String::as_str)- .chain(plan.junk_files.iter().map(|junk| junk.file_key.as_str()))- .collect();-- let mut added_content_groups: Vec<InventoryDeltaEntry> = files- .iter()- .zip(keys)- .filter(|(_, key)| !key.is_empty() && !durable_keys.contains(key.as_str()))- .map(|(file, key)| InventoryDeltaEntry {- file_key: key.clone(),- path: file.rel.clone(),- })- .collect();- let mut vanished_content_groups: Vec<InventoryDeltaEntry> = plan- .files- .iter()- .filter(|(key, _)| !current_keys.contains(key.as_str()))- .map(|(key, assignment)| InventoryDeltaEntry {- file_key: key.clone(),- path: assignment.rel.clone(),- })- .collect();- vanished_content_groups.extend(- plan.junk_files- .iter()- .filter(|junk| !current_keys.contains(junk.file_key.as_str()))- .map(|junk| InventoryDeltaEntry {- file_key: junk.file_key.clone(),- path: junk.rel.clone(),- }),- );-- let stable_order = |left: &InventoryDeltaEntry, right: &InventoryDeltaEntry| {- left.path- .cmp(&right.path)- .then_with(|| left.file_key.cmp(&right.file_key))- };- added_content_groups.sort_by(stable_order);- vanished_content_groups.sort_by(stable_order);- Self {- added_content_groups,- vanished_content_groups,- }- }-- fn is_empty(&self) -> bool {- self.added_content_groups.is_empty() && self.vanished_content_groups.is_empty()- }-- fn into_error(self) -> anyhow::Error {- UnsupportedInventoryDeltaError {- delta: self,- fresh_existing_plan: false,- }- .into()- }-- fn into_fresh_error(self) -> anyhow::Error {- UnsupportedInventoryDeltaError {- delta: self,- fresh_existing_plan: true,- }- .into()- }-}+impl std::error::Error for UnsafeFreshGenerationError {}fn alias_keys_to_reindex(previous: &[state::DuplicateFile],@@ -1854,20 +1770,34 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.committed_manifest.as_ref().is_some_and(|manifest| manifest.generation == 0 && manifest.groups.is_empty());- // `--fresh` must be refused before the journal is opened. `open_after_- // preflight` deletes journal.ndjson whenever `fresh` is set, and the- // `gc_snapshots` call that follows every open then sees an empty protected- // set and removes every sealed snapshot directory. The legacy plan gate- // further down cannot save a generated corpus: both generated branches are- // evaluated before it, so the committed manifest and any pending replay- // evidence would already be gone. Fail here, before anything is touched, so- // that `--fresh` really is "accepted only when the selected state directory- // has no durable plan" as the CLI help and docs state.- if cfg.fresh- && (preflight.pending_sync.is_some()- || (preflight.committed_manifest.is_some() && !genesis_recovery))- {- return Err(UnsupportedInventoryDelta::default().into_fresh_error());+ // `--fresh` must be refused before the journal is opened, and only for a+ // durable *generation*. `open_after_preflight` deletes journal.ndjson+ // whenever `fresh` is set, and the `gc_snapshots` call that follows every+ // open then sees an empty protected set and removes every sealed snapshot+ // directory — so nothing evaluated later can save a generated corpus.+ //+ // Scope matters here. A legacy (non-generated) journal keeps `--fresh`+ // exactly as it has always behaved: it is a crash-resume boundary, not a+ // generation, and `xerj brain` documents and depends on `--fresh` to+ // re-index a folder whose server-side data was wiped (brain.rs). Only+ // generated state — a pending sync, or a committed manifest past genesis —+ // has authority that `--fresh` would silently destroy.+ let blocking_generation = if !cfg.fresh {+ None+ } else if preflight.pending_sync.is_some() {+ Some(None)+ } else {+ preflight+ .committed_manifest+ .as_ref()+ .filter(|_| !genesis_recovery)+ .map(|manifest| Some(manifest.generation))+ };+ if let Some(committed_generation) = blocking_generation {+ return Err(UnsafeFreshGenerationError {+ committed_generation,+ }+ .into());}// A durable sync_begin owns the desired generation. Never rediscover and// replan from a mutable source tree while that transaction is pending.@@ -1942,6 +1872,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@@ -1980,7 +1911,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}).collect()});- let plan = reconcile_plan::reconcile_plan(&inventory, &base.plan, scans)?;+ let plan = reconcile_plan::reconcile_plan(&inventory, &base.plan, scans, cfg.sample)?;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)?;@@ -2084,37 +2015,6 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {rebuild_argv);}- if !genesis_recovery {- if let Some(prior_plan) = preflight.plan.as_ref() {- let comparison_keys = if cfg.fresh {- inventory.keys.clone()- } else {- // Ordinary resume preserves planned-key identity for supported- // same-path replacement and legacy plans.- select_resume_plan_keys(- &inventory.files,- &inventory.keys,- prior_plan,- &state_dir.join("journal.ndjson"),- )?- .into_iter()- .zip(inventory.keys.iter())- .map(|(planned, current)| planned.unwrap_or_else(|| current.clone()))- .collect()- };- let delta =- UnsupportedInventoryDelta::between(&inventory.files, &comparison_keys, prior_plan);- if cfg.fresh {- // Even an apparently unchanged content-key set can have alias,- // path, graph, catalog, or partial-publication history that only- // the old plan can reconcile. Route 1 cannot safely discard it.- return Err(delta.into_fresh_error());- }- if !delta.is_empty() {- return Err(delta.into_error());- }- }- }let mut journal = state::Journal::open_after_preflight(preflight,&root_str,@@ -2353,20 +2253,6 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {plan};- // A durable plan is a crash-resume boundary, not a folder-sync- // generation. Fail before index creation/mapping, replacement intent,- // graph invalidation, delete-by-query, bulk publication, refresh, or- // catalog writes when the current inventory adds or removes an entire- // canonical content group. Continuing would either silently skip new- // data or leave vanished source records searchable. Existing planned-key- // content replacement and crash repair remain supported.- if resumed_with_plan {- let delta = UnsupportedInventoryDelta::between(&files, &keys, &plan);- if !delta.is_empty() {- return Err(delta.into_error());- }- }-// ── stale junk-catalog sweep (#238) ──────────────────────────────────//// A junk/skipped file is never indexed and never enters the graph corpus@@ -4274,105 +4160,39 @@ mod section_label_tests {}#[cfg(test)]-mod inventory_delta_tests {+mod unsafe_fresh_generation_tests {use super::*;- use std::path::PathBuf;-- fn file(path: &str) -> walk::FileEntry {- walk::FileEntry {- path: PathBuf::from(path),- rel: path.to_owned(),- rel_id: format!("id:{path}"),- is_symlink: false,- size: 1,- }- }-- fn assignment(path: &str) -> FileAssignment {- FileAssignment {- rel: path.to_owned(),- path_id: format!("id:{path}"),- is_symlink: Some(false),- family: "csv".into(),- gzip: false,- content_digest: Some(format!("digest:{path}")),- assignments: vec![(None, "rows".into())],- }- }-- #[test]- fn classifier_is_empty_for_noop_and_sorts_added_and_vanished_groups() {- let mut plan = Plan::default();- plan.files.insert("keep".into(), assignment("keep.csv"));- assert!(- UnsupportedInventoryDelta::between(&[file("keep.csv")], &["keep".into()], &plan)- .is_empty()- );- plan.junk_files.push(JunkFile {- file_key: "junk".into(),- rel: "broken.pdf".into(),- format: "pdf".into(),- status: "junk".into(),- reason: "fixture".into(),- bytes: 1,- });- assert!(- UnsupportedInventoryDelta::between(- &[file("keep.csv"), file("broken.pdf")],- &["keep".into(), "junk".into()],- &plan,- )- .is_empty(),- "unchanged durable junk is not newly added content"- );-- plan.files.insert("old-z".into(), assignment("z-old.csv"));- plan.files.insert("old-a".into(), assignment("a-old.csv"));- let delta = UnsupportedInventoryDelta::between(- &[- file("keep.csv"),- file("broken.pdf"),- file("z-new.csv"),- file("m-new.csv"),- ],- &["keep".into(), "junk".into(), "new-z".into(), "new-m".into()],- &plan,- );- assert_eq!(- delta- .added_content_groups- .iter()- .map(|entry| entry.path.as_str())- .collect::<Vec<_>>(),- ["m-new.csv", "z-new.csv"]- );- assert_eq!(- delta- .vanished_content_groups- .iter()- .map(|entry| entry.path.as_str())- .collect::<Vec<_>>(),- ["a-old.csv", "z-old.csv"]- );- }#[test]fn cli_error_routing_separates_typed_json_from_unrelated_human_errors() {- let typed = UnsupportedInventoryDelta {- added_content_groups: vec![InventoryDeltaEntry {- file_key: "key".into(),- path: "new.csv".into(),- }],- vanished_content_groups: Vec::new(),+ let typed: anyhow::Error = UnsafeFreshGenerationError {+ committed_generation: Some(7),}- .into_error();+ .into();let route = route_cli_error(&typed, true);assert_eq!(route.exit_code, 1);assert!(route.stderr.is_none());let stdout = route.stdout.unwrap();let value: Value = serde_json::from_str(&stdout).unwrap();- assert_eq!(value["schema"], "xerj.autoindex.unsupported_sync_delta.v1");- assert_eq!(value["error"], "unsupported_inventory_delta");+ assert_eq!(value["schema"], "xerj.autoindex.unsafe_fresh_generation.v1");+ assert_eq!(value["error"], "unsafe_fresh_existing_generation");+ assert_eq!(value["blocking_state"]["kind"], "committed_generation");+ assert_eq!(value["blocking_state"]["generation"], 7);+ // The refusal must never print an empty inventory delta it never+ // computed: it names the durable state that is in the way instead.+ assert!(value.get("added_content_groups").is_none());+ assert!(format!("{typed:#}").contains("committed corpus generation 7"));++ let pending: anyhow::Error = UnsafeFreshGenerationError {+ committed_generation: None,+ }+ .into();+ let pending_value: Value =+ serde_json::from_str(&route_cli_error(&pending, true).stdout.unwrap()).unwrap();+ assert_eq!(+ pending_value["blocking_state"]["kind"],+ "pending_generation"+ );let unrelated = anyhow::anyhow!("endpoint unavailable");let route = route_cli_error(&unrelated, true);diff --git a/engine/crates/xerj-autoindex/src/reconcile_plan.rs b/engine/crates/xerj-autoindex/src/reconcile_plan.rsindex f93099de4..eee92c704 100644--- a/engine/crates/xerj-autoindex/src/reconcile_plan.rs+++ b/engine/crates/xerj-autoindex/src/reconcile_plan.rs@@ -12,6 +12,31 @@ use crate::FileScan;use anyhow::{Context, Result};use std::cmp::Ordering;use std::collections::{HashMap, HashSet};+use std::path::Path;++/// Field shape of a file as the *document* renderer sees it.+///+/// The mirror of the demoted-file re-sampling loop in `build_phase_a`: a+/// demoted config file's committed mapping was inferred from+/// `extract::extract_as_document`, so that is the only extractor whose output+/// may be compared against it. An unreadable file yields an empty shape, which+/// is trivially compatible — it junks at phase B like any other, and the+/// projection only needs the shape.+fn document_sample(path: &Path, gzip: bool, sample: usize) -> HashMap<String, FieldAcc> {+ let mut fields: HashMap<String, FieldAcc> = HashMap::new();+ let mut sampled = 0usize;+ let mut sink = |record: crate::extract::RawRecord| -> bool {+ if sampled < sample {+ for (name, value) in &record.fields {+ fields.entry(name.clone()).or_default().add(value);+ }+ }+ sampled += 1;+ sampled < sample+ };+ let _ = crate::extract::extract_as_document(path, gzip, &mut sink);+ fields+}/// Project the current, byte-verified inventory onto committed dataset schemas.///@@ -22,6 +47,7 @@ pub(crate) fn reconcile_plan(inventory: &Inventory,previous: &Plan,scans: Vec<FileScan>,+ sample: usize,) -> Result<Plan> {anyhow::ensure!(inventory.files.len() == inventory.keys.len()@@ -117,8 +143,26 @@ pub(crate) fn reconcile_plan(}let retained = content_owner.or_else(|| path_owner.map(|(_, assignment)| assignment));+ // A demoted one-off config file (#173) is committed to a *docs*+ // dataset and indexed through `extract::extract_as_document`, not its+ // family extractor. Its frozen mapping therefore describes the fixed+ // document shape, never the file's own flattened fields — so the scan+ // sketches (which come from the family extractor) are the wrong thing+ // to compare against it. Re-sample the file through the same document+ // renderer `build_phase_a` uses, exactly as the fresh path does, and+ // carry the committed `as_document` decision forward. Losing it would+ // index flattened records into a document mapping.+ let as_document = retained.is_some_and(|owner| owner.as_document);+ let document_fields = if as_document {+ Some(document_sample(&file.path, sniffed.gzip, sample))+ } else {+ None+ };+let mut assignments = Vec::with_capacity(scan.sketches.len());- for (group, fields, _records) in &scan.sketches {+ for sketch in &scan.sketches {+ let group = &sketch.group;+ let fields = document_fields.as_ref().unwrap_or(&sketch.fields);let slug = if let Some(owner) = retained {retained_slug(owner, group, sniffed.family.as_str(), fields, &datasets).with_context(|| format!("project retained file {}", file.rel))?@@ -145,6 +189,7 @@ pub(crate) fn reconcile_plan(gzip: sniffed.gzip,content_digest: Some(content_digest.clone()),assignments,+ as_document,},);anyhow::ensure!(@@ -416,7 +461,12 @@ mod tests {csv: None,encoding: "utf-8",}),- sketches: vec![(None, fields, 1)],+ sketches: vec![crate::GroupSketch {+ group: None,+ fields,+ key_fields: std::collections::HashSet::new(),+ records: 1,+ }],junk: None,}}@@ -439,6 +489,7 @@ mod tests {gzip: false,content_digest: Some("old-digest".into()),assignments: vec![(None, slug.into())],+ as_document: false,}}@@ -462,6 +513,7 @@ mod tests {&inventory("a.jsonl", "unix:61", "new"),&previous,vec![scan(fields)],+ 50,).unwrap();assert_eq!(@@ -494,6 +546,7 @@ mod tests {&inventory("new.jsonl", "unix:6e", "new"),&previous,vec![scan(fields)],+ 50,).unwrap();assert_eq!(plan.files["new"].assignments, vec![(None, "winner".into())]);@@ -518,6 +571,7 @@ mod tests {&inventory("new.jsonl", "unix:6e", "new"),&previous,vec![scan(fields)],+ 50,).unwrap_err();let message = format!("{error:#}");@@ -543,6 +597,7 @@ mod tests {&inventory("new.jsonl", "unix:6e", "new"),&previous,vec![scan(unknown)],+ 50,).unwrap_err();assert!(format!("{error:#}").contains("unsupported dataset/schema evolution"));@@ -558,6 +613,7 @@ mod tests {&inventory("new.jsonl", "unix:6e", "new"),&previous,vec![scan(object_field)],+ 50,).unwrap_err();assert!(format!("{error:#}").contains("unsupported dataset/schema evolution"));@@ -567,6 +623,7 @@ mod tests {&inventory("new.jsonl", "unix:6e", "new"),&previous,vec![scan(wrong_type)],+ 50,).unwrap_err();assert!(format!("{error:#}").contains("unsupported dataset/schema evolution"));@@ -591,7 +648,7 @@ mod tests {bytes: 10,});let fields = HashMap::from([("id".into(), acc(&[json!(7)]))]);- let plan = reconcile_plan(¤t, &previous, vec![scan(fields)]).unwrap();+ let plan = reconcile_plan(¤t, &previous, vec![scan(fields)], 50).unwrap();assert_eq!(plan.files["same"].rel, "renamed.jsonl");assert_eq!(plan.datasets[0].file_count, 1);assert_eq!(plan.duplicate_files.len(), 1);@@ -612,7 +669,7 @@ mod tests {let fields = || HashMap::from([("id".into(), acc(&[json!(7)]))]);let conflict = inventory("a.jsonl", "unix:62", "content-a");- let error = reconcile_plan(&conflict, &previous, vec![scan(fields())]).unwrap_err();+ let error = reconcile_plan(&conflict, &previous, vec![scan(fields())], 50).unwrap_err();assert!(format!("{error:#}").contains("conflicting committed content and path owners"));let duplicate = Inventory {@@ -621,8 +678,13 @@ mod tests {digests: vec!["digest".into(), "digest".into()],duplicates: vec![],};- let error = reconcile_plan(&duplicate, &previous, vec![scan(fields()), scan(fields())])- .unwrap_err();+ let error = reconcile_plan(+ &duplicate,+ &previous,+ vec![scan(fields()), scan(fields())],+ 50,+ )+ .unwrap_err();assert!(format!("{error:#}").contains("duplicate content identity"));}}diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex b89fab475..71e6ebe4e 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -1325,6 +1325,7 @@ mod sync_journal_tests {gzip: false,content_digest: Some("digest-a".into()),assignments: vec![(None, "reports".into())],+ as_document: false,},);PendingSync::new(@@ -1341,7 +1342,7 @@ mod sync_journal_tests {chunker_identity: "chunker-v1".into(),embedding_identity_sha256: "a".repeat(64),embedding_backend: "lexical".into(),- embedding_dimension: 384,+ embedding_dimension: Some(384),embedding_semantic_contract: "semantic_text-derived-vector.v1".into(),embedding_resumable: true,graph_enabled: false,diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rsindex 9a20f4352..6d32de31b 100644--- a/engine/crates/xerj-autoindex/src/sync.rs+++ b/engine/crates/xerj-autoindex/src/sync.rs@@ -12,6 +12,15 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};pub const EXECUTION_IDENTITY_VERSION: u32 = 2;+/// On-disk version of the durable corpus-generation format.+///+/// Bumping it declares that state directories written by older versions cannot+/// be adopted in place — `CommittedManifest::bootstrap_legacy` names this+/// version in the refusal, and the CLI turns that into a followable rebuild.+/// Version 1 is the first format: everything before it is a pre-generation+/// resume `Plan`.+pub const GENERATION_FORMAT_VERSION: u32 = 1;+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]pub struct ManifestPath {/// Reversible platform-native path identity (`unix:`/`windows:` encoding).@@ -70,7 +79,14 @@ pub struct ExecutionIdentity {/// space. Autoindex must never synthesize model/tokenizer labels.pub embedding_identity_sha256: String,pub embedding_backend: String,- pub embedding_dimension: usize,+ /// Vector width, exactly as the server reported it. `None` is the honest+ /// record for a backend whose width the server does not pin (`neural`,+ /// `proxy` — see `esclient::EmbeddingExecutionIdentity::dimensions`) and+ /// for the synthetic `disabled` identity a no-semantic plan pins. It must+ /// never be coerced to a number: a generation that recorded "unknown" and+ /// one that recorded 384 are different execution spaces.+ #[serde(default)]+ pub embedding_dimension: Option<usize>,pub embedding_semantic_contract: String,pub embedding_resumable: bool,pub graph_enabled: bool,@@ -129,28 +145,45 @@ impl CommittedManifest {Ok(())}+ /// Adopt a pre-generation resume `Plan` as generation zero, or state — once,+ /// by name and version — that it cannot be adopted.+ ///+ /// A non-empty legacy plan can *never* be adopted, and that is a deliberate,+ /// versioned format boundary rather than an accident of validation: a+ /// `Plan` records no stable group ID, no content byte length, and no+ /// validated per-group output counts, so no amount of per-file evidence+ /// could reconstruct a `ManifestGroup`. Every existing `--no-graph` state+ /// directory written before `GENERATION_FORMAT_VERSION` therefore requires+ /// an explicit rebuild into a new state directory and prefix.+ ///+ /// Saying that once, with the version in it, is the point. An earlier+ /// revision pushed one identical "no complete manifest group" line *per+ /// file key* — an O(files) refusal string (megabytes on a large corpus)+ /// that read as a pile of per-file validation failures rather than as the+ /// single migration decision it is. redb makes exactly this distinction:+ /// an old on-disk format returns a named, versioned `UpgradeRequired(v)`,+ /// kept separate from `Corrupted`, so the operator is told to migrate+ /// rather than handed evidence to debug (redb,+ /// `src/tree_store/page_store/header.rs:480-492` and+ /// `src/error.rs:212-213, 244-252`, Apache-2.0/MIT — approach only, no+ /// code taken).pub fn bootstrap_legacy(plan: Plan) -> Result<LegacyBootstrap> {- let mut reasons = Vec::new();- for (file_key, file) in &plan.files {- if file.content_digest.is_none() {- reasons.push(format!("{file_key}: missing full content digest"));- }- if !native_path_id_supported(&file.path_id) {- reasons.push(format!(- "{file_key}: missing or lossy native canonical path identity"- ));- }- if file.is_symlink.is_none() {- reasons.push(format!(- "{file_key}: legacy plan did not persist canonical symlink rank"- ));- }- // A Plan is not itself a generation manifest: it has no stable- // group ID, content byte length, or validated output counts.- reasons.push(format!(- "{file_key}: legacy plan has no complete manifest group"- ));+ if !plan.files.is_empty() {+ return Ok(LegacyBootstrap::MigrationRequired {+ reasons: vec![format!(+ "this state directory holds a pre-generation autoindex resume plan \+ ({} planned files); the durable corpus-generation format \+ (v{GENERATION_FORMAT_VERSION}) requires a stable group identity, content \+ byte length, and validated output counts that a resume plan never recorded, \+ so it cannot be adopted in place and must be rebuilt",+ plan.files.len()+ )],+ });}+ // An empty legacy plan is genesis: there is nothing to migrate. Alias+ // records without canonical files are the only remaining evidence that+ // could be malformed, so they are still checked individually.+ let mut reasons = Vec::new();for alias in &plan.duplicate_files {if !native_path_id_supported(&alias.path_id) {reasons.push(format!(@@ -697,8 +730,8 @@ fn validate_manifest(manifest: &GenerationManifest, legacy: bool) -> Result<()>"embedding execution identity must be a lowercase SHA-256 digest");anyhow::ensure!(- execution.embedding_dimension > 0,- "embedding execution dimension must be positive"+ execution.embedding_dimension != Some(0),+ "embedding execution dimension must be positive when the server pins one");anyhow::ensure!(execution.embedding_resumable,@@ -1209,6 +1242,7 @@ mod tests {gzip: false,content_digest: Some("digest".into()),assignments: Vec::new(),+ as_document: false,},);assert!(matches!(@@ -1233,6 +1267,7 @@ mod tests {gzip: false,content_digest: Some(format!("digest-{key}")),assignments: Vec::new(),+ as_document: false,},);}@@ -1264,7 +1299,7 @@ mod tests {chunker_identity: "chunker-v1".into(),embedding_identity_sha256: "a".repeat(64),embedding_backend: "lexical".into(),- embedding_dimension: 384,+ embedding_dimension: Some(384),embedding_semantic_contract: "semantic_text-derived-vector.v1".into(),embedding_resumable: true,graph_enabled: false,diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex 234d00de3..465b18a07 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -1721,6 +1721,7 @@ mod tests {gzip: false,content_digest: Some(inventory.digests[0].clone()),assignments: vec![(None, "docs".into())],+ as_document: false,},)]),alias_paths_indexed: false,@@ -1738,7 +1739,7 @@ mod tests {chunker_identity: "chunker-v1".into(),embedding_identity_sha256: "a".repeat(64),embedding_backend: "lexical".into(),- embedding_dimension: 384,+ embedding_dimension: Some(384),embedding_semantic_contract: "semantic_text-derived-vector.v1".into(),embedding_resumable: true,graph_enabled: false,diff --git a/landing/docs/recipes/zero-config-autoindex.html b/landing/docs/recipes/zero-config-autoindex.htmlindex ae18044c0..625485b98 100644--- a/landing/docs/recipes/zero-config-autoindex.html+++ b/landing/docs/recipes/zero-config-autoindex.html@@ -239,7 +239,7 @@ live indices at http://localhost:9280:ax-docs 1 docsax-exports 800 docsautoindex-catalog 9 docs</pre>- <p><code class="inline">--fresh</code> starts without resume state only when the selected state directory has no durable plan; it never removes stale destination records. For an independent rebuild, use a new <code class="inline">--state-dir</code>, new <code class="inline">--prefix</code>, and new <code class="inline">--brain</code> when graph detection is enabled (or add <code class="inline">--no-graph</code>). Validate before switching readers. The shared <code class="inline">autoindex-catalog</code> and old target require explicit, validated cleanup. Generated journals with <code class="inline">--no-graph</code> reconcile additions, changes, deletions, renames, and no-op reruns. Legacy journals and graph-enabled generations refuse membership changes before remote mutation.</p>+ <p><code class="inline">--fresh</code> ignores the resume journal and restarts (ids stay idempotent). It never removes stale records from the destination, and it is refused once the state directory holds a durable corpus generation — re-run without it and the generated <code class="inline">--no-graph</code> path reconciles additions, changes, deletions, renames and no-op reruns incrementally. For an independent rebuild, use a new <code class="inline">--state-dir</code> and a new <code class="inline">--prefix</code>, plus a new <code class="inline">--brain</code> when graph detection is enabled (or add <code class="inline">--no-graph</code>). Validate before switching readers; the shared <code class="inline">autoindex-catalog</code> and old target require explicit, validated cleanup. A <code class="inline">--no-graph</code> state directory written before the generation format cannot be adopted in place and must be rebuilt the same way.</p><hr>diff --git a/landing/llms-full.txt b/landing/llms-full.txtindex e64ac3d47..6145ed2eb 100644--- a/landing/llms-full.txt+++ b/landing/llms-full.txt@@ -140,14 +140,16 @@ destabilize the server.xerj autoindex map [--url U] [--json] [--dataset SLUG]xerj autoindex status [--url U] [--state-dir P]---fresh starts without resume state only when the selected state directory has-no durable plan. It never removes stale destination records. An independent-rebuild requires a new --state-dir, new --prefix, and new --brain when graph-detection is enabled (or --no-graph), followed by validation before switching-readers. The shared autoindex-catalog and old target require explicit,-validated cleanup. Generated journals with --no-graph reconcile additions,-changes, deletions, renames, and no-op reruns. Legacy journals and graph-enabled-generations refuse membership changes before remote mutation.+--fresh ignores the resume journal and restarts (ids stay idempotent). It never+removes stale destination records, and it is refused once the state directory+holds a durable corpus generation — re-run without it and the generated+--no-graph path reconciles additions, changes, deletions, renames and no-op+reruns incrementally. An independent rebuild requires a new --state-dir and a+new --prefix, plus a new --brain when graph detection is enabled (or+--no-graph), followed by validation before switching readers. The shared+autoindex-catalog and old target require explicit, validated cleanup. A+--no-graph state directory written before the generation format cannot be+adopted in place and must be rebuilt the same way.Exit codes: 0 complete · 3 completed-with-junk (junk recorded, never fatal) ·2 usage · 1 endpoint/journal error or refused unsafe corpus-state transition.