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): reindex graph additions and deletions without aborting (#2314) (#2317)
xerj-org461f199c0b70
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62fa1d2a9..92cecdd5c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -128,6 +128,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`keep_archived`) is marked on the `xerj code` header and on `xerj search`(#2327).+- Graph-mode `xerj autoindex` re-indexes a folder after files are added or+ deleted. An added file that fits a frozen dataset is indexed on the rerun;+ a file that needs a new dataset stays unindexed until `--fresh`. Documents,+ catalog rows, and graph edges for a file that left the folder are removed,+ and the run names that file, including when `--fresh` rebuilds the plan.+ `xerj autoindex remove` deletes that folder's resume journal (and+ `sync-snapshots`), and an explicit+ `--state-dir` on `remove` deletes the journal there too. A file whose size+ changes while a run is reading it is skipped with a warning instead of+ aborting the run, on the graph path and on `--no-graph` snapshot sealing.+ The catalog canonical/alias count refreshes and recounts before it aborts+ a generation. A rerun that removes documents for files that left the folder+ finishes exit 3 (`reason=files-removed`); the next unchanged rerun is exit 0+ ([#2314](https://github.com/xerj-org/xerj/issues/2314)).+- Scoped autoindex threads and `POST /{index}/_update/{id}` no longer abortthe process when a thread stack or a large body cannot be allocated(#1122). Indexing workers, sync replay, object-watch fetches, and mailboxdiff --git a/content/answers/keep-index-current-as-files-change.md b/content/answers/keep-index-current-as-files-change.mdindex a0884d2b0..fa081ec4e 100644--- a/content/answers/keep-index-current-as-files-change.md+++ b/content/answers/keep-index-current-as-files-change.md@@ -7,7 +7,7 @@ cluster: "Operations: freshness"question: "How do I keep a search index up to date as files change, without re-indexing everything?"intent: "how-to"published: "2026-09-19"-updated: "2026-10-19"+updated: "2026-10-24"author: "XERJ documentation team"reviewer: "XERJ engineering team"schema_type: "TechArticle"@@ -35,7 +35,7 @@ faq:- q: "How do I keep a search index up to date as files change, without re-indexing everything?"a: "Run xerj autoindex with --watch --no-graph. It indexes the folder once, then stays resident and reindexes only what the filesystem reports as changed, using one OS watch per indexed directory and no polling."- q: "Why does --watch require --no-graph?"- a: "Reconciling an added or deleted file exists only on the --no-graph route. On the default graph path a re-run resumes a frozen plan: a file added after that plan was frozen is reported as appeared after the resume plan was frozen and is not indexed until a --fresh rebuild, and a deleted file aborts the run and every re-run after it. A file whose content changed is reconciled there, so the limitation is additions and deletions, not edits."+ a: "The watcher re-runs the generated route, which reconciles added, changed, renamed and deleted files, including a file that would be a new dataset. On the default graph path a deleted file is swept and an added file that fits a frozen dataset is indexed, but a file that needs a new dataset still stops with reason=stale-resume-plan until --fresh, and the watcher is not built on that route."- q: "Is a file watcher cheaper than re-running the indexer on a timer?"a: "At idle, yes, and measurably. On a 10,000-file tree a re-run with nothing changed took 1.7 s and re-read all 4,576,300 bytes, while an idle watcher used 0.00 CPU-seconds over 60 s and read nothing. It does hold about 157 MiB resident between passes."- q: "Does --watch use less CPU per change than a re-run?"@@ -126,17 +126,20 @@ than a formality:* On the `--no-graph` route, a run reconciles the folder against a committedgeneration: added, changed, renamed and deleted files are all handled.* On the default graph path, a run resumes a *frozen* plan. A file whose content- changed **is** reconciled there (measured: 3.07 s, `files=1`, the new text- searchable). A file that was **added** is not. The run reports- `1 file(s) appeared after the resume plan was frozen and were NOT indexed`,- exits 3, and tells you to rebuild with `--fresh`. A file that was **deleted** is- worse. The run aborts in 0.24 s with "removing files from an indexed folder is- not reconciled yet". Its documents stay live, and every later re-run aborts the- same way.--A watcher on the graph path would therefore go stale on the first new file and-stop reindexing on the first deletion. The price of `--no-graph` is relationship-detection: no wikilink, local-link, section-order or directory-chain edges.+ changed **is** reconciled there (measured on 2026-09-19: 3.07 s, `files=1`,+ the new text searchable). A deleted file is swept (exit 3,+ `reason=files-removed`; the next unchanged rerun is exit 0), and an added+ file that fits a frozen dataset is indexed on the rerun. A file that needs a+ new dataset is not: the run exits 3 with `reason=stale-resume-plan` and names+ `--fresh`.+ Before that reconcile, the same 2026-09-19 capture recorded a deletion+ aborting in 0.24 s and leaving its documents live. Those timings were not+ re-measured here.++The watcher stays on `--no-graph` because that route also reconciles a file+that would be a new dataset, and the watcher is not built on the graph path.+The price of `--no-graph` is relationship detection: no wikilink, local-link,+section-order or directory-chain edges.## Which directories the watcher coversdiff --git a/docs/LIVE_REINDEXING.md b/docs/LIVE_REINDEXING.mdindex 7f6df454d..d5dc1f4d4 100644--- a/docs/LIVE_REINDEXING.md+++ b/docs/LIVE_REINDEXING.md@@ -21,29 +21,32 @@ is worth stating exactly what it means:against a committed generation. Added, changed, renamed and deleted files areall handled (`lib.rs::project_reconcile_plan`,`reconcile_plan::reconcile_plan`).-* On the **default graph path**, a re-run *resumes a frozen plan*, and what that- costs depends on the kind of change. Measured on a 10,000-file tree- (`docs/measurements/autoindex-watch-2026-09-19.md`, section 4):-- | Graph-route re-run after… | Result |+* On the **default graph path**, a re-run resumes a frozen plan. A file whose+ content changed is indexed. A deleted file is swept: its documents, catalog+ rows and graph edges are removed, including under `--fresh`, and that run+ finishes exit 3 with `reason=files-removed` (the next unchanged rerun is+ exit 0). An added file that fits a frozen dataset is indexed on the rerun.+ A file that needs a new dataset is not: the run exits 3 with+ `reason=stale-resume-plan` and names `--fresh`. The table below is the+ 2026-09-19 capture, from before that reconcile, on a 10,000-file tree+ (`docs/measurements/autoindex-watch-2026-09-19.md`, section 4). Those+ timings were not re-measured for the reconcile.++ | Graph-route re-run after… (2026-09-19 capture) | Result ||---|---|| a file's **content** changed | indexed: 3.07 s, `files=1`, exit 0, the new text searchable || a file was **added** | 3.32 s, **exit 3**, `1 file(s) appeared after the resume plan was frozen and were NOT indexed`; the new file stays unsearchable until `--fresh` || a file was **deleted** | **exit 1, aborted in 0.24 s** — "removing files from an indexed folder is not reconciled yet". Its documents stay live, and every later re-run aborts the same way until the corpus is rebuilt |-A current graph-path resume still does not index a file the frozen plan-predates. It reports `reason=stale-resume-plan` and `skipped_appeared=N`,-leaves `junk_files` for unusable input, and names `--fresh` as the flag that-rebuilds the plan in place. The 3.32 s row above is that measurement; the-capture's reason was `completed-with-junk`.--So the limitation is **additions and deletions**, not edits. A watcher on the-graph path would serve a folder that goes stale on the first new file and stops-reindexing entirely on the first deletion — worse than no watcher at all. That is-why `--watch` requires the route that reconciles all four cases, and says so-instead of quietly downgrading. (An earlier version of this page said a *changed*-file is not indexed on the graph path. It is; that claim came from a measurement-whose shell append had created a file instead of modifying one.) The cost of+A file that needs a new dataset still waits for `--fresh`. An added file that+fits a frozen dataset, and a deleted file, no longer do. The 3.32 s row above+is that measurement; the capture's reason was `completed-with-junk`.++`--watch` still requires `--no-graph`. The watcher re-runs the generated route,+which also reconciles a file that would be a new dataset. It does not watch a+graph corpus. (An earlier version of this page said a *changed* file is not+indexed on the graph path. It is; that claim came from a measurement whose+shell append had created a file instead of modifying one.) The cost of`--no-graph` is relationship detection: no wikilink, local-link, section-order ordirectory-chain edges, so no second-brain graph over a watched corpus.diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 92b086c39..0f3f00c11 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -205,6 +205,9 @@ pub struct RemoveCfg {pub json: bool,pub quiet: bool,pub xerj_url_note: Option<String>,+ /// When set, `remove` also deletes `journal.ndjson` here. The default+ /// journal for the selected folder is deleted either way.+ pub state_dir: Option<PathBuf>,}/// `xerj autoindex s3://bucket/prefix --watch`: poll a bucket and emit a change@@ -275,12 +278,13 @@ const FRESH_HELP: &str ="ignore an existing resume journal and restart, rebuild the plan in place\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(ids stay idempotent for unchanged bytes). A file republished\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20under a new content key drops the documents previously published for that path.\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20It does not remove documents for a file that disappeared, and is refused on a\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20It removes documents for a file that disappeared. It is refused on a\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20durable corpus generation — see RESUME POLICY";const RESUME_POLICY_HELP: &str ="generated --no-graph journals reconcile add, change, delete, rename, and no-op runs; \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";+--state-dir and --prefix; graph-enabled journals reconcile added files that fit a frozen \+dataset, delete documents for files that disappeared, and keep crash-resume of an interrupted run";pub fn print_help() {println!("{}", help_text());@@ -350,7 +354,10 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Prints those folders and continues. Without\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20this flag that run is refused and nothing\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20is written. --dry-run does not bypass it\n\- \x20\x20\x20\x20--state-dir <PATH> resume journal location (default ~/.xerj/autoindex/<hash>/);\n\+ \x20\x20\x20\x20--state-dir <PATH> resume journal location (default ~/.xerj/autoindex/<hash>/).\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20On `autoindex remove`, also deletes journal.ndjson in\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20this directory after the folder's indices are removed;\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20the default journal is deleted either way.\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20for an s3:// source this is also where the local\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20object mirror lives, so point it at a disk with room\n\\x20\x20\x20\x20--endpoint-url <URL> S3-compatible endpoint for an s3:// source (MinIO,\n\@@ -407,12 +414,13 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20--no-graph skip relationship detection (wikilinks, local links,\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20section order, directory chains) — no edges are written\n\\x20\x20\x20\x20--watch index once, then stay resident and reindex what changes.\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Needs --no-graph: the graph route refuses an ADDED file\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(exit 3, skipped until --fresh) and ABORTS on a deletion\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(exit 1, and every later re-run aborts too). It does\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20reindex a MODIFIED file. One OS watch per indexed\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20directory, no polling; respects the same ignore rules as\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20a re-run. docs/LIVE_REINDEXING.md has the measurements.\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Needs --no-graph. A graph-path rerun sweeps a deleted\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20file (exit 3, files-removed) and indexes an added file\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20that fits a frozen dataset. A file that needs a new\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20dataset still stops (exit 3, stale-resume-plan) until\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20--fresh. One OS watch per indexed directory, no polling;\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20respects the same ignore rules as a re-run.\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20docs/LIVE_REINDEXING.md has the measurements.\n\\x20\x20\x20\x20--debounce <MS> --watch quiet period before a pass (default 400, max\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2060000). One editor save is several filesystem events.\n\\x20\x20\x20\x20--max-minutes <N> stop and ask before indexing if phase A's MEASURED estimate\n\@@ -565,7 +573,9 @@ pub fn help_text_with(feedback: bool) -> String {\n\INCREMENTAL RECONCILIATION:\n\\x20\x20\x20\x20Generated journals with --no-graph reconcile added, removed, moved, and changed\n\- \x20\x20\x20\x20files. Legacy journals and graph-enabled generations remain fail-closed. Each\n\+ \x20\x20\x20\x20files. Graph-enabled journals absorb an added file that fits a frozen dataset,\n\+ \x20\x20\x20\x20delete documents for a file that disappeared, and leave a file that needs a new\n\+ \x20\x20\x20\x20dataset unindexed until --fresh rebuilds the plan. Each\n\\x20\x20\x20\x20changed generation currently copies and prepares the full corpus (O(N)); the\n\\x20\x20\x20\x20latest full snapshot remains retained, and cleanup re-reads protected artifacts\n\\x20\x20\x20\x20to verify them. --snapshot-max-gb limits logical staged payload bytes before each\n\@@ -775,6 +785,11 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20`skipped_appeared` names them. Re-run with --fresh to\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20rebuild the plan in place and include them. Read `reason`\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20to tell this apart from completed-with-junk;\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20or files-removed — a graph-path rerun deleted documents,\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20catalog rows and edges for files that left the folder.\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20The index matches the folder; the next unchanged rerun is\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20exit 0. Read `reason` to tell this apart from\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20completed-with-junk;\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x204 NEEDS A DECISION — the estimate exceeded --max-minutes, the\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20estimated index does not fit the disk budget, a reduced\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20plan would delete files that are already indexed, or a\n\@@ -1534,16 +1549,14 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {if !no_graph {return Err("--watch needs --no-graph today, and that is a real limitation rather than a \- formality: reconciling an ADDED or DELETED file exists only on the --no-graph \- (generated) route. On the default graph path a re-run resumes a frozen plan, \- so a file created after that plan was frozen is reported as 'appeared after \- the resume plan was frozen' and is NOT indexed until the corpus is rebuilt \- with --fresh, and a file deleted from the folder ABORTS the run — and every \- re-run after it — because its documents are still live in the destination. \- (A file whose CONTENT changed is reconciled there; additions and deletions \- are what a watcher on that route could not keep current.) Re-run as `xerj \- autoindex <folder> --watch --no-graph` (relationship detection off), or keep \- rebuilding a graph corpus with `xerj autoindex <folder> --fresh`"+ formality: the watcher re-runs the generated route, which reconciles added, \+ changed, renamed and deleted files against a committed generation, including \+ a file that would be a new dataset. The default graph path sweeps a deleted \+ file and indexes an added file that fits a frozen dataset, but a file that \+ needs a new dataset still stops with reason=stale-resume-plan until --fresh, \+ and this watcher is not built on that route. Re-run as `xerj autoindex \+ <folder> --watch --no-graph` (relationship detection off), or keep rebuilding \+ a graph corpus with `xerj autoindex <folder> --fresh`".into(),);}@@ -1819,6 +1832,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {json,quiet,xerj_url_note,+ state_dir: state_dir.clone(),},prefix_explicit,approve_set: approve.is_some(),@@ -1826,7 +1840,6 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {reject: RemoveReject {dry_run,replace_prefix,- state_dir: state_dir.is_some(),fresh,workers: workers.is_some(),pdf_workers: pdf_workers.is_some(),@@ -2049,7 +2062,6 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {struct RemoveReject {dry_run: bool,replace_prefix: bool,- state_dir: bool,fresh: bool,workers: bool,pdf_workers: bool,@@ -2111,14 +2123,6 @@ fn remove_cmd(input: RemoveParse) -> Result<Cmd, String> {.into(),);}- if reject.state_dir {- return Err(- "--state-dir is the local resume journal. `autoindex remove` does not read or delete \- it. The journal key includes the folder, so a later index of that folder still \- resumes from it. Drop --state-dir."- .into(),- );- }let flags = [("--dry-run", reject.dry_run),("--replace-prefix", reject.replace_prefix),@@ -2533,14 +2537,12 @@ mod tests {parse(args.iter().map(|s| s.to_string()).collect()).expect_err("must be refused")}- /// The `--watch` refusal must name the limitation it actually has. Measured- /// on the graph route against a 10,000-file corpus- /// (`docs/measurements/autoindex-watch-2026-09-19.md`, section 4): a re-run- /// after a file's CONTENT changed indexes it (3.07 s, `files=1`, searchable),- /// a re-run after an ADDITION skips the file with exit 3, and a re-run after a- /// DELETION aborts with exit 1 and keeps aborting. The message used to claim- /// the opposite about a changed file, which came from a measurement whose- /// shell append had created a new file rather than modifying one.+ /// The `--watch` refusal must name the limitation it actually has.+ /// The watcher is the generated route. On the default graph path a deleted+ /// file is swept and an added file that fits a frozen dataset is indexed;+ /// a file that needs a new dataset still waits for `--fresh`. The message+ /// used to claim a content change was lost, which came from a measurement+ /// whose shell append had created a new file rather than modifying one.#[test]fn the_watch_refusal_names_additions_and_deletions_not_content_changes() {let text = err(&["data", "--watch"]);@@ -2549,12 +2551,16 @@ mod tests {"the message must name the flag that makes it work: {text}");assert!(- text.contains("ADDED") && text.contains("DELETED"),- "the message must say which changes the graph route cannot reconcile: {text}"+ text.contains("sweeps a deleted") && text.contains("fits a frozen dataset"),+ "the message must say what the graph path does with a deletion and an addition: {text}");assert!(- text.contains("CONTENT changed is reconciled"),- "the message must not leave the operator thinking an edit is lost too: {text}"+ text.contains("stale-resume-plan"),+ "a new dataset still waits for --fresh: {text}"+ );+ assert!(+ !text.contains("ABORTS the run"),+ "a deletion is swept, not aborted: {text}");assert!(!text.contains("a file whose content changed is reported"),@@ -2756,7 +2762,7 @@ mod tests {assert!(help.contains("ignore an existing resume journal and restart"));assert!(help.contains("durable corpus generation"));assert!(help.contains("drops the documents previously published for that path"));- assert!(help.contains("does not remove documents for a file that disappeared"));+ assert!(help.contains("removes documents for a file that disappeared"));}#[test]@@ -2766,7 +2772,7 @@ mod tests {"generated --no-graph journals","add, change, delete, rename, and no-op","written before the generation format must be rebuilt",- "graph-enabled journals keep the existing crash-resume behaviour",+ "graph-enabled journals reconcile added files that fit a frozen",] {assert!(help.contains(claim), "missing resume-policy claim: {claim}");}@@ -2995,8 +3001,28 @@ mod tests {let walk = err(&["remove", "--prefix", "proj", "--walk-only"]);assert!(walk.contains("--walk-only"), "{walk}");assert!(walk.contains("not `autoindex remove`"), "{walk}");- let journal = err(&["remove", "--prefix", "proj", "--state-dir", "/tmp/j"]);- assert!(journal.contains("resume journal"), "{journal}");+ let cfg = match parse(+ [+ "remove",+ "--prefix",+ "proj",+ "--state-dir",+ "/tmp/j",+ "--yes",+ ]+ .into_iter()+ .map(str::to_string)+ .collect(),+ )+ .unwrap()+ {+ Cmd::Remove(cfg) => cfg,+ other => panic!("expected remove, got {other:?}"),+ };+ assert_eq!(+ cfg.state_dir.as_deref(),+ Some(std::path::Path::new("/tmp/j"))+ );assert!(err(&["data", "--root", "/tmp/a"]).contains("only supported with"));assert!(err(&["remove", "--prefix", "proj", "--approve", "proceed"]).contains("--yes"));assert!(super::help_text().contains("autoindex remove"));@@ -3107,9 +3133,9 @@ mod tests {}}- /// The graph route DOES reindex a modified file; what it cannot do is an- /// add or a delete. The help asserted the retracted version for as long as- /// the docs did, and pointed at a help section that does not exist.+ /// The graph route sweeps a deletion and indexes an addition that fits a+ /// frozen dataset. The help used to say a deletion aborts, and pointed at+ /// a help section that does not exist.#[test]fn the_watch_help_does_not_repeat_the_retracted_graph_claim() {let help = super::help_text();@@ -3117,7 +3143,11 @@ mod tests {!help.contains("only that route reindexes"),"the --watch help repeats the retracted claim about the graph route");- for expected in ["refuses an ADDED file", "ABORTS on a deletion"] {+ assert!(+ !help.contains("ABORTS on a deletion"),+ "the --watch help still says a deletion aborts"+ );+ for expected in ["sweeps a deleted", "files-removed", "stale-resume-plan"] {assert!(help.contains(expected),"--watch help is missing {expected:?}"diff --git a/engine/crates/xerj-autoindex/src/content.rs b/engine/crates/xerj-autoindex/src/content.rsindex d13b87d83..2afb0d894 100644--- a/engine/crates/xerj-autoindex/src/content.rs+++ b/engine/crates/xerj-autoindex/src/content.rs@@ -212,23 +212,52 @@ fn resolve_with_digests(files: Vec<FileEntry>, digests: Vec<String>) -> Result<I})}+/// A source file moved under the run after it was hashed (#1031, #1911, #2314).+///+/// The display text is the operator message. `path` is the live source, so a+/// seal that noticed the change on the staged copy can still name the file+/// the caller has to skip.+#[derive(Debug, Clone)]+pub struct SourceChanged {+ pub path: std::path::PathBuf,+ pub detail: String,+}++impl std::fmt::Display for SourceChanged {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(&self.detail)+ }+}++impl std::error::Error for SourceChanged {}+pub fn verify(path: &Path, expected_size: u64, expected_digest: &str) -> Result<()> {let actual_size = std::fs::metadata(path).with_context(|| format!("stat {}", path.display()))?.len();- anyhow::ensure!(- actual_size == expected_size,- "{} changed size during autoindex (expected {}, now {}); retry the run",- path.display(),- expected_size,- actual_size- );+ if actual_size != expected_size {+ return Err(SourceChanged {+ path: path.to_path_buf(),+ detail: format!(+ "{} changed size during autoindex (expected {}, now {}); retry the run",+ path.display(),+ expected_size,+ actual_size+ ),+ }+ .into());+ }let actual = full_digest(path, actual_size)?;- anyhow::ensure!(- actual == expected_digest,- "{} changed content during autoindex; retry the run",- path.display()- );+ if actual != expected_digest {+ return Err(SourceChanged {+ path: path.to_path_buf(),+ detail: format!(+ "{} changed content during autoindex; retry the run",+ path.display()+ ),+ }+ .into());+ }Ok(())}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex 7d47d2363..e6642c80a 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -454,11 +454,17 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {.retain(|_, doc| doc.get("file_key").and_then(Value::as_str) != Some(key.as_str()));}// Catalog only: every by-`_id` delete this client issues names- // `catalog::CATALOG_INDEX`.+ // `catalog::CATALOG_INDEX`. Report how many documents this pass+ // actually removed. `delete_by_query` repeats until a pass reports+ // zero, so answering `ids.len()` after the documents are gone loops+ // until the client gives up (#2314).+ let mut removed = 0u64;for id in &ids {- locked.catalog_docs.remove(id);+ if locked.catalog_docs.remove(id).is_some() {+ removed += 1;+ }}- (200, json!({"deleted": ids.len(), "failures": []}))+ (200, json!({"deleted": removed, "failures": []}))} else if method == "GET" && path.ends_with("/_count") {if state.lock().unwrap().fail_counts {(200, json!({"error": "count unavailable"}))@@ -606,6 +612,61 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {}),)}+ } else if path.contains(catalog::CATALOG_INDEX)+ && query.pointer("/query/bool/filter").is_some()+ {+ // #2314: a deletion sweep reads catalog candidates with a+ // `bool.filter` of term clauses and deletes the hits by `_id`.+ // An empty `hits` array made that sweep a no-op.+ let filters = query+ .pointer("/query/bool/filter")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let locked = state.lock().unwrap();+ let mut hits: Vec<Value> = locked+ .catalog_docs+ .iter()+ .filter(|(_, doc)| {+ filters.iter().all(|clause| {+ clause+ .get("term")+ .and_then(Value::as_object)+ .is_none_or(|term| {+ term.iter()+ .all(|(field, value)| doc.get(field) == Some(value))+ })+ && clause+ .get("terms")+ .and_then(Value::as_object)+ .and_then(|terms| terms.iter().next())+ .is_none_or(|(field, values)| {+ values.as_array().is_some_and(|values| {+ values.iter().any(|value| doc.get(field) == Some(value))+ })+ })+ })+ })+ .map(|(id, doc)| json!({"_id": id, "_source": doc}))+ .collect();+ hits.sort_by(|left, right| left["_id"].as_str().cmp(&right["_id"].as_str()));+ let total = hits.len();+ let from = query.get("from").and_then(Value::as_u64).unwrap_or(0) as usize;+ let size = query+ .get("size")+ .and_then(Value::as_u64)+ .map(|size| size as usize)+ .unwrap_or(total);+ let page: Vec<Value> = hits.into_iter().skip(from).take(size).collect();+ (+ 200,+ json!({+ "hits": {+ "total": {"value": total, "relation": "eq"},+ "hits": page+ }+ }),+ )} else {let ax_file = query.pointer("/query/term/ax_file")@@ -984,63 +1045,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()),- ("GET".to_owned(), "/_cat/allocation?format=json".to_owned(),),- ],- "a refused attempt may perform only the readiness GET and the read-only flood-stage probe"- );- 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("no longer exist in the folder"),- "{message}"- );- assert!(- message.contains("restore the DELETED file(s) and rerun"),- "{message}"- );- assert!(- message.contains("rebuild in place by deleting the indices"),- "{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}"- );- }-}-/// The documented headline workflow: point autoindex at a folder, add a file,/// rerun. The rerun must not fail, must say plainly that the added file was/// not indexed, and `--fresh` must then absorb it in place.@@ -1451,44 +1455,28 @@ fn a_rerun_after_an_added_file_succeeds_and_fresh_absorbs_it() {assert_eq!(run_index(config.clone()).unwrap(), 0);fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();- // 3 = stale-resume-plan: the added file is reported as skipped, not- // indexed, because the frozen plan cannot absorb it. It is not junk.+ // #2314: a csv that fits the frozen dataset is indexed on the rerun.+ // It is not a stale plan and not junk.let (code, report) = run_index_report(config.clone()).unwrap();- assert_eq!(code, 3);+ assert_eq!(code, 0, "{report:?}");let report = report.unwrap();- assert_eq!(- report["files_junk"], 0,- "a post-plan file is not junk: {report}"+ assert_eq!(report["files_junk"], 0, "{report}");+ assert!(+ report.get("skipped_appeared").is_none(),+ "a same-schema addition is indexed, not skipped: {report}");- // #346 / #2076: the file that appeared after the plan was frozen is- // `skipped_appeared`, and it is not folded into `files_junk`.- assert_eq!(report["skipped_appeared"], 1, "{report}");- // `records_total` is the live server-side count (#195), so it still reports- // the record the first run published. What must be zero is the run-local- // counter: this rerun indexed nothing, because the frozen plan cannot- // absorb a file that appeared after it was written.- assert_eq!(report["records_submitted_this_run"], 0, "{report}");- assert_eq!(report["files_submitted_this_run"], 0, "{report}");- // Two live documents for the one indexed source, not one: this module now- // indexes graph-enabled (`--no-graph` takes the generated executor), and a- // graph-enabled run publishes a file-level node document alongside the row.- // `second.csv` still published nothing — that is what the counters above- // pin.- assert_eq!(report["records_total"], 2, "{report}");{let locked = endpoint.state.lock().unwrap();- let live: Vec<&str> = locked+ let live: std::collections::HashSet<&str> = locked.docs.values().filter_map(|doc| doc["ax_path"].as_str()).collect();- assert!(- live.iter().all(|path| *path == "first.csv"),- "the added file must not be published by a plan that predates it: {live:?}"- );+ assert!(live.contains("first.csv"), "{live:?}");+ assert!(live.contains("second.csv"), "{live:?}");}- // --fresh rebuilds the plan in place and picks the new file up.+ // --fresh still rebuilds in place and keeps both files.config.fresh = true;assert_eq!(run_index(config).unwrap(), 0);let locked = endpoint.state.lock().unwrap();@@ -1696,7 +1684,7 @@ fn a_file_that_changes_mid_run_is_skipped_and_the_run_finishes() {}#[test]-fn completed_plan_rejects_vanished_content_group_before_remote_mutation() {+fn completed_plan_sweeps_a_vanished_content_group() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());@@ -1712,11 +1700,26 @@ fn completed_plan_rejects_vanished_content_group_before_remote_mutation() {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"]);+ assert_eq!(run_index(config).unwrap(), 3);+ let locked = endpoint.state.lock().unwrap();+ let live: std::collections::HashSet<&str> = locked+ .docs+ .values()+ .filter_map(|doc| doc["ax_path"].as_str())+ .collect();+ assert!(live.contains("first.csv"), "{live:?}");+ assert!(!live.contains("second.csv"), "{live:?}");+ assert!(locked+ .catalog_docs+ .values()+ .all(|doc| doc["path"].as_str() != Some("second.csv")));}#[test]-fn completed_plan_rejects_mixed_membership_delta_in_stable_order() {+/// #2314: a rerun that both deletes indexed files and adds same-schema files+/// used to refuse before any mutation. The deletions are swept and the+/// additions are indexed.+fn completed_plan_sweeps_deletions_and_indexes_same_schema_additions() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());@@ -1728,44 +1731,28 @@ fn completed_plan_rejects_mixed_membership_delta_in_stable_order() {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);+ let 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()),- ("GET".to_owned(), "/_cat/allocation?format=json".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())+ assert_eq!(run_index(config).unwrap(), 3);+ let locked = endpoint.state.lock().unwrap();+ let live: std::collections::HashSet<&str> = locked+ .docs+ .values()+ .filter_map(|doc| doc["ax_path"].as_str()).collect();- assert_eq!(added, ["m-new.csv", "z-new.csv"]);- assert_eq!(vanished, ["a-old.csv", "b-old.csv"]);+ assert!(+ live.contains("m-new.csv") && live.contains("z-new.csv"),+ "{live:?}"+ );+ assert!(+ !live.contains("a-old.csv") && !live.contains("b-old.csv"),+ "{live:?}"+ );}/// An in-place EDIT is a replacement, not a removal. `--fresh` is the route@@ -2052,9 +2039,8 @@ impl Jobs {\n\}\n\";-/// The composite workflow the run's own stderr recommends: index, then add one-/// file and edit another, rerun (added file reported and skipped by the frozen-/// plan), then `--fresh` to absorb both.+/// Index, then add one file and edit another. The rerun replaces the edit and+/// indexes the addition (#2314). `--fresh` afterwards keeps both.#[test]fn fresh_absorbs_an_addition_and_an_edit_after_a_reported_rerun() {let _guard = FAILPOINT_TEST_LOCK@@ -2072,10 +2058,27 @@ fn fresh_absorbs_an_addition_and_an_edit_after_a_reported_rerun() {fs::write(corpus.path().join("first.csv"), "id,value\n1,after\n").unwrap();fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();- // 3 = stale-resume-plan: the frozen plan cannot absorb the added file,- // so the rerun reports it as skipped rather than refusing, and does not- // count it as junk.- assert_eq!(run_index(config.clone()).unwrap(), 3);+ assert_eq!(+ run_index(config.clone()).unwrap(),+ 0,+ "an edit is replaced and a same-schema addition is indexed"+ );+ {+ let locked = endpoint.state.lock().unwrap();+ let live: std::collections::HashSet<&str> = locked+ .docs+ .values()+ .filter_map(|doc| doc["ax_path"].as_str())+ .collect();+ assert!(+ live.contains("first.csv") && live.contains("second.csv"),+ "{live:?}"+ );+ assert!(locked+ .docs+ .values()+ .any(|doc| doc["value"].as_str() == Some("after")));+ }config.fresh = true;assert_eq!(@@ -2101,8 +2104,11 @@ fn fresh_absorbs_an_addition_and_an_edit_after_a_reported_rerun() {);}+/// #2314: `--fresh` used to be refused when a file had disappeared, because+/// discarding the journal does not delete documents. The sweep runs first, so+/// the deleted file's documents are gone and the added file is indexed.#[test]-fn fresh_cannot_erase_the_plan_and_bypass_the_removal_gate() {+fn fresh_sweeps_a_deleted_file_and_indexes_the_addition() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());@@ -2119,7 +2125,15 @@ fn fresh_cannot_erase_the_plan_and_bypass_the_removal_gate() {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"]);+ assert_eq!(run_index(config).unwrap(), 3);+ let locked = endpoint.state.lock().unwrap();+ let live: std::collections::HashSet<&str> = locked+ .docs+ .values()+ .filter_map(|doc| doc["ax_path"].as_str())+ .collect();+ assert!(live.contains("new.csv"), "{live:?}");+ assert!(!live.contains("old.csv"), "{live:?}");}/// #345. A byte-identical duplicate is the ONLY thing that makes a run issue@@ -2332,13 +2346,25 @@ fn deleted_planned_junk_is_swept_rather_than_refused() {);}- // Deleting the INDEXED file is still refused: its documents are live.+ // Deleting the indexed file sweeps its documents too (#2314).fs::remove_file(corpus.path().join("rows.csv")).unwrap();- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["rows.csv"]);+ assert_eq!(run_index(config).unwrap(), 3);+ let locked = endpoint.state.lock().unwrap();+ assert!(locked+ .docs+ .values()+ .all(|doc| doc["ax_path"].as_str() != Some("rows.csv")));+ assert!(locked+ .catalog_docs+ .values()+ .all(|doc| doc["path"].as_str() != Some("rows.csv")));}#[test]-fn completed_plan_rejects_empty_current_folder_before_remote_mutation() {+/// #2314: emptying the folder sweeps the indexed file, including under+/// `--fresh`. Discarding the journal used to leave the documents live and+/// the command refused rather than recover.+fn emptying_the_folder_sweeps_the_indexed_file_including_fresh() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());@@ -2353,11 +2379,23 @@ fn completed_plan_rejects_empty_current_folder_before_remote_mutation() {assert_eq!(run_index(config.clone()).unwrap(), 0);fs::remove_file(corpus.path().join("only.csv")).unwrap();- assert_unsupported_delta_without_remote_mutation(&endpoint, config.clone(), &[], &["only.csv"]);- // Even `--fresh` must not erase the only durable inventory evidence and- // then report success while the destination still contains the document.+ assert_eq!(run_index(config.clone()).unwrap(), 3);+ assert!(endpoint+ .state+ .lock()+ .unwrap()+ .docs+ .values()+ .all(|doc| doc["ax_path"].as_str() != Some("only.csv")));config.fresh = true;- assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["only.csv"]);+ assert_eq!(run_index(config).unwrap(), 0);+ assert!(endpoint+ .state+ .lock()+ .unwrap()+ .docs+ .values()+ .all(|doc| doc["ax_path"].as_str() != Some("only.csv")));}#[test]@@ -2584,7 +2622,10 @@ fn changed_source_replaces_durable_dataset_bytes_across_reopen() {}#[test]-fn deleted_path_bytes_remain_while_its_documents_remain_live() {+/// #2314: deleting one of two indexed files removes its documents. Dataset+/// bytes then describe what is still live, and a second rerun sees the same+/// settled corpus.+fn deleted_path_documents_are_swept_and_bytes_follow_the_survivor() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());@@ -2613,28 +2654,19 @@ fn deleted_path_bytes_remain_while_its_documents_remain_live() {assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 4);fs::remove_file(&removed).unwrap();- // Autoindex still does not reconcile a missing canonical path: its indexed- // documents and FileDone stay live, so dataset bytes must keep describing- // that durable live index rather than silently pretend deletion (#249).- // What changed is the exit: the rerun that used to return 0 while leaving- // those documents stranded now refuses before any remote mutation. Run- // twice — a refusal is a stop, not a state change, so the second attempt- // must see exactly what the first one saw.- for _ in 0..2 {- assert_unsupported_delta_without_remote_mutation(- &endpoint,- config.clone(),- &[],- &["removed.csv"],- );- // Row documents only: this module indexes graph-enabled now that- // `--no-graph` takes the generated executor, so each source also- // publishes one file-level node document.- assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 4);- assert_eq!(- dataset_catalog_docs(&endpoint)[0]["bytes"],- durable_live_bytes- );+ let retained_bytes = fs::metadata(&retained).unwrap().len();+ // The sweep is exit 3 (files-removed). The next rerun of the settled+ // folder is exit 0: nothing left to remove.+ for expected in [3, 0] {+ assert_eq!(run_index(config.clone()).unwrap(), expected);+ let locked = endpoint.state.lock().unwrap();+ let rows = data_rows(&locked);+ assert_eq!(rows.len(), 2, "the removed file's rows are gone");+ assert!(rows+ .iter()+ .all(|doc| doc["ax_path"].as_str() == Some("retained.csv")));+ drop(locked);+ assert_eq!(dataset_catalog_docs(&endpoint)[0]["bytes"], retained_bytes);}}@@ -3365,12 +3397,10 @@ fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {.all(|doc| doc["value"].as_str() == Some("rewritten")));}-/// #238: a file added after the plan was frozen is skipped and reported in the-/// catalog. That report used to be immortal — `new_unplanned` was a per-run-/// `Vec`, so once the file left the corpus nothing remembered the document had-/// 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.+/// #2314: a same-schema file added after the plan was frozen is indexed.+/// Deleting it afterwards must take its catalog row with 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() {@@ -3391,56 +3421,34 @@ fn an_added_then_deleted_file_leaves_no_immortal_catalog_entry() {let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);assert_eq!(run_index(config.clone()).unwrap(), 0);- // Appears after the plan froze: not indexed, but reported as skipped.+ // Appears after the plan froze and fits the frozen dataset: indexed.fs::write(corpus.path().join("added.csv"),"id,value\n2,added\n3,added\n",).unwrap();- assert_eq!(run_index(config.clone()).unwrap(), 3);- let skipped_id = {+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ let indexed_id = {let locked = endpoint.state.lock().unwrap();let (id, doc) = locked.catalog_docs.iter().find(|(_, doc)| doc["path"].as_str() == Some("added.csv"))- .expect("a file skipped for being post-freeze is reported in the catalog");- assert_eq!(doc["status"].as_str(), Some("stale-plan"));+ .expect("a same-schema addition is reported in the catalog");assert_eq!(doc["doc_kind"].as_str(), Some("file"));+ assert_ne!(doc["status"].as_str(), Some("stale-plan"));id.clone()};- // The durable plan is the only record that the document exists. Without- // it no later run can ever delete it.- let replay = state::Journal::open(- state_dir.path(),- &config.root.to_string_lossy(),- &config.url,- &config.prefix,- config.bulk_timeout_secs,- false,- )- .unwrap();- assert!(- replay- .plan- .as_ref()- .unwrap()- .junk_files- .iter()- .any(|junk| junk.rel == "added.csv"),- "the skipped file must be recorded in the durable plan"- );- drop(replay);-- // Delete it: the catalog entry goes with it, and the run is clean again.+ // Delete it: the catalog entry goes with it. Exit 3 names the removal;+ // the following rerun of the settled folder is exit 0.fs::remove_file(corpus.path().join("added.csv")).unwrap();- assert_eq!(run_index(config.clone()).unwrap(), 0);+ assert_eq!(run_index(config.clone()).unwrap(), 3);{let locked = endpoint.state.lock().unwrap();assert!(- !locked.catalog_docs.contains_key(&skipped_id),- "the catalog entry for a deleted skipped file must not survive"+ !locked.catalog_docs.contains_key(&indexed_id),+ "the catalog entry for a deleted added file must not survive");assert!(locked@@ -3449,6 +3457,10 @@ fn an_added_then_deleted_file_leaves_no_immortal_catalog_entry() {.all(|doc| doc["path"].as_str() != Some("added.csv")),"no catalog document may still name the deleted file");+ assert!(locked+ .docs+ .values()+ .all(|doc| doc["ax_path"].as_str() != Some("added.csv")));// The file that is still there keeps its entry.assert!(locked.catalog_docs@@ -3484,20 +3496,13 @@ fn deleting_an_entire_duplicate_group_strands_no_pending_replacement() {assert_eq!(run_index(config.clone()).unwrap(), 0);let starts = event_count(state_dir.path(), "file_replace_start");- // The whole duplicate group disappears: its documents stay live with no- // source file, so the rerun is refused. The original invariant still- // holds and is still checked — a key with no current file must never get- // a replacement intent journaled, which would be re-appended forever- // without ever committing.+ // The whole duplicate group disappears. Its documents are swept (#2314).+ // A key with no current file must still never get a replacement intent+ // journaled, which would be re-appended forever without ever committing.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"],- );+ for expected in [3, 0] {+ assert_eq!(run_index(config.clone()).unwrap(), expected);assert_eq!(event_count(state_dir.path(), "file_replace_start"),starts,@@ -3513,6 +3518,25 @@ fn deleting_an_entire_duplicate_group_strands_no_pending_replacement() {).unwrap();assert!(replay.pending_replacements.is_empty());+ let locked = endpoint.state.lock().unwrap();+ let live: std::collections::HashSet<&str> = locked+ .docs+ .values()+ .filter_map(|doc| doc["ax_path"].as_str())+ .collect();+ assert!(live.contains("keep.csv"), "{live:?}");+ assert!(+ !live.contains("dup-a.csv") && !live.contains("dup-b.csv"),+ "{live:?}"+ );+ assert!(locked.catalog_docs.values().all(|doc| {+ let path = doc["path"].as_str();+ path != Some("dup-a.csv") && path != Some("dup-b.csv")+ }));+ assert!(replay+ .done+ .values()+ .all(|done| done.path != "dup-a.csv" && done.path != "dup-b.csv"));}}diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 233a18680..983a7fd56 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -116,6 +116,11 @@ struct HttpState {/// a serial index phase.in_flight_data_bulks: usize,max_concurrent_data_bulks: usize,+ /// #2314: the next N catalog searches that filter on `file_key` omit the+ /// last hit and report that shorter total. The visibility race four+ /// identical files hit. The counter, not refresh, clears it, so the+ /// recount after refresh sees the full set.+ short_catalog_file_key_pages: usize,}struct HttpEndpoint {@@ -294,8 +299,21 @@ fn handle_http(mut stream: TcpStream, state: &Arc<Mutex<HttpState>>) {}} else if method == "POST" && path == "/_bulk" {let locked = state.lock().unwrap();+ let writes_data = body.split(|byte| *byte == b'\n').any(|line| {+ serde_json::from_slice::<Value>(line)+ .ok()+ .and_then(|action| {+ action+ .pointer("/index/_index")+ .or_else(|| action.pointer("/update/_index"))+ .and_then(Value::as_str)+ .map(|index| index != catalog::CATALOG_INDEX)+ })+ .unwrap_or(false)+ });assert!(- locked.saw_dataset_mapping_update && locked.saw_catalog_mapping_update,+ locked.saw_catalog_mapping_update+ && (!writes_data || locked.saw_dataset_mapping_update),"bulk publication preceded exact generation mapping updates");drop(locked);@@ -906,7 +924,7 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value.map(str::to_owned).collect()});- let locked = state.lock().unwrap();+ let mut locked = state.lock().unwrap();// #890: a catalog field an older build left as `text` is ANALYZED, so a// `term` on it matches tokens, not the raw value. `legacy` is empty for// every other index, which keeps every other search byte-exact.@@ -1011,6 +1029,18 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> ValueSome((field, _)) => matching.sort_by(|(_, a), (_, b)| cmp_docs_by_field(a, b, field)),None => matching.sort_by_key(|(key, _)| *key),}+ // #2314: one short catalog page, internally consistent (total matches the+ // hits actually returned). The per-group equality then falls short and+ // the retry after refresh must see the document that was held back.+ let catalog_file_key_page = indices.contains(&catalog::CATALOG_INDEX)+ && filters+ .iter()+ .any(|filter| filter.pointer("/terms/file_key").is_some());+ let mut shorten = false;+ if catalog_file_key_page && locked.short_catalog_file_key_pages > 0 && matching.len() > 1 {+ matching.pop();+ shorten = true;+ }let total = matching.len();let from = query.get("from")@@ -1063,6 +1093,10 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> ValueValue::Object(body)}).unwrap_or_else(|| json!({}));+ drop(matching);+ if shorten {+ locked.short_catalog_file_key_pages -= 1;+ }json!({"hits": {"total": {"value": total, "relation": "eq"},@@ -7215,3 +7249,128 @@ mod delete_gate {}}}++/// #2314: four identical empty files must not abort on the catalog+/// canonical/alias count. They are junk (no rows), recorded, and a rerun+/// confirms instead of failing the equality that a one-shot read used to+/// trip.+#[test]+fn four_identical_empty_files_do_not_fail_the_catalog_count() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ for name in ["a.txt", "b.txt", "c.txt", "d.txt"] {+ fs::write(corpus.path().join(name), "").unwrap();+ }+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);+ let result = run_index_report(config.clone());+ let message = match &result {+ Ok((code, summary)) => format!("code={code} summary={summary:?}"),+ Err(error) => format!("{error:#}"),+ };+ assert!(+ !message.contains("catalog canonical/alias count disagrees"),+ "{message}"+ );+ let (code, _) = result.expect("four identical empty files must not abort the run");+ assert_eq!(code, 3, "empty files are recorded junk, not a failure");+ assert_eq!(run_index(config).unwrap(), 3);+}++/// #2314: the catalog canonical/alias read can come back one document+/// short, the race a folder of identical files hit. The check refreshes+/// and recounts; the run completes and the alias documents stay.+#[test]+fn a_short_catalog_alias_page_is_recounted_instead_of_aborting() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let body = "id,value\n1,same\n";+ for name in ["a.csv", "b.csv", "c.csv", "d.csv"] {+ fs::write(corpus.path().join(name), body).unwrap();+ }+ let endpoint = HttpEndpoint::start();+ endpoint.state.lock().unwrap().short_catalog_file_key_pages = 1;+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);+ let (code, summary) = run_index_report(config)+ .expect("a one-document-short catalog page must be recounted, not abort the generation");+ assert_eq!(code, 0, "{summary:?}");+ let summary = summary.expect("the generation commits");+ assert_eq!(summary["duplicate_files"], 3, "{summary}");+ assert_eq!(+ endpoint.state.lock().unwrap().short_catalog_file_key_pages,+ 0,+ "the short page must have been consumed by the first count"+ );+ let refreshes = endpoint+ .state+ .lock()+ .unwrap()+ .requests+ .iter()+ .filter(|(method, path)| {+ method == "POST" && path.contains("/_refresh") && path.contains(catalog::CATALOG_INDEX)+ })+ .count();+ assert!(+ refreshes >= 1,+ "the short count refreshes the catalog before recounting"+ );+}++/// #2314: a file that changes size between the hash and the snapshot seal+/// is skipped. The rest of the folder is indexed, the run exits 3, and+/// the next run indexes the file's current bytes.+#[test]+fn a_file_that_changes_size_during_snapshot_seal_is_skipped() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("stable.csv"), "id,value\n1,stable\n").unwrap();+ let changing = corpus.path().join("live.csv");+ fs::write(&changing, "id,value\n1,before\n").unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);+ let grow = changing.clone();+ sync_executor::arm_snapshot_source_hook(state_dir.path(), move || {+ let mut file = fs::OpenOptions::new().append(true).open(&grow).unwrap();+ file.write_all(b"2,after\n").unwrap();+ });+ let (code, summary) = run_index_report(config.clone())+ .expect("one file changing size during the seal must not abort the run");+ assert_eq!(+ code, 3,+ "the changing file is junk, not a failure: {summary:?}"+ );+ let indexed = paths(&endpoint.data_docs());+ assert!(+ indexed.iter().any(|path| path == "stable.csv"),+ "{indexed:?}"+ );+ assert!(+ indexed.iter().all(|path| path != "live.csv"),+ "the changing file must not be published from a torn read: {indexed:?}"+ );++ let (again, _) = run_index_report(config).expect("the settled file indexes on the rerun");+ assert_eq!(again, 0);+ let indexed = paths(&endpoint.data_docs());+ assert!(indexed.iter().any(|path| path == "live.csv"), "{indexed:?}");+ assert!(+ endpoint+ .data_docs()+ .iter()+ .any(|doc| doc.get("value").and_then(Value::as_str) == Some("after")),+ "the rerun indexes the bytes the file settled on"+ );+}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex a075c9037..8b42dda06 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -481,6 +481,30 @@ fn dataset_create_body(dataset: &PlanDataset) -> Value {dataset_mapping_body(dataset, &[])}+/// Mapping upgrade for an index the graph path already created.+///+/// `ensure_index` does not resend the body once the index exists, and a full+/// properties PUT can 400 when an older dynamic type disagrees. The upgrade+/// sends `ax_paths` plus scalar fields an incremental absorb added after the+/// schema was frozen (#2176, #2314) — names the frozen mapping does not have.+fn graph_mapping_upgrade(plan: &Plan, dataset: &PlanDataset) -> Value {+ let mut properties = serde_json::Map::new();+ properties.insert("ax_paths".into(), json!({"type": "keyword"}));+ for spec in extra_fields(plan, &dataset.slug) {+ if properties.contains_key(&spec.name) {+ continue;+ }+ let property = match spec.es_type.as_str() {+ "date" => {+ json!({"type": "date", "format": "strict_date_optional_time||epoch_millis"})+ }+ es_type => json!({"type": es_type}),+ };+ properties.insert(spec.name.clone(), property);+ }+ json!({"properties": properties})+}+fn extra_fields<'a>(plan: &'a Plan, slug: &str) -> &'a [infer::FieldSpec] {plan.incremental_fields.get(slug)@@ -1415,12 +1439,22 @@ const ALIAS_SWEEP_FAILED_REASON: &str = "catalog-alias-sweep-failed";////// Distinct from `completed-with-junk`. Those files are content the plan/// predates, not unusable input, and counting them as junk made a resume look-/// like an ordinary successful-with-junk run. The graph path does not-/// re-cluster a frozen plan (dataset identity and graph anchors stay put);-/// `--no-graph` is the route that reconciles additions. `--fresh` rebuilds-/// this plan in place and includes the files.+/// like an ordinary successful-with-junk run. A file that fits a frozen+/// dataset is absorbed in place (#2314). A file that needs a new dataset is+/// not: dataset identity and graph anchors stay put, and `--fresh` rebuilds+/// the plan in place to include it. `--no-graph` reconciles both.const STALE_RESUME_PLAN_REASON: &str = "stale-resume-plan";+/// `xerj-done` reason when a graph-path rerun removed documents for files+/// that left the folder (#2314).+///+/// Exit 3, not 0: a removal used to look like a no-op resume while the+/// documents stayed live, and exit 0 is what that bug printed. The index+/// matches the folder afterwards — this is success, the same way junk is —+/// and the next unchanged rerun is exit 0. Distinct from+/// `completed-with-junk`: the files were usable, they are gone.+const FILES_REMOVED_REASON: &str = "files-removed";+/// Catalog / plan status for a file the frozen resume plan does not cover.const STALE_RESUME_PLAN_STATUS: &str = "stale-plan";@@ -1526,6 +1560,7 @@ pub(crate) fn outcome_headline(junk_records: u64,alias_sweep_failed: bool,stale_plan_files: u64,+ files_removed: u64,) -> String {if code != 3 {return format!("ok: indexed and searchable (exit {code}, completed)");@@ -1566,6 +1601,27 @@ pub(crate) fn outcome_headline(condition clears");}+ if files_removed > 0 {+ let files = estimate::count_phrase(files_removed, "file", "files");+ let mut line = format!(+ "ok: indexed and searchable — exit 3 ({FILES_REMOVED_REASON}) is SUCCESS, not an \+ error: removed documents for {files} that no longer exist in the folder"+ );+ if junk_files > 0 || junk_records > 0 {+ let mut recorded = Vec::new();+ if junk_files > 0 {+ recorded.push(estimate::count_phrase(junk_files, "file", "files"));+ }+ if junk_records > 0 {+ recorded.push(estimate::count_phrase(junk_records, "record", "records"));+ }+ line.push_str(&format!(+ ". Also recorded as junk: {}",+ recorded.join(" and ")+ ));+ }+ return line;+ }let mut recorded = Vec::new();if junk_files > 0 {recorded.push(estimate::count_phrase(junk_files, "file", "files"));@@ -1686,6 +1742,148 @@ fn note_neural_ingest_cost(}}+fn recount_plan_file_counts(plan: &mut Plan) {+ for dataset in &mut plan.datasets {+ dataset.file_count = plan+ .files+ .values()+ .filter(|assignment| {+ assignment+ .assignments+ .iter()+ .any(|(_, slug)| *slug == dataset.slug)+ })+ .count();+ }+}++/// A schema refusal from [`reconcile_plan`], which tells the operator to+/// rebuild. On the graph path that rebuild is `--fresh` (a new dataset), not+/// a permanent junk row, so these files stay unplanned and the stale-plan+/// note names `--fresh`.+fn schema_evolution_junk(junk: &JunkFile) -> bool {+ junk.reason.contains("Stop the watcher and rebuild")+ || junk.reason.contains("no frozen dataset accepts")+ || junk.reason.contains("refusing ambiguous assignment")+ || junk.reason.contains("unsupported dataset/schema evolution")+}++/// Fold files that appeared after a graph plan was frozen into that plan+/// when they fit a dataset it already has (#2314).+///+/// A no-op resume (every key already planned or junk) does not call+/// [`project_reconcile_plan`], so the durable plan is not rewritten just+/// because the projection would re-order junk. Files that need a new dataset+/// are left unplanned: the stale-plan note still names `--fresh`.+fn absorb_compatible_additions(+ plan: &mut Plan,+ inventory: &content::Inventory,+ cfg: &IndexCfg,+ state_dir: &Path,+ pr: &Progress,+ meter: &estimate::Meter,+ tally: &ScanTally,+) -> Result<bool> {+ let unplanned = inventory.keys.iter().any(|key| {+ !key.is_empty()+ && !plan.files.contains_key(key)+ && !plan.junk_files.iter().any(|junk| &junk.file_key == key)+ });+ if !unplanned {+ return Ok(false);+ }+ let projected = match project_reconcile_plan(inventory, plan, cfg, state_dir, pr, meter, tally)+ {+ Ok(projected) => projected,+ Err(error) => {+ pr.note(&format!(+ "autoindex: files added after the resume plan was frozen could not be absorbed \+ ({error:#}); re-run with --fresh to rebuild the plan in place"+ ));+ return Ok(false);+ }+ };+ let inventory_keys: HashSet<&str> = inventory.keys.iter().map(String::as_str).collect();+ let mut changed = false;+ for (key, assignment) in projected.files {+ if !inventory_keys.contains(key.as_str())+ || plan.files.contains_key(&key)+ || plan.junk_files.iter().any(|junk| junk.file_key == key)+ {+ continue;+ }+ plan.files.insert(key, assignment);+ changed = true;+ }+ for junk in projected.junk_files {+ if !inventory_keys.contains(junk.file_key.as_str())+ || plan.files.contains_key(&junk.file_key)+ || plan+ .junk_files+ .iter()+ .any(|existing| existing.file_key == junk.file_key)+ || schema_evolution_junk(&junk)+ {+ continue;+ }+ plan.junk_files.push(junk);+ changed = true;+ }+ for (slug, specs) in projected.incremental_fields {+ let dest = plan.incremental_fields.entry(slug).or_default();+ for spec in specs {+ if dest.iter().any(|existing| existing.name == spec.name) {+ continue;+ }+ dest.push(spec);+ changed = true;+ }+ }+ if changed {+ recount_plan_file_counts(plan);+ }+ Ok(changed)+}++/// Drop one live source out of a generation that is about to seal (#2314).+///+/// Returns false when `path` is not a canonical inventory file, so the caller+/// does not retry a failure it cannot attribute.+fn quarantine_changed_source(+ plan: &mut Plan,+ inventory: &mut content::Inventory,+ path: &Path,+ detail: &str,+) -> bool {+ let Some(index) = inventory.files.iter().position(|file| file.path == path) else {+ return false;+ };+ let key = inventory.keys[index].clone();+ let format = plan+ .files+ .get(&key)+ .map(|assignment| {+ if assignment.gzip {+ format!("{}(gzip)", assignment.family)+ } else {+ assignment.family.clone()+ }+ })+ .unwrap_or_else(|| "unknown".into());+ let file = inventory.files.remove(index);+ inventory.keys.remove(index);+ inventory.digests.remove(index);+ plan.files.remove(&key);+ plan.duplicate_files+ .retain(|alias| alias.file_key != key && plan.files.contains_key(&alias.file_key));+ let error = anyhow::anyhow!("{detail}");+ plan.junk_files.push(changed_during_run_junk(+ &key, &file.rel, &format, file.size, &error,+ ));+ recount_plan_file_counts(plan);+ true+}+#[allow(clippy::too_many_arguments)] // cutover threads the whole run contextfn begin_non_graph_generation(es: &Es,@@ -1720,23 +1918,15 @@ fn begin_non_graph_generation(.context("generation cutover has no committed base")?.clone();let tx_id = format!("{}-g{}", journal.run_id, base.generation + 1);- // #1723: derive the content groups and check the plan's projection onto- // them BEFORE sealing. Both depend only on the plan, the inventory and the- // base; only the counts need the snapshot (`bind_prepared_counts` below).- // A plan that cannot be accepted used to be refused only after the whole- // corpus was sealed — ~25 minutes per attempt on the report's corpus.- let mut groups = desired_content_groups(&base.groups, &plan, inventory)?;- sync::preflight_plan_projection(&plan, &groups).with_context(|| {- format!(- "autoindex refused generation {} before sealing any file: the plan built from this \- walk does not project onto its own content groups, so every run over this input \- fails the same way, --fresh included. No snapshot was written and no remote data \- was changed. This is an autoindex defect for this corpus; please report it with \- this message",- base.generation + 1- )- })?;- let preparation_contract = preparation_contract_digest(cfg, &plan)?;+ let mut plan = plan;+ // #2314: a file that changes between the hash and the seal is dropped and+ // the seal is retried. The owned copy is what the generation publishes.+ let mut sealed = content::Inventory {+ files: inventory.files.clone(),+ keys: inventory.keys.clone(),+ digests: inventory.digests.clone(),+ duplicates: inventory.duplicates.clone(),+ };// #971: the prior committed generation's snapshot is the reuse source for// sealing. A file whose content digest and preparation identity match its// entry there is hardlinked instead of re-copied and re-extracted, so the@@ -1748,18 +1938,91 @@ fn begin_non_graph_generation(.map(|_| sync_executor::open_committed_snapshot(state_dir, &base)).transpose()?;let chunker_identity = prepared_records_identity(cfg)?;- let snapshot = sync_executor::create_prepared_snapshot_reporting(- state_dir,- &tx_id,- inventory,- &plan,- &preparation_contract,- cfg.snapshot_max_bytes,- pr,- prior_snapshot.as_ref(),- &chunker_identity,- labeler,- )?;+ let (snapshot, mut groups) = {+ let mut prepared = None;+ let mut groups_out = None;+ // One file leaves per attempt, plus the successful seal.+ let max_attempts = sealed.files.len().saturating_add(2).max(1);+ for _attempt in 0..max_attempts {+ let failing: Vec<(std::path::PathBuf, String)> = sealed+ .files+ .iter()+ .zip(sealed.digests.iter())+ .filter_map(|(file, digest)| {+ content::verify(&file.path, file.size, digest)+ .err()+ .map(|error| (file.path.clone(), format!("{error:#}")))+ })+ .collect();+ let mut quarantined = false;+ for (path, detail) in failing {+ if quarantine_changed_source(&mut plan, &mut sealed, &path, &detail) {+ quarantined = true;+ pr.note(&format!(+ "warning: {} changed while this run was reading it, so it was skipped \+ ({detail})",+ path.display()+ ));+ }+ }+ if quarantined {+ continue;+ }+ // #1723: derive the content groups and check the plan's projection+ // onto them BEFORE sealing. A plan that cannot be accepted used to+ // be refused only after the whole corpus was sealed.+ let groups = desired_content_groups(&base.groups, &plan, &sealed)?;+ sync::preflight_plan_projection(&plan, &groups).with_context(|| {+ format!(+ "autoindex refused generation {} before sealing any file: the plan built \+ from this walk does not project onto its own content groups, so every run \+ over this input fails the same way, --fresh included. No snapshot was \+ written and no remote data was changed. This is an autoindex defect for \+ this corpus; please report it with this message",+ base.generation + 1+ )+ })?;+ let preparation_contract = preparation_contract_digest(cfg, &plan)?;+ match sync_executor::create_prepared_snapshot_reporting(+ state_dir,+ &tx_id,+ &sealed,+ &plan,+ &preparation_contract,+ cfg.snapshot_max_bytes,+ pr,+ prior_snapshot.as_ref(),+ &chunker_identity,+ labeler,+ ) {+ Ok(snapshot) => {+ prepared = Some(snapshot);+ groups_out = Some(groups);+ break;+ }+ Err(error) => {+ let Some(changed) = error.downcast_ref::<content::SourceChanged>() else {+ return Err(error);+ };+ let path = changed.path.clone();+ let detail = changed.detail.clone();+ if !quarantine_changed_source(&mut plan, &mut sealed, &path, &detail) {+ return Err(error);+ }+ pr.note(&format!(+ "warning: {} changed while this run was sealing it, so it was skipped \+ ({detail})",+ path.display()+ ));+ }+ }+ }+ let snapshot = prepared.context(+ "autoindex could not seal a snapshot after skipping files that changed during the \+ run",+ )?;+ (snapshot, groups_out.expect("a sealed snapshot has groups"))+ };// #1062: every vote the generated route makes happens during sealing, so// the Labeler's counters are final here — the same accounting the legacy// path prints after its walk, stated where this route's cost was paid.@@ -1820,7 +2083,7 @@ fn begin_non_graph_generation(}};- sync_executor::bind_prepared_counts(&mut groups, &snapshot, &inventory.keys)?;+ sync_executor::bind_prepared_counts(&mut groups, &snapshot, &sealed.keys)?;let (schema_identity, index_identity) = generation_contract_identities(&plan)?;let desired = sync::GenerationManifest {generation: base.generation + 1,@@ -5479,6 +5742,10 @@ struct RefusalTargets {}impl RefusalTargets {+ /// The destination a removal refusal would name. The run sweeps deletions+ /// instead of returning that error (#2314); the constructor stays so the+ /// typed message can still be built from a plan.+ #[allow(dead_code)]fn describe(cfg: &IndexCfg, state_dir: &Path, plan: &Plan) -> Self {let mut data_indices: Vec<String> = plan.datasets.iter().map(|d| d.index.clone()).collect();data_indices.sort();@@ -5724,6 +5991,21 @@ impl std::fmt::Display for UnsupportedInventoryDeltaError {impl std::error::Error for UnsupportedInventoryDeltaError {}+/// Paths of swept content groups, capped the same way a refusal lists them.+fn deleted_group_list(entries: &[InventoryDeltaEntry]) -> String {+ let mut rendered = entries+ .iter()+ .take(REFUSAL_LIST_CAP)+ .map(|entry| entry.path.as_str())+ .collect::<Vec<_>>()+ .join(", ");+ let remaining = entries.len().saturating_sub(REFUSAL_LIST_CAP);+ if remaining > 0 {+ rendered.push_str(&format!(", … and {remaining} more"));+ }+ rendered+}+/// Whether a plan file that vanished from the walk is still on disk (#439).////// The disk probe uses the file's reversible raw-bytes identity (`path_id`:@@ -5880,23 +6162,20 @@ impl UnsupportedInventoryDelta {}}- /// A rerun is refused only when a content group the plan published has- /// vanished from the folder: those documents stay live and searchable with- /// no source file behind them, and nothing in this pipeline removes them.- /// Additions are not refused — they are skipped by the frozen plan exactly- /// as before and `--fresh` rebuilds the plan in place to include them.+ /// Whether the classifier sees a genuine deletion.+ ///+ /// The run does not return [`Self::into_error`] for that anymore (#2314):+ /// both gates sweep `deleted_content_groups` with `sweep_excluded_groups`,+ /// including `--fresh`, which used to be refused because discarding the+ /// journal does not delete published documents. This method stays so the+ /// classifier tests can tell a deletion from an exclusion or an addition.+ /// An exclusion is swept the same way and is not a refusal (#589).+ #[cfg(test)]fn refuses(&self) -> bool {- // #589: only a GENUINE deletion (source file gone from disk) refuses the- // rerun — its published documents would be left live with no file behind- // them and nothing else removes them. An EXCLUSION (file still on disk,- // newly matched by a widened ignore/hidden/`.xerjignore` rule) is data- // the exclusion must REMOVE, so it is SWEPT by `sweep_excluded_groups`- // and the run continues (#439's data-exposure headline). When a genuine- // deletion co-occurs the whole rerun is refused, and `into_error` still- // reports the excluded set too because it also stays live in that case.!self.deleted_content_groups.is_empty()}+ #[cfg(test)]fn into_error(self, targets: RefusalTargets) -> anyhow::Error {UnsupportedInventoryDeltaError {delta: self,@@ -6236,6 +6515,7 @@ fn finish_generated_run(es: &Es, journal: &mut state::Journal, cfg: &IndexCfg) -count("junk_records_total"),false,0,+ 0,));for line in &skip_lines {@@ -8377,6 +8657,12 @@ fn run_index_report_inner();}}+ // #2314: deletions are swept before the journal opens, so `--fresh` (which+ // deletes `journal.ndjson` inside `open_after_preflight`) still has the+ // frozen plan to name the indices and keys. `deleted_file_keys` is then+ // dropped from the resumed plan so the second gate does not see them.+ let mut swept_membership = false;+ let mut deleted_file_keys: HashSet<String> = HashSet::new();if let Some(prior_plan) = preflight.plan.as_ref() {let comparison_keys = if cfg.fresh {inventory.keys.clone()@@ -8394,9 +8680,11 @@ fn run_index_report_inner(.map(|(planned, current)| planned.unwrap_or_else(|| current.clone())).collect()};- // `--fresh` is checked here too: discarding the plan does not delete- // the documents already published for a file that is now gone, so a- // removal is unsafe in place whether or not the plan is kept.+ // #2314: a file that left the folder used to refuse the rerun, and+ // `--fresh` with it, because discarding the journal does not delete+ // documents already published. Sweep them here, with the frozen plan+ // still in hand, the same way an exclusion is swept. `--dry-run`+ // names them and does not mutate.let delta = inventory_delta(&cfg.root,&inventory.files,@@ -8404,13 +8692,42 @@ fn run_index_report_inner(prior_plan,&dataless_skipped_files,);- if delta.refuses() {- return Err(delta.into_error(RefusalTargets::describe(&cfg, &state_dir, prior_plan)));+ if !delta.deleted_content_groups.is_empty() {+ deleted_file_keys.extend(+ delta+ .deleted_content_groups+ .iter()+ .map(|entry| entry.file_key.clone()),+ );+ let count = delta.deleted_content_groups.len();+ let paths = deleted_group_list(&delta.deleted_content_groups);+ if cfg.dry_run {+ pr.note(&format!(+ "autoindex: {count} file(s) indexed under this resume plan no longer exist in \+ the folder ({paths}); a real run removes their documents"+ ));+ } else {+ let edges_index = graph_edges_index(&cfg);+ sweep_excluded_groups(+ &es,+ &cfg.prefix,+ prior_plan,+ &delta.deleted_content_groups,+ edges_index.as_deref(),+ chrono::Utc::now().timestamp_millis(),+ )+ .context("sweep deleted content groups")?;+ swept_membership = true;+ pr.note(&format!(+ "autoindex: removed documents for {count} file(s) that no longer exist in the \+ folder ({paths})"+ ));+ }}// #589: a widened exclusion (file still on disk, newly ignored) is data// the exclusion must remove — sweep the excluded group's documents and- // continue, rather than leaving them live in the destination. Genuine- // deletions above still refuse; never mutate under --dry-run.+ // continue, rather than leaving them live in the destination. Never+ // mutate under --dry-run.if !delta.excluded_content_groups.is_empty() && !cfg.dry_run {let edges_index = graph_edges_index(&cfg);sweep_excluded_groups(@@ -8492,9 +8809,33 @@ fn run_index_report_inner(// `inventory.duplicates` after this block.let mut own_unprefixed_alias_ids: HashSet<String> = HashSet::new();let mut plan_changed = journal.plan.is_none();+ // #2314: drop completions for files swept before the journal opened, so+ // the catalog write below does not advertise them again.+ if journal.plan.is_some() {+ let forgotten: Vec<String> = deleted_file_keys+ .iter()+ .filter(|key| journal.done.contains_key(key.as_str()))+ .cloned()+ .collect();+ for key in forgotten {+ journal.file_removed(&key)?;+ }+ }// Preserve legacy document IDs while upgrading old plans with full digests.// A later same-size/tail mutation is then detected and reindexed.if let Some(plan) = &mut journal.plan {+ if !deleted_file_keys.is_empty() {+ let before = plan.files.len();+ plan.files.retain(|key, _| !deleted_file_keys.contains(key));+ plan.duplicate_files.retain(|alias| {+ !deleted_file_keys.contains(&alias.file_key)+ && plan.files.contains_key(&alias.file_key)+ });+ if plan.files.len() != before {+ recount_plan_file_counts(plan);+ plan_changed = true;+ }+ }let needs_alias_path_migration = !plan.alias_paths_indexed;let previous_aliases = plan.duplicate_files.clone();alias_paths_to_replace.extend(previous_aliases.iter().map(|alias| alias.rel.clone()));@@ -8611,6 +8952,10 @@ fn run_index_report_inner(plan_changed = true;}plan.duplicate_files = inventory.duplicates.clone();+ if absorb_compatible_additions(plan, &inventory, &cfg, &state_dir, &pr, &scan_meter, tally)?+ {+ plan_changed = true;+ }}alias_paths_to_replace.extend(inventory.duplicates.iter().map(|alias| alias.rel.clone()));own_unprefixed_alias_ids.extend(inventory.duplicates.iter().flat_map(|alias| {@@ -8709,27 +9054,62 @@ fn run_index_report_inner(plan};- // Second gate, after key selection has settled: fail before index- // creation/mapping, replacement intent, graph invalidation,- // delete-by-query, bulk publication, refresh, or catalog writes when a- // canonical content group the plan published is gone from the folder.- // Continuing would leave those documents searchable with no source file.- // Additions, same-path replacement and crash repair remain supported.- //- // It runs before the #238 junk sweep below on purpose: a refused rerun- // must compute nothing and mutate nothing.- // An exclusion sweep removes a file's documents without this run re-reading- // anything; a reply edge from a surviving mailbox into the swept one would- // stay live. The corpus-wide mail pass below re-derives those edges when- // this is set (see `carry_over_unread_mail`).+ // Second gate, after key selection has settled. Deletions the first gate+ // already swept are gone from the plan. Anything still classified as a+ // deletion here (a key the first comparison missed) is swept the same way+ // rather than refusing the run (#2314). An exclusion sweep removes a+ // file's documents without this run re-reading anything; a reply edge from+ // a surviving mailbox into the swept one would stay live. The corpus-wide+ // mail pass below re-derives those edges when this is set (see+ // `carry_over_unread_mail`).let mut swept_excluded = false;if resumed_with_plan {let delta = inventory_delta(&cfg.root, &files, &keys, &plan, &dataless_skipped_files);- if delta.refuses() {- return Err(delta.into_error(RefusalTargets::describe(&cfg, &state_dir, &plan)));+ if !delta.deleted_content_groups.is_empty() {+ let gone: HashSet<String> = delta+ .deleted_content_groups+ .iter()+ .map(|entry| entry.file_key.clone())+ .collect();+ let count = delta.deleted_content_groups.len();+ let paths = deleted_group_list(&delta.deleted_content_groups);+ if cfg.dry_run {+ pr.note(&format!(+ "autoindex: {count} file(s) indexed under this resume plan no longer exist in \+ the folder ({paths}); a real run removes their documents"+ ));+ } else {+ swept_membership = true;+ let edges_index = graph_edges_index(&cfg);+ sweep_excluded_groups(+ &es,+ &cfg.prefix,+ &plan,+ &delta.deleted_content_groups,+ edges_index.as_deref(),+ chrono::Utc::now().timestamp_millis(),+ )+ .context("sweep deleted content groups")?;+ pr.note(&format!(+ "autoindex: removed documents for {count} file(s) that no longer exist in the \+ folder ({paths})"+ ));+ }+ plan.files.retain(|key, _| !gone.contains(key));+ plan.duplicate_files.retain(|alias| {+ !gone.contains(&alias.file_key) && plan.files.contains_key(&alias.file_key)+ });+ recount_plan_file_counts(&mut plan);+ plan_changed = true;+ for key in &gone {+ deleted_file_keys.insert(key.clone());+ if journal.done.contains_key(key) {+ journal.file_removed(key)?;+ }+ }}// #589: sweep documents left behind by a widened exclusion (see gate- // above). Genuine deletions still refuse; never mutate under --dry-run.+ // above). Never mutate under --dry-run.if !delta.excluded_content_groups.is_empty() && !cfg.dry_run {swept_excluded = true;let edges_index = graph_edges_index(&cfg);@@ -9088,11 +9468,8 @@ fn run_index_report_inner(.ensure_index(&d.index, &dataset_create_body(d)).with_context(|| format!("create index {}", d.index)).and_then(|()| {- es.update_mapping(- &d.index,- &json!({"properties": {"ax_paths": {"type": "keyword"}}}),- )- .with_context(|| format!("upgrade alias-path mapping for {}", d.index))+ es.update_mapping(&d.index, &graph_mapping_upgrade(&plan, d))+ .with_context(|| format!("upgrade alias-path mapping for {}", d.index))});match installed {Ok(()) => {}@@ -10030,6 +10407,20 @@ fn run_index_report_inner(}}Err(e) => {+ // #2314: extract fails when the file shrinks or vanishes+ // after the pre-extract verify. That is one skipped+ // file. A genuine extract error, with the bytes still+ // what phase A hashed, still aborts the run.+ if let Err(changed) = content::verify(&f.path, f.size, expected_digest) {+ extra_junk.lock().unwrap().push(changed_during_run_junk(+ key,+ &f.rel,+ &format_str(Some(&sn)),+ f.size,+ &changed,+ ));+ continue;+ }send_err = Some(format!("extract {}: {e}", f.rel));extra_junk.lock().unwrap().push(JunkFile {file_key: key.clone(),@@ -10406,7 +10797,7 @@ fn run_index_report_inner(gr,&index_of_slug,&reread,- journal_interrupted || swept_excluded,+ journal_interrupted || swept_excluded || swept_membership,) {Ok(carried) => carried,Err(e) => {@@ -10629,10 +11020,19 @@ fn run_index_report_inner(// classification does not recognise.let (files_done_journaled, journal_records) = {let journal = journal_mx.lock().unwrap();- (- journal.done.len(),- journal.done.values().map(|fd| fd.records).sum::<u64>(),- )+ // #2314: a file swept because it left the folder is still in+ // `journal.done` until the next plan write forgets to republish it.+ // Those records are supposed to be gone. Counting them made a folder+ // that had just been emptied look like a write that never landed.+ let mut files_done_journaled = 0usize;+ let mut journal_records = 0u64;+ for (key, done) in &journal.done {+ if plan.files.contains_key(key) {+ files_done_journaled += 1;+ journal_records += done.records;+ }+ }+ (files_done_journaled, journal_records)};let live_records: u64 = ds_counts.values().sum();if !count_unknown.is_empty() {@@ -10892,6 +11292,11 @@ fn run_index_report_inner({let j = journal_mx.lock().unwrap();for fd in j.done.values() {+ // A swept deletion stays in an older file_done until+ // `file_removed` replays. Do not advertise it (#2314).+ if deleted_file_keys.contains(&fd.file_key) {+ continue;+ }completed_keys.insert(fd.file_key.clone());let current_path = plan.files@@ -11204,6 +11609,17 @@ fn run_index_report_inner(if skipped_appeared > 0 {run_doc["skipped_appeared"] = json!(skipped_appeared);}+ // #2314: present only when this run deleted documents for files that left+ // the folder. A later unchanged rerun does not set it, so exit 0 there is+ // a real no-op and not another removal.+ let files_removed = if swept_membership {+ deleted_file_keys.len() as u64+ } else {+ 0+ };+ if files_removed > 0 {+ run_doc["files_removed"] = json!(files_removed);+ }// #2056: the exit-3 headline stays one line. The paths themselves are a// separate list, capped, with the reason. Present only when something// was skipped, so a clean run document is unchanged.@@ -11291,21 +11707,23 @@ fn run_index_report_inner(// ── summary ──────────────────────────────────────────────────────────let junk_total_records = junk_records.load(Ordering::Relaxed);- // Exit 3 means "completed, some input was unusable". Backend rejections- // are not consulted and must not be: a rejected item aborts the run with- // an error long before this line, so `rejected_records` is provably 0- // here. Splitting them out of `junk_total_records` therefore changes no- // exit code.+ // Exit 3 means "completed, and something about this run is recorded+ // rather than fatal" (`cli.rs` EXIT CODES). Junk is the everyday case.+ // Backend rejections are not consulted and must not be: a rejected item+ // aborts the run with an error long before this line, so+ // `rejected_records` is provably 0 here. Splitting them out of+ // `junk_total_records` therefore changes no exit code.//- // A failed alias sweep lands here too, and on 3 rather than on a code of- // its own: 3 already means "completed, and something about this run is- // recorded rather than fatal" (`cli.rs` EXIT CODES), and inventing a fourth- // success code would break every caller that already branches on 0/3. The- // `reason` is what tells the two apart.+ // A failed alias sweep and a swept deletion land here too, on 3 rather+ // than on a code of their own: inventing another success code would break+ // every caller that already branches on 0/3. The `reason` is what tells+ // them apart. A removal is not exit 0: that is what the run printed when+ // the documents stayed live (#2314).let code = if junk_total_records > 0|| junk_file_count > 0|| alias_sweep_error.is_some()|| skipped_appeared > 0+ || files_removed > 0{3} else {@@ -11322,6 +11740,7 @@ fn run_index_report_inner(junk_total_records,alias_sweep_error.is_some(),skipped_appeared as u64,+ files_removed,));for line in &skip_lines {@@ -11467,6 +11886,9 @@ fn run_index_report_inner(if skipped_appeared > 0 {done_fields.push(("skipped_appeared", skipped_appeared as u64));}+ if files_removed > 0 {+ done_fields.push(("files_removed", files_removed));+ }if dataless_skipped > 0 {done_fields.push(("skipped_dataless", dataless_skipped));}@@ -11481,6 +11903,8 @@ fn run_index_report_inner(STALE_RESUME_PLAN_REASON} else if alias_sweep_error.is_some() {ALIAS_SWEEP_FAILED_REASON+ } else if files_removed > 0 {+ FILES_REMOVED_REASON} else if code == 3 {"completed-with-junk"} else {@@ -11598,6 +12022,7 @@ fn run_remove(cfg: cli::RemoveCfg) -> Result<i32> {root: cfg.root,yes: cfg.yes,prompt,+ state_dir: cfg.state_dir,})?;println!("{}",@@ -13494,11 +13919,11 @@ mod generation_contract_identity_tests {/// what was recorded instead of hiding it.#[test]fn a_finished_run_leads_with_an_ok_line_that_spells_out_exit_3() {- let clean = outcome_headline(0, 0, 0, false, 0);+ let clean = outcome_headline(0, 0, 0, false, 0, 0);assert!(clean.starts_with("ok: indexed and searchable"), "{clean}");assert!(clean.contains("exit 0"), "{clean}");- let junk = outcome_headline(3, 1, 0, false, 0);+ let junk = outcome_headline(3, 1, 0, false, 0, 0);assert!(junk.starts_with("ok: indexed and searchable"), "{junk}");assert!(junk.contains("exit 3 (completed-with-junk) is SUCCESS, not an error"),@@ -13508,10 +13933,30 @@ mod generation_contract_identity_tests {assert!(junk.contains("xerj autoindex"), "{junk}");assert!(!junk.contains('\n'), "one line: {junk}");- let both = outcome_headline(3, 2, 5, false, 0);+ let both = outcome_headline(3, 2, 5, false, 0, 0);assert!(both.contains("2 files and 5 records"), "{both}");- let stale = outcome_headline(3, 0, 0, false, 2);+ let removed = outcome_headline(3, 0, 0, false, 0, 1);+ assert!(+ removed.contains("exit 3 (files-removed) is SUCCESS, not an error"),+ "{removed}"+ );+ assert!(+ removed.contains("no longer exist in the folder"),+ "{removed}"+ );+ assert!(+ !removed.contains("recorded as junk"),+ "a removal is not junk: {removed}"+ );+ assert!(!removed.contains('\n'), "one line: {removed}");+ let removed_and_junk = outcome_headline(3, 1, 0, false, 0, 2);+ assert!(+ removed_and_junk.contains("Also recorded as junk: 1 file"),+ "{removed_and_junk}"+ );++ let stale = outcome_headline(3, 0, 0, false, 2, 0);assert!(stale.contains("exit 3 (stale-resume-plan)"), "{stale}");assert!(stale.contains("2 files skipped because the resumed plan is stale"),@@ -13523,13 +13968,13 @@ mod generation_contract_identity_tests {"a stale plan is not junk: {stale}");assert!(!stale.contains('\n'), "one line: {stale}");- let stale_and_junk = outcome_headline(3, 1, 0, false, 2);+ let stale_and_junk = outcome_headline(3, 1, 0, false, 2, 0);assert!(stale_and_junk.contains("Also recorded as junk: 1 file"),"{stale_and_junk}");- let sweep = outcome_headline(3, 4, 0, true, 0);+ let sweep = outcome_headline(3, 4, 0, true, 0, 0);assert!(sweep.starts_with("ok: indexed and searchable"), "{sweep}");assert!(sweep.contains(ALIAS_SWEEP_FAILED_REASON), "{sweep}");assert!(sweep.contains("rerun the same command"), "{sweep}");diff --git a/engine/crates/xerj-autoindex/src/remove.rs b/engine/crates/xerj-autoindex/src/remove.rsindex e5a142265..f410c5efb 100644--- a/engine/crates/xerj-autoindex/src/remove.rs+++ b/engine/crates/xerj-autoindex/src/remove.rs@@ -14,6 +14,7 @@use std::collections::{BTreeMap, BTreeSet};use std::io::{BufRead, Write};+use std::path::{Path, PathBuf};use anyhow::{Context, Result};use serde_json::{json, Value};@@ -101,6 +102,10 @@ pub struct RemoveRequest {/// Read a `y`/`yes` line from stdin. The CLI sets this only on a terminal./// MCP leaves it false: an agent passes `confirm: true` instead.pub prompt: bool,+ /// Explicit `--state-dir`. The default journal (keyed by folder, URL, and+ /// prefix) is always removed after a successful delete; this one is too,+ /// because the default hash cannot find a journal the operator moved.+ pub state_dir: Option<PathBuf>,}pub struct RemoveReport {@@ -142,7 +147,36 @@ pub fn execute(req: RemoveRequest) -> Result<RemoveReport> {return Ok(report(&plan, EXIT_NEEDS_DECISION, false, None));}match apply(&es, &plan) {- Ok(()) => Ok(report(&plan, 0, true, None)),+ Ok(()) => {+ let root = selected_root_display(&plan);+ let journals = match root.as_deref() {+ Some(root) => {+ discard_resume_journals(root, &req.url, &req.prefix, req.state_dir.as_deref())+ }+ None => Ok(Vec::new()),+ };+ match journals {+ Ok(removed) => {+ let mut out = report(&plan, 0, true, None);+ out.body["resume_journals_removed"] = json!(removed);+ if !removed.is_empty() {+ out.summary+ .push_str(&format!("\nRemoved resume state: {}.", removed.join(", ")));+ }+ Ok(out)+ }+ Err(err) => Ok(report(+ &plan,+ 1,+ true,+ Some(format!(+ "the indices and catalog rows were deleted, but the resume journal was \+ not: {err:#}. The next autoindex of this folder will abort on that \+ journal until it is removed"+ )),+ )),+ }+ }Err(err) => {let left = match refetch(&es, &req.prefix, req.root.as_deref()) {Ok(left) => Some(left),@@ -813,6 +847,68 @@ fn apply(es: &Es, plan: &RemovePlan) -> Result<()> {Ok(())}+fn selected_root_display(plan: &RemovePlan) -> Option<String> {+ let key = plan.selected_key.as_ref()?;+ plan.roots+ .iter()+ .find(|group| group.key == *key)+ .map(|group| group.display.clone())+}++/// State directories whose `journal.ndjson` would make the next autoindex of+/// `root_display` resume a corpus this command just deleted (#2314).+fn resume_state_dirs(+ root_display: &str,+ url: &str,+ prefix: &str,+ explicit: Option<&Path>,+) -> Vec<PathBuf> {+ let mut dirs = vec![crate::state::default_state_dir(root_display, url, prefix)];+ if let Ok(canonical) = std::fs::canonicalize(root_display) {+ let text = canonical.to_string_lossy();+ if text != root_display {+ dirs.push(crate::state::default_state_dir(&text, url, prefix));+ }+ }+ if let Some(explicit) = explicit {+ dirs.push(explicit.to_path_buf());+ }+ dirs.sort();+ dirs.dedup();+ dirs+}++/// Delete `journal.ndjson` and `sync-snapshots` for one removed folder.+///+/// The directory itself stays: it may hold notes the operator put there. A+/// missing journal is success. A journal for a different root is a different+/// directory, because the default path hashes the root.+pub fn discard_resume_journals(+ root_display: &str,+ url: &str,+ prefix: &str,+ explicit: Option<&Path>,+) -> Result<Vec<String>> {+ let mut removed = Vec::new();+ for dir in resume_state_dirs(root_display, url, prefix, explicit) {+ let journal = dir.join("journal.ndjson");+ match std::fs::remove_file(&journal) {+ Ok(()) => removed.push(journal.display().to_string()),+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}+ Err(err) => {+ anyhow::bail!("remove {}: {err}", journal.display());+ }+ }+ let snapshots = dir.join("sync-snapshots");+ if snapshots.is_dir() {+ std::fs::remove_dir_all(&snapshots)+ .with_context(|| format!("remove {}", snapshots.display()))?;+ removed.push(snapshots.display().to_string());+ }+ }+ Ok(removed)+}+fn path_escape(s: &str) -> String {let mut out = String::new();for b in s.bytes() {@@ -1276,6 +1372,7 @@ mod tests {root: None,yes: false,prompt: false,+ state_dir: None,}).expect("plan");assert_eq!(report.exit_code, EXIT_NEEDS_DECISION, "{}", report.summary);@@ -1308,6 +1405,7 @@ mod tests {root: None,yes: true,prompt: false,+ state_dir: None,}).expect("plan");assert_eq!(report.exit_code, EXIT_NEEDS_DECISION, "{}", report.summary);@@ -1335,6 +1433,7 @@ mod tests {root: Some("/data/a".into()),yes: true,prompt: false,+ state_dir: None,}).expect("remove");assert_eq!(report.exit_code, 0, "{}\n{}", report.summary, report.body);@@ -1487,4 +1586,53 @@ mod tests {json_body.len())}++ /// #2314: `remove` used to leave `journal.ndjson`, and the next autoindex+ /// of that folder aborted on it. Only the selected root's default journal+ /// and an explicit `--state-dir` are deleted. A sibling folder's journal+ /// and an unrelated file in the explicit directory stay.+ #[test]+ fn discard_resume_journals_removes_the_selected_roots_journal_only() {+ let root = tempfile::tempdir().unwrap();+ let root_s = root.path().to_string_lossy().to_string();+ let url = "http://127.0.0.1:9200";+ let prefix = "proj";+ let selected = crate::state::default_state_dir(&root_s, url, prefix);+ let sibling = crate::state::default_state_dir("/other/folder", url, prefix);+ let explicit = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(&selected).unwrap();+ std::fs::create_dir_all(selected.join("sync-snapshots").join("gen")).unwrap();+ std::fs::write(selected.join("journal.ndjson"), "{}\n").unwrap();+ std::fs::create_dir_all(&sibling).unwrap();+ std::fs::write(sibling.join("journal.ndjson"), "{}\n").unwrap();+ std::fs::write(explicit.path().join("journal.ndjson"), "{}\n").unwrap();+ std::fs::create_dir_all(explicit.path().join("sync-snapshots")).unwrap();+ std::fs::write(explicit.path().join("notes.txt"), "keep\n").unwrap();++ let removed = discard_resume_journals(&root_s, url, prefix, Some(explicit.path())).unwrap();+ assert!(+ removed.iter().any(|path| path.ends_with("journal.ndjson")),+ "{removed:?}"+ );+ assert!(!selected.join("journal.ndjson").exists());+ assert!(!selected.join("sync-snapshots").exists());+ assert!(+ sibling.join("journal.ndjson").exists(),+ "a sibling journal stays"+ );+ assert!(!explicit.path().join("journal.ndjson").exists());+ assert!(!explicit.path().join("sync-snapshots").exists());+ assert_eq!(+ std::fs::read_to_string(explicit.path().join("notes.txt")).unwrap(),+ "keep\n"+ );++ let again = discard_resume_journals(&root_s, url, prefix, Some(explicit.path())).unwrap();+ assert!(+ again.is_empty(),+ "a missing journal is not an error: {again:?}"+ );+ let _ = std::fs::remove_dir_all(&selected);+ let _ = std::fs::remove_dir_all(&sibling);+ }}diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex 4e132190d..c2ef99d4d 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -1512,6 +1512,15 @@ impl Journal {.insert(file_key.to_string(), generation.to_string());}}+ // #2314: a file that left the folder is not a+ // replacement. Drop its completion so a later+ // catalog write does not advertise it again.+ Some("file_removed") => {+ if let Some(file_key) = v.get("file_key").and_then(Value::as_str) {+ done.remove(file_key);+ pending_replacements.remove(file_key);+ }+ }_ => {}}}@@ -1939,6 +1948,23 @@ impl Journal {Ok(())}+ /// A planned file left the folder and its documents were swept (#2314).+ ///+ /// Unlike [`Self::file_replace_start`], this does not schedule a+ /// replacement: there is no current file to republish.+ pub fn file_removed(&mut self, file_key: &str) -> Result<()> {+ self.append_transaction(+ &serde_json::json!({+ "kind": "file_removed",+ "file_key": file_key,+ }),+ "file_removed",+ )?;+ self.done.remove(file_key);+ self.pending_replacements.remove(file_key);+ Ok(())+ }+/// Durably invalidate an older completion before persisting a new plan or/// changing live visibility. Replaying this record schedules repair until/// a later durable file_done commits the generation.diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex 99a0d1876..84f45d31f 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -2201,7 +2201,7 @@ impl SyncOperationBackend for EsSyncBackend<'_> {// record counts above, only changed groups ask — a kept group's// canonical/alias documents intentionally keep the run_id of the// generation that last wrote them.- let catalog_counts = if catalog_wanted.is_empty() {+ let mut catalog_counts = if catalog_wanted.is_empty() {HashMap::new()} else {let _reading = self.pr.watch_file(crate::catalog::CATALOG_INDEX, 0);@@ -2244,9 +2244,30 @@ impl SyncOperationBackend for EsSyncBackend<'_> {group.expected_vectors,group.dataset_slugs);+ // #2314: the equality used to be one shot. A folder of identical+ // empty files published the canonical doc and its aliases, then+ // lost the race with catalog visibility and aborted; the same+ // command retried clean. Recount after a refresh, the same bound+ // as the short read-back walk, before calling it a disagreement.+ let expected = 1 + group.aliases.len() as u64;+ let mut observed = catalog_counts.get(&group.content_id).copied().unwrap_or(0);+ let mut attempt = 1usize;+ while observed != expected && attempt < Self::READBACK_WALK_ATTEMPTS {+ self.pr.note(&format!(+ "autoindex: catalog canonical/alias count for {} saw {observed} of \+ {expected} document(s) — refreshing and recounting (attempt {attempt} of {})",+ group.group_id,+ Self::READBACK_WALK_ATTEMPTS+ ));+ self.es.refresh_once(crate::catalog::CATALOG_INDEX)?;+ catalog_counts = self.windowed_catalog_counts(&catalog_wanted, &snapshot.tx_id)?;+ observed = catalog_counts.get(&group.content_id).copied().unwrap_or(0);+ attempt += 1;+ }anyhow::ensure!(- catalog_counts[&group.content_id] == 1 + group.aliases.len() as u64,- "catalog canonical/alias count disagrees with desired group {}",+ observed == expected,+ "catalog canonical/alias count disagrees with desired group {}: \+ observed {observed}, expected {expected}",group.group_id);}@@ -3145,6 +3166,9 @@ fn create_snapshot_inner(// Entered only when there is work to report: a retry that reuses a verified// final snapshot returned above and never claims a phase it did not run.pr.phase("snapshot", inventory.files.len() as u64, source_bytes);+ // #2314: a test grows one source in the window after the hash and before+ // this seal. Production runs leave the hook empty.+ snapshot_source_hook(state_dir);for (ordinal, ((source, content_id), content_digest)) in inventory.files.iter()@@ -3254,9 +3278,24 @@ fn create_snapshot_inner(});}None => {- crate::content::verify(&source.path, source.size, content_digest)?;- copy_synced(&source.path, &destination, &mut budget)?;- crate::content::verify(&destination, source.size, content_digest)?;+ // #2314: a file that changes size (or disappears) between the+ // hash and this copy used to abort the generation on the `?`.+ // The error names the live source so the caller can drop that+ // one file and seal the rest.+ verify_live_source(source, content_digest)?;+ if let Err(error) = copy_synced(&source.path, &destination, &mut budget) {+ if verify_live_source(source, content_digest).is_err() {+ return Err(source_changed(+ &source.path,+ format!(+ "{} changed while it was being copied into the snapshot ({error:#})",+ source.path.display()+ ),+ ));+ }+ return Err(error);+ }+ verify_sealed_blob(source, &destination, content_digest)?;#[cfg(test)]apply_post_seal_source_replacement(&source.path)?;let prepared = match assignment {@@ -3817,6 +3856,76 @@ fn apply_post_seal_source_replacement(path: &Path) -> Result<()> {Ok(())}+/// A live source no longer matches the bytes this generation hashed.+///+/// Stat failures are included: a file deleted between the hash and the seal+/// is the same skip, not a reason to abort every other file.+fn verify_live_source(source: &crate::walk::FileEntry, digest: &str) -> Result<()> {+ match crate::content::verify(&source.path, source.size, digest) {+ Ok(()) => Ok(()),+ Err(error) => Err(source_changed(&source.path, format!("{error:#}"))),+ }+}++/// The staged blob does not match the hashed source. A size or content miss+/// is reported against the live path, which is the file the caller can drop.+fn verify_sealed_blob(source: &crate::walk::FileEntry, sealed: &Path, digest: &str) -> Result<()> {+ match crate::content::verify(sealed, source.size, digest) {+ Ok(()) => Ok(()),+ Err(error)+ if error+ .downcast_ref::<crate::content::SourceChanged>()+ .is_some() =>+ {+ Err(source_changed(&source.path, format!("{error:#}")))+ }+ Err(error) => Err(error),+ }+}++fn source_changed(path: &Path, detail: String) -> anyhow::Error {+ crate::content::SourceChanged {+ path: path.to_path_buf(),+ detail,+ }+ .into()+}++/// Test-only: run once at the start of a snapshot seal, keyed by state dir+/// so a parallel test cannot grow another run's files (#2314).+#[cfg(test)]+type SnapshotSourceHook = (std::path::PathBuf, Box<dyn FnOnce() + Send>);+#[cfg(test)]+static SNAPSHOT_SOURCE_HOOK: std::sync::Mutex<Option<SnapshotSourceHook>> =+ std::sync::Mutex::new(None);++#[cfg(test)]+pub(crate) fn arm_snapshot_source_hook(state_dir: &Path, action: impl FnOnce() + Send + 'static) {+ *SNAPSHOT_SOURCE_HOOK+ .lock()+ .unwrap_or_else(|poison| poison.into_inner()) =+ Some((state_dir.to_path_buf(), Box::new(action)));+}++#[cfg(test)]+fn snapshot_source_hook(state_dir: &Path) {+ let action = {+ let mut armed = SNAPSHOT_SOURCE_HOOK+ .lock()+ .unwrap_or_else(|poison| poison.into_inner());+ match armed.as_ref() {+ Some((dir, _)) if dir == state_dir => armed.take().map(|(_, action)| action),+ _ => None,+ }+ };+ if let Some(action) = action {+ action();+ }+}++#[cfg(not(test))]+fn snapshot_source_hook(_state_dir: &Path) {}+#[cfg(test)]fn fail_next_snapshot(boundary: u8) {SNAPSHOT_FAILPOINT.with(|failpoint| failpoint.set(boundary));diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 1a6181278..3ae947fab 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -2890,6 +2890,7 @@ async fn run_autoindex_remove(ctx: &Ctx, args: &Value) -> Value {root,yes: confirm,prompt: false,+ state_dir: None,})}).await;diff --git a/landing/answers/index.html b/landing/answers/index.htmlindex 9fb17fca9..52ba6bb06 100644--- a/landing/answers/index.html+++ b/landing/answers/index.html@@ -75,7 +75,7 @@"url": "https://xerj.org/answers/","image": "https://xerj.org/og/xerj-card.png","inLanguage": "en",- "dateModified": "2026-10-20",+ "dateModified": "2026-10-24","isPartOf": {"@id": "https://xerj.org/#website"},diff --git a/landing/answers/index.json b/landing/answers/index.jsonindex 53eaffb43..e66e6a612 100644--- a/landing/answers/index.json+++ b/landing/answers/index.json@@ -1096,7 +1096,7 @@"canonical_url": "https://xerj.org/answers/keep-index-current-as-files-change","markdown_url": "https://xerj.org/answers/keep-index-current-as-files-change.md","cluster": "Operations: freshness",- "updated": "2026-10-19",+ "updated": "2026-10-24","summary": "Run xerj autoindex --watch --no-graph. It indexes once, then reindexes what the filesystem reports. Measured: 0.00 CPU-seconds per idle minute against 1.7 s and a full corpus re-read for every poll.","intent_group": "operating autoindex","answer": "How do I keep a search index up to date as files change, without re-indexing everything? Run xerj autoindex ./folder --watch --no-graph. It indexes once, then reindexes only what the filesystem reports changed. Measured idle cost was 0.00 CPU-seconds per minute, against 1.7 s and a full corpus re-read for every timed re-run.",diff --git a/landing/answers/keep-index-current-as-files-change.html b/landing/answers/keep-index-current-as-files-change.htmlindex 849375cc0..d1019ebf8 100644--- a/landing/answers/keep-index-current-as-files-change.html+++ b/landing/answers/keep-index-current-as-files-change.html@@ -77,7 +77,7 @@"image": "https://xerj.org/og/xerj-card.png","inLanguage": "en","datePublished": "2026-09-19",- "dateModified": "2026-10-19",+ "dateModified": "2026-10-24","author": {"@type": "Person","name": "XERJ documentation team"@@ -156,9 +156,9 @@<div class="breadcrumb"><a href="/">HOME</a><span class="sep">·</span><a href="/answers/">ANSWERS</a><span class="sep">·</span>HOW DO I KEEP A SEARCH INDEX UP TO DATE AS FILES CHANGE, WITHOUT RE-INDEXING EVERYTHING?</div><div class="kicker"><span>ANSWERS · OPERATIONS: FRESHNESS</span></div><h1 class="h1-long">How do I keep a search index up to date as files change, without re-indexing everything?</h1>- <div class="source-note">AUTHOR · XERJ documentation team · REVIEWED BY · XERJ engineering team · PUBLISHED · 2026-09-19 · UPDATED · 2026-10-19</div>+ <div class="source-note">AUTHOR · XERJ documentation team · REVIEWED BY · XERJ engineering team · PUBLISHED · 2026-09-19 · UPDATED · 2026-10-24</div><div class="prompt-card answer-first" id="short-answer">- <span class="prompt-label">SHORT ANSWER · UPDATED 2026-10-19</span>+ <span class="prompt-label">SHORT ANSWER · UPDATED 2026-10-24</span><p>How do I keep a search index up to date as files change, without re-indexing everything? Run xerj autoindex ./folder --watch --no-graph. It indexes once, then reindexes only what the filesystem reports changed. Measured idle cost was 0.00 CPU-seconds per minute, against 1.7 s and a full corpus re-read for every timed re-run.</p><p class="key-fact"><strong>Key number:</strong> The --debounce quiet period accepts at most 60,000 ms (<code class="inline">MAX_DEBOUNCE_MS</code>); longer than a minute is a timer, not a debounce. <span class="mute">(as of 2026-10-19 · source: <a href="https://github.com/xerj-org/xerj/blob/main/engine/crates/xerj-autoindex/src/cli.rs">engine/crates/xerj-autoindex/src/cli.rs</a>)</span></p></div>@@ -225,8 +225,8 @@ xerj autoindex ./notes --url http://127.0.0.1:9200 \<ul><li>On the default graph path, a run resumes a <em>frozen</em> plan. A file whose content</li></ul>- <p>changed <strong>is</strong> reconciled there (measured: 3.07 s, <code class="inline">files=1</code>, the new text searchable). A file that was <strong>added</strong> is not. The run reports <code class="inline">1 file(s) appeared after the resume plan was frozen and were NOT indexed</code>, exits 3, and tells you to rebuild with <code class="inline">--fresh</code>. A file that was <strong>deleted</strong> is worse. The run aborts in 0.24 s with "removing files from an indexed folder is not reconciled yet". Its documents stay live, and every later re-run aborts the same way.</p>- <p>A watcher on the graph path would therefore go stale on the first new file and stop reindexing on the first deletion. The price of <code class="inline">--no-graph</code> is relationship detection: no wikilink, local-link, section-order or directory-chain edges.</p>+ <p>changed <strong>is</strong> reconciled there (measured on 2026-09-19: 3.07 s, <code class="inline">files=1</code>, the new text searchable). A deleted file is swept (exit 3, <code class="inline">reason=files-removed</code>; the next unchanged rerun is exit 0), and an added file that fits a frozen dataset is indexed on the rerun. A file that needs a new dataset is not: the run exits 3 with <code class="inline">reason=stale-resume-plan</code> and names <code class="inline">--fresh</code>. Before that reconcile, the same 2026-09-19 capture recorded a deletion aborting in 0.24 s and leaving its documents live. Those timings were not re-measured here.</p>+ <p>The watcher stays on <code class="inline">--no-graph</code> because that route also reconciles a file that would be a new dataset, and the watcher is not built on the graph path. The price of <code class="inline">--no-graph</code> is relationship detection: no wikilink, local-link, section-order or directory-chain edges.</p><h2>Which directories the watcher covers</h2><p>The watch set is the directories the indexing walk <strong>admits</strong>. Same traversal, same hidden-name rule, same <code class="inline">.gitignore</code> and <code class="inline">.xerjignore</code> stack. An ignored <code class="inline">target/</code> therefore costs no watch and cannot wake the watcher at all. A watched run and a plain re-run also agree about what is indexed, because they read the same rules from the same code. Editing <code class="inline">.gitignore</code> or <code class="inline">.xerjignore</code> invalidates the directory it governs. The rule you change takes effect on the next pass.</p><p>Events on hidden names such as <code class="inline">.file.swp</code> or <code class="inline">.git/index.lock</code> are dropped without a pass, because no run indexes those either.</p>@@ -247,7 +247,7 @@ xerj autoindex ./notes --url http://127.0.0.1:9200 \<h3>How do I keep a search index up to date as files change, without re-indexing everything?</h3><p>Run xerj autoindex with --watch --no-graph. It indexes the folder once, then stays resident and reindexes only what the filesystem reports as changed, using one OS watch per indexed directory and no polling.</p><h3>Why does --watch require --no-graph?</h3>- <p>Reconciling an added or deleted file exists only on the --no-graph route. On the default graph path a re-run resumes a frozen plan: a file added after that plan was frozen is reported as appeared after the resume plan was frozen and is not indexed until a --fresh rebuild, and a deleted file aborts the run and every re-run after it. A file whose content changed is reconciled there, so the limitation is additions and deletions, not edits.</p>+ <p>The watcher re-runs the generated route, which reconciles added, changed, renamed and deleted files, including a file that would be a new dataset. On the default graph path a deleted file is swept and an added file that fits a frozen dataset is indexed, but a file that needs a new dataset still stops with reason=stale-resume-plan until --fresh, and the watcher is not built on that route.</p><h3>Is a file watcher cheaper than re-running the indexer on a timer?</h3><p>At idle, yes, and measurably. On a 10,000-file tree a re-run with nothing changed took 1.7 s and re-read all 4,576,300 bytes, while an idle watcher used 0.00 CPU-seconds over 60 s and read nothing. It does hold about 157 MiB resident between passes.</p><h3>Does --watch use less CPU per change than a re-run?</h3>diff --git a/landing/answers/keep-index-current-as-files-change.md b/landing/answers/keep-index-current-as-files-change.mdindex 8235e744c..22f9868f6 100644--- a/landing/answers/keep-index-current-as-files-change.md+++ b/landing/answers/keep-index-current-as-files-change.md@@ -2,13 +2,13 @@---title: "How do I keep a XERJ index up to date as files change?"canonical: "https://xerj.org/answers/keep-index-current-as-files-change"-updated: "2026-10-19"+updated: "2026-10-24"source: "content/answers/keep-index-current-as-files-change.md"---# How do I keep a search index up to date as files change, without re-indexing everything?-**Short answer** (updated 2026-10-19): How do I keep a search index up to date as files change, without re-indexing everything? Run xerj autoindex ./folder --watch --no-graph. It indexes once, then reindexes only what the filesystem reports changed. Measured idle cost was 0.00 CPU-seconds per minute, against 1.7 s and a full corpus re-read for every timed re-run.+**Short answer** (updated 2026-10-24): How do I keep a search index up to date as files change, without re-indexing everything? Run xerj autoindex ./folder --watch --no-graph. It indexes once, then reindexes only what the filesystem reports changed. Measured idle cost was 0.00 CPU-seconds per minute, against 1.7 s and a full corpus re-read for every timed re-run.**Key number:** The --debounce quiet period accepts at most 60,000 ms (`MAX_DEBOUNCE_MS`); longer than a minute is a timer, not a debounce. (as of 2026-10-19; source: [engine/crates/xerj-autoindex/src/cli.rs](https://github.com/xerj-org/xerj/blob/main/engine/crates/xerj-autoindex/src/cli.rs))@@ -120,17 +120,20 @@ than a formality:* On the `--no-graph` route, a run reconciles the folder against a committedgeneration: added, changed, renamed and deleted files are all handled.* On the default graph path, a run resumes a *frozen* plan. A file whose content- changed **is** reconciled there (measured: 3.07 s, `files=1`, the new text- searchable). A file that was **added** is not. The run reports- `1 file(s) appeared after the resume plan was frozen and were NOT indexed`,- exits 3, and tells you to rebuild with `--fresh`. A file that was **deleted** is- worse. The run aborts in 0.24 s with "removing files from an indexed folder is- not reconciled yet". Its documents stay live, and every later re-run aborts the- same way.--A watcher on the graph path would therefore go stale on the first new file and-stop reindexing on the first deletion. The price of `--no-graph` is relationship-detection: no wikilink, local-link, section-order or directory-chain edges.+ changed **is** reconciled there (measured on 2026-09-19: 3.07 s, `files=1`,+ the new text searchable). A deleted file is swept (exit 3,+ `reason=files-removed`; the next unchanged rerun is exit 0), and an added+ file that fits a frozen dataset is indexed on the rerun. A file that needs a+ new dataset is not: the run exits 3 with `reason=stale-resume-plan` and names+ `--fresh`.+ Before that reconcile, the same 2026-09-19 capture recorded a deletion+ aborting in 0.24 s and leaving its documents live. Those timings were not+ re-measured here.++The watcher stays on `--no-graph` because that route also reconciles a file+that would be a new dataset, and the watcher is not built on the graph path.+The price of `--no-graph` is relationship detection: no wikilink, local-link,+section-order or directory-chain edges.## Which directories the watcher covers@@ -206,7 +209,7 @@ Run xerj autoindex with --watch --no-graph. It indexes the folder once, then sta### Why does --watch require --no-graph?-Reconciling an added or deleted file exists only on the --no-graph route. On the default graph path a re-run resumes a frozen plan: a file added after that plan was frozen is reported as appeared after the resume plan was frozen and is not indexed until a --fresh rebuild, and a deleted file aborts the run and every re-run after it. A file whose content changed is reconciled there, so the limitation is additions and deletions, not edits.+The watcher re-runs the generated route, which reconciles added, changed, renamed and deleted files, including a file that would be a new dataset. On the default graph path a deleted file is swept and an added file that fits a frozen dataset is indexed, but a file that needs a new dataset still stops with reason=stale-resume-plan until --fresh, and the watcher is not built on that route.### Is a file watcher cheaper than re-running the indexer on a timer?diff --git a/landing/sitemap.xml b/landing/sitemap.xmlindex 84a3dfca0..f560fc2ff 100644--- a/landing/sitemap.xml+++ b/landing/sitemap.xml@@ -14,7 +14,7 @@</url><url><loc>https://xerj.org/answers/</loc>- <lastmod>2026-10-20</lastmod>+ <lastmod>2026-10-24</lastmod></url><url><loc>https://xerj.org/answers/agent-memory-without-postgres-qdrant</loc>@@ -166,7 +166,7 @@</url><url><loc>https://xerj.org/answers/keep-index-current-as-files-change</loc>- <lastmod>2026-10-19</lastmod>+ <lastmod>2026-10-24</lastmod></url><url><loc>https://xerj.org/answers/keep-s3-bucket-index-current</loc>