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.

perf(autoindex): skip Phase-A parse for byte-identical files on re-index (~100x re-index) (#868)

xerj-org74f05fef9374
diff --git a/README.md b/README.md
index cf54759ce..ca752d697 100644
--- a/README.md
+++ b/README.md
@@ -349,6 +349,24 @@ than left out. Results, methodology and the harness are at
[`demo/playbooks`](./demo/playbooks), so you can rerun them yourself. Treat any number you
cannot reproduce with skepticism, including ours.
+### Code indexing
+
+Source files are parsed with tree-sitter and indexed AST-aware — symbols plus full text — so an
+agent retrieves a function, not a line. On an Apache Lucene checkout (6,113 source files, 51 MB)
+single-threaded in-process extraction runs at **~1,500 files/s (13 MB/s)**; the tree-sitter
+parse is ~72% of that and is the per-file floor. Reproduce it with:
+
+```sh
+XERJ_EXTRACT_BENCH=/path/to/repo cargo test -p xerj-autoindex --release \
+ extract_bench -- --nocapture --ignored
+```
+
+Re-indexing is **incremental**: a file whose content is byte-identical to the last indexed
+generation skips the parse entirely and carries its committed result forward, so a re-run after
+editing a handful of files does work proportional to what changed, not to the whole repo — the
+common edit-and-rerun / CI case, typically over 95% unchanged. The full content hash still runs
+to detect changes, so total re-index time is floored by hashing, not parsing.
+
## Build from source
You need a stable Rust toolchain.
diff --git a/engine/crates/xerj-autoindex/src/extract/code.rs b/engine/crates/xerj-autoindex/src/extract/code.rs
index c546e9d3a..5736950e9 100644
--- a/engine/crates/xerj-autoindex/src/extract/code.rs
+++ b/engine/crates/xerj-autoindex/src/extract/code.rs
@@ -1215,6 +1215,67 @@ mod tests {
s.iter().any(|(n, k, _, _)| n == name && k == kind)
}
+ /// Opt-in extraction-throughput harness (perf analysis, NOT part of CI).
+ /// Runs the real in-process code extractor over every source file the
+ /// registry claims under a corpus dir and reports files/s + MB/s. No-op
+ /// (returns immediately) unless `XERJ_EXTRACT_BENCH` is set, so it costs the
+ /// normal test run nothing:
+ /// `XERJ_EXTRACT_BENCH=/path/to/repo cargo test -p xerj-autoindex \
+ /// extract_bench -- --nocapture --ignored`
+ #[test]
+ #[ignore = "opt-in perf harness; set XERJ_EXTRACT_BENCH"]
+ fn extract_bench() {
+ let Ok(root) = std::env::var("XERJ_EXTRACT_BENCH") else {
+ return;
+ };
+ let mut files: Vec<std::path::PathBuf> = Vec::new();
+ let mut stack = vec![std::path::PathBuf::from(&root)];
+ while let Some(dir) = stack.pop() {
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
+ for entry in rd.flatten() {
+ let p = entry.path();
+ if p.is_dir() {
+ stack.push(p);
+ } else if p
+ .extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(is_code_ext)
+ {
+ files.push(p);
+ }
+ }
+ }
+ let mut total_bytes = 0u64;
+ let mut parsed = 0usize;
+ let start = std::time::Instant::now();
+ for path in &files {
+ let Ok(bytes) = std::fs::read(path) else {
+ continue;
+ };
+ let text = String::from_utf8_lossy(&bytes);
+ let ext = path
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+ let Some(def) = registry().iter().find(|d| d.exts.contains(&ext.as_str())) else {
+ continue;
+ };
+ let _ = parse_symbols(def, &text);
+ total_bytes += bytes.len() as u64;
+ parsed += 1;
+ }
+ let secs = start.elapsed().as_secs_f64().max(1e-9);
+ eprintln!(
+ "extract_bench: {parsed} files, {:.1} MB in {secs:.2}s -> {:.0} files/s, {:.1} MB/s",
+ total_bytes as f64 / 1e6,
+ parsed as f64 / secs,
+ total_bytes as f64 / 1e6 / secs,
+ );
+ }
+
#[test]
fn all_queries_compile() {
// registry() builds every Query; a malformed query panics here.
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 ca4cbc6b6..5a7c97900 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -688,6 +688,67 @@ fn initial_generation_and_noop_are_end_to_end_idempotent() {
assert_eq!(journal_events(state_dir.path(), "finish"), 2);
}
+/// Incremental re-index must NOT re-run the Phase-A scan/parse for files whose
+/// content is byte-identical to the committed generation — that is the ~100x
+/// win for the edit-and-rerun / CI workflow, since the tree-sitter parse
+/// dominates per-file cost. Proven directly with the `SCAN_FILE_PARSED` counter
+/// (0 on an unchanged re-run, exactly the changed count when one file changes),
+/// and the committed index stays byte-identical.
+#[test]
+fn unchanged_reindex_skips_the_parse_and_stays_byte_identical() {
+ use std::sync::atomic::Ordering;
+ 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();
+ // A code file (tree-sitter parse is the expensive Phase-A work) + a data file.
+ fs::write(
+ corpus.path().join("main.py"),
+ "def add(a, b):\n return a + b\n\nclass Calc:\n def run(self):\n return add(1, 2)\n",
+ )
+ .unwrap();
+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n2,beta\n").unwrap();
+ let endpoint = HttpEndpoint::start();
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+
+ // Genesis: everything is parsed.
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ let first_docs = endpoint.data_docs();
+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);
+
+ // Re-index with NOTHING changed → zero files parsed, index byte-identical.
+ crate::SCAN_FILE_PARSED.store(0, Ordering::Relaxed);
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ assert_eq!(
+ crate::SCAN_FILE_PARSED.load(Ordering::Relaxed),
+ 0,
+ "unchanged re-index must parse zero files"
+ );
+ assert_eq!(
+ endpoint.data_docs(),
+ first_docs,
+ "unchanged re-index must leave the index byte-identical"
+ );
+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);
+
+ // Change ONE file → exactly that file is parsed (gate is digest-driven, not
+ // a blanket skip).
+ fs::write(
+ corpus.path().join("main.py"),
+ "def add(a, b):\n return a + b + 1\n",
+ )
+ .unwrap();
+ crate::SCAN_FILE_PARSED.store(0, Ordering::Relaxed);
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ assert_eq!(
+ crate::SCAN_FILE_PARSED.load(Ordering::Relaxed),
+ 1,
+ "only the one changed file must be parsed; the unchanged file stays skipped"
+ );
+}
+
#[test]
fn add_change_delete_and_rename_converge_over_real_http() {
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.rs
index 0be875f20..7e4f70176 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -340,9 +340,35 @@ fn project_reconcile_plan(
inventory
.files
.par_iter()
+ .zip(inventory.keys.par_iter())
.zip(inventory.digests.par_iter())
- .map(|(file, digest)| {
+ .map(|((file, content_id), digest)| {
let _in_flight = pr.file(&file.rel, file.size);
+ // Incremental re-index fast path: a file whose content is
+ // byte-identical to the committed generation (its content_id is
+ // present AND its freshly-hashed digest matches the committed
+ // one) needs no fresh scan — `reconcile_plan` carries the
+ // committed assignment forward untouched. The tree-sitter parse
+ // is the dominant per-file cost, so skipping it turns an
+ // unchanged re-index from O(corpus) into O(changed). Correctness
+ // authority is the identical digest check in `reconcile_plan`:
+ // if this ever skipped a *changed* file, that fast path declines
+ // and the run fails closed on empty sketches rather than
+ // carrying stale docs forward.
+ let unchanged = base_plan
+ .files
+ .get(content_id.as_str())
+ .and_then(|o| o.content_digest.as_deref())
+ == Some(digest.as_str());
+ if unchanged {
+ return FileScan {
+ sniffed: None,
+ sketches: Vec::new(),
+ junk: None,
+ pdf_spool: None,
+ pdf_spool_fallbacks: Vec::new(),
+ };
+ }
scan_file(
&file.path,
file.size,
@@ -1330,6 +1356,13 @@ struct PhaseAContext<'a> {
meter: &'a estimate::Meter,
}
+/// Count of files that actually ran the Phase-A scan/parse. The incremental
+/// re-index fast path skips this for byte-identical files, so a test can assert
+/// that an unchanged re-run parses zero files. `Relaxed` — a single counter per
+/// scanned file, negligible against the parse it guards.
+pub(crate) static SCAN_FILE_PARSED: std::sync::atomic::AtomicUsize =
+ std::sync::atomic::AtomicUsize::new(0);
+
fn scan_file(
path: &Path,
size: u64,
@@ -1339,6 +1372,7 @@ fn scan_file(
max_file_gb: u64,
stub: bool,
) -> FileScan {
+ SCAN_FILE_PARSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let state_dir = ctx.state_dir;
let pdf_spool_budget = ctx.budget;
let mut out = FileScan {
diff --git a/engine/crates/xerj-autoindex/src/reconcile_plan.rs b/engine/crates/xerj-autoindex/src/reconcile_plan.rs
index dbc21658a..d94062a74 100644
--- a/engine/crates/xerj-autoindex/src/reconcile_plan.rs
+++ b/engine/crates/xerj-autoindex/src/reconcile_plan.rs
@@ -107,6 +107,41 @@ pub(crate) fn reconcile_plan(
.zip(&inventory.digests)
.zip(scans)
{
+ // Incremental fast path: content byte-identical to the committed plan
+ // (content_id present AND its freshly-hashed digest matches the
+ // committed one) carries its committed assignment forward verbatim — no
+ // fresh scan required. This is the correctness authority for the
+ // scan-skip in `project_reconcile_plan`: because the digest is the hash
+ // of the CURRENT bytes, a match proves byte identity; a changed file
+ // whose scan was (wrongly) skipped mismatches here, falls through to the
+ // normal path, and fails closed on empty sketches rather than carrying
+ // stale docs forward. A legacy plan without a committed digest
+ // (`content_digest: None`) never matches, so it re-scans safely.
+ if let Some(owner) = previous.files.get(content_id) {
+ if owner.content_digest.as_deref() == Some(content_digest.as_str()) {
+ let mut assignments = owner.assignments.clone();
+ assignments.sort();
+ assignments.dedup();
+ let replaced = files.insert(
+ content_id.clone(),
+ FileAssignment {
+ rel: file.rel.clone(),
+ path_id: file.rel_id.clone(),
+ is_symlink: Some(file.is_symlink),
+ family: owner.family.clone(),
+ gzip: owner.gzip,
+ content_digest: Some(content_digest.clone()),
+ assignments,
+ as_document: owner.as_document,
+ },
+ );
+ anyhow::ensure!(
+ replaced.is_none(),
+ "byte-verified inventory contains duplicate content identity {content_id}"
+ );
+ continue;
+ }
+ }
if let Some((status, reason)) = scan.junk {
junk_files.push(JunkFile {
file_key: content_id.clone(),