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): exclusion sweep invalidates a removed file's graph edges (#694)

xerj-org535e4c95e535
diff --git a/engine/crates/xerj-autoindex/src/detect/mod.rs b/engine/crates/xerj-autoindex/src/detect/mod.rs
index e4258d6e3..a039d4420 100644
--- a/engine/crates/xerj-autoindex/src/detect/mod.rs
+++ b/engine/crates/xerj-autoindex/src/detect/mod.rs
@@ -673,7 +673,15 @@ pub fn invalidate_prior_edges(es: &Es, edges_index: &str, rel: &str, now_ms: i64
});
let mut total = 0u64;
for _ in 0..MAX_PASSES {
- let resp = es.search(edges_index, &query)?;
+ // `search_present`, not `search`: the exclusion sweep (#694) may call
+ // this before the edges index has ever been created (it runs ahead of
+ // the graph phase's `ensure_index`). A missing index is not a failure —
+ // it simply holds no edges to invalidate. The replacement-invalidation
+ // caller always ensures the index first, so its behaviour is unchanged
+ // (the index is present → `Some`).
+ let Some(resp) = es.search_present(edges_index, &query)? else {
+ return Ok(total);
+ };
let hits = resp
.pointer("/hits/hits")
.and_then(Value::as_array)
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 7c0d046a8..7ec292cb6 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -349,6 +349,12 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value
let exists = query
.pointer("/query/bool/must/1/exists/field")
.and_then(Value::as_str);
+ // #694: `invalidate_prior_edges` filters live edges with
+ // `must_not:[{exists:{field:"invalid_at"}}]`; honour it so the pass
+ // converges (an already-invalidated edge must drop out of the result).
+ let must_not_exists = query
+ .pointer("/query/bool/must_not/0/exists/field")
+ .and_then(Value::as_str);
let locked = state.lock().unwrap();
let matching: Vec<_> = locked
.docs
@@ -386,6 +392,9 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value
})
})
&& exists.map(|field| doc.get(field).is_some()).unwrap_or(true)
+ && must_not_exists
+ .map(|field| doc.get(field).is_none())
+ .unwrap_or(true)
})
.collect();
let hits = matching
@@ -2067,7 +2076,7 @@ fn sweep_excluded_groups_deletes_only_the_excluded_files_documents() {
path: "secret.csv".into(),
}];
- sweep_excluded_groups(&es, &plan, &excluded).expect("sweep");
+ sweep_excluded_groups(&es, &plan, &excluded, None, 0).expect("sweep");
let st = ep.state.lock().unwrap();
// The excluded file's dataset record is gone.
@@ -2101,6 +2110,79 @@ fn sweep_excluded_groups_deletes_only_the_excluded_files_documents() {
);
}
+/// #694: `sweep_excluded_groups` also soft-invalidates the graph edges an
+/// excluded file taught (reusing the replacement hook `invalidate_prior_edges`),
+/// while leaving a different file's edges live. The bi-temporal record survives
+/// (`as_of` time travel), so the edge is stamped `invalid_at`, not deleted.
+/// Fail-before: with the `invalidate_prior_edges` call reverted, the excluded
+/// file's edge carries no `invalid_at` and stays searchable.
+#[test]
+fn sweep_excluded_groups_invalidates_the_excluded_files_edges() {
+ let ep = HttpEndpoint::start();
+ let edges = ".xerj-memory-testbrain-edges";
+
+ // Two live edges (no `invalid_at`): one taught by the file about to be
+ // excluded, one by a file that stays.
+ {
+ let mut st = ep.state.lock().unwrap();
+ // The mock's `_bulk` guard asserts mappings were seen first (ingest
+ // ordering); the invalidation re-index is a bulk, so satisfy it — this
+ // test exercises edge invalidation, not the mapping-ordering invariant.
+ st.saw_dataset_mapping_update = true;
+ st.saw_catalog_mapping_update = true;
+ st.docs.insert(
+ (edges.to_string(), "edge-secret".to_string()),
+ json!({"src_file": "secret.csv", "kind": "samedir", "dst_file": "other.csv"}),
+ );
+ st.docs.insert(
+ (edges.to_string(), "edge-kept".to_string()),
+ json!({"src_file": "kept.csv", "kind": "samedir", "dst_file": "other.csv"}),
+ );
+ }
+
+ let es = Es::with_bulk_timeout(&ep.url, None, 30).expect("es client");
+ let mut plan = Plan::default();
+ plan.datasets.push(crate::state::PlanDataset {
+ slug: "ds".into(),
+ index: "incremental-http-ds".into(),
+ family: "csv".into(),
+ group: None,
+ specs: Vec::new(),
+ time_field: None,
+ semantic_field: None,
+ sampled_records: 1,
+ file_count: 1,
+ });
+ let excluded = vec![InventoryDeltaEntry {
+ file_key: "key-excluded".into(),
+ path: "secret.csv".into(),
+ }];
+
+ let now_ms = 1_724_500_000_000i64;
+ sweep_excluded_groups(&es, &plan, &excluded, Some(edges), now_ms).expect("sweep");
+
+ let st = ep.state.lock().unwrap();
+ // The excluded file's edge is soft-invalidated (present, stamped invalid_at).
+ let secret_edge = st
+ .docs
+ .get(&(edges.to_string(), "edge-secret".to_string()))
+ .expect("excluded file's edge is soft-invalidated, not deleted");
+ assert_eq!(
+ secret_edge.get("invalid_at").and_then(Value::as_i64),
+ Some(now_ms),
+ "#694: the excluded file's edge must be stamped invalid_at by the sweep"
+ );
+ // A different file's edge stays live (no over-invalidation).
+ let kept_edge = st
+ .docs
+ .get(&(edges.to_string(), "edge-kept".to_string()))
+ .expect("kept file's edge present");
+ assert!(
+ kept_edge.get("invalid_at").is_none(),
+ "#694: a different file's edge must NOT be invalidated"
+ );
+}
+
/// #585 (case 1): a pending (uncommitted) `--no-graph` generation must NOT be
/// resumed and committed on the default graph path — doing so silently commits
/// a no-graph generation under a graph authority (the #584 hazard, but for a
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 2cf998fd1..38fb5f2ac 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -3163,10 +3163,20 @@ fn finish_generated_run(es: &Es, journal: &mut state::Journal, cfg: &IndexCfg) -
/// (a co-occurring deletion refuses the whole rerun, mutating nothing) and
/// never under `--dry-run`.
///
-/// KNOWN GAP (#589, next hunk): graph edges taught by the file remain in the
-/// edges index until it is swept too — the same limitation the refusal message
-/// already documents in `edges_note`.
-fn sweep_excluded_groups(es: &Es, plan: &Plan, excluded: &[InventoryDeltaEntry]) -> Result<()> {
+/// #694: graph edges taught by the excluded file are soft-invalidated too, when
+/// this run has a graph (`edges_index` is `Some`). It reuses the replacement
+/// hook `detect::invalidate_prior_edges` — the excluded entry's `path` IS the
+/// `src_file` the edges carry — so an edge naming a now-excluded file stops
+/// being searchable (the bi-temporal record survives for `as_of` time travel,
+/// exactly like a replaced file's edges). Under `--no-graph` (`edges_index` is
+/// `None`) there is no edges index to touch.
+fn sweep_excluded_groups(
+ es: &Es,
+ plan: &Plan,
+ excluded: &[InventoryDeltaEntry],
+ edges_index: Option<&str>,
+ now_ms: i64,
+) -> Result<()> {
// Exact dataset indices from the plan — the same resolution the replacement
// delete path uses (`ds_rt` → `rt.index`); a `{prefix}-*` wildcard would be
// untestable and could reach indices this corpus does not own.
@@ -3188,10 +3198,36 @@ fn sweep_excluded_groups(es: &Es, plan: &Plan, excluded: &[InventoryDeltaEntry])
&json!({"term": {"path": entry.path}}),
)
.with_context(|| format!("sweep catalog entry for newly-excluded {}", entry.path))?;
+ // #694: soft-invalidate the edges this file taught. `invalidate_prior_edges`
+ // tolerates a not-yet-created edges index (returns 0), so a graph run whose
+ // edges index has not been ensured at this point is safe.
+ if let Some(edges) = edges_index {
+ detect::invalidate_prior_edges(es, edges, &entry.path, now_ms)
+ .with_context(|| format!("sweep graph edges for newly-excluded {}", entry.path))?;
+ }
}
Ok(())
}
+/// The edges index this run's graph writes to, or `None` when there is none to
+/// sweep: `--no-graph`, or a brain name that fails validation (a run that could
+/// never have written edges — the graph phase bails on it before any write).
+/// #694: the exclusion sweep uses this to invalidate a removed file's edges,
+/// mirroring `edges_index_name(&brain)` at the graph phase without duplicating
+/// the `--brain`/`derive_brain_name` fallback.
+fn graph_edges_index(cfg: &IndexCfg) -> Option<String> {
+ if cfg.no_graph {
+ return None;
+ }
+ let brain = cfg
+ .brain
+ .clone()
+ .unwrap_or_else(|| derive_brain_name(&cfg.root));
+ detect::validate_brain(&brain)
+ .ok()
+ .map(|()| detect::edges_index_name(&brain))
+}
+
/// Catalog doc id for a time correlation, corpus-prefix-scoped (#673): the
/// `autoindex-catalog` index is shared across corpora, so a time correlation
/// keyed only by dataset slugs would overwrite the same-slug correlation from
@@ -3775,8 +3811,15 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
// continue, rather than leaving them live in the destination. Genuine
// deletions above still refuse; never mutate under --dry-run.
if !delta.excluded_content_groups.is_empty() && !cfg.dry_run {
- sweep_excluded_groups(&es, prior_plan, &delta.excluded_content_groups)
- .context("sweep newly-excluded content groups")?;
+ let edges_index = graph_edges_index(&cfg);
+ sweep_excluded_groups(
+ &es,
+ prior_plan,
+ &delta.excluded_content_groups,
+ edges_index.as_deref(),
+ chrono::Utc::now().timestamp_millis(),
+ )
+ .context("sweep newly-excluded content groups")?;
}
}
let mut journal = state::Journal::open_after_preflight(
@@ -4035,8 +4078,15 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
// #589: sweep documents left behind by a widened exclusion (see gate
// above). Genuine deletions still refuse; never mutate under --dry-run.
if !delta.excluded_content_groups.is_empty() && !cfg.dry_run {
- sweep_excluded_groups(&es, &plan, &delta.excluded_content_groups)
- .context("sweep newly-excluded content groups")?;
+ let edges_index = graph_edges_index(&cfg);
+ sweep_excluded_groups(
+ &es,
+ &plan,
+ &delta.excluded_content_groups,
+ edges_index.as_deref(),
+ chrono::Utc::now().timestamp_millis(),
+ )
+ .context("sweep newly-excluded content groups")?;
}
}