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
autoindex: drop previous symbol generations when a file is replaced (#2197)
xerj-orgce018d1c6cc4
diff --git a/demo/usecases/autoindex/RECIPE_DRAFT.md b/demo/usecases/autoindex/RECIPE_DRAFT.mdindex 8b3e8fbc1..bf6812ade 100644--- a/demo/usecases/autoindex/RECIPE_DRAFT.md+++ b/demo/usecases/autoindex/RECIPE_DRAFT.md@@ -203,12 +203,12 @@ done in 0.1s — 3 datasets, 5801 records live, 0 junk records, 1 junk/skipped fjust polite re-runs: in the robustness evaluation, a `kill -9` at 18 s into a200 MB file followed by a re-run converged to **byte-identical counts acrossall 9 datasets** — no duplicates. `xerj autoindex status` shows the journal-and live index counts. `--fresh` ignores the resume journal and restarts (ids stay idempotent), which on a-graph-enabled or pre-generation state directory is how a rerun picks up files added-since the last one. It never removes stale records from the destination, and it is-refused once the state directory holds a durable corpus generation — re-run without it-and the generated `--no-graph` path reconciles additions, changes, deletions, renames-and no-op reruns incrementally.+and live index counts. `--fresh` ignores the resume journal and restarts (ids stay idempotent for unchanged+bytes), which on a graph-enabled or pre-generation state directory is how a rerun picks up files added+since the last one. A file that is still present and whose content key changed is republished, and the+documents previously published for that path are removed. It does not remove documents for a file that+disappeared, and it is refused once the state directory holds a durable corpus generation — re-run without it+and the generated `--no-graph` path reconciles additions, changes, deletions, renames and no-op reruns incrementally.On a graph-enabled or pre-generation journal, a rerun that resumes an existing planindexes changed files and reports added ones as skipped. Deleting a file is refuseddiff --git a/docs/recipes/zero-config-indexing.md b/docs/recipes/zero-config-indexing.mdindex 1e7da79ba..025aaa1ee 100644--- a/docs/recipes/zero-config-indexing.md+++ b/docs/recipes/zero-config-indexing.md@@ -229,12 +229,14 @@ live indices at http://localhost:9280:autoindex-catalog 9 docs```-`--fresh` ignores the resume journal and restarts (ids stay idempotent), which on a-graph-enabled or pre-generation state directory is how a rerun picks up files added-since the last one. It never removes stale records from the destination, and it is-refused once the state directory holds a durable corpus generation — re-run without it-and the generated `--no-graph` path reconciles additions, changes, deletions, renames-and no-op reruns incrementally.+`--fresh` ignores the resume journal and restarts (ids stay idempotent for unchanged+bytes), which on a graph-enabled or pre-generation state directory is how a rerun picks+up files added since the last one. A file that is still present and whose content key+changed is republished, and the documents previously published for that path are+removed. It does not remove documents for a file that disappeared, and it is refused+once the state directory holds a durable corpus generation — re-run without it and the+generated `--no-graph` path reconciles additions, changes, deletions, renames and no-op+reruns incrementally.On a graph-enabled or pre-generation journal, a rerun that resumes an existing planindexes changed files and reports added ones as skipped. Deleting a file is refuseddiff --git a/engine/crates/xerj-api/tests/autoindex_changed_file_drops_stale_symbols.rs b/engine/crates/xerj-api/tests/autoindex_changed_file_drops_stale_symbols.rsnew file mode 100644index 000000000..002fc8762--- /dev/null+++ b/engine/crates/xerj-api/tests/autoindex_changed_file_drops_stale_symbols.rs@@ -0,0 +1,407 @@+//! Issue #2139: re-indexing a changed source file must not leave documents+//! for symbols that moved or disappeared.+//!+//! Per-symbol `_id`s are `code:<line>:<name>` (#500). A signature edit that+//! also shifts the declaration does not overwrite the old symbol document,+//! so the file-level delete on `ax_file` is what has to remove it. The+//! autoindex HTTP mocks honour that `term` exactly, and the CSV / same-line+//! reindex tests overwrite a stable locator, so a delete the real engine+//! does not apply still looks clean there.+//!+//! This boots the ES-compat router and drives `xerj autoindex` over HTTP,+//! once with the graph enabled (the resume path the field reports hit) and+//! once with `--no-graph`.++use std::path::Path;+use std::time::Duration;++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;+use xerj_autoindex::cli::IndexCfg;++const CODE_V1: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ pub fn gone_symbol() -> i32 {\n\+ 1\n\+ }\n\+\n\+ pub fn query_job(group_id: &str, raw: &str) -> bool {\n\+ !raw.is_empty()\n\+ }\n\+}\n\+";++const CODE_V2: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ // the signature gained &self and the declaration moved down\n\+\n\+\n\+ pub fn query_job(&self, group_id: &str, raw: &str) -> bool {\n\+ !raw.is_empty()\n\+ }\n\+}\n\+";++async fn app() -> axum::Router {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.auth.enabled = false;+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ // Leak the temp dir for the process lifetime: the router keeps the data+ // dir path, and dropping `TempDir` at the end of this function would+ // delete it out from under the engine.+ std::mem::forget(dir);+ xerj_api::router::build_es_compat_router(state)+}++async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(path);+ let body = if body.is_null() {+ Body::empty()+ } else {+ req = req.header("content-type", "application/json");+ Body::from(body.to_string())+ };+ let response = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++fn index_cfg(+ root: &Path,+ state_dir: &Path,+ url: &str,+ prefix: &str,+ no_graph: bool,+ fresh: bool,+) -> IndexCfg {+ IndexCfg {+ root: root.to_owned(),+ endpoint_url: None,+ stub_globs: Vec::new(),+ url: url.to_owned(),+ api_key: None,+ api_key_file: None,+ workers: 1,+ scan_workers: 1,+ pdf_workers: 1,+ resource_notes: Vec::new(),+ xerj_url_note: None,+ pdf_timeout_secs: 30,+ bulk_mb: 1,+ bulk_timeout_secs: 30,+ snapshot_max_bytes: 64 << 30,+ prefix: prefix.to_owned(),+ replace_prefix: false,+ prefix_note: None,+ state_dir: Some(state_dir.to_owned()),+ fresh,+ follow_symlinks: false,+ follow_symlinks_outside_root: false,+ ignore: xerj_autoindex::ignore_rules::IgnoreOptions::default(),+ max_file_bytes: 1 << 30,+ sample: 50,+ // The field reports ran a default autoindex, which elects semantic+ // text on code. `no_semantic` hides any passage document that election+ // writes beside the symbol records.+ no_semantic: false,+ code_analyzer: Default::default(),+ brain: Some(format!("brain-{prefix}")),+ no_graph,+ max_minutes: 0,+ approve: None,+ max_index_bytes: None,+ budget_plan: None,+ drop_indexed: false,+ dry_run: false,+ walk_only: false,+ json: false,+ quiet: true,+ progress: xerj_autoindex::progress::ProgressMode::None,+ progress_interval: None,+ watch: false,+ label: None,+ debounce: Duration::from_millis(0),+ exclude_rels: Vec::new(),+ skip_corpus_data: false,+ }+}++fn run_autoindex(+ root: &Path,+ state_dir: &Path,+ url: &str,+ prefix: &str,+ no_graph: bool,+ fresh: bool,+) -> i32 {+ let cfg = index_cfg(root, state_dir, url, prefix, no_graph, fresh);+ match xerj_autoindex::run_index_report(cfg) {+ Ok((code, _)) => code,+ Err(error) => panic!("autoindex {prefix} failed: {error:#}"),+ }+}++/// `xerj autoindex` builds a reqwest blocking client, which owns a tokio+/// runtime. Constructing that client on the test runtime panics ("Cannot+/// drop a runtime in a context where blocking is not allowed"), so the run+/// happens on the blocking pool.+async fn run_autoindex_blocking(+ root: &Path,+ state_dir: &Path,+ url: &str,+ prefix: &str,+ no_graph: bool,+ fresh: bool,+) -> i32 {+ let root = root.to_owned();+ let state_dir = state_dir.to_owned();+ let url = url.to_owned();+ let prefix = prefix.to_owned();+ tokio::task::spawn_blocking(move || {+ run_autoindex(&root, &state_dir, &url, &prefix, no_graph, fresh)+ })+ .await+ .expect("autoindex task")+}++/// Every `_source` under `{prefix}-*`, file cards included.+async fn prefix_docs(app: &axum::Router, prefix: &str) -> Vec<Value> {+ let (status, body) = call(+ app,+ "POST",+ &format!("/{prefix}-*/_search"),+ json!({+ "size": 200,+ "query": {"match_all": {}},+ "sort": [{"_id": "asc"}]+ }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "search {prefix}-*: {body}");+ body["hits"]["hits"]+ .as_array()+ .unwrap_or_else(|| panic!("no hits array: {body}"))+ .iter()+ .map(|hit| hit["_source"].clone())+ .collect()+}++fn symbol_rows(docs: &[Value]) -> Vec<(String, u64, String)> {+ let mut rows: Vec<(String, u64, String)> = docs+ .iter()+ .filter(|doc| doc.get("defs").is_none() && doc["ax_locator"].as_str() != Some("file"))+ .filter_map(|doc| {+ Some((+ doc.get("name")?.as_str()?.to_string(),+ doc.get("line")?.as_u64()?,+ doc.get("code")?.as_str()?.to_string(),+ ))+ })+ .collect();+ rows.sort();+ rows+}++fn assert_only_current(label: &str, live: &[Value], fresh: &[Value]) {+ let rendered = serde_json::to_string(live).unwrap();+ assert!(+ !rendered.contains("gone_symbol"),+ "{label}: removed symbol gone_symbol is still indexed: {rendered}"+ );+ assert!(+ !rendered.contains("pub fn query_job(group_id"),+ "{label}: the pre-edit query_job signature is still indexed: {rendered}"+ );+ assert!(+ rendered.contains("pub fn query_job(&self"),+ "{label}: the current query_job signature is missing: {rendered}"+ );+ assert_eq!(+ symbol_rows(live),+ symbol_rows(fresh),+ "{label}: symbol documents (name, line, code) must match a fresh index of the edited file\n\+ live={rendered}\nfresh={}",+ serde_json::to_string(fresh).unwrap()+ );+ assert_eq!(+ live.len(),+ fresh.len(),+ "{label}: document count must match a fresh index of the edited file\n\+ live={rendered}\nfresh={}",+ serde_json::to_string(fresh).unwrap()+ );+}++/// Index v1, shift `query_job` and delete `gone_symbol`, reindex on the same+/// prefix, and compare with a from-scratch index of v2.+async fn reindex_changed_code(app: &axum::Router, url: &str, no_graph: bool) {+ let mode = if no_graph { "nograph" } else { "graph" };+ let edited = tempfile::tempdir().unwrap();+ let edited_state = tempfile::tempdir().unwrap();+ std::fs::write(edited.path().join("jobs.rs"), CODE_V1).unwrap();+ let prefix = format!("stale{mode}");+ let code = run_autoindex_blocking(+ edited.path(),+ edited_state.path(),+ url,+ &prefix,+ no_graph,+ false,+ )+ .await;+ assert_eq!(code, 0, "{mode} genesis exit {code}");+ let first = prefix_docs(app, &prefix).await;+ let first_rows = symbol_rows(&first);+ assert!(+ first_rows.iter().any(|(name, _, code)| {+ name == "query_job" && code.contains("group_id") && !code.contains("&self")+ }),+ "{mode} genesis must index the original query_job: {first_rows:?}"+ );+ assert!(+ first_rows.iter().any(|(name, _, _)| name == "gone_symbol"),+ "{mode} genesis must index gone_symbol: {first_rows:?}"+ );++ // Graph resume keeps the planned key and deletes by it. A document for+ // the same path under some other key (a previous `--fresh`) must go too.+ if !no_graph {+ let (status, body) = call(+ app,+ "POST",+ &format!("/{prefix}-*/_search"),+ json!({"size": 1, "query": {"match_all": {}}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let index = body["hits"]["hits"][0]["_index"]+ .as_str()+ .unwrap()+ .to_string();+ let (status, planted) = call(+ app,+ "PUT",+ &format!("/{index}/_doc/stale-plant"),+ json!({+ "ax_path": "jobs.rs",+ "ax_file": "stale-generation-key",+ "ax_locator": "code:1:query_job",+ "name": "query_job",+ "line": 1,+ "code": "pub fn query_job(group_id: &str, raw: &str) -> bool"+ }),+ )+ .await;+ assert!(+ status.is_success(),+ "plant stale symbol: {status} {planted}"+ );+ }++ std::fs::write(edited.path().join("jobs.rs"), CODE_V2).unwrap();+ let code = run_autoindex_blocking(+ edited.path(),+ edited_state.path(),+ url,+ &prefix,+ no_graph,+ false,+ )+ .await;+ assert_eq!(code, 0, "{mode} incremental reindex exit {code}");++ let fresh_root = tempfile::tempdir().unwrap();+ let fresh_state = tempfile::tempdir().unwrap();+ std::fs::write(fresh_root.path().join("jobs.rs"), CODE_V2).unwrap();+ let fresh_prefix = format!("fresh{mode}");+ let code = run_autoindex_blocking(+ fresh_root.path(),+ fresh_state.path(),+ url,+ &fresh_prefix,+ no_graph,+ false,+ )+ .await;+ assert_eq!(code, 0, "{mode} fresh index exit {code}");++ let live = prefix_docs(app, &prefix).await;+ let fresh = prefix_docs(app, &fresh_prefix).await;+ assert_only_current(&format!("{mode} incremental reindex"), &live, &fresh);+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn changed_code_file_reindex_drops_shifted_and_removed_symbols_on_the_engine() {+ let app = app().await;+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let served = app.clone();+ tokio::spawn(async move {+ axum::serve(listener, served).await.unwrap();+ });+ let url = format!("http://{addr}");++ // The graph resume path is what the field reports ran. `--no-graph` is+ // the other incremental executor and has to drop the same documents.+ reindex_changed_code(&app, &url, false).await;+ reindex_changed_code(&app, &url, true).await;+ reindex_with_fresh(&app, &url).await;+}++/// `--fresh` rebuilds the content key. The previous symbol documents must+/// still disappear, and a from-scratch index of v2 is the oracle.+async fn reindex_with_fresh(app: &axum::Router, url: &str) {+ let edited = tempfile::tempdir().unwrap();+ let edited_state = tempfile::tempdir().unwrap();+ std::fs::write(edited.path().join("jobs.rs"), CODE_V1).unwrap();+ let prefix = "stalefresh";+ let code = run_autoindex_blocking(+ edited.path(),+ edited_state.path(),+ url,+ prefix,+ false,+ false,+ )+ .await;+ assert_eq!(code, 0, "fresh-path genesis exit {code}");++ std::fs::write(edited.path().join("jobs.rs"), CODE_V2).unwrap();+ let code =+ run_autoindex_blocking(edited.path(), edited_state.path(), url, prefix, false, true).await;+ assert_eq!(code, 0, "--fresh reindex exit {code}");++ let oracle_root = tempfile::tempdir().unwrap();+ let oracle_state = tempfile::tempdir().unwrap();+ std::fs::write(oracle_root.path().join("jobs.rs"), CODE_V2).unwrap();+ let code = run_autoindex_blocking(+ oracle_root.path(),+ oracle_state.path(),+ url,+ "oraclefresh",+ false,+ false,+ )+ .await;+ assert_eq!(code, 0, "oracle exit {code}");+ let live = prefix_docs(app, prefix).await;+ let oracle = prefix_docs(app, "oraclefresh").await;+ assert_only_current("--fresh reindex", &live, &oracle);+}diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex ce3d19257..ded9bd3af 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -273,9 +273,10 @@ pub const MAX_POLL_INTERVAL_SECS: u64 = 86_400;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); it never resets destination records,\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\x20and is refused on a durable corpus generation — see\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\x20RESUME POLICY";+ \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\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 \@@ -674,11 +675,14 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20Restore the file and rerun, or rebuild — in place by deleting the published\n\\x20\x20\x20\x20indices and the state directory, or isolated under a new --state-dir, --prefix\n\\x20\x20\x20\x20and --brain (or --no-graph), validated before you switch readers.\n\- \x20\x20\x20\x20--fresh is not cleanup and is not destination reconciliation: it never removes\n\- \x20\x20\x20\x20stale records from the destination, and it is refused outright once a durable\n\- \x20\x20\x20\x20corpus generation exists (re-run without it — the generated path reconciles the\n\- \x20\x20\x20\x20change incrementally). For an independent rebuild use a new --state-dir and a\n\- \x20\x20\x20\x20new --prefix, plus a new --brain when graph is enabled (or --no-graph).\n\+ \x20\x20\x20\x20--fresh is not a destination wipe. A file that is still present and whose\n\+ \x20\x20\x20\x20content key changed is republished, and the documents previously published\n\+ \x20\x20\x20\x20for that path are removed. A disappeared file is still refused before any\n\+ \x20\x20\x20\x20remote mutation, and its documents stay. --fresh is refused outright once a\n\+ \x20\x20\x20\x20durable corpus generation exists (re-run without it — the generated path\n\+ \x20\x20\x20\x20reconciles the change incrementally). For an independent rebuild use a new\n\+ \x20\x20\x20\x20--state-dir and a new --prefix, plus a new --brain when graph is enabled\n\+ \x20\x20\x20\x20(or --no-graph).\n\\x20\x20\x20\x20Validate before switching readers; explicitly clean the shared\n\\x20\x20\x20\x20autoindex-catalog and old target only after validation.\n\\n\@@ -2750,7 +2754,8 @@ mod tests {let help = super::FRESH_HELP;assert!(help.contains("ignore an existing resume journal and restart"));assert!(help.contains("durable corpus generation"));- assert!(help.contains("never resets destination records"));+ assert!(help.contains("drops the documents previously published for that path"));+ assert!(help.contains("does not remove documents for a file that disappeared"));}#[test]diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rsindex 3a2a85670..ce826326e 100644--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs@@ -163,15 +163,43 @@ fn handle(stream: TcpStream, docs: &Arc<Mutex<Docs>>) {if method == "POST" && path.contains("/_delete_by_query") {let index = path.trim_start_matches('/').split('/').next().unwrap_or("");let query: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);- let key = query- .pointer("/query/term/ax_file")- .and_then(Value::as_str)- .map(str::to_owned);+ // A replacement purge is a `bool.should` of `ax_file` and `ax_path`+ // (#2139). A lone `term` is the older shape, still sent by sweeps.+ // Either matching term is enough: the path term drops a generation+ // published under a different content key.+ let mut terms: Vec<(String, String)> = Vec::new();+ for field in ["ax_file", "ax_path"] {+ if let Some(value) = query+ .pointer(&format!("/query/term/{field}"))+ .and_then(Value::as_str)+ {+ terms.push((field.to_string(), value.to_string()));+ }+ if let Some(should) = query+ .pointer("/query/bool/should")+ .and_then(Value::as_array)+ {+ for clause in should {+ if let Some(value) = clause+ .pointer(&format!("/term/{field}"))+ .and_then(Value::as_str)+ {+ terms.push((field.to_string(), value.to_string()));+ }+ }+ }+ }let mut deleted = 0u64;- if let (Some(key), Some(store)) = (key, docs.lock().unwrap().get_mut(index)) {- let before = store.len();- store.retain(|_, d| d.get("ax_file").and_then(Value::as_str) != Some(key.as_str()));- deleted = (before - store.len()) as u64;+ if let Some(store) = docs.lock().unwrap().get_mut(index) {+ if !terms.is_empty() {+ let before = store.len();+ store.retain(|_, doc| {+ !terms.iter().any(|(field, expected)| {+ doc.get(field).and_then(Value::as_str) == Some(expected.as_str())+ })+ });+ deleted = (before - store.len()) as u64;+ }}return respond(stream, 200, &json!({"deleted": deleted, "failures": []}));}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex cb74cd4bd..bf498f5cc 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -385,10 +385,34 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {(200, bulk_response(&body, state))} else if method == "POST" && path.contains("/_delete_by_query") {let query: Value = serde_json::from_slice(&body).unwrap();- let ax_file = query- .pointer("/query/term/ax_file")- .and_then(Value::as_str)- .map(str::to_owned);+ // A replacement purge is a `bool.should` of `ax_file` and `ax_path`+ // (#2139). A lone `term` is the older shape, still sent by sweeps.+ // Either term matching is enough: the path term is what drops a+ // generation published under a different content key.+ let mut file_terms: Vec<(String, String)> = Vec::new();+ for field in ["ax_file", "ax_path"] {+ if let Some(value) = query+ .pointer(&format!("/query/term/{field}"))+ .and_then(Value::as_str)+ {+ file_terms.push((field.to_string(), value.to_string()));+ }+ }+ if let Some(should) = query+ .pointer("/query/bool/should")+ .and_then(Value::as_array)+ {+ for clause in should {+ for field in ["ax_file", "ax_path"] {+ if let Some(value) = clause+ .pointer(&format!("/term/{field}"))+ .and_then(Value::as_str)+ {+ file_terms.push((field.to_string(), value.to_string()));+ }+ }+ }+ }let file_key = query.pointer("/query/term/file_key").and_then(Value::as_str)@@ -409,10 +433,12 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {.unwrap_or_default();let mut locked = state.lock().unwrap();locked.delete_calls += 1;- if let Some(key) = ax_file {- locked- .docs- .retain(|_, doc| doc.get("ax_file").and_then(Value::as_str) != Some(key.as_str()));+ if !file_terms.is_empty() {+ locked.docs.retain(|_, doc| {+ !file_terms.iter().any(|(field, expected)| {+ doc.get(field).and_then(Value::as_str) == Some(expected.as_str())+ })+ });}if let Some(key) = file_key {locked@@ -1548,28 +1574,24 @@ fn fresh_absorbs_an_edited_file_instead_of_calling_it_a_removal() {"the new content is live: {:?}",locked.docs);- // Documented, and NOT what this gate is for: `--fresh` rebuilds the plan,- // it does not reconcile the destination. Document ids derive from the- // content key (`ids::doc_id`), so the pre-edit record stays live beside- // the new one — the same outcome `--fresh` has always had. An ordinary- // rerun is the clean route for an edit: it keeps the planned key and runs- // a delete-before-replace transaction on it. What must never happen is- // this run being REFUSED by a message claiming a file that is sitting in- // the folder has vanished.+ // What must never happen is this run being REFUSED by a message claiming a+ // file that is sitting in the folder has vanished. The previous content+ // key is not the one `--fresh` writes, so the purge is by path (#2139):+ // the pre-edit row must not stay live beside the new one.assert!(locked.docs.values()- .any(|doc| doc["value"].as_str() == Some("before")),- "known --fresh gap: superseded records are not deleted: {:?}",+ .all(|doc| doc["value"].as_str() != Some("before")),+ "--fresh must drop the pre-edit row: {:?}",locked.docs);}-/// The clean route for the same edit: an ordinary rerun keeps the planned key-/// and replaces its records, so nothing is stranded. This is the contrast that-/// makes the `--fresh` gap above a documented trade-off rather than a silent-/// one.+/// An ordinary rerun keeps the planned key and replaces its records, so+/// nothing is stranded. `--fresh` of the same edit now purges by path as well+/// ([`fresh_absorbs_an_edited_file_instead_of_calling_it_a_removal`]); this+/// test is the path that does not need a new key to get there.#[test]fn an_ordinary_rerun_replaces_an_edited_file_without_stranding_records() {let _guard = FAILPOINT_TEST_LOCK@@ -1596,6 +1618,211 @@ fn an_ordinary_rerun_replaces_an_edited_file_without_stranding_records() {assert_eq!(values, ["after"], "the superseded record is replaced");}+/// #2139: graph resume must drop symbol documents whose declaration moved or+/// disappeared. CSV row locators (`r0`) stay put when a cell changes, so+/// [`an_ordinary_rerun_replaces_an_edited_file_without_stranding_records`]+/// still passes when the file-level `ax_file` delete is a no-op. Per-symbol+/// ids are `code:<line>:<name>` and do not.+#[test]+fn graph_resume_drops_shifted_and_removed_symbols() {+ let _guard = FAILPOINT_TEST_LOCK+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ let _io_guard = state::FILE_DONE_IO_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("jobs.rs"), GRAPH_CODE_V1).unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ {+ let locked = endpoint.state.lock().unwrap();+ let rows = graph_symbol_rows(&locked);+ assert!(+ rows.iter().any(|(name, _, code)| {+ name == "query_job" && code.contains("group_id") && !code.contains("&self")+ }),+ "genesis must index the original query_job symbol: {rows:?}"+ );+ assert!(+ rows.iter().any(|(name, _, _)| name == "gone_symbol"),+ "genesis must index gone_symbol: {rows:?}"+ );+ }++ // A previous generation under a different content key (what `--fresh`, or+ // an earlier key change, leaves behind). Ordinary resume keeps the planned+ // key and used to delete only that key, so this document survived.+ endpoint.state.lock().unwrap().docs.insert(+ "stale-generation".to_string(),+ json!({+ "ax_path": "jobs.rs",+ "ax_file": "stale-generation-key",+ "ax_locator": "code:1:query_job",+ "name": "query_job",+ "line": 1,+ "code": "pub fn query_job(group_id: &str, raw: &str) -> bool"+ }),+ );++ fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V2).unwrap();+ assert_eq!(+ run_index(config).unwrap(),+ 0,+ "graph resume of an edited code file must succeed"+ );+ let locked = endpoint.state.lock().unwrap();+ let live = graph_symbol_rows(&locked);+ let rendered = serde_json::to_string(&locked.docs).unwrap();+ assert!(+ !rendered.contains("gone_symbol"),+ "removed symbol gone_symbol is still indexed: {rendered}"+ );+ assert!(+ !rendered.contains("pub fn query_job(group_id"),+ "the pre-edit query_job signature is still indexed: {rendered}"+ );+ assert!(+ rendered.contains("pub fn query_job(&self"),+ "the current query_job signature is missing: {rendered}"+ );+ drop(locked);++ let fresh_corpus = tempfile::tempdir().unwrap();+ let fresh_state = tempfile::tempdir().unwrap();+ fs::write(fresh_corpus.path().join("jobs.rs"), GRAPH_CODE_V2).unwrap();+ let fresh = MockEndpoint::start(usize::MAX);+ let fresh_config = cfg(fresh_corpus.path(), fresh_state.path(), &fresh.url);+ assert_eq!(run_index(fresh_config).unwrap(), 0);+ let fresh_locked = fresh.state.lock().unwrap();+ let fresh_rows = graph_symbol_rows(&fresh_locked);+ assert_eq!(+ live, fresh_rows,+ "symbol documents (name, line, code) must match a fresh graph index of the edited file"+ );+ let live_docs = endpoint.state.lock().unwrap().docs.len();+ assert_eq!(+ live_docs,+ fresh_locked.docs.len(),+ "document count must match a fresh graph index of the edited file\n\+ live={}\nfresh={}",+ serde_json::to_string(&endpoint.state.lock().unwrap().docs).unwrap(),+ serde_json::to_string(&fresh_locked.docs).unwrap()+ );+}++/// #2139: `--fresh` gives the edited file a new content key and used to skip+/// the delete, so the previous symbol documents stayed searchable. A second+/// edit then resumes on that new key and must not bring the first generation+/// back either.+#[test]+fn fresh_then_resume_drops_every_previous_symbol_generation() {+ let _guard = FAILPOINT_TEST_LOCK+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ let _io_guard = state::FILE_DONE_IO_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("jobs.rs"), GRAPH_CODE_V1).unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V2).unwrap();+ config.fresh = true;+ assert_eq!(run_index(config.clone()).unwrap(), 0, "--fresh of an edit");+ {+ let rendered = serde_json::to_string(&endpoint.state.lock().unwrap().docs).unwrap();+ assert!(+ !rendered.contains("gone_symbol"),+ "--fresh left the removed symbol: {rendered}"+ );+ assert!(+ !rendered.contains("pub fn query_job(group_id"),+ "--fresh left the pre-edit signature: {rendered}"+ );+ assert!(+ rendered.contains("pub fn query_job(&self"),+ "--fresh did not index the current signature: {rendered}"+ );+ }++ fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V3).unwrap();+ config.fresh = false;+ assert_eq!(run_index(config).unwrap(), 0, "resume after --fresh");+ let rendered = serde_json::to_string(&endpoint.state.lock().unwrap().docs).unwrap();+ assert!(+ !rendered.contains("gone_symbol")+ && !rendered.contains("pub fn query_job(group_id")+ && !rendered.contains("pub fn query_job(&self, group_id"),+ "a later resume must not keep either previous generation: {rendered}"+ );+ assert!(+ rendered.contains("pub fn query_job(&self, id: u64)"),+ "the third signature is missing: {rendered}"+ );+}++fn graph_symbol_rows(state: &MockState) -> Vec<(String, u64, String)> {+ let mut rows: Vec<(String, u64, String)> = state+ .docs+ .values()+ .filter(|doc| doc.get("defs").is_none() && doc["ax_locator"].as_str() != Some("file"))+ .filter_map(|doc| {+ Some((+ doc.get("name")?.as_str()?.to_string(),+ doc.get("line")?.as_u64()?,+ doc.get("code")?.as_str()?.to_string(),+ ))+ })+ .collect();+ rows.sort();+ rows+}++const GRAPH_CODE_V1: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ pub fn gone_symbol() -> i32 {\n\+ 1\n\+ }\n\+\n\+ pub fn query_job(group_id: &str, raw: &str) -> bool {\n\+ !raw.is_empty()\n\+ }\n\+}\n\+";++const GRAPH_CODE_V2: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ // the signature gained &self and the declaration moved down\n\+\n\+\n\+ pub fn query_job(&self, group_id: &str, raw: &str) -> bool {\n\+ !raw.is_empty()\n\+ }\n\+}\n\+";++/// Not a substring of [`GRAPH_CODE_V2`], so a search of the indexed text can+/// tell the third generation from the second.+const GRAPH_CODE_V3: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ pub fn query_job(&self, id: u64) -> bool {\n\+ id > 0\n\+ }\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.diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 5eddd164d..26bae1a0b 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -1877,6 +1877,143 @@ fn code_file_reindex_does_not_abort_on_absent_symbols_field() {);}+/// #2139: re-indexing a changed code file must drop documents for symbols that+/// no longer exist, including when a declaration moves to a new line.+///+/// Per-symbol `_id`s are `code:<line>:<name>` (#500). A signature edit that+/// also shifts the declaration does not overwrite the old symbol document, so+/// the file-level delete on `ax_file` is what has to remove it. The sibling+/// code reindex above changes a field type without moving the declaration, so+/// the same locator is overwritten and a missed delete still looks clean.+///+/// `--no-graph` (this module). The graph-enabled twin lives in+/// `failure_resume_http_tests`.+#[test]+fn changed_code_file_reindex_drops_shifted_and_removed_symbols() {+ 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 source = corpus.path().join("jobs.rs");+ fs::write(&source, CODE_V1).unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ let first = endpoint.data_docs();+ assert!(+ symbol_rows(&first).iter().any(|(name, _, code)| {+ name == "query_job" && code.contains("group_id") && !code.contains("&self")+ }),+ "genesis must index the original query_job symbol: {}",+ serde_json::to_string(&symbol_rows(&first)).unwrap()+ );+ assert!(+ symbol_rows(&first)+ .iter()+ .any(|(name, _, _)| name == "gone_symbol"),+ "genesis must index gone_symbol: {}",+ serde_json::to_string(&symbol_rows(&first)).unwrap()+ );++ fs::write(&source, CODE_V2).unwrap();+ assert_eq!(+ run_index(config).unwrap(),+ 0,+ "an ordinary incremental reindex of an edited code file must succeed"+ );+ let live = endpoint.data_docs();+ assert_code_matches_fresh(&live, "no-graph incremental reindex");+}++/// A from-scratch index of [`CODE_V2`], the oracle for #2139: the edited file's+/// live documents must match this, not a superset that still holds v1 symbols.+fn fresh_code_v2_docs() -> Vec<Value> {+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("jobs.rs"), CODE_V2).unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);+ assert_eq!(run_index(config).unwrap(), 0);+ endpoint.data_docs()+}++fn assert_code_matches_fresh(live: &[Value], label: &str) {+ let rendered = serde_json::to_string(live).unwrap();+ assert!(+ !rendered.contains("gone_symbol"),+ "{label}: removed symbol gone_symbol is still indexed: {rendered}"+ );+ assert!(+ !rendered.contains("pub fn query_job(group_id"),+ "{label}: the pre-edit query_job signature is still indexed: {rendered}"+ );+ assert!(+ rendered.contains("pub fn query_job(&self"),+ "{label}: the current query_job signature is missing: {rendered}"+ );+ let fresh = fresh_code_v2_docs();+ assert_eq!(+ symbol_rows(live),+ symbol_rows(&fresh),+ "{label}: symbol documents (name, line, code) must match a fresh index of the edited file"+ );+ assert_eq!(+ live.len(),+ fresh.len(),+ "{label}: document count must match a fresh index of the edited file\n\+ live={rendered}\nfresh={}",+ serde_json::to_string(&fresh).unwrap()+ );+}++/// `(name, line, code)` of per-symbol documents, in a stable order.+fn symbol_rows(docs: &[Value]) -> Vec<(String, u64, String)> {+ let mut rows: Vec<(String, u64, String)> = docs+ .iter()+ .filter(|doc| doc.get("defs").is_none())+ .filter_map(|doc| {+ Some((+ doc.get("name")?.as_str()?.to_string(),+ doc.get("line")?.as_u64()?,+ doc.get("code")?.as_str()?.to_string(),+ ))+ })+ .collect();+ rows.sort();+ rows+}++/// v1: `gone_symbol` plus a two-argument `query_job`.+const CODE_V1: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ pub fn gone_symbol() -> i32 {\n\+ 1\n\+ }\n\+\n\+ pub fn query_job(group_id: &str, raw: &str) -> bool {\n\+ !raw.is_empty()\n\+ }\n\+}\n\+";++/// v2: `gone_symbol` removed, `query_job` gains `&self` and moves down.+const CODE_V2: &str = "\+struct Jobs;\n\+\n\+impl Jobs {\n\+ // the signature gained &self and the declaration moved down\n\+\n\+\n\+ pub fn query_job(&self, group_id: &str, raw: &str) -> bool {\n\+ !raw.is_empty()\n\+ }\n\+}\n\+";+#[test]fn pending_generation_replays_sealed_source_after_live_source_mutates() {let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 9925b32a6..46b4b1f75 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -4756,6 +4756,92 @@ fn build_mapping(specs: &[infer::FieldSpec]) -> Value {// ─── the main run ────────────────────────────────────────────────────────+/// One file's documents as the previous plan published them.+///+/// Kept across `--fresh`, which deletes the journal (and this plan) before+/// phase B. The new run's content key no longer matches `file_key`, so a+/// delete keyed only on the key about to be written leaves these documents+/// live (#2139).+#[derive(Clone)]+struct PriorPublication {+ rel: String,+ file_key: String,+ indices: Vec<String>,+}++fn prior_publications(+ plan: &Plan,+) -> (+ HashMap<String, PriorPublication>,+ HashMap<String, PriorPublication>,+) {+ let index_of: HashMap<&str, &str> = plan+ .datasets+ .iter()+ .map(|dataset| (dataset.slug.as_str(), dataset.index.as_str()))+ .collect();+ let mut by_rel = HashMap::new();+ let mut by_path_id = HashMap::new();+ for (key, assignment) in &plan.files {+ let mut indices: Vec<String> = assignment+ .assignments+ .iter()+ .filter_map(|(_, slug)| {+ index_of+ .get(slug.as_str())+ .map(|index| (*index).to_string())+ })+ .collect();+ indices.sort();+ indices.dedup();+ let published = PriorPublication {+ rel: assignment.rel.clone(),+ file_key: key.clone(),+ indices,+ };+ by_rel.insert(assignment.rel.clone(), published.clone());+ if !assignment.path_id.is_empty() {+ by_path_id.insert(assignment.path_id.clone(), published);+ }+ }+ (by_rel, by_path_id)+}++/// Selector for every document a file replacement must remove (#2139).+///+/// `ax_file` is the content key this run writes. An ordinary resume keeps the+/// planned key, so that term removes the previous generation. It does not+/// remove a generation published under a different key: `--fresh` rebuilds+/// the key from the new digest, and a later resume only knows the latest+/// one. Per-symbol ids are `code:<line>:<name>`, so those older documents are+/// not overwritten when the declaration moves. `ax_path` is the same path+/// across those keys. `prior` adds the previous key and path when a rename+/// or a key change means the current pair does not name them.+fn replacement_purge_query(+ current_key: &str,+ current_rel: &str,+ prior: Option<&PriorPublication>,+) -> Value {+ let mut should = vec![+ json!({"term": {"ax_file": current_key}}),+ json!({"term": {"ax_path": current_rel}}),+ ];+ if let Some(prior) = prior {+ if prior.file_key != current_key {+ should.push(json!({"term": {"ax_file": prior.file_key}}));+ }+ if prior.rel != current_rel {+ should.push(json!({"term": {"ax_path": prior.rel}}));+ }+ }+ json!({+ "bool": {+ "should": should,+ "minimum_should_match": 1+ }+ })+}+/// Files phase B still has work for: planned, with a real content key, and/// either never finished or finished against different bytes.///@@ -7709,6 +7795,13 @@ fn run_index_report_inner(Some(prior) if graph_edges_index(&cfg).is_some() => plan_anchor_nodes(prior),_ => Vec::new(),};+ // Same moment as the anchor snapshot: `--fresh` drops the plan inside+ // `open_after_preflight`, and phase B needs the previous key to notice+ // that the documents it is about to supersede are not under the new one.+ let (prior_by_rel, prior_by_path_id) = match preflight.plan.as_ref() {+ Some(prior) => prior_publications(prior),+ None => (HashMap::new(), HashMap::new()),+ };let mut journal = state::Journal::open_after_preflight(preflight,&root_str,@@ -8555,6 +8648,26 @@ fn run_index_report_inner(// genuinely fresh and skip the delete round trip.cleanup_required.extend(todo.iter().map(|&i| keys[i].clone()));}+ // #2139: `--fresh` rebuilds every content key and wipes `journal.done`+ // first, so the set above is empty. The file is then republished under+ // the new key and the previous key's symbol documents stay live. A later+ // ordinary resume only deletes the latest key, which is how one function+ // ends up indexed at several line numbers. Schedule a purge for every+ // path whose published key just changed. Unchanged keys are not scheduled:+ // their ids already overwrite, and a delete per unchanged file is the+ // refresh cost #1224 removed.+ let mut superseded: HashMap<String, PriorPublication> = HashMap::new();+ for (i, file) in files.iter().enumerate() {+ let prior = prior_by_path_id+ .get(&file.rel_id)+ .or_else(|| prior_by_rel.get(&file.rel));+ if let Some(prior) = prior {+ if prior.file_key != keys[i] {+ cleanup_required.insert(keys[i].clone());+ superseded.insert(file.rel.clone(), prior.clone());+ }+ }+ }let todo_set: std::collections::HashSet<usize> = todo.iter().copied().collect();for (index, spool) in pdf_spools.iter_mut().enumerate() {if spool.is_none() {@@ -9327,17 +9440,25 @@ fn run_index_report_inner(// full-content verification. Delete-before-replace makes// a retry clean up any partial prior attempt.if send_err.is_none() && cleanup_required.contains(key) {- let mut indices: Vec<&str> = fa+ let prior = superseded.get(&f.rel);+ let mut indices: Vec<String> = fa.assignments.iter()- .filter_map(|(_, slug)| ds_rt.get(slug).map(|rt| rt.index.as_str()))+ .filter_map(|(_, slug)| ds_rt.get(slug).map(|rt| rt.index.clone())).collect();- indices.sort_unstable();+ if let Some(prior) = prior {+ indices.extend(prior.indices.iter().cloned());+ }+ indices.sort();indices.dedup();- for index in indices {- if let Err(error) =- es.delete_by_query(index, &json!({"term": {"ax_file": key}}))- {+ // One query: the key this run writes, and the path. The path+ // term is what removes a previous generation whose key this+ // run no longer uses (#2139). `prior` adds that generation's+ // own key and path when either differs (a `--fresh` key+ // change, or a rename).+ let query = replacement_purge_query(key, &f.rel, prior);+ for index in &indices {+ if let Err(error) = es.delete_by_query(index, &query) {send_err = Some(format!("remove prior records for {} before replacement: {error:#}",f.reldiff --git a/landing/docs/recipes/zero-config-autoindex.html b/landing/docs/recipes/zero-config-autoindex.htmlindex 21a00aa68..f15a2860a 100644--- a/landing/docs/recipes/zero-config-autoindex.html+++ b/landing/docs/recipes/zero-config-autoindex.html@@ -356,7 +356,7 @@ live indices at http://localhost:9280:ax-docs 1 docsax-exports 800 docsautoindex-catalog 9 docs</pre>- <p><code class="inline">--fresh</code> ignores the resume journal and restarts (ids stay idempotent), which on a graph-enabled or pre-generation state directory is how a rerun picks up files added since the last one. It never removes stale records from the destination, and it is refused once the state directory holds a durable corpus generation — re-run without it and the generated <code class="inline">--no-graph</code> path reconciles additions, changes, deletions, renames and no-op reruns incrementally.</p>+ <p><code class="inline">--fresh</code> ignores the resume journal and restarts (ids stay idempotent for unchanged bytes), which on a graph-enabled or pre-generation state directory is how a rerun picks up files added since the last one. A file that is still present and whose content key changed is republished, and the documents previously published for that path are removed. It does not remove documents for a file that disappeared, and it is refused once the state directory holds a durable corpus generation — re-run without it and the generated <code class="inline">--no-graph</code> path reconciles additions, changes, deletions, renames and no-op reruns incrementally.</p><p>On a graph-enabled or pre-generation journal, a rerun that resumes an existing plan indexes changed files and reports added ones as skipped. Deleting a file is refused there: nothing on that path removes the documents it already published, so the rerun stops before touching the destination and names what is gone — the first ten, then an <code class="inline">… and N more</code> tail, with <code class="inline">--json</code> carrying every entry. Restore the file and rerun, or rebuild — in place by deleting the named indices and the state directory, or isolated under a new <code class="inline">--state-dir</code>, <code class="inline">--prefix</code> and <code class="inline">--brain</code> (or <code class="inline">--no-graph</code>), validated before you switch readers. The shared <code class="inline">autoindex-catalog</code> and the old target require explicit cleanup. A <code class="inline">--no-graph</code> state directory written before the generation format cannot be adopted in place and must be rebuilt the same way.</p><hr>diff --git a/landing/llms-full.txt b/landing/llms-full.txtindex 0e8756ec1..04bd9b733 100644--- a/landing/llms-full.txt+++ b/landing/llms-full.txt@@ -462,12 +462,15 @@ after any --no-graph/--approve fast run over code,POST /<prefix>-*/_count {"query":{"exists":{"field":"language"}}}must be > 0 for a tree that contains source. If it is 0, re-run without --no-graph.---fresh ignores the resume journal and restarts (ids stay idempotent); on a-graph-enabled or pre-generation state directory that is how you pick up files-added since the last run. It never removes stale destination records, and it is-refused once the state directory holds a durable corpus generation — re-run-without it and the generated --no-graph path reconciles additions, changes,-deletions, renames and no-op reruns incrementally.+--fresh ignores the resume journal and restarts (ids stay idempotent for+unchanged bytes); on a graph-enabled or pre-generation state directory that is+how you pick up files added since the last run. A file that is still present+and whose content key changed is republished, and the documents previously+published for that path are removed. It does not remove documents for a file+that disappeared, and it is refused once the state directory holds a durable+corpus generation — re-run without it and the generated --no-graph path+reconciles additions, changes, deletions, renames and no-op reruns+incrementally.On a graph-enabled or pre-generation journal, a rerun that resumes an existingplan indexes changed files and reports added ones as skipped. Deleting an