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): batch prior-edge invalidation so --fresh stops refreshing per file (#2640) (#2703)

xerj-orgc349f7323cac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7fe1dd7cf..fd70bcb14 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `xerj autoindex --fresh` over an already-indexed folder no longer pays one
+ edges-index search, bulk and refresh per replaced file (and again per
+ superseded anchor) to soft-invalidate prior relationship edges. The graph
+ phase now invalidates them in batched, terms-sliced sweeps with one refresh
+ per sweep. On a 1,050-file markdown corpus with 14,724 prior edges the
+ `--fresh` run went from 152.0 s to 26.7 s (edges refreshes 1,052 → 3), with
+ the same 14,724 edges invalidated (#2640).
- A background merge no longer starts alone when its own memory reservation
would carry the node past the merge-pool ceiling. It waits (at most 30 s)
while the next batches are planned small enough to fit, so merging still
diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rs
index 2a4add003..cbe5801c9 100644
--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs
+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs
@@ -12,6 +12,7 @@ use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
@@ -21,6 +22,8 @@ pub(super) type Docs = BTreeMap<String, BTreeMap<String, Value>>;
pub(super) struct MockEs {
pub(super) url: String,
pub(super) docs: Arc<Mutex<Docs>>,
+ /// `POST /{index}/_refresh` requests served (#2640).
+ pub(super) refreshes: Arc<AtomicU64>,
stop: Arc<Mutex<bool>>,
join: Option<thread::JoinHandle<()>>,
}
@@ -32,14 +35,15 @@ impl MockEs {
let url = format!("http://{}", listener.local_addr().unwrap());
let docs: Arc<Mutex<Docs>> = Arc::default();
let stop = Arc::new(Mutex::new(false));
- let (sd, ss) = (Arc::clone(&docs), Arc::clone(&stop));
+ let refreshes: Arc<AtomicU64> = Arc::default();
+ let (sd, ss, sr) = (Arc::clone(&docs), Arc::clone(&stop), Arc::clone(&refreshes));
let join = thread::spawn(move || loop {
match listener.accept() {
Ok((stream, _)) => {
// BSD/macOS: accepted sockets inherit the listener's
// O_NONBLOCK; the handler does blocking reads.
stream.set_nonblocking(false).unwrap();
- handle(stream, &sd)
+ handle(stream, &sd, &sr)
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if *ss.lock().unwrap() {
@@ -53,6 +57,7 @@ impl MockEs {
Self {
url,
docs,
+ refreshes,
stop,
join: Some(join),
}
@@ -113,7 +118,7 @@ fn respond(mut stream: TcpStream, status: u16, body: &Value) {
.unwrap();
}
-fn handle(stream: TcpStream, docs: &Arc<Mutex<Docs>>) {
+fn handle(stream: TcpStream, docs: &Arc<Mutex<Docs>>, refreshes: &AtomicU64) {
let clone = stream.try_clone().unwrap();
let mut reader = BufReader::new(clone);
let mut request_line = String::new();
@@ -141,6 +146,9 @@ fn handle(stream: TcpStream, docs: &Arc<Mutex<Docs>>) {
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("").to_string();
+ if method == "POST" && path.ends_with("/_refresh") {
+ refreshes.fetch_add(1, Ordering::SeqCst);
+ }
if method == "POST" && path == "/_bulk" {
return respond(stream, 200, &bulk(&body, docs));
}
@@ -947,6 +955,88 @@ fn replaced_file_soft_invalidates_its_prior_edges() {
);
}
+/// #2640: `autoindex --fresh` after a branch switch supersedes most of the
+/// corpus's anchors at once. Invalidation used to run one
+/// `search → bulk → refresh` round per replaced file (and again per
+/// superseded anchor on `dst`), so a ~1k-file repo paid ~2k refreshes of the
+/// edges index and the phase took hours. The batched sweep must invalidate
+/// exactly the same edges with a constant number of refreshes, across more
+/// values than one `terms` slice and more hits than one bulk page.
+/// Fail-before: the per-value loop issues one refresh per value (600 here).
+#[test]
+fn batched_invalidation_matches_per_file_result_with_constant_refreshes() {
+ let es = MockEs::start();
+ let client = crate::esclient::Es::new(&es.url, None).unwrap();
+ let edges = ".xerj-memory-fresh2640-edges";
+ const FILES: usize = 600; // > SCAN_TERMS (256): several `terms` slices
+ const PER_FILE: usize = 3; // 1,800 hits > SCAN_PAGE (1,000): paged bulks
+ let mut store = BTreeMap::new();
+ let mut replaced: Vec<String> = Vec::new();
+ for f in 0..FILES {
+ let rel = format!("d/{f:04}.md");
+ for e in 0..PER_FILE {
+ store.insert(
+ format!("e-{f:04}-{e}"),
+ json!({"src_file": rel, "dst": format!("n-{e}"), "type": "links_to"}),
+ );
+ }
+ replaced.push(rel);
+ }
+ // Untouched: a surviving file's live edge, and an edge already
+ // invalidated by an earlier generation (its stamp must not move).
+ store.insert(
+ "keep".into(),
+ json!({"src_file": "kept.md", "dst": "n-0", "type": "links_to"}),
+ );
+ store.insert(
+ "old".into(),
+ json!({"src_file": "d/0000.md", "dst": "n-0", "type": "links_to",
+ "invalid_at": 5, "expired_at": 5}),
+ );
+ es.docs.lock().unwrap().insert(edges.to_string(), store);
+
+ let rels: Vec<&str> = replaced.iter().map(String::as_str).collect();
+ let now_ms = 1_800_000_000_000i64;
+ let n = detect::invalidate_edges_by_field_values(&client, edges, "src_file", &rels, now_ms)
+ .unwrap();
+ assert_eq!(n, (FILES * PER_FILE) as u64);
+ let after = es.index(edges);
+ for (id, doc) in &after {
+ match id.as_str() {
+ "keep" => assert!(doc.get("invalid_at").is_none(), "survivor stays live"),
+ "old" => assert_eq!(doc["invalid_at"], json!(5), "prior stamp kept"),
+ _ => {
+ assert_eq!(doc["invalid_at"], json!(now_ms), "{id} invalidated");
+ assert_eq!(doc["expired_at"], json!(now_ms), "{id} expired");
+ }
+ }
+ }
+ assert!(
+ es.refreshes.load(Ordering::SeqCst) <= 2,
+ "one refresh per sweep, not per file: {}",
+ es.refreshes.load(Ordering::SeqCst)
+ );
+
+ // The inbound (`dst`) half takes the same path; a second call is a no-op
+ // sweep over already-invalidated edges and refreshes nothing.
+ let before = es.refreshes.load(Ordering::SeqCst);
+ let again =
+ detect::invalidate_edges_by_field_values(&client, edges, "src_file", &rels, now_ms + 1)
+ .unwrap();
+ assert_eq!(again, 0);
+ assert_eq!(es.refreshes.load(Ordering::SeqCst), before);
+ let dst =
+ detect::invalidate_edges_by_field_values(&client, edges, "dst", &["n-0"], now_ms).unwrap();
+ assert_eq!(dst, 1, "only the surviving file's live edge points at n-0");
+ assert_eq!(es.index(edges)["keep"]["invalid_at"], json!(now_ms));
+ // An absent edges index holds nothing to invalidate.
+ assert_eq!(
+ detect::invalidate_edges_by_field_values(&client, ".missing-edges", "dst", &["x"], 1)
+ .unwrap(),
+ 0
+ );
+}
+
fn preseed_meta(es: &MockEs, edges: &str, nodes_index: &str, created_at: i64) {
let mut store = BTreeMap::new();
store.insert(
diff --git a/engine/crates/xerj-autoindex/src/detect/mod.rs b/engine/crates/xerj-autoindex/src/detect/mod.rs
index 65bceeb10..6bcb1bc5e 100644
--- a/engine/crates/xerj-autoindex/src/detect/mod.rs
+++ b/engine/crates/xerj-autoindex/src/detect/mod.rs
@@ -770,10 +770,10 @@ fn write_brain_meta(
}
/// Soft-invalidate every live edge whose keyword `field` equals `value`.
-/// Each pass re-indexes its hits with `invalid_at = expired_at = now` and
-/// refreshes, so repeat-until-empty converges; the pass bound turns a broken
-/// endpoint into an error instead of an infinite loop. Callers pass `src_file`
-/// (edges a file taught) or `dst` (edges pointing at a file's anchor node).
+/// Callers pass `src_file` (edges a file taught) or `dst` (edges pointing at a
+/// file's anchor node). One value is the one-element case of
+/// [`invalidate_edges_by_field_values`]; a caller holding many values must
+/// use that directly (#2640).
pub fn invalidate_edges_by_field(
es: &Es,
edges_index: &str,
@@ -781,73 +781,111 @@ pub fn invalidate_edges_by_field(
value: &str,
now_ms: i64,
) -> Result<u64> {
- const MAX_PASSES: usize = 1_000;
- let query = json!({
- "query": {"bool": {
- "filter": [{"term": {field: value}}],
- "must_not": [{"exists": {"field": "invalid_at"}}]
- }},
- "size": 1000,
- "_source": true
- });
+ invalidate_edges_by_field_values(es, edges_index, field, &[value], now_ms)
+}
+
+/// Upper bound on full sweeps in [`invalidate_edges_by_field_values`]. One
+/// sweep pages through every match, so a healthy endpoint converges on the
+/// second (verifying) sweep; the bound turns a broken endpoint into an error
+/// instead of an infinite loop.
+const INVALIDATE_MAX_SWEEPS: usize = 16;
+
+/// Soft-invalidate every live edge whose keyword `field` equals ANY of
+/// `values`, re-indexing each hit with `invalid_at = expired_at = now_ms`.
+///
+/// #2640: this used to be one `search → bulk → refresh → search` round per
+/// value. Under `autoindex --fresh` after a branch switch every changed file
+/// supersedes its anchor, so a ~1k-file repo paid ~2k refreshes of the edges
+/// index, each publishing a segment of a handful of re-indexed edges; search
+/// and refresh cost grew with the segment count, so the phase went
+/// super-linear (hours on a corpus a from-scratch build edges in seconds).
+///
+/// Now the values are walked in [`SCAN_TERMS`] slices with one `terms` filter
+/// each, paged by [`scan_by_id`], re-indexed in [`SCAN_PAGE`] bulks while the
+/// walk streams (memory stays bounded by one page, not by the match count),
+/// and the index is refreshed once per sweep. A sweep that invalidated
+/// anything is followed by a verifying sweep after its refresh, so the
+/// repeat-until-empty contract of the per-value loop is kept. A missing
+/// edges index holds nothing to invalidate and is not an error (the
+/// exclusion sweep, #694, can run before the graph phase creates it).
+pub fn invalidate_edges_by_field_values(
+ es: &Es,
+ edges_index: &str,
+ field: &str,
+ values: &[&str],
+ now_ms: i64,
+) -> Result<u64> {
+ if values.is_empty() {
+ return Ok(0);
+ }
let mut total = 0u64;
- for _ in 0..MAX_PASSES {
- // `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);
+ for _ in 0..INVALIDATE_MAX_SWEEPS {
+ let mut swept = 0u64;
+ let mut body: Vec<u8> = Vec::new();
+ let mut pending = 0usize;
+ let mut failure: Option<anyhow::Error> = None;
+ let flush = |body: &mut Vec<u8>, pending: &mut usize| -> Result<()> {
+ if *pending == 0 {
+ return Ok(());
+ }
+ let outcome = es
+ .bulk(std::mem::take(body))
+ .context("invalidate prior edges")?;
+ *pending = 0;
+ if outcome.server_errors > 0 || outcome.item_errors > 0 {
+ return Err(anyhow!(
+ "edge invalidation by {field} was partial: {}",
+ outcome
+ .first_server_error
+ .or(outcome.first_error)
+ .unwrap_or_else(|| "unknown bulk error".into())
+ ));
+ }
+ Ok(())
};
- let hits = resp
- .pointer("/hits/hits")
- .and_then(Value::as_array)
- .cloned()
- .unwrap_or_default();
- if hits.is_empty() {
- return Ok(total);
- }
- let mut body = Vec::new();
- for hit in &hits {
- let id = hit
- .get("_id")
- .and_then(Value::as_str)
- .ok_or_else(|| anyhow!("edge hit without _id in {edges_index}"))?;
- let mut source = hit
- .get("_source")
- .and_then(Value::as_object)
- .cloned()
- .ok_or_else(|| anyhow!("edge {id} returned without _source"))?;
- source.insert("invalid_at".into(), json!(now_ms));
- source.insert("expired_at".into(), json!(now_ms));
- body.extend_from_slice(
- json!({"index": {"_index": edges_index, "_id": id}})
- .to_string()
- .as_bytes(),
- );
- body.push(b'\n');
- body.extend_from_slice(Value::Object(source).to_string().as_bytes());
- body.push(b'\n');
+ for slice in values.chunks(SCAN_TERMS) {
+ let query = json!({"bool": {
+ "filter": [{"terms": {field: slice}}],
+ "must_not": [{"exists": {"field": "invalid_at"}}]
+ }});
+ scan_by_id(es, edges_index, &query, &json!(true), &mut |id, source| {
+ if failure.is_some() {
+ return;
+ }
+ let mut source = source.clone();
+ source.insert("invalid_at".into(), json!(now_ms));
+ source.insert("expired_at".into(), json!(now_ms));
+ body.extend_from_slice(
+ json!({"index": {"_index": edges_index, "_id": id}})
+ .to_string()
+ .as_bytes(),
+ );
+ body.push(b'\n');
+ body.extend_from_slice(Value::Object(source).to_string().as_bytes());
+ body.push(b'\n');
+ pending += 1;
+ swept += 1;
+ if pending >= SCAN_PAGE {
+ if let Err(e) = flush(&mut body, &mut pending) {
+ failure = Some(e);
+ }
+ }
+ })?;
+ if let Some(e) = failure.take() {
+ return Err(e);
+ }
}
- let outcome = es.bulk(body).context("invalidate prior edges")?;
- if outcome.server_errors > 0 || outcome.item_errors > 0 {
- return Err(anyhow!(
- "edge invalidation for {}={} was partial: {}",
- field,
- value,
- outcome
- .first_server_error
- .or(outcome.first_error)
- .unwrap_or_else(|| "unknown bulk error".into())
- ));
+ flush(&mut body, &mut pending)?;
+ if swept == 0 {
+ return Ok(total);
}
- total += hits.len() as u64;
+ total += swept;
es.refresh(edges_index)?;
}
Err(anyhow!(
- "edge invalidation for {field}={value} still found live edges after {MAX_PASSES} passes"
+ "edge invalidation by {field} ({} values) still found live edges after \
+ {INVALIDATE_MAX_SWEEPS} sweeps",
+ values.len()
))
}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 731833108..d6799fb60 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -10919,29 +10919,48 @@ fn run_index_report_inner(
replaced_rels.extend(superseded.iter().map(|(_, rel)| rel.as_str()));
replaced_rels.sort_unstable();
replaced_rels.dedup();
- for rel in replaced_rels {
- invalidated +=
- detect::invalidate_prior_edges(&es, &edges_index, rel, created_at_ms)
- .with_context(|| format!("invalidate prior edges taught by {rel}"))?;
- }
+ // #2640: one batched sweep for every replaced file, not one
+ // search/bulk/refresh round each. After `--fresh` on a switched
+ // branch this set is most of the corpus, and the per-file refresh
+ // storm is what made the phase take hours.
+ invalidated += detect::invalidate_edges_by_field_values(
+ &es,
+ &edges_index,
+ "src_file",
+ &replaced_rels,
+ created_at_ms,
+ )
+ .with_context(|| {
+ format!(
+ "invalidate prior edges taught by {} replaced files",
+ replaced_rels.len()
+ )
+ })?;
// The inbound half. Keyed on the SUPERSEDED anchor only — never on a
// surviving file — so an unchanged file's edges are left exactly as
// they are (#868). This runs before any edge this run writes, and
// this run's edges name the NEW anchor, so it can only ever match
// prior generations. Same soft-invalidate as the src side: the
// bi-temporal record survives for `as_of` time travel.
- for (anchor, rel) in superseded {
- invalidated += detect::invalidate_edges_by_field(
- &es,
- &edges_index,
- "dst",
- anchor,
- created_at_ms,
+ let mut superseded_anchors: Vec<&str> = superseded
+ .iter()
+ .map(|(anchor, _)| anchor.as_str())
+ .collect();
+ superseded_anchors.sort_unstable();
+ superseded_anchors.dedup();
+ invalidated += detect::invalidate_edges_by_field_values(
+ &es,
+ &edges_index,
+ "dst",
+ &superseded_anchors,
+ created_at_ms,
+ )
+ .with_context(|| {
+ format!(
+ "invalidate inbound edges to {} superseded anchor nodes",
+ superseded_anchors.len()
)
- .with_context(|| {
- format!("invalidate inbound edges to the superseded anchor node of {rel}")
- })?;
- }
+ })?;
}
// Structural detection (samedir chains) + bulk write, cut at the same