Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(autoindex): a reduced plan no longer deletes an existing index (#2128)

xerj-orgf887ff4c415e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6bee5674..307e18dd6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `xerj autoindex` no longer deletes an existing index when a later run uses
+ a reduced disk-budget plan (`--plan code-and-docs`, or `--yes` when the
+ default plan does not fit). The plan's keep-set was applied to the walk
+ before reconcile, so files the plan left out looked removed: the
+ `--no-graph` generation emitted `Delete` for their groups, and the graph
+ path swept them as exclusions. A re-run that would drop already-indexed
+ files now exits 4 and lists those files and the datasets that would be
+ left empty. `--drop-indexed` is the confirmation that deletes them.
+ `--plan` and `--yes` choose what to index; they do not agree to the
+ deletion.
+
- A bare hub question that names a language or a technology
(`xerj "how do I use async let in Swift"`, `xerj "Swift Result type map"`)
routes from the catalogue entry — slug, topics, a language word in the
diff --git a/engine/crates/xerj-autoindex/src/budget.rs b/engine/crates/xerj-autoindex/src/budget.rs
index 2425673a5..3db31f8ef 100644
--- a/engine/crates/xerj-autoindex/src/budget.rs
+++ b/engine/crates/xerj-autoindex/src/budget.rs
@@ -388,6 +388,9 @@ pub enum Outcome {
keep: Option<Vec<String>>,
no_semantic: bool,
note: String,
+ /// Set when a named plan (or `--yes`) produced `keep`. `None` on the
+ /// default plan, which does not filter the walk.
+ plan_name: Option<String>,
},
/// `body` is `Null` for a cancel, which prints no JSON.
Stop { code: i32, body: Value },
@@ -619,6 +622,7 @@ pub fn resolve(assessment: &Assessment, choice: Choice) -> Outcome {
keep: None,
no_semantic: false,
note: assessment.note.clone(),
+ plan_name: None,
};
};
match assessment.plans.iter().find(|p| p.name == name) {
@@ -642,6 +646,7 @@ pub fn resolve(assessment: &Assessment, choice: Choice) -> Outcome {
} else {
assessment.note.clone()
},
+ plan_name: Some(plan.name.to_string()),
},
None => {
let mut body = assessment.body.clone();
@@ -658,6 +663,151 @@ pub fn resolve(assessment: &Assessment, choice: Choice) -> Outcome {
}
}
+/// How many plan-excluded paths the decision JSON lists before it counts the rest.
+const REMOVAL_LIST_CAP: usize = 20;
+
+/// Files a reduced plan would drop that are already published and still in the walk.
+///
+/// The budget keep-set is applied to the walk *before* reconcile. On the
+/// `--no-graph` path those files are absent from the inventory, so
+/// `plan_operations` emits `Delete` for their groups. On the graph path they
+/// are still on disk, so they are classified as exclusions and
+/// `sweep_excluded_groups` deletes their documents. Either way a smaller plan
+/// silently unindexes data the folder still has. This is the list that refusal
+/// prints, and that `--drop-indexed` agrees to remove.
+///
+/// A file that is in a prior plan but no longer in the walk is a real deletion
+/// or an ignore-rule exclusion, not this decision, and is left out of the list.
+pub(crate) fn removal_decision(
+ plan_name: &str,
+ plans: &[&crate::state::Plan],
+ discovered: &[FileEntry],
+ keep: &[String],
+) -> Option<Value> {
+ let keep: std::collections::HashSet<&str> = keep.iter().map(String::as_str).collect();
+ let walked: std::collections::HashSet<&str> =
+ discovered.iter().map(|file| file.rel.as_str()).collect();
+ let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
+ let mut drops: Vec<Removal> = Vec::new();
+ for prior in plans {
+ for (key, assignment) in &prior.files {
+ if !walked.contains(assignment.rel.as_str()) || keep.contains(assignment.rel.as_str()) {
+ continue;
+ }
+ if !seen.insert((key.clone(), assignment.rel.clone())) {
+ continue;
+ }
+ let mut datasets: Vec<String> = assignment
+ .assignments
+ .iter()
+ .map(|(_, slug)| slug.clone())
+ .collect();
+ datasets.sort();
+ datasets.dedup();
+ drops.push(Removal {
+ path: assignment.rel.clone(),
+ file_key: key.clone(),
+ datasets,
+ });
+ }
+ }
+ if drops.is_empty() {
+ return None;
+ }
+ drops.sort_by(|left, right| {
+ left.path
+ .cmp(&right.path)
+ .then_with(|| left.file_key.cmp(&right.file_key))
+ });
+ let total = drops.len();
+ let listed = drops.len().min(REMOVAL_LIST_CAP);
+ let dropped_keys: std::collections::HashSet<&str> = drops
+ .iter()
+ .map(|removed| removed.file_key.as_str())
+ .collect();
+ let datasets = emptied_datasets(plans, &walked, &keep, &dropped_keys);
+ let listed_paths = drops
+ .iter()
+ .take(listed)
+ .map(|removed| removed.path.as_str())
+ .collect::<Vec<_>>()
+ .join(", ");
+ let more = if total > listed {
+ format!(" (and {} more)", total - listed)
+ } else {
+ String::new()
+ };
+ let dataset_phrase = if datasets.is_empty() {
+ String::new()
+ } else {
+ format!(" Dataset(s) left with no files: {}.", datasets.join(", "))
+ };
+ let would_remove: Vec<Value> = drops
+ .iter()
+ .take(listed)
+ .map(|removed| {
+ json!({
+ "path": removed.path,
+ "file_key": removed.file_key,
+ "datasets": removed.datasets,
+ })
+ })
+ .collect();
+ Some(json!({
+ "xerj": "autoindex-plan-removal",
+ "decision_required": true,
+ "exit_code": crate::gate::EXIT_NEEDS_DECISION,
+ "plan": plan_name,
+ "would_remove": would_remove,
+ "would_remove_total": total,
+ "would_remove_truncated": total > listed,
+ "datasets": datasets,
+ "accept": format!(
+ "plan {plan_name} leaves out {total} already-indexed file(s) still in the folder: \
+ {listed_paths}{more}.{dataset_phrase} A reconcile would delete them. Nothing was \
+ changed. Re-run the same command with --drop-indexed to delete them, or drop \
+ --plan to keep the full index. --yes and --plan do not agree to this deletion"
+ ),
+ }))
+}
+
+struct Removal {
+ path: String,
+ file_key: String,
+ datasets: Vec<String>,
+}
+
+/// A dataset the plan would empty: at least one of its published files is in
+/// the drop list, and none of its published files are both still walked and kept.
+fn emptied_datasets(
+ plans: &[&crate::state::Plan],
+ walked: &std::collections::HashSet<&str>,
+ keep: &std::collections::HashSet<&str>,
+ dropped_keys: &std::collections::HashSet<&str>,
+) -> Vec<String> {
+ let mut survivor: std::collections::HashSet<&str> = std::collections::HashSet::new();
+ let mut touched: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
+ for prior in plans {
+ for (key, assignment) in &prior.files {
+ let survives =
+ walked.contains(assignment.rel.as_str()) && keep.contains(assignment.rel.as_str());
+ for (_, slug) in &assignment.assignments {
+ if survives {
+ survivor.insert(slug.as_str());
+ }
+ if dropped_keys.contains(key.as_str()) {
+ touched.insert(slug.as_str());
+ }
+ }
+ }
+ }
+ touched
+ .into_iter()
+ .filter(|slug| !survivor.contains(slug))
+ .map(str::to_owned)
+ .collect()
+}
+
fn budget_bytes_of(body: &Value) -> Option<u64> {
body.get("budget_bytes").and_then(Value::as_u64)
}
@@ -1550,4 +1700,141 @@ mod tests {
let mut input = std::io::Cursor::new("cancel\n");
assert_eq!(read_choice(&mut input, &names, |_| {}), Choice::Cancel);
}
+
+ fn assignment(rel: &str, datasets: &[&str]) -> crate::state::FileAssignment {
+ crate::state::FileAssignment {
+ rel: rel.to_string(),
+ path_id: format!("unix:{rel}"),
+ is_symlink: Some(false),
+ family: "text".into(),
+ gzip: false,
+ content_digest: None,
+ assignments: datasets
+ .iter()
+ .map(|slug| (None, (*slug).to_string()))
+ .collect(),
+ as_document: false,
+ }
+ }
+
+ fn walked(rel: &str) -> FileEntry {
+ FileEntry {
+ path: std::path::PathBuf::from(rel),
+ rel: rel.to_string(),
+ rel_id: format!("unix:{rel}"),
+ is_symlink: false,
+ size: 8,
+ }
+ }
+
+ fn plan_with(files: Vec<(&str, &str, &[&str])>) -> crate::state::Plan {
+ let mut plan = crate::state::Plan::default();
+ for (key, rel, datasets) in files {
+ plan.files
+ .insert(key.to_string(), assignment(rel, datasets));
+ }
+ plan
+ }
+
+ #[test]
+ fn a_reduced_plan_lists_indexed_files_it_would_drop_and_the_datasets_it_empties() {
+ let prior = plan_with(vec![
+ ("key-rs", "main.rs", &["code"]),
+ ("key-md", "notes.md", &["docs"]),
+ ("key-csv", "rows.csv", &["rows"]),
+ ("key-gone", "old.csv", &["rows"]),
+ ]);
+ let discovered = vec![walked("main.rs"), walked("notes.md"), walked("rows.csv")];
+ let body = removal_decision(
+ "code-and-docs",
+ &[&prior],
+ &discovered,
+ &["main.rs".into(), "notes.md".into()],
+ )
+ .expect("rows.csv is indexed and the plan leaves it out");
+ assert_eq!(body["xerj"], "autoindex-plan-removal");
+ assert_eq!(body["exit_code"], crate::gate::EXIT_NEEDS_DECISION);
+ assert_eq!(body["decision_required"], true);
+ assert_eq!(body["plan"], "code-and-docs");
+ assert_eq!(body["would_remove_total"], 1);
+ assert_eq!(body["would_remove_truncated"], false);
+ assert_eq!(body["would_remove"][0]["path"], "rows.csv");
+ assert_eq!(body["would_remove"][0]["file_key"], "key-csv");
+ assert_eq!(body["would_remove"][0]["datasets"][0], "rows");
+ // old.csv is not in the walk: a real deletion, not this decision.
+ // rows.csv is the only remaining rows file, so the dataset would be empty.
+ assert_eq!(body["datasets"][0], "rows");
+ assert_eq!(body["datasets"].as_array().map(Vec::len), Some(1));
+ let accept = body["accept"].as_str().unwrap();
+ assert!(accept.contains("rows.csv"), "{accept}");
+ assert!(accept.contains("rows"), "{accept}");
+ assert!(accept.contains("--drop-indexed"), "{accept}");
+ assert!(
+ !accept.contains("old.csv"),
+ "a file already gone from the folder is not a plan removal: {accept}"
+ );
+ }
+
+ #[test]
+ fn a_kept_sibling_keeps_the_dataset_off_the_emptied_list() {
+ let prior = plan_with(vec![
+ ("key-a", "keep.csv", &["tables"]),
+ ("key-b", "drop.csv", &["tables"]),
+ ]);
+ let discovered = vec![walked("keep.csv"), walked("drop.csv")];
+ let body = removal_decision("skip-data", &[&prior], &discovered, &["keep.csv".into()])
+ .expect("drop.csv would be removed");
+ assert_eq!(body["would_remove"][0]["path"], "drop.csv");
+ assert!(
+ body["datasets"].as_array().unwrap().is_empty(),
+ "tables still has keep.csv: {}",
+ body
+ );
+ }
+
+ #[test]
+ fn a_plan_that_keeps_every_indexed_file_has_nothing_to_confirm() {
+ let prior = plan_with(vec![("key-rs", "main.rs", &["code"])]);
+ let discovered = vec![walked("main.rs"), walked("new.rs")];
+ assert!(removal_decision(
+ "code-and-docs",
+ &[&prior],
+ &discovered,
+ &["main.rs".into(), "new.rs".into()],
+ )
+ .is_none());
+ }
+
+ #[test]
+ fn the_removal_list_is_capped_and_the_total_is_not() {
+ let mut plan = crate::state::Plan::default();
+ let mut discovered = Vec::new();
+ for i in 0..(REMOVAL_LIST_CAP + 3) {
+ let rel = format!("f{i:02}.csv");
+ plan.files
+ .insert(format!("key-{i}"), assignment(&rel, &["tables"]));
+ discovered.push(walked(&rel));
+ }
+ let body = removal_decision("skip-data", &[&plan], &discovered, &[])
+ .expect("every csv is indexed and the plan keeps none");
+ assert_eq!(body["would_remove_total"], REMOVAL_LIST_CAP + 3);
+ assert_eq!(body["would_remove_truncated"], true);
+ assert_eq!(
+ body["would_remove"].as_array().map(Vec::len),
+ Some(REMOVAL_LIST_CAP)
+ );
+ assert_eq!(body["would_remove"][0]["path"], "f00.csv");
+ assert_eq!(body["datasets"][0], "tables");
+ let accept = body["accept"].as_str().unwrap();
+ assert!(accept.contains("and 3 more"), "{accept}");
+ }
+
+ #[test]
+ fn the_same_file_in_two_plans_is_listed_once() {
+ let prior = plan_with(vec![("key-csv", "rows.csv", &["rows"])]);
+ let discovered = vec![walked("rows.csv")];
+ let body = removal_decision("code-and-docs", &[&prior, &prior], &discovered, &[])
+ .expect("one file");
+ assert_eq!(body["would_remove_total"], 1);
+ }
}
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 7ed13c1f8..ac95fa2a9 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -123,6 +123,10 @@ pub struct IndexCfg {
/// and refused when it does not. A named plan runs even when the estimate
/// says it does not fit (with a warning): that is the override.
pub budget_plan: Option<String>,
+ /// `--drop-indexed`. Confirms that a reduced plan may delete files it
+ /// leaves out when those files are already indexed. Without it that
+ /// re-run exits 4 and lists them. `--plan` and `--yes` do not set this.
+ pub drop_indexed: bool,
pub json: bool,
pub quiet: bool,
/// Progress surface. Orthogonal to `json`: `--json` shapes *stdout* (the
@@ -395,7 +399,8 @@ pub fn help_text_with(feedback: bool) -> String {
\x20\x20\x20\x20--yes, -y alias for --approve proceed. When the default index\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\x20plan does not fit the disk budget, --yes takes the\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\x20recommended plan that does fit. It does not index 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\x20plan that is over budget.\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\x20plan that is over budget. It does not delete 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\x20files a smaller plan leaves out; that is --drop-indexed.\n\
\x20\x20\x20\x20--max-index-size <N> cap the estimated index (bytes, or a KB/MB/GB suffix).\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 disk budget is the free space under the node's\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\x20flood-stage watermark; this flag lowers that cap.\n\
@@ -405,6 +410,9 @@ 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\x20code-and-docs-no-vectors. A named plan runs even\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\x20when the estimate says it does not fit (warned).\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\x20See DISK BUDGET.\n\
+ \x20\x20\x20\x20--drop-indexed delete already-indexed files a reduced plan leaves\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\x20out. Without this flag that re-run exits 4 and lists\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\x20them. --plan and --yes do not agree to the deletion.\n\
\x20\x20\x20\x20--dry-run walk+sniff+infer, print the plan, index nothing\n\
\x20\x20\x20\x20--walk-only stop after the walk. Prints each top-level folder's\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 count and size, what the ignore rules would drop\n\
@@ -702,6 +710,11 @@ pub fn help_text_with(feedback: bool) -> String {
\x20\x20\x20\x20list and the run exits 4 unless --yes takes the recommended plan that\n\
\x20\x20\x20\x20fits, or --plan names one (a named plan is the override: it runs\n\
\x20\x20\x20\x20over the estimate with a warning; the estimate errs high).\n\
+ \x20\x20\x20\x20A reduced plan on a folder that is already indexed does not delete\n\
+ \x20\x20\x20\x20the files it leaves out. That re-run exits 4 and lists the files\n\
+ \x20\x20\x20\x20and the datasets a reconcile would remove, until --drop-indexed\n\
+ \x20\x20\x20\x20confirms it. --yes chooses a plan; it does not agree to delete\n\
+ \x20\x20\x20\x20indexed data.\n\
\x20\x20\x20\x20A terminal with the question visible is asked. Kinds without a\n\
\x20\x20\x20\x20calibration are reported as unmeasured and do not refuse the run.\n\
\x20\x20\x20\x20Skipped files are listed after the ok: line (up to 20, then a count).\n\
@@ -727,10 +740,13 @@ pub fn help_text_with(feedback: bool) -> String {
\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\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, or a --watch\n\
- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20poll cost more than --max-monthly-ops; nothing was indexed\n\
- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20and a JSON decision request is on stdout. A plan that does\n\
- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20not fit is not started, including with --yes;\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\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20--watch poll cost more than --max-monthly-ops; nothing was\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20indexed and a JSON decision request is on stdout. A plan\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20that does not fit is not started, including with --yes.\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Already-indexed files are not deleted unless --drop-indexed\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20is also set;\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x202 usage; 1 endpoint/journal failure, a refused corpus removal, or a\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20refused unsafe state transition\n",
feedback_block = xerj_common::feedback::block(feedback),
@@ -879,6 +895,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
let mut max_index_bytes: Option<u64> = None;
let mut max_index_explicit = false;
let mut budget_plan: Option<String> = None;
+ let mut drop_indexed = false;
let mut json = false;
let mut quiet = false;
let mut progress: Option<ProgressMode> = None;
@@ -1122,6 +1139,12 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
}
budget_plan = Some(raw);
}
+ "--drop-indexed" => {
+ if drop_indexed {
+ return Err("--drop-indexed was given twice".into());
+ }
+ drop_indexed = true;
+ }
"--yes" | "-y" => {
if let Some(previous) = approve {
if previous != Approval::Proceed {
@@ -1630,10 +1653,16 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.into(),
);
}
- if max_minutes_explicit || approve_explicit || max_index_explicit || budget_plan.is_some() {
+ if max_minutes_explicit
+ || approve_explicit
+ || max_index_explicit
+ || budget_plan.is_some()
+ || drop_indexed
+ {
return Err(
- "--max-minutes/--approve/--yes/--max-index-size/--plan are the folder-indexing \
- gate; a watch has its own cost gate (--max-monthly-ops, --allow-cost)"
+ "--max-minutes/--approve/--yes/--max-index-size/--plan/--drop-indexed are the \
+ folder-indexing gate; a watch has its own cost gate (--max-monthly-ops, \
+ --allow-cost)"
.into(),
);
}
@@ -1715,11 +1744,12 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
if max_minutes_explicit
|| approve_explicit
|| max_index_explicit
- || budget_plan.is_some() =>
+ || budget_plan.is_some()
+ || drop_indexed =>
{
Err(format!(
- "--max-minutes/--approve/--yes/--max-index-size/--plan apply only to indexing, \
- not `autoindex {}`",
+ "--max-minutes/--approve/--yes/--max-index-size/--plan/--drop-indexed apply only \
+ to indexing, not `autoindex {}`",
sub.as_deref().unwrap_or_default()
))
}
@@ -1866,6 +1896,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
approve,
max_index_bytes,
budget_plan,
+ drop_indexed,
json,
quiet,
progress,
@@ -2788,6 +2819,7 @@ mod tests {
vec!["map", "--max-minutes", "5"],
vec!["status", "--approve", "proceed"],
vec!["--yes", "map"],
+ vec!["map", "--drop-indexed"],
] {
let err = parse(args.into_iter().map(str::to_string).collect()).unwrap_err();
assert!(err.contains("apply only to indexing"), "{err}");
@@ -2828,6 +2860,7 @@ mod tests {
"--yes, -y",
"--max-index-size",
"--plan <NAME>",
+ "--drop-indexed",
"DISK BUDGET:",
"0 disables the gate",
"ESTIMATE + DECISION GATE:",
@@ -2856,6 +2889,13 @@ mod tests {
let cfg = index(&["data", "--plan", "code-and-docs", "--max-index-size", "2MB"]);
assert_eq!(cfg.budget_plan.as_deref(), Some("code-and-docs"));
assert_eq!(cfg.max_index_bytes, Some(2 * 1024 * 1024));
+ assert!(
+ !cfg.drop_indexed,
+ "--plan does not agree to delete an existing index"
+ );
+ let confirmed = index(&["data", "--plan", "code-and-docs", "--drop-indexed"]);
+ assert!(confirmed.drop_indexed);
+ assert!(!index(&["data", "--yes"]).drop_indexed);
let plan_err = err(&["data", "--plan", "everything"]);
assert!(plan_err.contains("not a plan"), "{plan_err}");
}
diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rs
index c9aaf7d9a..3a2a85670 100644
--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs
+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs
@@ -378,6 +378,7 @@ pub(super) fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
approve: None,
max_index_bytes: None,
budget_plan: None,
+ drop_indexed: false,
dry_run: false,
walk_only: false,
json: false,
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index e8182aa8b..cb74cd4bd 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -816,6 +816,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
approve: None,
max_index_bytes: None,
budget_plan: None,
+ drop_indexed: false,
dry_run: false,
walk_only: false,
json: false,
diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
index 106eeedd4..bdb4692ba 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -972,6 +972,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str, semantic: bool) -> IndexCfg {
approve: None,
max_index_bytes: None,
budget_plan: None,
+ drop_indexed: false,
dry_run: false,
walk_only: false,
json: false,
@@ -6500,6 +6501,239 @@ mod delete_gate {
);
}
+ /// A folder that was indexed in full, then re-run under a reduced plan.
+ ///
+ /// `--plan code-and-docs` (and `--yes`, when it selects that plan) filters
+ /// the walk before reconcile. The csv is still on disk and already
+ /// published, but it is absent from the inventory, so the generation's
+ /// `Delete` operations would remove its documents. The same filter is what
+ /// the graph path's exclusion sweep would treat as a widened ignore. A
+ /// reduced plan must not do that unless `--drop-indexed` confirms it.
+ ///
+ /// The refusal is before the journal is opened for write and before any
+ /// delete or bulk, so the committed generation and the live documents are
+ /// unchanged and a later full re-run still reconciles.
+ #[test]
+ fn a_reduced_plan_does_not_delete_datasets_already_indexed() {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());
+ let corpus = tempfile::tempdir().unwrap();
+ fs::write(
+ corpus.path().join("main.rs"),
+ "fn main() { println!(\"kept\"); }\n",
+ )
+ .unwrap();
+ fs::write(corpus.path().join("notes.md"), "# notes\n\nstill indexed\n").unwrap();
+ fs::write(corpus.path().join("rows.csv"), "id,value\n1,alpha\n").unwrap();
+
+ let endpoint = HttpEndpoint::start();
+ let state_dir = tempfile::tempdir().unwrap();
+ let mut full = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ full.prefix = "plan-removal".into();
+ assert_eq!(run_index(full).unwrap(), 0, "the full folder indexes");
+ let indexed = paths(&endpoint.data_docs());
+ assert!(
+ indexed.iter().any(|path| path.ends_with("main.rs")),
+ "code indexed: {indexed:?}"
+ );
+ assert!(
+ indexed.iter().any(|path| path.ends_with("notes.md")),
+ "prose indexed: {indexed:?}"
+ );
+ assert!(
+ indexed.iter().any(|path| path.ends_with("rows.csv")),
+ "the csv dataset indexed: {indexed:?}"
+ );
+
+ let journal_before = fs::read(state_dir.path().join("journal.ndjson")).unwrap();
+ let snapshots_before = snapshot_names(state_dir.path());
+ let deletes_before = endpoint
+ .state
+ .lock()
+ .unwrap()
+ .requests
+ .iter()
+ .filter(|(method, path)| method == "POST" && path.contains("/_delete_by_query"))
+ .count();
+ let bulks_before = endpoint.data_bulk_requests();
+
+ let mut reduced = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ reduced.prefix = "plan-removal".into();
+ reduced.budget_plan = Some("code-and-docs".into());
+ assert_eq!(
+ run_index(reduced).unwrap(),
+ gate::EXIT_NEEDS_DECISION,
+ "a reduced plan must stop before it deletes indexed data"
+ );
+ assert_eq!(
+ paths(&endpoint.data_docs()),
+ indexed,
+ "the csv dataset is still live"
+ );
+ assert_eq!(
+ fs::read(state_dir.path().join("journal.ndjson")).unwrap(),
+ journal_before,
+ "the refusal must not commit a generation"
+ );
+ assert_eq!(
+ snapshot_names(state_dir.path()),
+ snapshots_before,
+ "the refusal must not seal or drop a snapshot"
+ );
+ let deletes_after = endpoint
+ .state
+ .lock()
+ .unwrap()
+ .requests
+ .iter()
+ .filter(|(method, path)| method == "POST" && path.contains("/_delete_by_query"))
+ .count();
+ assert_eq!(
+ deletes_after, deletes_before,
+ "the refusal must not delete_by_query"
+ );
+ assert_eq!(
+ endpoint.data_bulk_requests(),
+ bulks_before,
+ "the refusal must not bulk"
+ );
+
+ let mut again = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ again.prefix = "plan-removal".into();
+ assert_eq!(
+ run_index(again).unwrap(),
+ 0,
+ "after the refusal a full re-run still reconciles"
+ );
+ assert_eq!(
+ paths(&endpoint.data_docs()),
+ indexed,
+ "the full re-run keeps the csv dataset"
+ );
+
+ let mut confirmed = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ confirmed.prefix = "plan-removal".into();
+ confirmed.budget_plan = Some("code-and-docs".into());
+ confirmed.drop_indexed = true;
+ assert_eq!(
+ run_index(confirmed).unwrap(),
+ 0,
+ "--drop-indexed is the confirmation that removes the plan's files"
+ );
+ let after = paths(&endpoint.data_docs());
+ assert!(
+ after.iter().any(|path| path.ends_with("main.rs"))
+ && after.iter().any(|path| path.ends_with("notes.md")),
+ "the plan keeps code and prose: {after:?}"
+ );
+ assert!(
+ after.iter().all(|path| !path.ends_with("rows.csv")),
+ "the confirmed plan deletes the csv dataset: {after:?}"
+ );
+
+ let mut repeat = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ repeat.prefix = "plan-removal".into();
+ repeat.budget_plan = Some("code-and-docs".into());
+ assert_eq!(
+ run_index(repeat).unwrap(),
+ 0,
+ "once the csv is gone, the same plan has nothing indexed left to delete"
+ );
+ assert_eq!(paths(&endpoint.data_docs()), after);
+ }
+
+ /// The graph path (the default, `no_graph: false`) has no generated
+ /// manifest; the prior plan is the legacy `plan.json`. A reduced plan
+ /// would make its exclusion sweep delete the csv documents. Same contract
+ /// as the `--no-graph` test above: exit 4 and nothing changed, then
+ /// `--drop-indexed` removes exactly the files the plan leaves out.
+ #[test]
+ fn a_reduced_plan_on_the_graph_path_does_not_delete_indexed_data() {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());
+ let corpus = tempfile::tempdir().unwrap();
+ fs::write(
+ corpus.path().join("main.rs"),
+ "fn main() { println!(\"kept\"); }\n",
+ )
+ .unwrap();
+ fs::write(corpus.path().join("notes.md"), "# notes\n\nstill indexed\n").unwrap();
+ fs::write(corpus.path().join("rows.csv"), "id,value\n1,alpha\n").unwrap();
+
+ let endpoint = HttpEndpoint::start();
+ let state_dir = tempfile::tempdir().unwrap();
+ let graph_cfg = || {
+ let mut c = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ c.prefix = "plan-removal-graph".into();
+ c.no_graph = false;
+ c
+ };
+ assert_eq!(
+ run_index(graph_cfg()).unwrap(),
+ 0,
+ "the full folder indexes"
+ );
+ let indexed = paths(&endpoint.data_docs());
+ assert!(
+ indexed.iter().any(|path| path.ends_with("rows.csv")),
+ "the csv dataset indexed: {indexed:?}"
+ );
+ let deletes = |endpoint: &HttpEndpoint| {
+ endpoint
+ .state
+ .lock()
+ .unwrap()
+ .requests
+ .iter()
+ .filter(|(method, path)| {
+ method == "DELETE" || (method == "POST" && path.contains("/_delete_by_query"))
+ })
+ .count()
+ };
+ let deletes_before = deletes(&endpoint);
+
+ let mut reduced = graph_cfg();
+ reduced.budget_plan = Some("code-and-docs".into());
+ assert_eq!(
+ run_index(reduced).unwrap(),
+ gate::EXIT_NEEDS_DECISION,
+ "a reduced plan on the graph path must stop before it deletes indexed data"
+ );
+ assert_eq!(
+ paths(&endpoint.data_docs()),
+ indexed,
+ "the csv is still live"
+ );
+ assert_eq!(
+ deletes(&endpoint),
+ deletes_before,
+ "the refusal must not delete"
+ );
+
+ let mut yes = graph_cfg();
+ yes.budget_plan = Some("code-and-docs".into());
+ yes.approve = Some(crate::gate::Approval::Proceed);
+ assert_eq!(
+ run_index(yes).unwrap(),
+ gate::EXIT_NEEDS_DECISION,
+ "--yes does not agree to the deletion"
+ );
+ assert_eq!(paths(&endpoint.data_docs()), indexed);
+
+ let mut confirmed = graph_cfg();
+ confirmed.budget_plan = Some("code-and-docs".into());
+ confirmed.drop_indexed = true;
+ assert_eq!(run_index(confirmed).unwrap(), 0, "--drop-indexed confirms");
+ let after = paths(&endpoint.data_docs());
+ assert!(
+ after.iter().any(|path| path.ends_with("main.rs"))
+ && after.iter().any(|path| path.ends_with("notes.md")),
+ "the plan keeps code and prose: {after:?}"
+ );
+ assert!(
+ after.iter().all(|path| !path.ends_with("rows.csv")),
+ "the confirmed plan removes the csv: {after:?}"
+ );
+ }
+
fn base() -> CommittedManifest {
CommittedManifest {
generation: 0,
diff --git a/engine/crates/xerj-autoindex/src/label_http_tests.rs b/engine/crates/xerj-autoindex/src/label_http_tests.rs
index 148ed845e..be8413077 100644
--- a/engine/crates/xerj-autoindex/src/label_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/label_http_tests.rs
@@ -386,6 +386,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str, label: &Path) -> IndexCfg {
approve: None,
max_index_bytes: None,
budget_plan: None,
+ drop_indexed: false,
dry_run: false,
walk_only: false,
json: false,
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index eb17e34ad..9e3fe4828 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -3523,6 +3523,7 @@ mod phase_a_grouping_tests {
approve: None,
max_index_bytes: None,
budget_plan: None,
+ drop_indexed: false,
dry_run: true,
walk_only: false,
json: false,
@@ -6417,6 +6418,9 @@ fn legacy_rebuild_argv(cfg: &IndexCfg, state_dir: &Path, prefix: &str) -> Vec<St
argv.push("--plan".to_owned());
argv.push(plan.clone());
}
+ if cfg.drop_indexed {
+ argv.push("--drop-indexed".to_owned());
+ }
if cfg.follow_symlinks {
argv.push("--follow-symlinks".to_owned());
}
@@ -7081,10 +7085,60 @@ fn run_index_report_inner(
keep,
no_semantic,
note,
+ plan_name,
} => {
if no_semantic {
cfg.no_semantic = true;
}
+ // A reduced plan filters the walk before hashing and before
+ // either reconcile. Files it leaves out are then absent from
+ // the inventory: the `--no-graph` generation emits Delete for
+ // their groups, and the graph path classifies them as
+ // exclusions and sweeps their documents. Both are silent
+ // deletions of data that is still in the folder. Stop and
+ // list them unless `--drop-indexed` is the explicit yes.
+ // `--plan` and `--yes` choose what to index; they do not
+ // agree to delete what is already indexed.
+ if let Some(keep_rels) = keep.as_ref() {
+ let mut plans: Vec<&Plan> = Vec::new();
+ if let Some(manifest) = preflight.committed_manifest.as_ref() {
+ plans.push(&manifest.plan);
+ }
+ if let Some(plan) = preflight.plan.as_ref() {
+ plans.push(plan);
+ }
+ let name = plan_name.as_deref().unwrap_or("reduced");
+ if let Some(body) =
+ budget::removal_decision(name, &plans, &discovered_files, keep_rels)
+ {
+ if !cfg.drop_indexed {
+ println!("{}", serde_json::to_string(&body)?);
+ pr.note(&format!(
+ "autoindex: {}",
+ body["accept"]
+ .as_str()
+ .unwrap_or("a reduced plan would delete already-indexed files")
+ ));
+ pr.finish(false, gate::EXIT_NEEDS_DECISION, "needs-decision", &[]);
+ return Ok((gate::EXIT_NEEDS_DECISION, None));
+ }
+ pr.note(&format!(
+ "autoindex: --drop-indexed: removing {} already-indexed file(s) this \
+ plan leaves out",
+ body["would_remove_total"].as_u64().unwrap_or(0)
+ ));
+ } else if cfg.drop_indexed {
+ pr.note(
+ "autoindex: --drop-indexed: this plan leaves out no already-indexed \
+ file",
+ );
+ }
+ } else if cfg.drop_indexed {
+ pr.note(
+ "autoindex: --drop-indexed confirms removal of files a reduced plan \
+ leaves out, and this run keeps every walked file",
+ );
+ }
if let Some(keep) = keep {
let keep: std::collections::HashSet<String> = keep.into_iter().collect();
let before = discovered_files.len();
@@ -13479,6 +13533,8 @@ mod legacy_rebuild_argv_tests {
assert_eq!(rebuilt.sample, cfg.sample);
assert_eq!(rebuilt.workers, cfg.workers);
assert_eq!(rebuilt.bulk_mb, cfg.bulk_mb);
+ assert_eq!(rebuilt.budget_plan, cfg.budget_plan, "{argv:?}");
+ assert_eq!(rebuilt.drop_indexed, cfg.drop_indexed, "{argv:?}");
}
#[test]
@@ -13506,6 +13562,13 @@ mod legacy_rebuild_argv_tests {
assert_round_trip(&["data", "--no-graph", "--max-file-mb", "10"]);
assert_round_trip(&["data", "--no-graph", "--max-file-bytes", "4096"]);
assert_round_trip(&["data", "--no-graph", "--max-file-gb", "3"]);
+ assert_round_trip(&[
+ "data",
+ "--no-graph",
+ "--plan",
+ "code-and-docs",
+ "--drop-indexed",
+ ]);
}
/// #1233: the "skipped: oversized" note renders the byte cap in the
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 3a2378957..48ecd4020 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -645,6 +645,7 @@ fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {
approve: None,
max_index_bytes: None,
budget_plan: None,
+ drop_indexed: false,
json: false,
quiet: false,
// `xerj brain` is a foreground command a human watches; it gets the