From 310ef079b75798d5a218429d2b01d10429046867 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 10:23:00 -0500 Subject: [PATCH 1/5] feat(storage): count a migration source table's rows --- crates/nostream-storage/src/lib.rs | 3 +- crates/nostream-storage/src/migration.rs | 22 +++++++++---- .../src/postgres/migration.rs | 31 +++++++++++++++++++ crates/nostream-storage/tests/migration_pg.rs | 20 ++++++++++++ 4 files changed, 69 insertions(+), 7 deletions(-) diff --git a/crates/nostream-storage/src/lib.rs b/crates/nostream-storage/src/lib.rs index 2a58e834d..e467fea06 100644 --- a/crates/nostream-storage/src/lib.rs +++ b/crates/nostream-storage/src/lib.rs @@ -18,7 +18,8 @@ //! What it deliberately does **not** own: the relay handlers that call these traits, the //! payments service, the daemon's backend factory and the tool behind //! `nostream-cli migrate pg-to-lmdb`. It owns that tool's seam — [`migration`], the paged source -//! read and the exact-per-row target write — which exists for that one caller and for no other; +//! read, its per-table row count and the exact-per-row target write — which exists for that one +//! caller and for no other; //! the copy, its manifest and its verification live in the CLI. The cache is not a cache server: //! no Redis client is added and `src/cache/client.ts` / `src/adapters/redis-adapter.ts` are not //! ported — the decision and what would overturn it are ADR diff --git a/crates/nostream-storage/src/migration.rs b/crates/nostream-storage/src/migration.rs index 08e2e0843..baccc849f 100644 --- a/crates/nostream-storage/src/migration.rs +++ b/crates/nostream-storage/src/migration.rs @@ -11,10 +11,11 @@ //! lists and nine index write paths and drift from them. //! //! The seam is two traits and the rows they move. [`MigrationSource`] reads a table one keyset -//! page at a time with no filter of any kind; [`MigrationTarget`] writes a page exactly as the -//! source carries it and reads a page back for the verification pass. Neither goes through the -//! nine repository traits: no trait enumerates a table, and every trait write stamps, clears or -//! drops at least one column, so a trait-shaped copy would be both lossy and partial. +//! page at a time with no filter of any kind, and answers the table's own row count once before +//! the first page; [`MigrationTarget`] writes a page exactly as the source carries it and reads +//! a page back for the verification pass. Neither goes through the nine repository traits: no +//! trait enumerates a table, and every trait write stamps, clears or drops at least one column, +//! so a trait-shaped copy would be both lossy and partial. //! //! Every type here compiles with no driver. The two implementations are `#[cfg(feature)]`, and //! this vocabulary must stay buildable with neither. @@ -219,9 +220,18 @@ impl MigrationRow { /// Reads one table of the source, a keyset page at a time. /// -/// The implementation issues no statement but these reads: the migration never writes to the -/// source (`docs/rewrite/decisions/0013-pg-to-lmdb-migration.md`, D12). +/// The implementation issues no statement but these reads and one `count(*)` per table: the +/// migration never writes to the source +/// (`docs/rewrite/decisions/0013-pg-to-lmdb-migration.md`, D12). pub trait MigrationSource: Send + Sync { + /// The number of rows `table` holds in the source, asked once before the table's first + /// page. + /// + /// This is a read-only statement, and it is what lets the verification pass prove the copy + /// read every row the source held + /// (`docs/rewrite/decisions/0013-pg-to-lmdb-migration.md`, D12). + fn count_rows<'a>(&'a self, table: MigratedTable) -> StorageFuture<'a, u64>; + /// The rows of `table` after `after`, in the table's key order, at most `limit` of them. /// /// `after` is exclusive and `None` starts at the table's first row. A page shorter than diff --git a/crates/nostream-storage/src/postgres/migration.rs b/crates/nostream-storage/src/postgres/migration.rs index 70a6e6243..b602b6a31 100644 --- a/crates/nostream-storage/src/postgres/migration.rs +++ b/crates/nostream-storage/src/postgres/migration.rs @@ -29,6 +29,20 @@ COALESCE(is_vanished, false) AS is_vanished, COALESCE(balance, 0) AS balance, cr updated_at, tos_accepted_at"; impl MigrationSource for PostgresBackend { + fn count_rows<'a>(&'a self, table: MigratedTable) -> StorageFuture<'a, u64> { + Box::pin(async move { + let row = EventQuery { + sql: count_statement(table), + args: Args::default(), + } + .into_query() + .fetch_one(self.master()) + .await?; + let count: i64 = row.try_get(0)?; + Ok(count as u64) + }) + } + fn read_batch<'a>( &'a self, table: MigratedTable, @@ -46,6 +60,11 @@ impl MigrationSource for PostgresBackend { } } +/// `SELECT count(*) FROM `: the source's own count, with no filter, cursor or limit. +fn count_statement(table: MigratedTable) -> String { + format!("SELECT count(*) FROM {}", table.name()) +} + /// How a table's unique key is bound as a keyset cursor. /// /// Each variant is the *column's* type, read from `migrations/`, not the shape the key looks @@ -223,6 +242,18 @@ mod tests { .0 } + #[test] + fn the_count_statement_names_each_table() { + for table in MigratedTable::ALL { + assert_eq!( + count_statement(table), + format!("SELECT count(*) FROM {}", table.name()), + "{} is counted by its own name", + table.name() + ); + } + } + #[test] fn the_first_page_of_every_table_binds_no_cursor() { for table in MigratedTable::ALL { diff --git a/crates/nostream-storage/tests/migration_pg.rs b/crates/nostream-storage/tests/migration_pg.rs index c5e0af6ab..6f8073bba 100644 --- a/crates/nostream-storage/tests/migration_pg.rs +++ b/crates/nostream-storage/tests/migration_pg.rs @@ -302,6 +302,26 @@ async fn every_text_and_uuid_cursor_pages_over_its_own_column_type() { } } +/// The manifest's `source_rows` is this number, so the source's own count must match the +/// `count(*)` the copy is compared against — one statement per table, asked through the seam. +#[tokio::test] +#[ignore = "needs PARITY_ADMIN_URL; the Rust Checks job sets it"] +async fn count_rows_matches_each_seeded_table() { + let source = scratch().await; + seed(&source).await; + + for table in MigratedTable::ALL { + assert_eq!( + MigrationSource::count_rows(&source, table) + .await + .expect("the source counts"), + source_count(source.master(), table).await as u64, + "{} is counted", + table.name() + ); + } +} + /// Two rows in each seeded table, except events (three, one per liveness state) and the two /// tables the manifest does not move. async fn seed(backend: &PostgresBackend) { From 4074fee00adc58764e8cdfa9560442d0c14d8718 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 10:23:00 -0500 Subject: [PATCH 2/5] feat(cli): record and verify the migration source count --- crates/nostream-cli/src/app.rs | 4 +- crates/nostream-cli/src/commands/migrate.rs | 30 +- .../src/commands/migrate_unsupported.rs | 2 +- crates/nostream-cli/tests/migrate_cli.rs | 272 ++++++++++++++++-- 4 files changed, 284 insertions(+), 24 deletions(-) diff --git a/crates/nostream-cli/src/app.rs b/crates/nostream-cli/src/app.rs index 8d16f5744..2d1835460 100644 --- a/crates/nostream-cli/src/app.rs +++ b/crates/nostream-cli/src/app.rs @@ -696,6 +696,8 @@ enum MigrateCommand { /// rows and no manifest is refused, so starting over takes a fresh `--target`, or the /// manifest and the store removed together. Nothing may write to either store while a run /// is in progress, so the relay must be stopped on both before the first batch is read. + /// + /// It reads the store only and proves the copy read every source row the counts recorded PgToLmdb { /// The store root (the environment lives under `/lmdb`). #[arg(long, value_name = "DIR")] @@ -708,7 +710,7 @@ enum MigrateCommand { value_parser = clap::builder::RangedU64ValueParser::::new().range(1..) )] batch_size: usize, - /// Verify the store against its manifest and copy nothing. + /// Verify the store against the manifest and recorded source counts. #[arg(long)] verify: bool, }, diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index 225a5e6d9..a755a79fc 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -31,7 +31,7 @@ use crate::error::CliError; const MANIFEST_FILE: &str = "migration-manifest.json"; /// The manifest format this tool writes. -const MANIFEST_FORMAT: u32 = 1; +const MANIFEST_FORMAT: u32 = 2; /// The options one run carries. #[derive(Debug, Clone, PartialEq, Eq)] @@ -40,7 +40,7 @@ pub struct MigrateOptions { pub target: PathBuf, /// Rows per batch, which is also the page size verify reads with. pub batch_size: usize, - /// Verify the target against its manifest and copy nothing. + /// Verify the store against the manifest and its recorded source counts, and copy nothing. pub verify: bool, } @@ -232,6 +232,12 @@ pub async fn migrate_with( if entry.complete { continue; } + // The source's own count, asked once before this table's first page: what verify + // requires the target's row count to equal. + let source_rows = source + .count_rows(table) + .await + .map_err(|error| as_resumable(table_failed(table, &error)))?; let mut rows = entry.rows; let mut sum = RowSum::from_hex(&entry.checksum)?; let mut after = decode_key(&entry.after)?; @@ -263,6 +269,7 @@ pub async fn migrate_with( let complete = count < options.batch_size; let entry = manifest.entry(table); entry.rows = rows; + entry.source_rows = source_rows; entry.checksum = sum.to_hex(); entry.after = after.as_deref().map(hex::encode).unwrap_or_default(); entry.complete = complete; @@ -296,7 +303,8 @@ pub async fn migrate_with( /// the nine entries with the manifest. /// /// Every table is paged to its end, so a table longer than one page is read rather than cut at -/// its first. The pass writes nothing to the store and never opens the source. +/// its first. The pass writes nothing to the store and never opens the source; it proves the +/// store matches the manifest, and that the copy read every source row the manifest recorded. /// /// `root` is the path the store and the manifest are read through: the target's own descriptor /// spelling where procfs answers, and the operator's path otherwise. @@ -354,13 +362,20 @@ pub async fn verify_with( )); } else if !entry.complete { failures.push(format!("[{}] the manifest is incomplete", table.name())); + } else if rows != entry.source_rows { + failures.push(format!( + "[{}] source {} rows, target {rows} rows", + table.name(), + entry.source_rows + )); } } if failures.is_empty() { writeln!( out, - "Verified {} tables, {total} rows", + "Verified {} tables, {total} rows: the store matches the manifest, and the copy read \ + every source row", MigratedTable::ALL.len() ) .map_err(write_failed)?; @@ -436,6 +451,12 @@ impl Manifest { struct TableEntry { /// The rows the table's batches have written. rows: u64, + /// The rows the source held when the copy first asked, its own `count(*)`. + /// + /// Defaulted so a manifest of the previous shape parses and is refused by its format + /// number rather than by a serde `missing field` error. + #[serde(default)] + source_rows: u64, /// The hex of the table's running row sum; sixty-four `0` characters when it is empty. checksum: String, /// The hex of the last written key; empty before the first batch. @@ -448,6 +469,7 @@ impl Default for TableEntry { fn default() -> Self { Self { rows: 0, + source_rows: 0, checksum: RowSum::default().to_hex(), after: String::new(), complete: false, diff --git a/crates/nostream-cli/src/commands/migrate_unsupported.rs b/crates/nostream-cli/src/commands/migrate_unsupported.rs index 6f22619c4..0e64771ae 100644 --- a/crates/nostream-cli/src/commands/migrate_unsupported.rs +++ b/crates/nostream-cli/src/commands/migrate_unsupported.rs @@ -20,7 +20,7 @@ pub struct MigrateOptions { pub target: PathBuf, /// Rows per batch, which is also the page size verify reads with. pub batch_size: usize, - /// Verify the target against its manifest and copy nothing. + /// Verify the store against the manifest and its recorded source counts, and copy nothing. pub verify: bool, } diff --git a/crates/nostream-cli/tests/migrate_cli.rs b/crates/nostream-cli/tests/migrate_cli.rs index c86b2c947..20ba83835 100644 --- a/crates/nostream-cli/tests/migrate_cli.rs +++ b/crates/nostream-cli/tests/migrate_cli.rs @@ -246,9 +246,14 @@ fn rows_of(rows: &[MigrationRow], table: MigratedTable) -> Vec { /// A source that serves a fixed row set, in key order, and records every call it is asked for. struct StubSource { rows: Vec, - /// The ordinal of the call that answers `Err`, if any. + /// The ordinal of the read call that answers `Err`, if any. fail_at: Option, + /// A table whose page is cut short while rows remain, and the rows it serves. + short_at: Option<(MigratedTable, usize)>, + /// A table whose count answers `Err`, if any. + fail_count: Option, calls: Mutex>)>>, + counts: Mutex>, } impl StubSource { @@ -256,7 +261,10 @@ impl StubSource { Self { rows, fail_at: None, + short_at: None, + fail_count: None, calls: Mutex::new(Vec::new()), + counts: Mutex::new(Vec::new()), } } @@ -267,15 +275,51 @@ impl StubSource { } } + fn short(rows: Vec, table: MigratedTable, served: usize) -> Self { + Self { + short_at: Some((table, served)), + ..Self::new(rows) + } + } + + fn failing_count(rows: Vec, table: MigratedTable) -> Self { + Self { + fail_count: Some(table), + ..Self::new(rows) + } + } + fn calls(&self) -> Vec<(MigratedTable, Option>)> { self.calls .lock() .expect("the counter is not poisoned") .clone() } + + fn counts(&self) -> Vec { + self.counts + .lock() + .expect("the counter is not poisoned") + .clone() + } } impl MigrationSource for StubSource { + fn count_rows<'a>(&'a self, table: MigratedTable) -> StorageFuture<'a, u64> { + Box::pin(async move { + self.counts + .lock() + .expect("the counter is not poisoned") + .push(table); + if self.fail_count == Some(table) { + return Err(StorageError::InvalidArgument { + message: "the stub's count failed", + }); + } + Ok(rows_of(&self.rows, table).len() as u64) + }) + } + fn read_batch<'a>( &'a self, table: MigratedTable, @@ -299,6 +343,11 @@ impl MigrationSource for StubSource { rows.retain(|row| row.key().as_slice() > after); } rows.truncate(limit); + if let Some((short_table, served)) = self.short_at + && table == short_table + { + rows.truncate(served); + } Ok(rows) }) } @@ -324,7 +373,7 @@ fn manifest_bytes(directory: &std::path::Path) -> Vec { /// and `complete` as the caller asks. fn write_manifest_fixture(directory: &std::path::Path, complete: bool) { let manifest = json!({ - "format": 1, + "format": 2, "not_migrated": MigratedTable::NOT_MIGRATED, "tables": MigratedTable::ALL .iter() @@ -422,7 +471,7 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { assert_eq!(output.exit_code, 0); let written = manifest(directory.path()); - assert_eq!(written["format"], 1); + assert_eq!(written["format"], 2); assert_eq!( written["not_migrated"], json!(["event_tags", "user_subscriptions"]) @@ -434,6 +483,7 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { for table in MigratedTable::ALL { let entry = &tables[table.name()]; assert_eq!(entry["rows"], 3, "{} rows", table.name()); + assert_eq!(entry["source_rows"], 3, "{} source rows", table.name()); assert_eq!(entry["complete"], true, "{} is complete", table.name()); } @@ -542,6 +592,11 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { 0, "the second run never asked the source for a row" ); + assert_eq!( + counting.counts().len(), + 0, + "the second run never asked the source for a count" + ); assert_eq!( manifest_bytes(directory.path()), before, @@ -564,8 +619,10 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { usage, "the store was not written" ); - assert!( - output_text(out).contains("Verified 9 tables"), + assert_eq!( + output_text(out), + "Verified 9 tables, 27 rows: the store matches the manifest, and the copy read every \ + source row\n", "the second run verified rather than short-circuiting" ); @@ -810,6 +867,61 @@ async fn verify_accepts_the_runs_own_target_and_rejects_a_changed_row() { ); } +// --------------------------------------------------------------------------------------- +// A source page that ends early is recorded as the source's count and refused by verify. +// --------------------------------------------------------------------------------------- + +#[tokio::test] +async fn a_short_page_from_the_source_is_refused_by_verify() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + // Three events in the source, of which the events table's first page serves one while more + // remain: the page is short, so the copy marks the table complete at one row. + let source = StubSource::short(source_rows(), MigratedTable::Events, 1); + let options = options(directory.path(), 1_000); + + let mut out = Vec::new(); + let output = migrate::migrate_with(&source, &target, &options.target, &options, &mut out) + .await + .expect("the copy runs"); + assert_eq!(output.exit_code, 0, "the copy does not refuse a short read"); + + let written = manifest(directory.path()); + let events = &written["tables"][MigratedTable::Events.name()]; + assert_eq!(events["rows"], 1, "the short page is what was written"); + assert_eq!( + events["source_rows"], 3, + "the source's own count is recorded" + ); + assert_eq!(events["complete"], true, "the short page ends the table"); + for table in MigratedTable::ALL { + if table == MigratedTable::Events { + continue; + } + let entry = &written["tables"][table.name()]; + assert_eq!(entry["source_rows"], 3, "{} source rows", table.name()); + assert_eq!(entry["rows"], 3, "{} rows", table.name()); + } + assert_eq!( + source.counts(), + MigratedTable::ALL.to_vec(), + "the source was asked its count once per table, in the copy's order" + ); + + let mut out = Vec::new(); + let output = migrate::verify_with(&target, &options.target, &options, &mut out) + .await + .expect("the verify runs"); + assert_eq!(output.exit_code, 1, "the short copy does not verify"); + assert_eq!( + output_text(out), + "[events] source 3 rows, target 1 rows\n", + "the store matches its manifest, and the source count is what fails" + ); +} + // --------------------------------------------------------------------------------------- // AC6: no manifest. // --------------------------------------------------------------------------------------- @@ -937,6 +1049,53 @@ fn verify_creates_nothing_and_rejects_a_target_with_no_store_or_no_manifest() { }); } +// --------------------------------------------------------------------------------------- +// A source that cannot answer its count stops the copy before the first page. +// --------------------------------------------------------------------------------------- + +#[tokio::test] +async fn a_failing_source_count_stops_the_copy() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let usage = target + .map_usage() + .await + .expect("the usage reads") + .used_bytes; + // `dvm_jobs` is the first table, so a count that fails there leaves every later table + // untouched. + let source = StubSource::failing_count(source_rows(), MigratedTable::DvmJobs); + let options = options(directory.path(), 1_000); + + let error = migrate::migrate_with(&source, &target, &options.target, &options, &mut Vec::new()) + .await + .expect_err("a failed count stops the copy"); + assert!( + matches!(error, nostream_cli::CliError::MigrateResumable(_)), + "a failed count is resumable like a failed read" + ); + assert!( + error.to_string().contains(MigratedTable::DvmJobs.name()), + "the failure names the table: {error}" + ); + assert_eq!( + source.calls().len(), + 0, + "the count is asked before the table's first page" + ); + assert_eq!( + target + .map_usage() + .await + .expect("the usage reads") + .used_bytes, + usage, + "nothing was written to the store" + ); +} + // --------------------------------------------------------------------------------------- // AC17: a crash between the first batch's commit and its manifest write. // --------------------------------------------------------------------------------------- @@ -991,7 +1150,7 @@ async fn a_crash_between_the_first_batch_and_the_manifest_write_resumes_to_the_c let fresh = manifest_bytes(crashed.path()); let fresh: Value = serde_json::from_slice(&fresh).expect("the fresh manifest is json"); - assert_eq!(fresh["format"], 1); + assert_eq!(fresh["format"], 2); assert_eq!( fresh["not_migrated"], json!(["event_tags", "user_subscriptions"]) @@ -1438,7 +1597,7 @@ async fn a_manifest_of_another_format_is_refused_before_anything_is_written() { .expect("the store opens"); std::fs::write( directory.path().join("migration-manifest.json"), - br#"{"format":2,"not_migrated":[],"tables":{}}"#, + br#"{"format":1,"not_migrated":[],"tables":{}}"#, ) .expect("the fixture manifest is written"); let usage = target @@ -1456,10 +1615,11 @@ async fn a_manifest_of_another_format_is_refused_before_anything_is_written() { &mut Vec::new(), ) .await - .expect_err("format 2 is refused"); + .expect_err("format 1 is refused"); let message = error.to_string(); assert!(message.contains("migration-manifest.json"), "{message}"); - assert!(message.contains("format 2"), "{message}"); + assert!(message.contains("format 1"), "{message}"); + assert!(message.contains("reads and writes 2"), "{message}"); assert_eq!(source.calls().len(), 0, "nothing was read"); assert_eq!( target @@ -1479,8 +1639,78 @@ async fn a_manifest_of_another_format_is_refused_before_anything_is_written() { &mut Vec::new(), ) .await - .expect_err("format 2 is refused by verify too"); - assert!(error.to_string().contains("format 2"), "{error}"); + .expect_err("format 1 is refused by verify too"); + assert!(error.to_string().contains("format 1"), "{error}"); +} + +// An old manifest whose entries carry no `source_rows` must reach the format refusal rather +// than a serde `missing field` error that names no format. +#[tokio::test] +async fn an_old_manifest_without_a_source_count_is_refused_by_format() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let manifest = directory.path().join("migration-manifest.json"); + let mut tables = serde_json::Map::new(); + for table in MigratedTable::ALL { + tables.insert( + table.name().to_owned(), + json!({"rows": 0, "checksum": "0".repeat(64), "after": "", "complete": false}), + ); + } + let fixture = + json!({"format": 1, "not_migrated": MigratedTable::NOT_MIGRATED, "tables": tables}); + std::fs::write( + &manifest, + serde_json::to_vec(&fixture).expect("the fixture serialises"), + ) + .expect("the fixture manifest is written"); + let usage = target + .map_usage() + .await + .expect("the usage reads") + .used_bytes; + + let source = StubSource::new(source_rows()); + let options = options(directory.path(), 1_000); + let error = migrate::migrate_with(&source, &target, &options.target, &options, &mut Vec::new()) + .await + .expect_err("format 1 is refused"); + assert!( + matches!(error, nostream_cli::CliError::Migrate(_)), + "the refusal is a migration error" + ); + let message = error.to_string(); + assert!(message.contains("migration-manifest.json"), "{message}"); + assert!(message.contains("format 1"), "{message}"); + assert!(message.contains("reads and writes 2"), "{message}"); + assert!( + !message.contains("source_rows"), + "the refusal names the format, not a missing field: {message}" + ); + assert_eq!(source.calls().len(), 0, "nothing was read"); + assert_eq!(source.counts().len(), 0, "nothing was counted"); + assert_eq!( + target + .map_usage() + .await + .expect("the usage reads") + .used_bytes, + usage, + "nothing was written" + ); + + let error = migrate::verify_with(&target, &options.target, &options, &mut Vec::new()) + .await + .expect_err("format 1 is refused by verify too"); + assert!( + matches!(error, nostream_cli::CliError::Migrate(_)), + "the refusal is a migration error" + ); + let message = error.to_string(); + assert!(message.contains("format 1"), "{message}"); + assert!(message.contains("reads and writes 2"), "{message}"); } #[tokio::test] @@ -1500,7 +1730,7 @@ async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { ); let manifest = directory.path().join("migration-manifest.json"); - std::fs::write(&manifest, br#"{"format":1,"not_migrated":[],"tables":{}}"#) + std::fs::write(&manifest, br#"{"format":2,"not_migrated":[],"tables":{}}"#) .expect("the fixture manifest is written"); let source = StubSource::new(source_rows()); let error = migrate::migrate_with( @@ -1536,7 +1766,7 @@ async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { json!({"rows": 0, "checksum": "0".repeat(64), "after": "", "complete": false}), ); } - let fixture = json!({"format": 1, "not_migrated": ["event_tags"], "tables": tables}); + let fixture = json!({"format": 2, "not_migrated": ["event_tags"], "tables": tables}); std::fs::write( &manifest, serde_json::to_vec(&fixture).expect("the fixture serialises"), @@ -1572,7 +1802,7 @@ async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { json!({"rows": 0, "checksum": "0".repeat(64), "after": "", "complete": false}), ); let fixture = - json!({"format": 1, "not_migrated": MigratedTable::NOT_MIGRATED, "tables": tables}); + json!({"format": 2, "not_migrated": MigratedTable::NOT_MIGRATED, "tables": tables}); std::fs::write( &manifest, serde_json::to_vec(&fixture).expect("the fixture serialises"), @@ -2045,9 +2275,11 @@ fn the_binary_verifies_a_store_this_process_wrote() { Some(0), "a fresh process verifies what the store holds: stdout {stdout} stderr {stderr}" ); - assert!( - stdout.starts_with("Verified 9 tables, "), - "the verify reports its work: {stdout}" + assert_eq!( + stdout.as_ref(), + "Verified 9 tables, 27 rows: the store matches the manifest, and the copy read every \ + source row\n", + "the verify names the claim it proves: {stdout}" ); } @@ -2111,7 +2343,7 @@ async fn a_manifest_that_counts_rows_over_a_store_without_them_is_refused() { tables.insert(table.name().to_owned(), entry); } let fixture = - json!({"format": 1, "not_migrated": MigratedTable::NOT_MIGRATED, "tables": tables}); + json!({"format": 2, "not_migrated": MigratedTable::NOT_MIGRATED, "tables": tables}); std::fs::write( directory.path().join("migration-manifest.json"), serde_json::to_vec(&fixture).expect("the fixture serialises"), @@ -2598,6 +2830,10 @@ fn the_help_names_the_resume_and_the_restart() { help.contains("relay must be stopped"), "and that the relay must be stopped: {help}" ); + assert!( + help.contains("Verify the store against the manifest and recorded source counts"), + "the --verify option names the claim it checks: {help}" + ); } // AC7: the summary names the store the copy landed in, so a path that went through a link is From 1fe1a76e6141180b974763c93a982a04db5e793a Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 10:23:00 -0500 Subject: [PATCH 3/5] docs: say what migration verify proves --- .changeset/migration-source-rows.md | 2 + .../decisions/0013-pg-to-lmdb-migration.md | 26 ++++++++-- docs/rewrite/migrating.md | 52 ++++++++++++------- 3 files changed, 55 insertions(+), 25 deletions(-) create mode 100644 .changeset/migration-source-rows.md diff --git a/.changeset/migration-source-rows.md b/.changeset/migration-source-rows.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/migration-source-rows.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md index 2cd6495eb..750244628 100644 --- a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md +++ b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md @@ -98,6 +98,19 @@ It is a corruption and completeness check — any added, removed or altered row not a cryptographic commitment, and it is not a defence against a deliberate collision. Nothing here needs one. +The checksum proves the target, not the source. It is recomputed from the store alone and +moves when a row there is added, removed or altered, so it proves the store holds exactly the +rows the copy wrote — and nothing about what the source held. The manifest's `rows` and +checksum are folded from the same batches the store receives, so a source read that ended a +table early was recorded as that table's complete total and verified clean against itself +(#1306). What closes that is the manifest's second number: `source_rows`, the source's own +`count(*)` taken once per table before its first page, which verify requires the target's row +count to equal. A count proves the copy moved every row the source held when it was asked; it +does not prove the source did not change while it was being copied — a row deleted after the +count and before its page fails verify, and a delete and an insert that leave the total +unchanged can still pass — so the premise stays D9's stopped relay, and the proof remains a +corruption and completeness check rather than a cryptographic commitment. + ## Resume is per table, and a replay is one batch (D5) The manifest holds, per table, a keyset cursor `after`, the accumulated `rows` and @@ -227,8 +240,11 @@ Postgres from `DB_URI`, else the `DB_*` parts. ## The manifest (D7) -The manifest is `/migration-manifest.json`: `format: 1`, `not_migrated` with the two -table names, and one entry per table carrying `rows`, `checksum`, `after` and `complete`. +The manifest is `/migration-manifest.json`: `format: 2`, `not_migrated` with the two +table names, and one entry per table carrying `rows`, `source_rows`, `checksum`, `after` and +`complete`. `source_rows` is the source's own `count(*)`, taken once before the table's first +page. The reader refuses any other format, so a manifest of the previous shape is refused +rather than verified under the weaker claim that had no source count. It carries no timestamp, no rate and no path. That is what makes two runs over the same source produce byte-identical manifests, and what lets an interrupted-then-resumed run be @@ -290,9 +306,9 @@ colliding with them. ## The source is read-only (D12) The migration issues no `INSERT`, `UPDATE`, `DELETE` or DDL against Postgres, does not run -the embedded migrator, and runs no statement but the nine paged reads. Its schema contract -is the migrations' own, so a source that has not been migrated fails with the driver's -error rather than being repaired in place. +the embedded migrator, and runs no statement but the nine paged reads and one `count(*)` per +table. Its schema contract is the migrations' own, so a source that has not been migrated +fails with the driver's error rather than being repaired in place. A read that repaired its source would be a second writer on a live relay's database and would make a failed run something an operator has to undo. diff --git a/docs/rewrite/migrating.md b/docs/rewrite/migrating.md index 53ac86273..668050fee 100644 --- a/docs/rewrite/migrating.md +++ b/docs/rewrite/migrating.md @@ -23,7 +23,7 @@ Usage: nostream migrate pg-to-lmdb [OPTIONS] --target Options: --target The store root (the environment lives under `/lmdb`) --batch-size Rows per batch, and the page size verify reads with [default: 1000] - --verify Verify the store against its manifest and copy nothing + --verify Verify the store against the manifest and recorded source counts exit 0 ``` @@ -171,14 +171,22 @@ rests on the manifest's fields (`:7-10`, `:427-436`). ## Verify -`--verify` reads the store and compares it to **its own manifest**, table by table: the rows the -store's scan returns against the manifest's `rows`, and the row sum against the manifest's -`checksum` (`crates/nostream-cli/src/commands/migrate.rs:294-350`). It reads nothing from the -source. A store that matches the manifest verifies clean whether or not the source ever held -those rows. +`--verify` reads the store and compares it to the manifest, table by table, and to the source +count the copy recorded: the rows the store's scan returns against the manifest's `rows`, the +row sum against the manifest's `checksum`, and the same row count against the manifest's +`source_rows` — the source's own `count(*)`, taken once before that table's first page +(`crates/nostream-cli/src/commands/migrate.rs:303-386`). It reads nothing from the source. A +store that matches the manifest verifies clean only when its row count also matches what the +source held, so a copy that ended a table early is refused rather than called complete. -Demonstrated by handing the tool a manifest of the right shape that records no rows, beside a -store holding three events: +A clean run prints the claim it checked: + +``` +Verified 9 tables, 27 rows: the store matches the manifest, and the copy read every source row +``` + +Demonstrated by handing the tool a manifest of the right shape (format 2) that records no rows, +beside a store holding three events: ``` $ nostream-cli migrate pg-to-lmdb --target /tmp/046-scratch/mig/seed --verify @@ -194,23 +202,27 @@ $ nostream-cli migrate pg-to-lmdb --target /tmp/046-scratch/mig/seed --verify exit 1 ``` -`manifest 0 rows, target 3 rows` is the whole point: the target's number is the store's own, and -the number it is compared to is the manifest's — not the source's row count. The manifest's rows -and checksum are folded from the same batches the store received, so a source read that ended a -table early is recorded as that table's complete total and verifies clean. - -That is [#1306](https://github.com/cameri/nostream/issues/1306): `verify` proves the store -matches its manifest, not that the manifest matches the source. And -[#1314](https://github.com/cameri/nostream/issues/1314) records the other half of the gap — -neither the copy loop nor the verify loop has an executing test, so a cursor or checksum -regression reaches a cutover unmeasured. +`manifest 0 rows, target 3 rows` is the target-side half: the target's number is the store's +own, and the number it is compared to is the manifest's. The source-side half is +`[
] source {n} rows, target {m} rows`, which fires when the store's count differs from +the source count the copy recorded; both failures exit 1. + +That gap was [#1306](https://github.com/cameri/nostream/issues/1306): `verify` proved the store +matched its manifest, not that the copy had read the whole source, because a source read that +ended a table early was recorded as that table's complete total and verified clean against +itself. The manifest now records the source's own count per table and verify asserts it, and the +short-page case is an executing test — `a_short_page_from_the_source_is_refused_by_verify` in +`crates/nostream-cli/tests/migrate_cli.rs` — so a cursor or checksum regression that truncates a +table reaches the cutover as a failure. [#1314](https://github.com/cameri/nostream/issues/1314), +which recorded that neither the copy loop nor the verify loop had an executing test, no longer +describes this tree: the copy and verify passes are driven by the 49 tests in that file. Two refusals guard the manifest's shape before any table is scanned: ``` -$ echo '{"format":2,...}' > /tmp/046-scratch/mig/seed/migration-manifest.json +$ echo '{"format":1,...}' > /tmp/046-scratch/mig/seed/migration-manifest.json $ nostream-cli migrate pg-to-lmdb --target /tmp/046-scratch/mig/seed --verify -Migration failed: /tmp/046-scratch/mig/seed/migration-manifest.json: manifest format 2 is not supported; this tool reads and writes 1 +Migration failed: /tmp/046-scratch/mig/seed/migration-manifest.json: manifest format 1 is not supported; this tool reads and writes 2 exit 1 $ nostream-cli migrate pg-to-lmdb --target /tmp/046-scratch/mig/empty --verify From 1faa41e744643ace02151631ba5d25dd60a133fa Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 10:41:08 -0500 Subject: [PATCH 4/5] docs: correct what verify proves and the format-1 restart --- .../decisions/0013-pg-to-lmdb-migration.md | 5 ++++- docs/rewrite/migrating.md | 22 ++++++++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md index 750244628..aa16aa639 100644 --- a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md +++ b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md @@ -244,7 +244,10 @@ The manifest is `/migration-manifest.json`: `format: 2`, `not_migrated` table names, and one entry per table carrying `rows`, `source_rows`, `checksum`, `after` and `complete`. `source_rows` is the source's own `count(*)`, taken once before the table's first page. The reader refuses any other format, so a manifest of the previous shape is refused -rather than verified under the weaker claim that had no source count. +rather than verified under the weaker claim that had no source count. The consequence is +recorded because it is not free: a copy interrupted under the previous build cannot advance a +format-1 manifest, and a store that holds rows and carries no manifest is refused too, so such +a run restarts on a fresh `--target`. It carries no timestamp, no rate and no path. That is what makes two runs over the same source produce byte-identical manifests, and what lets an interrupted-then-resumed run be diff --git a/docs/rewrite/migrating.md b/docs/rewrite/migrating.md index 668050fee..45ed56025 100644 --- a/docs/rewrite/migrating.md +++ b/docs/rewrite/migrating.md @@ -164,6 +164,14 @@ exit 1 Starting over therefore takes a fresh `--target`, or removing the manifest and the store together — which is what the help text says and what the two refusals protect. +**A manifest of the previous format is the same dead end.** A copy interrupted under a build +that wrote `format: 1` cannot advance that manifest: this tool refuses it by its format, `… +manifest format 1 is not supported; this tool reads and writes 2; restart on a fresh --target` +(`crates/nostream-cli/src/commands/migrate.rs:598-605`), and because a store that holds rows and +carries no manifest is refused too, the run restarts on a fresh `--target` (ADR 0013, D7). The +refusal is the copy arm's as well as `--verify`'s: the copy reads the manifest before it dials +the source (`crates/nostream-cli/src/commands/migrate.rs:96`, `:170`). + [unverified] because the copy's own rows refusal is only reached after the source connects, and no Postgres exists here: its sentence above is a code reading (`crates/nostream-cli/src/commands/migrate.rs:163-171`), not a transcript, and the resume path @@ -175,7 +183,7 @@ rests on the manifest's fields (`:7-10`, `:427-436`). count the copy recorded: the rows the store's scan returns against the manifest's `rows`, the row sum against the manifest's `checksum`, and the same row count against the manifest's `source_rows` — the source's own `count(*)`, taken once before that table's first page -(`crates/nostream-cli/src/commands/migrate.rs:303-386`). It reads nothing from the source. A +(`crates/nostream-cli/src/commands/migrate.rs:311-392`). It reads nothing from the source. A store that matches the manifest verifies clean only when its row count also matches what the source held, so a copy that ended a table early is refused rather than called complete. @@ -215,14 +223,15 @@ short-page case is an executing test — `a_short_page_from_the_source_is_refuse `crates/nostream-cli/tests/migrate_cli.rs` — so a cursor or checksum regression that truncates a table reaches the cutover as a failure. [#1314](https://github.com/cameri/nostream/issues/1314), which recorded that neither the copy loop nor the verify loop had an executing test, no longer -describes this tree: the copy and verify passes are driven by the 49 tests in that file. +describes this tree: the copy and verify passes are driven by the 50 tests in that file. -Two refusals guard the manifest's shape before any table is scanned: +Two refusals guard the manifest's shape before any table is scanned — the format one applies to +the copy arm too, and what it means for an interrupted run is §Resume's: ``` $ echo '{"format":1,...}' > /tmp/046-scratch/mig/seed/migration-manifest.json $ nostream-cli migrate pg-to-lmdb --target /tmp/046-scratch/mig/seed --verify -Migration failed: /tmp/046-scratch/mig/seed/migration-manifest.json: manifest format 1 is not supported; this tool reads and writes 2 +Migration failed: /tmp/046-scratch/mig/seed/migration-manifest.json: manifest format 1 is not supported; this tool reads and writes 2; restart on a fresh --target exit 1 $ nostream-cli migrate pg-to-lmdb --target /tmp/046-scratch/mig/empty --verify @@ -286,7 +295,8 @@ sentence rests on the copy's read-only source access, which is `crates/nostream-storage/src/lib.rs:26-33`; the subscription surface is #1036's. - **The cutover run itself.** A parallel run, a cutover date and the TypeScript retirement are #869's; this page moves a store, not a deployment. -- **What `verify` cannot tell you** is stated above rather than repeated here: it is the - manifest's yardstick, not the source's (#1306), and its loop has no executing test (#1314). +- **What `verify` cannot tell you** is stated above rather than repeated here: the source count + is cardinality, not content, so it proves how many rows the copy moved and not what they held + (ADR 0013, D4). - **Performance.** How long a copy takes, at what batch size, and what it does to the source's load is the benchmark's (#1132 needs a host with Docker to measure the TypeScript side). From f62ed09460865d650041b843eaf2f3178fe0dd11 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 10:41:08 -0500 Subject: [PATCH 5/5] fix(cli): name the next move when a manifest format is refused --- crates/nostream-cli/src/commands/migrate.rs | 3 +- crates/nostream-cli/tests/migrate_cli.rs | 37 +++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index a755a79fc..d749f33e5 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -597,7 +597,8 @@ fn read_manifest(root: &Path, target: &Path) -> Result, CliErro .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", path.display()))))?; if manifest.format != MANIFEST_FORMAT { return Err(CliError::Migrate(shown(format!( - "{}: manifest format {} is not supported; this tool reads and writes {MANIFEST_FORMAT}", + "{}: manifest format {} is not supported; this tool reads and writes \ + {MANIFEST_FORMAT}; restart on a fresh --target", path.display(), manifest.format )))); diff --git a/crates/nostream-cli/tests/migrate_cli.rs b/crates/nostream-cli/tests/migrate_cli.rs index 20ba83835..0fb31ed5b 100644 --- a/crates/nostream-cli/tests/migrate_cli.rs +++ b/crates/nostream-cli/tests/migrate_cli.rs @@ -369,8 +369,8 @@ fn manifest_bytes(directory: &std::path::Path) -> Vec { std::fs::read(directory.join("migration-manifest.json")).expect("the manifest is written") } -/// The manifest of the shape R6 writes: nine entries, `rows: 0`, the zero checksum, `after: ""`, -/// and `complete` as the caller asks. +/// The manifest of the shape R6 writes: nine entries carrying `rows: 0`, a defaulted +/// `source_rows`, the zero checksum, `after: ""`, and `complete` as the caller asks. fn write_manifest_fixture(directory: &std::path::Path, complete: bool) { let manifest = json!({ "format": 2, @@ -1713,6 +1713,39 @@ async fn an_old_manifest_without_a_source_count_is_refused_by_format() { assert!(message.contains("reads and writes 2"), "{message}"); } +#[tokio::test] +async fn the_format_refusal_names_the_next_move() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let manifest = directory.path().join("migration-manifest.json"); + std::fs::write(&manifest, br#"{"format":1,"not_migrated":[],"tables":{}}"#) + .expect("the fixture manifest is written"); + let options = options(directory.path(), 1_000); + let expected = format!( + "{}: manifest format 1 is not supported; this tool reads and writes 2; restart on a \ + fresh --target", + manifest.display() + ); + + let error = migrate::migrate_with( + &StubSource::new(source_rows()), + &target, + &options.target, + &options, + &mut Vec::new(), + ) + .await + .expect_err("format 1 is refused"); + assert_eq!(error.to_string(), expected); + + let error = migrate::verify_with(&target, &options.target, &options, &mut Vec::new()) + .await + .expect_err("format 1 is refused by verify too"); + assert_eq!(error.to_string(), expected); +} + #[tokio::test] async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { let directory = tempfile::tempdir().expect("a temporary directory");