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): keep map metadata stable on resume

xerj-org9e961f980c4c
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rs
index 0e0c72f6a..2bae791b7 100644
--- a/engine/crates/xerj-autoindex/src/catalog.rs
+++ b/engine/crates/xerj-autoindex/src/catalog.rs
@@ -9,7 +9,7 @@ use serde_json::{json, Value};
pub const CATALOG_INDEX: &str = "autoindex-catalog";
pub fn catalog_mapping() -> Value {
- json!({
+ let mut mapping = json!({
"mappings": {"properties": {
"doc_kind": {"type": "keyword"},
"slug": {"type": "keyword"},
@@ -49,7 +49,24 @@ pub fn catalog_mapping() -> Value {
"pearson_r": {"type": "double"},
"activity_correlated": {"type": "boolean"},
}}
- })
+ });
+ let properties = mapping
+ .pointer_mut("/mappings/properties")
+ .and_then(Value::as_object_mut)
+ .expect("catalog mapping properties");
+ properties.insert(
+ "started".into(),
+ json!({"type": "date", "format": "strict_date_optional_time"}),
+ );
+ properties.insert(
+ "summary_generated_at".into(),
+ json!({"type": "date", "format": "strict_date_optional_time"}),
+ );
+ properties.insert(
+ "invocation_telemetry_scope".into(),
+ json!({"type": "keyword"}),
+ );
+ mapping
}
pub const GOTCHAS: &[&str] = &[
@@ -67,6 +84,11 @@ pub struct DatasetDocInput<'a> {
pub pd: &'a PlanDataset,
pub record_count: u64,
pub junk_records: u64,
+ /// Canonical source bytes backing this dataset's durably live records.
+ ///
+ /// This is not a scan-time filesystem total: a removed path stays
+ /// represented until autoindex also removes its live records, and one
+ /// source feeding several datasets contributes its bytes to each.
pub bytes: u64,
pub file_count: usize,
pub formats: Vec<String>,
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 b00e26f8e..3e7c4a40d 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -27,6 +27,10 @@ struct MockState {
fail_data_bulk: usize,
failed_once: bool,
delete_calls: usize,
+ response_delay_ms: u64,
+ catalog_preexists: bool,
+ catalog_mapping_upgraded: bool,
+ catalog_bulk_before_upgrade: bool,
stop: bool,
embedding_identity_sha256: String,
/// Reject every data-bulk item with a 403 explicit write-block error
@@ -46,11 +50,16 @@ struct MockEndpoint {
impl MockEndpoint {
fn start(fail_data_bulk: usize) -> Self {
+ Self::start_with_delay(fail_data_bulk, 0)
+ }
+
+ fn start_with_delay(fail_data_bulk: usize, response_delay_ms: u64) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let state = Arc::new(Mutex::new(MockState {
fail_data_bulk,
+ response_delay_ms,
embedding_identity_sha256: "a".repeat(64),
..MockState::default()
}));
@@ -73,6 +82,12 @@ impl MockEndpoint {
join: Some(join),
}
}
+
+ fn start_with_existing_catalog() -> Self {
+ let endpoint = Self::start(usize::MAX);
+ endpoint.state.lock().unwrap().catalog_preexists = true;
+ endpoint
+ }
}
impl Drop for MockEndpoint {
@@ -111,19 +126,50 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("");
+ let response_delay_ms = state.lock().unwrap().response_delay_ms;
+ if response_delay_ms > 0 {
+ thread::sleep(std::time::Duration::from_millis(response_delay_ms));
+ }
- let response = if method == "GET" && path == "/v1/embedding/identity" {
+ let (status, response) = if method == "GET" && path == "/v1/embedding/identity" {
let identity = state.lock().unwrap().embedding_identity_sha256.clone();
- json!({"data": {
- "version": 1,
- "backend": "lexical",
- "identity_sha256": identity,
- "dimensions": 384,
- "semantic_contract": "semantic_text-derived-vector.v1",
- "resumable": true
- }, "took_ms": 0, "request_id": "test"})
+ (
+ 200,
+ json!({"data": {
+ "version": 1,
+ "backend": "lexical",
+ "identity_sha256": identity,
+ "dimensions": 384,
+ "semantic_contract": "semantic_text-derived-vector.v1",
+ "resumable": true
+ }, "took_ms": 0, "request_id": "test"}),
+ )
+ } else if method == "PUT" && path == "/autoindex-catalog" {
+ if state.lock().unwrap().catalog_preexists {
+ (
+ 400,
+ json!({"error": {"type": "resource_already_exists_exception"}}),
+ )
+ } else {
+ (200, json!({"acknowledged": true}))
+ }
+ } else if method == "PUT" && path == "/autoindex-catalog/_mapping" {
+ let mapping: Value = serde_json::from_slice(&body).unwrap();
+ let required = [
+ "started",
+ "summary_generated_at",
+ "invocation_telemetry_scope",
+ ];
+ let upgraded = required.iter().all(|field| {
+ mapping
+ .pointer(&format!("/properties/{field}/type"))
+ .and_then(Value::as_str)
+ .is_some()
+ });
+ state.lock().unwrap().catalog_mapping_upgraded = upgraded;
+ (200, json!({"acknowledged": true}))
} else if method == "POST" && path == "/_bulk" {
- bulk_response(&body, state)
+ (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
@@ -137,23 +183,27 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {
.docs
.retain(|_, doc| doc.get("ax_file").and_then(Value::as_str) != Some(key.as_str()));
}
- json!({"deleted": 0, "failures": []})
+ (200, json!({"deleted": 0, "failures": []}))
} else if method == "GET" && path.ends_with("/_count") {
- json!({"count": state.lock().unwrap().docs.len()})
+ (200, json!({"count": state.lock().unwrap().docs.len()}))
} else if method == "POST" && path.ends_with("/_search") {
// Report the REAL number of stored docs: `run_index` now verifies
// live counts against the journal (#195), so a mock that always
// answered 0 hits would (rightly) fail every successful run.
let total = state.lock().unwrap().docs.len();
- json!({"hits":{"total":{"value":total},"hits":[]},"aggregations":{}})
+ (
+ 200,
+ json!({"hits":{"total":{"value":total},"hits":[]},"aggregations":{}}),
+ )
} else {
// ping, index creation/mapping, refresh, and catalog operations
- json!({"acknowledged": true})
+ (200, json!({"acknowledged": true}))
};
let bytes = response.to_string();
+ let reason = if status == 200 { "OK" } else { "Bad Request" };
write!(
stream,
- "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
bytes.len(),
bytes
)
@@ -176,6 +226,9 @@ fn bulk_response(body: &[u8], state: &Arc<Mutex<MockState>>) -> Value {
// the junk sweep of #238), so walk the NDJSON rather than assuming
// action/document pairs — a delete carries no document line.
let mut locked = state.lock().unwrap();
+ if locked.catalog_preexists && !locked.catalog_mapping_upgraded {
+ locked.catalog_bulk_before_upgrade = true;
+ }
let mut line = 0;
while line < lines.len() {
let Ok(action) = serde_json::from_slice::<Value>(lines[line]) else {
@@ -305,6 +358,25 @@ fn event_count(state_dir: &Path, kind: &str) -> usize {
.count()
}
+fn dataset_catalog_docs(endpoint: &MockEndpoint) -> Vec<Value> {
+ let mut docs: Vec<Value> = endpoint
+ .state
+ .lock()
+ .unwrap()
+ .catalog_docs
+ .values()
+ .filter(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("dataset"))
+ .cloned()
+ .collect();
+ docs.sort_by_key(|doc| {
+ doc.get("slug")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string()
+ });
+ docs
+}
+
#[test]
fn semantic_resume_rejects_embedding_identity_drift_before_another_bulk() {
let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
@@ -349,21 +421,241 @@ fn fresh_publication_skips_delete_and_noop_resume_does_not_append_plan() {
"id,value\n0,fresh\n1,fresh\n",
)
.unwrap();
- let endpoint = MockEndpoint::start(usize::MAX);
+ // A fixed endpoint delay makes the start/summary chronology
+ // deterministic instead of relying on scheduler timing.
+ let endpoint = MockEndpoint::start_with_delay(usize::MAX, 5);
let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
- assert_eq!(run_index(config.clone()).unwrap(), 0);
+ let (initial_code, initial_summary) = run_index_report(config.clone()).unwrap();
+ assert_eq!(initial_code, 0);
assert_eq!(endpoint.state.lock().unwrap().delete_calls, 0);
assert_eq!(event_count(state_dir.path(), "plan"), 1);
assert_eq!(event_count(state_dir.path(), "file_replace_start"), 1);
+ let source_bytes = fs::metadata(corpus.path().join("records.csv"))
+ .unwrap()
+ .len();
+ let initial_dataset = endpoint
+ .state
+ .lock()
+ .unwrap()
+ .catalog_docs
+ .values()
+ .find(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("dataset"))
+ .cloned()
+ .expect("dataset catalog document");
+ let initial_dataset_bytes = initial_dataset
+ .get("bytes")
+ .and_then(Value::as_u64)
+ .unwrap();
+ assert_eq!(initial_dataset_bytes, source_bytes);
+ let initial_summary = initial_summary.unwrap();
+ assert_eq!(
+ initial_summary["invocation_telemetry_scope"],
+ json!("latest_invocation_of_durable_run")
+ );
+ let initial_started =
+ chrono::DateTime::parse_from_rfc3339(initial_summary["started"].as_str().unwrap()).unwrap();
+ let initial_summary_generated_at = chrono::DateTime::parse_from_rfc3339(
+ initial_summary["summary_generated_at"].as_str().unwrap(),
+ )
+ .unwrap();
+ assert!(
+ initial_summary_generated_at - initial_started >= chrono::Duration::milliseconds(5),
+ "started must be captured before work, not synthesized with the summary"
+ );
- assert_eq!(run_index(config).unwrap(), 0);
+ let (resume_code, resume_summary) = run_index_report(config).unwrap();
+ assert_eq!(resume_code, 0);
assert_eq!(endpoint.state.lock().unwrap().delete_calls, 0);
assert_eq!(
event_count(state_dir.path(), "plan"),
1,
"an identical resume must reuse the durable plan"
);
+ let resumed_dataset = endpoint
+ .state
+ .lock()
+ .unwrap()
+ .catalog_docs
+ .values()
+ .find(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("dataset"))
+ .cloned()
+ .expect("dataset catalog document after resume");
+ assert_eq!(
+ resumed_dataset["bytes"],
+ json!(source_bytes),
+ "an unchanged resume must not replace durable dataset bytes with zero"
+ );
+ assert_eq!(
+ resume_summary.unwrap()["invocation_telemetry_scope"],
+ json!("latest_invocation_of_durable_run")
+ );
+}
+
+#[test]
+fn changed_source_replaces_durable_dataset_bytes_across_reopen() {
+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ let path = corpus.path().join("records.csv");
+ fs::write(&path, "id,value\n0,old\n").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 initial_bytes = fs::metadata(&path).unwrap().len();
+ assert_eq!(dataset_catalog_docs(&endpoint)[0]["bytes"], initial_bytes);
+
+ fs::write(
+ &path,
+ "id,value,description\n0,new,a longer replacement source\n1,new,second row\n",
+ )
+ .unwrap();
+ let replacement_bytes = fs::metadata(&path).unwrap().len();
+ assert_ne!(replacement_bytes, initial_bytes);
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+
+ // Reopen the durable journal independently of the product invocation.
+ let root = config.root.canonicalize().unwrap();
+ let reopened = state::Journal::open(
+ state_dir.path(),
+ &root.to_string_lossy(),
+ &config.url,
+ &config.prefix,
+ config.bulk_timeout_secs,
+ false,
+ )
+ .unwrap();
+ assert_eq!(reopened.done.len(), 1);
+ assert_eq!(
+ reopened.done.values().next().unwrap().bytes,
+ replacement_bytes
+ );
+ drop(reopened);
+
+ // A following unchanged product rescan must publish the replacement
+ // generation's durable bytes, not zero and not the historical size.
+ assert_eq!(run_index(config).unwrap(), 0);
+ assert_eq!(
+ dataset_catalog_docs(&endpoint)[0]["bytes"],
+ replacement_bytes
+ );
+}
+
+#[test]
+fn deleted_path_bytes_remain_while_its_documents_remain_live() {
+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ let removed = corpus.path().join("removed.csv");
+ let retained = corpus.path().join("retained.csv");
+ fs::write(&removed, "id,value\n0,removed\n1,removed\n").unwrap();
+ fs::write(&retained, "id,value\n2,retained\n3,retained\n").unwrap();
+ let durable_live_bytes =
+ fs::metadata(&removed).unwrap().len() + fs::metadata(&retained).unwrap().len();
+ let endpoint = MockEndpoint::start(usize::MAX);
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
+
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ assert_eq!(
+ dataset_catalog_docs(&endpoint)[0]["bytes"],
+ durable_live_bytes
+ );
+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), 4);
+
+ fs::remove_file(&removed).unwrap();
+ // Current autoindex semantics do not reconcile a missing canonical path:
+ // its indexed documents and FileDone remain live. Dataset bytes must
+ // describe that durable live index rather than silently pretend deletion.
+ for _ in 0..2 {
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), 4);
+ assert_eq!(
+ dataset_catalog_docs(&endpoint)[0]["bytes"],
+ durable_live_bytes
+ );
+ }
+}
+
+#[test]
+fn product_path_counts_shared_source_once_per_distinct_dataset() {
+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ let path = corpus.path().join("finance.sqlite");
+ {
+ let db = rusqlite::Connection::open(&path).unwrap();
+ db.execute_batch(
+ "CREATE TABLE quarterly (quarter TEXT, revenue INTEGER);
+ INSERT INTO quarterly VALUES ('2026-Q1', 100);
+ CREATE TABLE annual (year INTEGER, filing TEXT);
+ INSERT INTO annual VALUES (2026, '10-K');",
+ )
+ .unwrap();
+ }
+ let source_bytes = fs::metadata(&path).unwrap().len();
+ 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 root = config.root.canonicalize().unwrap();
+ let mut journal = state::Journal::open(
+ state_dir.path(),
+ &root.to_string_lossy(),
+ &config.url,
+ &config.prefix,
+ config.bulk_timeout_secs,
+ false,
+ )
+ .unwrap();
+ let mut plan = journal.plan.clone().unwrap();
+ assert_eq!(plan.datasets.len(), 2);
+ let assignment = plan.files.values_mut().next().unwrap();
+ assert_eq!(assignment.assignments.len(), 2);
+ // Model a compatible historical plan that repeated one group assignment.
+ // Catalog accounting must deduplicate it by dataset slug.
+ assignment
+ .assignments
+ .push(assignment.assignments[0].clone());
+ journal.write_plan(&plan).unwrap();
+ drop(journal);
+
+ assert_eq!(run_index(config).unwrap(), 0);
+ let datasets = dataset_catalog_docs(&endpoint);
+ assert_eq!(datasets.len(), 2);
+ assert!(datasets
+ .iter()
+ .all(|dataset| dataset["bytes"] == json!(source_bytes)));
+}
+
+#[test]
+fn existing_catalog_is_upgraded_before_new_run_metadata_is_written() {
+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ fs::write(corpus.path().join("records.csv"), "id,value\n0,one\n").unwrap();
+ let endpoint = MockEndpoint::start_with_existing_catalog();
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
+
+ let (code, summary) = run_index_report(config).unwrap();
+ assert_eq!(code, 0);
+ let summary = summary.unwrap();
+ assert!(summary["started"].is_string());
+ assert!(summary["summary_generated_at"].is_string());
+ assert_eq!(
+ summary["invocation_telemetry_scope"],
+ json!("latest_invocation_of_durable_run")
+ );
+ let state = endpoint.state.lock().unwrap();
+ assert!(state.catalog_mapping_upgraded);
+ assert!(
+ !state.catalog_bulk_before_upgrade,
+ "new run metadata must not reach a legacy catalog before its additive mapping upgrade"
+ );
}
#[test]
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index db02d51d0..b1d89cd52 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -920,6 +920,39 @@ pub fn derive_brain_name(root: &Path) -> String {
}
}
+/// Source bytes durably represented by each dataset.
+///
+/// `FileDone` is the commit record for a successfully published canonical
+/// source. A source can feed more than one inferred dataset (for example, a
+/// workbook or database with multiple tables), so each distinct assigned
+/// dataset reports the complete source bytes it depends on. Repeated groups
+/// within the same dataset count the source only once.
+fn durable_dataset_bytes(plan: &Plan, done: &HashMap<String, FileDone>) -> HashMap<String, u64> {
+ let mut bytes_by_dataset = HashMap::new();
+ for (file_key, completed) in done {
+ let Some(assignment) = plan.files.get(file_key) else {
+ continue;
+ };
+ let assigned_datasets: std::collections::HashSet<&str> = assignment
+ .assignments
+ .iter()
+ .map(|(_, slug)| slug.as_str())
+ .collect();
+ for slug in assigned_datasets {
+ let bytes = bytes_by_dataset.entry(slug.to_string()).or_insert(0u64);
+ *bytes = bytes.saturating_add(completed.bytes);
+ }
+ }
+ bytes_by_dataset
+}
+
+fn invocation_report_timestamps(
+ started: chrono::DateTime<chrono::Utc>,
+ summary_generated_at: chrono::DateTime<chrono::Utc>,
+) -> (String, String) {
+ (started.to_rfc3339(), summary_generated_at.to_rfc3339())
+}
+
fn run_index(cfg: IndexCfg) -> Result<i32> {
run_index_report(cfg).map(|(code, _)| code)
}
@@ -932,6 +965,9 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
/// `None` when the run ended before a plan produced one (empty folder,
/// `--dry-run`).
pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
+ // The very first statement of the function, deliberately: `started` must
+ // be when this invocation began, not when its summary was built.
+ let invocation_started = chrono::Utc::now();
// Fix the phase-A pool width BEFORE anything parallel starts: hashing and
// sniffing are the CPU-bound phase, and they used to take every core no
// matter what the caller asked for (#240 §2).
@@ -1281,9 +1317,14 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
es.ensure_index(catalog::CATALOG_INDEX, &catalog::catalog_mapping())?;
es.update_mapping(
catalog::CATALOG_INDEX,
- &json!({"properties": {"duplicate_of": {"type": "keyword"}}}),
+ &json!({"properties": {
+ "duplicate_of": {"type": "keyword"},
+ "started": {"type": "date", "format": "strict_date_optional_time"},
+ "summary_generated_at": {"type": "date", "format": "strict_date_optional_time"},
+ "invocation_telemetry_scope": {"type": "keyword"}
+ }}),
)
- .context("upgrade autoindex catalog mapping for duplicate aliases")?;
+ .context("upgrade autoindex catalog mapping")?;
// A replacement transaction starts before the effective new plan is
// persisted and before live visibility changes. If the process dies at
// any later boundary, journal replay removes the older file_done and
@@ -1337,7 +1378,6 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
records: AtomicU64,
junk: AtomicU64,
dropped: AtomicU64,
- bytes: AtomicU64,
}
let mut ds_rt: HashMap<String, DsRt> = HashMap::new();
for d in &plan.datasets {
@@ -1349,7 +1389,6 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
records: AtomicU64::new(0),
junk: AtomicU64::new(0),
dropped: AtomicU64::new(0),
- bytes: AtomicU64::new(0),
},
);
}
@@ -1999,10 +2038,6 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
records_total.fetch_add(file_records, Ordering::Relaxed);
junk_records.fetch_add(file_junk, Ordering::Relaxed);
if let Some(rt) = fa.assignments.first().and_then(|(_, slug)| ds_rt.get(slug)) {
- rt.bytes.fetch_add(
- f.size / fa.assignments.len().max(1) as u64,
- Ordering::Relaxed,
- );
if file_junk > 0 {
rt.junk.fetch_add(file_junk, Ordering::Relaxed);
}
@@ -2301,6 +2336,10 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
// dataset docs
let mut junk_records_by_run: u64 = junk_records.load(Ordering::Relaxed);
+ let dataset_bytes = {
+ let journal = journal_mx.lock().unwrap();
+ durable_dataset_bytes(&plan, &journal.done)
+ };
for d in &plan.datasets {
let rt = &ds_rt[&d.slug];
let sample_queries = catalog::build_sample_queries(d, &key_corrs);
@@ -2339,7 +2378,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
pd: d,
record_count: *ds_counts.get(&d.slug).unwrap_or(&0),
junk_records: rt.junk.load(Ordering::Relaxed),
- bytes: rt.bytes.load(Ordering::Relaxed),
+ bytes: dataset_bytes.get(&d.slug).copied().unwrap_or(0),
file_count: d.file_count,
formats,
time_min: tmin,
@@ -2443,6 +2482,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
}
let wall = t0.elapsed().as_secs_f64();
+ let (started, summary_generated_at) =
+ invocation_report_timestamps(invocation_started, chrono::Utc::now());
let total_records: u64 = ds_counts.values().sum();
// Run-summary honesty (§6.6.4): what the detectors wrote AND what they
// could not resolve — a dangling [[link]] is a fact about the corpus, not
@@ -2475,13 +2516,18 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
"edges_invalidated": gr.invalidated,
})
});
+ // A resume intentionally reuses and upserts the durable run id. Timing
+ // and detector counters therefore describe this latest invocation,
+ // while corpus descriptors describe the durable live run state.
let mut run_doc = json!({
"doc_kind": "run",
"run_id": run_id,
"root": root_str,
"url": cfg.url,
"prefix": cfg.prefix,
- "started": chrono::Utc::now().to_rfc3339(),
+ "started": started,
+ "summary_generated_at": summary_generated_at,
+ "invocation_telemetry_scope": "latest_invocation_of_durable_run",
"files_total": paths_discovered,
"unique_content_files": files.len(),
"files_indexed": journal_mx.lock().unwrap().done.len(),
@@ -3164,5 +3210,129 @@ mod duplicate_integration_tests {
}
}
+#[cfg(test)]
+mod map_metadata_tests {
+ use super::*;
+
+ fn assignment(slugs: &[&str]) -> FileAssignment {
+ FileAssignment {
+ rel: "report.dat".into(),
+ path_id: "path:report.dat".into(),
+ family: "json".into(),
+ gzip: false,
+ content_digest: Some("digest".into()),
+ assignments: slugs
+ .iter()
+ .enumerate()
+ .map(|(group, slug)| (Some(format!("group-{group}")), (*slug).to_string()))
+ .collect(),
+ }
+ }
+
+ #[test]
+ fn unchanged_resume_keeps_durable_assignment_aware_dataset_bytes() {
+ let _guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ let plan = Plan {
+ files: HashMap::from([
+ (
+ "shared".into(),
+ assignment(&["quarterly", "quarterly", "annual"]),
+ ),
+ ("quarterly-only".into(), assignment(&["quarterly"])),
+ ]),
+ ..Plan::default()
+ };
+ let mut initial = state::Journal::open(
+ state_dir.path(),
+ "corpus",
+ "http://engine",
+ "ax",
+ 300,
+ false,
+ )
+ .unwrap();
+ initial.write_plan(&plan).unwrap();
+ initial
+ .file_done(&FileDone {
+ file_key: "shared".into(),
+ path: "report.dat".into(),
+ records: 10,
+ junk: 0,
+ bytes: 100,
+ generation: Some("digest".into()),
+ })
+ .unwrap();
+ initial
+ .file_done(&FileDone {
+ file_key: "quarterly-only".into(),
+ path: "quarterly.json".into(),
+ records: 2,
+ junk: 0,
+ bytes: 23,
+ generation: Some("digest-2".into()),
+ })
+ .unwrap();
+ let before_resume = durable_dataset_bytes(&plan, &initial.done);
+ drop(initial);
+
+ // Opening the same durable run appends only an invocation-level
+ // resume record. No source is processed and no FileDone is appended.
+ let resumed = state::Journal::open(
+ state_dir.path(),
+ "corpus",
+ "http://engine",
+ "ax",
+ 300,
+ false,
+ )
+ .unwrap();
+ let after_unchanged_resume =
+ durable_dataset_bytes(resumed.plan.as_ref().unwrap(), &resumed.done);
+
+ assert_eq!(before_resume, after_unchanged_resume);
+ assert_eq!(after_unchanged_resume["quarterly"], 123);
+ assert_eq!(after_unchanged_resume["annual"], 100);
+ }
+
+ #[test]
+ fn invocation_started_is_not_derived_from_summary_generation() {
+ let started = chrono::DateTime::parse_from_rfc3339("2026-08-04T00:29:05.673023686Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
+ let summary_generated_at =
+ chrono::DateTime::parse_from_rfc3339("2026-08-04T00:31:37.937589283Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
+
+ let (reported_started, reported_summary_generated_at) =
+ invocation_report_timestamps(started, summary_generated_at);
+
+ assert_eq!(reported_started, "2026-08-04T00:29:05.673023686+00:00");
+ assert_eq!(
+ reported_summary_generated_at,
+ "2026-08-04T00:31:37.937589283+00:00"
+ );
+ assert_ne!(reported_started, reported_summary_generated_at);
+ }
+
+ #[test]
+ fn catalog_mapping_declares_latest_invocation_telemetry_fields() {
+ let mapping = catalog::catalog_mapping();
+ assert_eq!(
+ mapping.pointer("/mappings/properties/started/type"),
+ Some(&json!("date"))
+ );
+ assert_eq!(
+ mapping.pointer("/mappings/properties/summary_generated_at/type"),
+ Some(&json!("date"))
+ );
+ assert_eq!(
+ mapping.pointer("/mappings/properties/invocation_telemetry_scope/type"),
+ Some(&json!("keyword"))
+ );
+ }
+}
+
#[cfg(test)]
mod failure_resume_http_tests;