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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(autoindex): seal record counts per dataset, not per file (#360)
xerj-org11ab6ad95443
diff --git a/engine/crates/xerj-autoindex/src/generation_catalog.rs b/engine/crates/xerj-autoindex/src/generation_catalog.rsindex c5a6283bd..11b8c05d8 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog.rs@@ -381,6 +381,7 @@ mod tests {expected_passages: 0,expected_vectors: 0,expected_junk_records: 0,+ expected_records_by_dataset: BTreeMap::from([("reports".to_string(), 2)]),}}diff --git a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rsindex 166bb0f86..f485819d5 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs@@ -115,6 +115,7 @@ fn group(key: &str, path: &str, aliases: &[&str]) -> ManifestGroup {expected_passages: 0,expected_vectors: 0,expected_junk_records: 0,+ expected_records_by_dataset: BTreeMap::from([("reports".to_string(), 2)]),}}diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 39a801e06..660cafde4 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -5,7 +5,7 @@//! the same HTTP client and validation barriers as a real server.use super::*;-use std::collections::HashMap;+use std::collections::{BTreeMap, HashMap};use std::fs;use std::io::{BufRead, BufReader, Read, Write};use std::net::{TcpListener, TcpStream};@@ -371,6 +371,19 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value.and_then(Value::as_object).and_then(|term| term.iter().next()).is_none_or(|(field, value)| doc.get(field) == Some(value))+ // A per-dataset read-back scopes `terms` on `ax_file`+ // and `term` on `ax_dataset` in the same `bool.filter`,+ // so an endpoint that honoured only the latter would+ // count every file's records into every dataset.+ && filter+ .get("terms")+ .and_then(Value::as_object)+ .and_then(|terms| terms.iter().next())+ .is_none_or(|(field, values)| {+ values.as_array().is_some_and(|values| {+ values.iter().any(|value| doc.get(field) == Some(value))+ })+ })})&& exists.map(|field| doc.get(field).is_some()).unwrap_or(true)})@@ -1300,6 +1313,102 @@ fn a_junk_record_is_counted_into_the_generation_and_never_fatal() {assert_eq!(file_doc["records"], 40);}+/// #360: one file can feed several datasets — a SQL dump is one file and N+/// tables — but the generated executor sealed a single flat record total per+/// *file* and reconciled that whole-file total against *each* dataset's+/// read-back. Every ordinary multi-table dump therefore aborted at catalog+/// publication with `exit=1` on a run whose data was already complete.+#[test]+fn a_multi_table_dump_reconciles_each_dataset_against_its_own_sealed_count() {+ 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();+ fs::write(+ corpus.path().join("dump.sql"),+ "CREATE TABLE `users` (`id` int, `name` varchar(64));\n\+ INSERT INTO `users` VALUES (1,'ann'),(2,'bob');\n\+ CREATE TABLE `orders` (`id` int, `total` int);\n\+ INSERT INTO `orders` VALUES (10,100),(11,200);\n",+ )+ .unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);++ let (code, summary) = run_index_report(config).unwrap();+ let summary = summary.expect("a two-table dump must commit its generation");+ assert_eq!(code, 0, "a valid multi-table dump is not a failed run");+ assert_eq!(summary["generation"], 1);+ assert_eq!(summary["records_total"], 4);+ assert_eq!(summary["junk_records_total"], 0);+ assert_eq!(endpoint.data_docs().len(), 4);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);++ // Both tables became datasets, and each one's catalog document reports the+ // records it actually holds — not the whole file's total.+ let dataset_docs: BTreeMap<String, Value> = endpoint+ .state+ .lock()+ .unwrap()+ .docs+ .iter()+ .filter(|((index, _), doc)| {+ index == catalog::CATALOG_INDEX+ && doc.get("doc_kind").and_then(Value::as_str) == Some("dataset")+ })+ .map(|((_, id), doc)| (id.clone(), doc.clone()))+ .collect();+ assert_eq!(+ dataset_docs.len(),+ 2,+ "one dataset per table: {dataset_docs:?}"+ );+ for (id, doc) in &dataset_docs {+ assert_eq!(doc["record_count"], 2, "dataset {id} holds two rows");+ }+ // Each table's rows really are in their own index, under their own slug.+ for doc in endpoint.data_docs() {+ let slug = doc["ax_dataset"].as_str().unwrap().to_owned();+ assert!(+ dataset_docs.contains_key(&format!("ds:{slug}")),+ "record published under an uncatalogued dataset {slug}"+ );+ }+}++/// The other everyday shape of #360: a real database file. One `.sqlite` is+/// one content group and one dataset per table, exactly like the dump above.+#[test]+fn a_two_table_sqlite_file_commits_its_generation() {+ 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();+ let connection = rusqlite::Connection::open(corpus.path().join("shop.sqlite")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);\n\+ INSERT INTO users VALUES (1,'ann'),(2,'bob');\n\+ CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER);\n\+ INSERT INTO orders VALUES (10,100),(11,200);",+ )+ .unwrap();+ drop(connection);+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);++ let (code, summary) = run_index_report(config).unwrap();+ let summary = summary.expect("a two-table database must commit its generation");+ assert_eq!(code, 0);+ assert_eq!(summary["records_total"], 4);+ assert_eq!(endpoint.data_docs().len(), 4);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);+}+/// Where this branch and #241 meet.////// The generated `--no-graph` route returns from inside `run_index_report`,diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 503ec5367..ddc96bce5 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -34,7 +34,7 @@ pub mod walk;use anyhow::{Context, Result};use serde::Serialize;use serde_json::{json, Map, Value};-use std::collections::{HashMap, HashSet};+use std::collections::{BTreeMap, HashMap, HashSet};use std::io::{BufRead, BufReader, Seek, Write};use std::path::Path;use std::sync::atomic::{AtomicU64, Ordering};@@ -529,6 +529,7 @@ fn begin_non_graph_generation(expected_passages: 0,expected_vectors: 0,expected_junk_records: 0,+ expected_records_by_dataset: BTreeMap::new(),});}let mut groups = sync::reconcile_groups(&base.groups, candidates)?;diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex e26a0f114..af21df0bf 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -1498,6 +1498,7 @@ mod sync_journal_tests {expected_passages: 1,expected_vectors: 1,expected_junk_records: 0,+ expected_records_by_dataset: std::collections::BTreeMap::new(),}],},)diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rsindex ef96ac3a0..83aeac88b 100644--- a/engine/crates/xerj-autoindex/src/sync.rs+++ b/engine/crates/xerj-autoindex/src/sync.rs@@ -56,12 +56,44 @@ pub struct ManifestGroup {/// Junk is recorded, never fatal (`cli.rs` EXIT CODES).#[serde(default)]pub expected_junk_records: u64,+ /// Per-dataset breakdown of `expected_records`, keyed by the same dataset+ /// identity the records were written under. One content can feed several+ /// datasets — a SQL dump is one file and N tables, so N datasets — and the+ /// flat total is then comparable to no single dataset's read-back. Empty+ /// on a generation sealed before this ledger existed; `expected_records_for`+ /// decides what such a group can still attribute.+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub expected_records_by_dataset: BTreeMap<String, u64>,}impl ManifestGroup {fn all_paths(&self) -> impl Iterator<Item = &ManifestPath> {std::iter::once(&self.canonical).chain(self.aliases.iter())}++ /// Records this group contributed to one dataset, or `None` when the seal+ /// genuinely cannot say.+ ///+ /// A group sealed before `expected_records_by_dataset` existed carries only+ /// the whole-content total. That total is attributable when the content fed+ /// a single dataset, and zero is attributable to every dataset; a legacy+ /// fan-out group that produced records is unattributable and must be+ /// reported as such rather than guessed at.+ pub fn expected_records_for(&self, slug: &str) -> Option<u64> {+ if !self.expected_records_by_dataset.is_empty() {+ return Some(+ self.expected_records_by_dataset+ .get(slug)+ .copied()+ .unwrap_or(0),+ );+ }+ if self.expected_records == 0 || self.dataset_slugs == [slug] {+ Some(self.expected_records)+ } else {+ None+ }+ }}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]@@ -559,6 +591,7 @@ pub struct DesiredContentGroup {pub expected_passages: u64,pub expected_vectors: u64,pub expected_junk_records: u64,+ pub expected_records_by_dataset: BTreeMap<String, u64>,}/// Content identity is collision-safe and byte-verified by the inventory@@ -642,6 +675,7 @@ pub fn reconcile_groups(expected_passages: candidate.expected_passages,expected_vectors: candidate.expected_vectors,expected_junk_records: candidate.expected_junk_records,+ expected_records_by_dataset: candidate.expected_records_by_dataset,});}result.sort_by(|left, right| left.group_id.cmp(&right.group_id));@@ -814,6 +848,28 @@ fn validate_groups(groups: &[ManifestGroup]) -> Result<()> {group.dataset_slugs.windows(2).all(|pair| pair[0] < pair[1]),"dataset assignments are not canonical");+ // The per-dataset ledger is the identity the records were sealed under,+ // so it can only name datasets the group actually feeds and must add up+ // to the group total. Checking it here moves detection of a fan-out+ // accounting error from catalog-publish time — where it surfaces as an+ // opaque read-back mismatch that aborts a finished run — to manifest+ // validation, before anything is published.+ anyhow::ensure!(+ group+ .expected_records_by_dataset+ .keys()+ .all(|slug| group.dataset_slugs.contains(slug)),+ "per-dataset record ledger names a dataset the group does not feed"+ );+ anyhow::ensure!(+ group.expected_records_by_dataset.is_empty()+ || group+ .expected_records_by_dataset+ .values()+ .try_fold(0u64, |sum, count| sum.checked_add(*count))+ == Some(group.expected_records),+ "per-dataset record ledger disagrees with the group record total"+ );}anyhow::ensure!(groups@@ -1274,6 +1330,7 @@ mod tests {expected_passages: 1,expected_vectors: 1,expected_junk_records: 0,+ expected_records_by_dataset: BTreeMap::from([("reports".to_string(), 1)]),}}@@ -1288,6 +1345,7 @@ mod tests {expected_passages: 1,expected_vectors: 1,expected_junk_records: 0,+ expected_records_by_dataset: BTreeMap::from([("reports".to_string(), 1)]),}}@@ -1621,6 +1679,67 @@ mod tests {assert_eq!(manifest_digest(&a).unwrap(), manifest_digest(&b).unwrap());}+ /// #360 back-compat: `manifest_digest` covers the serialized groups and+ /// every committed generation is re-verified against it. A manifest sealed+ /// before the per-dataset ledger existed must keep hashing to the value it+ /// was sealed with, which is exactly what `skip_serializing_if` buys.+ #[test]+ fn a_manifest_without_the_per_dataset_ledger_keeps_its_sealed_digest() {+ let mut sealed = group("a", "a", path("61", false));+ sealed.expected_records_by_dataset = BTreeMap::new();+ let manifest = GenerationManifest {+ generation: 0,+ execution: None,+ plan: Plan::default(),+ groups: vec![sealed.clone()],+ };+ let encoded = serde_json::to_string(&manifest).unwrap();+ assert!(+ !encoded.contains("expected_records_by_dataset"),+ "an empty ledger must serialize to nothing: {encoded}"+ );+ let decoded: GenerationManifest = serde_json::from_str(&encoded).unwrap();+ assert_eq!(+ manifest_digest(&decoded).unwrap(),+ manifest_digest(&manifest).unwrap()+ );+ // Such a group is still attributable while it feeds one dataset, and+ // honestly unattributable once it fans out.+ assert_eq!(sealed.expected_records_for("reports"), Some(1));+ assert_eq!(sealed.expected_records_for("other"), None);+ sealed.dataset_slugs = vec!["orders".into(), "users".into()];+ assert_eq!(sealed.expected_records_for("users"), None);+ sealed.expected_records = 0;+ assert_eq!(sealed.expected_records_for("users"), Some(0));+ }++ /// The invariant that makes #360 impossible to reintroduce, checked at+ /// manifest validation rather than at catalog-publish time.+ #[test]+ fn validation_rejects_a_per_dataset_ledger_that_does_not_add_up() {+ let mut fan_out = group("a", "a", path("61", false));+ fan_out.dataset_slugs = vec!["orders".into(), "users".into()];+ fan_out.expected_records = 4;+ fan_out.expected_records_by_dataset =+ BTreeMap::from([("orders".to_string(), 2), ("users".to_string(), 2)]);+ validate_groups(std::slice::from_ref(&fan_out)).unwrap();++ let mut whole_file_total = fan_out.clone();+ whole_file_total.expected_records_by_dataset =+ BTreeMap::from([("orders".to_string(), 4), ("users".to_string(), 4)]);+ let error = validate_groups(&[whole_file_total]).unwrap_err();+ assert!(+ format!("{error:#}").contains("disagrees with the group record total"),+ "{error:#}"+ );++ let mut foreign_dataset = fan_out;+ foreign_dataset.expected_records_by_dataset =+ BTreeMap::from([("orders".to_string(), 2), ("invoices".to_string(), 2)]);+ let error = validate_groups(&[foreign_dataset]).unwrap_err();+ assert!(format!("{error:#}").contains("does not feed"), "{error:#}");+ }+fn identity(inventory: &str) -> ExecutionIdentity {ExecutionIdentity {version: EXECUTION_IDENTITY_VERSION,diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex 21d898ab4..4d46bb8d4 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -57,6 +57,14 @@ pub struct PreparedArtifact {/// never published, so no read-back count sees it.#[serde(default)]pub junk: u64,+ /// Per-dataset breakdown of `records`, keyed by the dataset each record was+ /// written under. One file can feed several datasets — a SQL dump is one+ /// file and N tables — so the flat total is not comparable to any single+ /// dataset's read-back. Omitted when empty: `snapshot_digest` covers the+ /// serialized artifact, so an in-flight snapshot sealed before this field+ /// existed must keep hashing to the same value.+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub records_by_dataset: BTreeMap<String, u64>,pub bytes: u64,pub digest: String,}@@ -379,10 +387,18 @@ impl<'a> EsSyncBackend<'a> {.iter().map(|group| group.content_id.as_str()).collect();+ // Filter on `ax_dataset` as well as `ax_file`: the read-back is then+ // per-dataset by construction, matching the identity the records+ // were sealed under, and stays exact even if two datasets ever share+ // one index. `ax_dataset` is written at every sink site and is a+ // mapped `PROVENANCE_FIELDS` keyword.let mut body = serde_json::json!({"size": 0,"track_total_hits": true,- "query": {"terms": {"ax_file": content_ids}}+ "query": {"bool": {"filter": [+ {"terms": {"ax_file": content_ids}},+ {"term": {"ax_dataset": dataset.slug}}+ ]}}});if let Some(field) = &dataset.time_field {body["aggs"] = serde_json::json!({@@ -395,16 +411,40 @@ impl<'a> EsSyncBackend<'a> {.pointer("/hits/total/value").and_then(Value::as_u64).context("dataset exact read-back has no total")?;- let expected = groups.iter().try_fold(0u64, |sum, group| {- sum.checked_add(group.expected_records)- .context("dataset expected record count overflow")- })?;- anyhow::ensure!(- record_count == expected,- "dataset {} exact read-back count {record_count} disagrees with sealed count \- {expected}",- dataset.slug- );+ // A group's sealed record count is a property of the *content*, not+ // of a dataset: one file fans out over N datasets (a SQL dump is N+ // tables), so its flat total is comparable to no single dataset's+ // read-back. Fold the per-dataset ledger instead — the counts keyed+ // by the identity they were written under. `None` is a group sealed+ // before that ledger existed which fanned out anyway: genuinely+ // unattributable, so the equality is skipped for this dataset rather+ // than guessed at, and the exact read-back is still published as the+ // statistic. The check itself stays fatal — a read-back that+ // disagrees with a seal it *can* be compared against is a corruption+ // signal, not junk.+ let expected = groups+ .iter()+ .map(|group| group.expected_records_for(&dataset.slug))+ .try_fold(Some(0u64), |sum, count| match (sum, count) {+ (Some(sum), Some(count)) => sum+ .checked_add(count)+ .context("dataset expected record count overflow")+ .map(Some),+ _ => Ok(None),+ })?;+ if let Some(expected) = expected {+ anyhow::ensure!(+ record_count == expected,+ "dataset {} exact read-back count {record_count} disagrees with sealed count \+ {expected} across groups {}",+ dataset.slug,+ groups+ .iter()+ .map(|group| group.group_id.as_str())+ .collect::<Vec<_>>()+ .join(",")+ );+ }let mut formats: Vec<String> = desired.plan.files@@ -1093,6 +1133,9 @@ pub fn groups_from_inventory(expected_passages: prior.map_or(0, |group| group.expected_passages),expected_vectors: prior.map_or(0, |group| group.expected_vectors),expected_junk_records: prior.map_or(0, |group| group.expected_junk_records),+ expected_records_by_dataset: prior+ .map(|group| group.expected_records_by_dataset.clone())+ .unwrap_or_default(),})}).collect::<Result<Vec<_>>>()?;@@ -1130,6 +1173,7 @@ pub fn bind_prepared_counts(group.expected_passages = prepared.passages;group.expected_vectors = prepared.vectors;group.expected_junk_records = prepared.junk;+ group.expected_records_by_dataset = prepared.records_by_dataset.clone();}Ok(())}@@ -1466,6 +1510,7 @@ fn prepare_artifact(budget,};let mut records = 0u64;+ let mut records_by_dataset: BTreeMap<String, u64> = BTreeMap::new();let mut passages = 0u64;let mut vectors = 0u64;let mut sink_error: Option<anyhow::Error> = None;@@ -1521,6 +1566,10 @@ fn prepare_artifact(return false;}records += 1;+ // Seal the count under the same dataset identity the record was written+ // under, so a file that fans out over several datasets stays reconcilable+ // against each one separately.+ *records_by_dataset.entry(slug.to_string()).or_default() += 1;if dataset.semantic_field.as_ref()@@ -1552,6 +1601,7 @@ fn prepare_artifact(passages,vectors,junk: stats.junk,+ records_by_dataset,bytes,digest: stream_digest(&path, "axp1")?,})@@ -1768,6 +1818,155 @@ mod tests {}}+ /// One file, two tables, two datasets — the ordinary shape of a SQL dump.+ fn sql_plan_for(inventory: &Inventory) -> Plan {+ let key = inventory.keys[0].clone();+ let file = &inventory.files[0];+ let dataset = |slug: &str| PlanDataset {+ slug: slug.into(),+ index: format!("ax-{slug}"),+ family: "sqldump".into(),+ group: Some(slug.into()),+ specs: vec![],+ time_field: None,+ semantic_field: None,+ sampled_records: 2,+ file_count: 1,+ };+ Plan {+ datasets: vec![dataset("orders"), dataset("users")],+ files: HashMap::from([(+ key,+ FileAssignment {+ rel: file.rel.clone(),+ path_id: file.rel_id.clone(),+ is_symlink: Some(file.is_symlink),+ family: "sqldump".into(),+ gzip: false,+ content_digest: Some(inventory.digests[0].clone()),+ assignments: vec![+ (Some("orders".into()), "orders".into()),+ (Some("users".into()), "users".into()),+ ],+ as_document: false,+ },+ )]),+ alias_paths_indexed: false,+ ..Plan::default()+ }+ }++ fn two_table_dump() -> &'static str {+ "CREATE TABLE `users` (`id` int, `name` varchar(64));\n\+ INSERT INTO `users` VALUES (1,'ann'),(2,'bob');\n\+ CREATE TABLE `orders` (`id` int, `total` int);\n\+ INSERT INTO `orders` VALUES (10,100),(11,200);\n"+ }++ /// #360: the seal has to say which dataset each record went to. A flat+ /// per-file total is comparable to no single dataset's read-back once the+ /// file fans out, and the executor reconciled it against every one of them.+ #[test]+ fn preparation_seals_records_under_each_dataset_a_file_feeds() {+ let _guard = SNAPSHOT_TEST_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let corpus = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ std::fs::write(corpus.path().join("dump.sql"), two_table_dump()).unwrap();+ let inventory = inventory(corpus.path());+ let plan = sql_plan_for(&inventory);+ let snapshot = create_prepared_snapshot(+ state.path(),+ "tx-fan-out",+ &inventory,+ &plan,+ "test-preparation-v1",+ u64::MAX,+ )+ .unwrap();++ let prepared = snapshot.files[0].prepared.as_ref().unwrap();+ assert_eq!(prepared.records, 4);+ assert_eq!(+ prepared.records_by_dataset,+ BTreeMap::from([("orders".to_string(), 2), ("users".to_string(), 2)])+ );++ let mut groups = groups_from_inventory(&inventory, &plan, &[]).unwrap();+ bind_prepared_counts(&mut groups, &snapshot, &inventory.keys).unwrap();+ assert_eq!(groups[0].expected_records, 4);+ assert_eq!(groups[0].expected_records_for("users"), Some(2));+ assert_eq!(groups[0].expected_records_for("orders"), Some(2));+ assert_eq!(groups[0].expected_records_for("absent"), Some(0));+ }++ /// `snapshot_digest` covers the serialized `PreparedArtifact` and+ /// `open_snapshot` re-verifies it on every resume, so a snapshot sealed+ /// before the per-dataset ledger existed has to keep hashing to the value+ /// it was sealed with. Otherwise this fix turns a bug affecting SQL corpora+ /// into "protected snapshot digest disagrees" for everyone mid-generation.+ #[test]+ fn a_snapshot_sealed_without_the_per_dataset_ledger_still_resumes() {+ let _guard = SNAPSHOT_TEST_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let corpus = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ std::fs::write(corpus.path().join("dump.sql"), two_table_dump()).unwrap();+ let inventory = inventory(corpus.path());+ let plan = sql_plan_for(&inventory);+ let snapshot = create_prepared_snapshot(+ state.path(),+ "tx-legacy-ledger",+ &inventory,+ &plan,+ "test-preparation-v1",+ u64::MAX,+ )+ .unwrap();+ assert!(!snapshot.files[0]+ .prepared+ .as_ref()+ .unwrap()+ .records_by_dataset+ .is_empty());++ // Rewrite the manifest exactly as a pre-upgrade binary wrote it: no+ // `records_by_dataset` key anywhere, and a digest computed over that+ // form. `skip_serializing_if` is what makes the two byte-identical.+ let manifest = state+ .path()+ .join("sync-snapshots/tx-legacy-ledger/manifest.json");+ let raw = std::fs::read_to_string(&manifest).unwrap();+ assert!(raw.contains("records_by_dataset"));+ let mut legacy: SourceSnapshot =+ serde_json::from_str(&raw.replace("\"records_by_dataset\"", "\"ignored_by_serde\""))+ .unwrap();+ assert!(legacy.files[0]+ .prepared+ .as_ref()+ .unwrap()+ .records_by_dataset+ .is_empty());+ assert!(!serde_json::to_string(&legacy)+ .unwrap()+ .contains("records_by_dataset"));+ legacy.snapshot_digest = snapshot_digest(+ &legacy.tx_id,+ &legacy.started,+ &legacy.preparation_contract_digest,+ &legacy.footprint,+ &legacy.files,+ )+ .unwrap();+ std::fs::write(&manifest, serde_json::to_vec(&legacy).unwrap()).unwrap();++ let resumed = open_snapshot(state.path(), "tx-legacy-ledger").unwrap();+ assert_eq!(resumed, legacy);+ assert_eq!(resumed.files[0].prepared.as_ref().unwrap().records, 4);+ }+fn execution(tx_id: &str, digest: &str) -> ExecutionIdentity {ExecutionIdentity {version: EXECUTION_IDENTITY_VERSION,