From f186ca7ee74e7c118e0e9f69ba803ac5288b77ee Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 5 Dec 2026 11:43:15 -0500 Subject: [PATCH 1/6] feat(cli): report migration progress as it goes --- crates/nostream-cli/src/commands/migrate.rs | 107 +++++++ crates/nostream-cli/tests/migrate_cli.rs | 300 +++++++++++++++++++- 2 files changed, 400 insertions(+), 7 deletions(-) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index d749f33e..0b2cec4e 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -242,6 +242,17 @@ pub async fn migrate_with( let mut sum = RowSum::from_hex(&entry.checksum)?; let mut after = decode_key(&entry.after)?; + // D13: what a resumed run continues from, printed before this table's first read. + if entry.rows != 0 || !entry.after.is_empty() { + writeln!( + out, + "Resuming {} from {rows}/{source_rows} rows, after {}", + table.name(), + format_cursor(table, after.as_deref()) + ) + .map_err(write_failed)?; + } + loop { let batch = source .read_batch(table, after.as_deref(), options.batch_size) @@ -275,6 +286,17 @@ pub async fn migrate_with( entry.complete = complete; write_manifest(root, &options.target, &manifest).map_err(as_resumable)?; + // D13: printed after the manifest write, so the numbers are the durable entry's. + if reports_progress(rows, written, complete) { + writeln!( + out, + "{}: {rows}/{source_rows} rows, after {}", + table.name(), + format_cursor(table, after.as_deref()) + ) + .map_err(write_failed)?; + } + if complete { break; } @@ -296,6 +318,11 @@ pub async fn migrate_with( ) .map_err(write_failed)?; + // D13: the migration's own total, the sum its entries carry and a resume never resets, + // beside this run's — which the `Migrated` line above already states. + let migrated: u64 = manifest.tables.values().map(|entry| entry.rows).sum(); + writeln!(out, "Migration total: {migrated} rows ({total} this run)").map_err(write_failed)?; + Ok(CommandOutput::default()) } @@ -1275,10 +1302,90 @@ fn write_failed(error: std::io::Error) -> CliError { CliError::Migrate(format!("unable to write the migration's output: {error}")) } +/// The rows a table's progress line is throttled by: at the default batch of 1 000 that is one +/// line per 100 batches. A 10 000 000-row table at that batch prints 102 lines — its first +/// batch, 100 crossings of the stride and the read that completes it — where one line per batch +/// would print 10 001; the completing read carries the last full batch's numbers, so the final +/// two lines are identical. +const PROGRESS_STRIDE: u64 = 100_000; + +/// Whether a batch earns a progress line: a table's first batch, one that carries its row count +/// across a stride boundary, and the read that completes it — which is also the one read an +/// empty table makes. +fn reports_progress(rows: u64, written: u64, complete: bool) -> bool { + let crossed = rows / PROGRESS_STRIDE > (rows - written) / PROGRESS_STRIDE; + complete || (written > 0 && (rows == written || crossed)) +} + +/// A cursor as a progress line prints it: the manifest's hexadecimal spelling, `none` before the +/// table's first batch, and `redacted` for `invite_codes`, whose key is the invite code itself — +/// a NIP-43 bearer credential (ADR 0013, D5). +fn format_cursor(table: MigratedTable, after: Option<&[u8]>) -> String { + match after { + None => "none".to_owned(), + Some(_) if table == MigratedTable::InviteCodes => "redacted".to_owned(), + Some(key) => hex::encode(key), + } +} + #[cfg(test)] mod tests { use super::*; + /// The four cases the copy's progress line is printed for, and the volume the stride is + /// chosen for: a 10 000 000-row table at the default batch of 1 000 prints one line for its + /// first batch, one per 100 000 rows, and one for the read that completes it — 102, not one + /// per batch. + #[test] + fn a_progress_line_is_reported_at_each_stride_boundary() { + assert!(reports_progress(0, 0, true), "an empty table reports"); + assert!( + !reports_progress(0, 0, false), + "a read that wrote nothing does not" + ); + assert!( + reports_progress(1, 1, false), + "a table's first batch reports" + ); + assert!( + !reports_progress(2, 1, false), + "a batch inside the stride does not" + ); + assert!(!reports_progress(PROGRESS_STRIDE - 1, 1, false)); + assert!( + reports_progress(PROGRESS_STRIDE, 1, false), + "the crossing reports" + ); + assert!( + reports_progress(PROGRESS_STRIDE + 500, 1_000, false), + "a batch that overshoots a boundary reports" + ); + assert!( + !reports_progress(PROGRESS_STRIDE + 1, 1, false), + "a batch just past a boundary does not" + ); + assert!(reports_progress(2 * PROGRESS_STRIDE, 1_000, false)); + assert!(reports_progress(1, 1, true), "the completing read reports"); + + let mut reported = 0; + let mut rows = 0u64; + for _ in 0..10_000 { + rows += 1_000; + if reports_progress(rows, 1_000, false) { + reported += 1; + } + } + assert_eq!( + reported, 101, + "the first batch plus one line per stride crossing" + ); + assert_eq!(rows, 10_000_000); + assert!( + reports_progress(rows, 0, true), + "the completing read is the 102nd line, carrying the last full batch's rows" + ); + } + /// A link where the data file belongs is followed by `is_file()` and by LMDB both, so the /// copy would read or write through it and heed would put `lock.mdb` beside the link's /// target. The predicate over the file's own metadata is what AC18 asks for. diff --git a/crates/nostream-cli/tests/migrate_cli.rs b/crates/nostream-cli/tests/migrate_cli.rs index 0fb31ed5..931966e8 100644 --- a/crates/nostream-cli/tests/migrate_cli.rs +++ b/crates/nostream-cli/tests/migrate_cli.rs @@ -644,6 +644,248 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { assert_eq!(created.id, 4, "the migrated ids raised the sequence"); } +// --------------------------------------------------------------------------------------- +// D13: the copy reports progress as it goes. +// --------------------------------------------------------------------------------------- + +#[tokio::test] +async fn a_copy_over_two_tables_prints_progress_before_the_closing_lines() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let all = source_rows(); + let dvm = rows_of(&all, MigratedTable::DvmJobs); + let events = rows_of(&all, MigratedTable::Events); + let j1 = hex::encode(dvm[0].key()); + let j2 = hex::encode(dvm[1].key()); + let e1 = hex::encode(events[0].key()); + let e2 = hex::encode(events[1].key()); + let mut rows = dvm[..2].to_vec(); + rows.extend(events[..2].iter().cloned()); + let options = options(directory.path(), 1); + + let mut out = Vec::new(); + migrate::migrate_with( + &StubSource::new(rows), + &target, + &options.target, + &options, + &mut out, + ) + .await + .expect("the copy succeeds"); + + let text = output_text(out); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!( + lines.len(), + 15, + "eleven progress lines and then the four closing lines" + ); + assert_eq!(lines[0], format!("dvm_jobs: 1/2 rows, after {j1}")); + assert_eq!(lines[1], format!("dvm_jobs: 2/2 rows, after {j2}")); + assert_eq!(lines[2], format!("events: 1/2 rows, after {e1}")); + assert_eq!(lines[3], format!("events: 2/2 rows, after {e2}")); + assert_eq!( + &lines[4..11], + &[ + "invite_codes: 0/0 rows, after none", + "invoices: 0/0 rows, after none", + "nip05_verifications: 0/0 rows, after none", + "notification_delivery_log: 0/0 rows, after none", + "notification_outbox: 0/0 rows, after none", + "reports: 0/0 rows, after none", + "users: 0/0 rows, after none", + ], + "the seven empty tables each report once" + ); + assert!( + lines[11].starts_with("Migrated 4 rows in ") && lines[11].ends_with(" ms"), + "{}", + lines[11] + ); + assert!( + lines[12].starts_with("Events throughput: ") && lines[12].ends_with(" events/s"), + "{}", + lines[12] + ); + assert_eq!( + lines[13], + format!( + "Store: {}", + std::fs::canonicalize(directory.path().join("lmdb")) + .expect("the store exists") + .display() + ) + ); + assert_eq!(lines[14], "Migration total: 4 rows (4 this run)"); + assert!( + !text.lines().any(|line| line.starts_with("Resuming ")), + "a fresh run resumes nothing" + ); + assert!(text.ends_with('\n'), "the total line ends the stream"); +} + +#[tokio::test] +async fn an_invite_code_cursor_is_never_printed() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let options = options(directory.path(), 1); + + let mut out = Vec::new(); + migrate::migrate_with( + &StubSource::new(source_rows()), + &target, + &options.target, + &options, + &mut out, + ) + .await + .expect("the copy succeeds"); + + let text = output_text(out); + let invite_lines: Vec<&str> = text + .lines() + .filter(|line| line.starts_with("invite_codes: ")) + .collect(); + assert_eq!( + invite_lines.len(), + 2, + "the first batch and the completing read" + ); + assert_eq!(invite_lines[0], "invite_codes: 1/3 rows, after redacted"); + assert_eq!(invite_lines[1], "invite_codes: 3/3 rows, after redacted"); + + for seed in 1..=3 { + let code = invite(seed).code; + assert!( + !text.contains(hex::encode(code.as_bytes()).as_str()), + "the invite code's hex reached the output: {code}" + ); + assert!( + !text.contains(code.as_str()), + "the invite code itself reached the output: {code}" + ); + } + + let lines: Vec<&str> = text.lines().collect(); + assert_eq!( + lines.len(), + 22, + "eighteen progress lines and then the four closing lines" + ); + assert!( + lines[18].starts_with("Migrated 27 rows in "), + "{}", + lines[18] + ); + assert!( + lines[19].starts_with("Events throughput: "), + "{}", + lines[19] + ); + assert!(lines[20].starts_with("Store: "), "{}", lines[20]); + assert_eq!(lines[21], "Migration total: 27 rows (27 this run)"); + + assert_eq!( + manifest(directory.path())["tables"]["invite_codes"]["after"], + hex::encode(invite(3).code.as_bytes()), + "the redaction is in the output only; the manifest still records the real cursor" + ); +} + +#[tokio::test] +async fn a_resumed_invite_code_table_redacts_its_resumed_cursor() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + let options = options(directory.path(), 1); + + // The interrupted run: dvm_jobs (empty) and events complete, then the seventh read fails + // after invite_codes' first row. The tables after it are never reached. + let all = source_rows(); + let mut partial = rows_of(&all, MigratedTable::Events); + partial.extend(rows_of(&all, MigratedTable::InviteCodes)); + let error = migrate::migrate_with( + &StubSource::failing_at(partial, 6), + &target, + &options.target, + &options, + &mut Vec::new(), + ) + .await + .expect_err("the seventh read fails"); + assert!(matches!(error, nostream_cli::CliError::MigrateResumable(_))); + let interrupted = manifest(directory.path()); + assert_eq!(interrupted["tables"]["invite_codes"]["rows"], 1); + assert_eq!(interrupted["tables"]["invite_codes"]["complete"], false); + + // Mark the tables the interrupted run never reached as the completed empty tables it would + // have recorded, so the resumed run visits invite_codes alone — the state the criterion is + // about. Their rows stay zero, so the migration's total is events' 3 plus invite_codes' 3. + let mut staged = interrupted; + for table in MigratedTable::ALL { + if table != MigratedTable::InviteCodes { + staged["tables"][table.name()]["complete"] = json!(true); + } + } + std::fs::write( + directory.path().join("migration-manifest.json"), + serde_json::to_vec(&staged).expect("the manifest serialises"), + ) + .expect("the manifest is rewritten"); + + let resumed = StubSource::new(source_rows()); + let mut out = Vec::new(); + migrate::migrate_with(&resumed, &target, &options.target, &options, &mut out) + .await + .expect("the resumed run succeeds"); + + let text = output_text(out); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!( + lines.len(), + 6, + "a resume line, a completing line and the four closing lines" + ); + assert_eq!( + lines[0], "Resuming invite_codes from 1/3 rows, after redacted", + "the resumed cursor is redacted on the resume line too" + ); + assert_eq!(lines[1], "invite_codes: 3/3 rows, after redacted"); + assert_eq!( + text.lines() + .filter(|line| line.starts_with("invite_codes: ")) + .count(), + 1, + "the batches writing the second and third codes print nothing" + ); + assert!( + !text.contains(hex::encode(invite(1).code.as_bytes()).as_str()), + "the cursor the run resumed from reached the output" + ); + assert!( + !text.contains("code-"), + "no invite code, and no prefix of one, reached the output" + ); + assert!(lines[2].starts_with("Migrated 2 rows in "), "{}", lines[2]); + assert!(lines[3].starts_with("Events throughput: "), "{}", lines[3]); + assert!(lines[4].starts_with("Store: "), "{}", lines[4]); + assert_eq!( + lines[5], "Migration total: 6 rows (2 this run)", + "the total counts events, which this run never visited" + ); + assert_eq!( + manifest(directory.path())["tables"]["invite_codes"]["after"], + hex::encode(invite(3).code.as_bytes()), + "the manifest still records the real cursor after the resumed run" + ); +} + // --------------------------------------------------------------------------------------- // AC3: resume. // --------------------------------------------------------------------------------------- @@ -721,6 +963,33 @@ async fn an_interrupted_run_resumes_to_the_clean_run_manifest() { // 3. The resumed run lands on the clean run's manifest, byte for byte. assert_eq!(output.exit_code, 0); assert_eq!(manifest_bytes(directory.path()), clean); + + // 4. The resumed run says which table it continues and from which cursor, and prints the + // manifest's total beside its own. + let text = output_text(out); + let resuming: Vec<&str> = text + .lines() + .filter(|line| line.starts_with("Resuming ")) + .collect(); + assert_eq!(resuming.len(), 1, "one table records progress"); + assert_eq!( + resuming[0], + format!( + "Resuming dvm_jobs from 1/3 rows, after {}", + hex::encode(dvm_job(1).id.as_bytes()) + ), + "the resume line names the table, its counts and the cursor it continues from" + ); + assert_eq!( + text.lines().next(), + Some(resuming[0]), + "the resume line comes before the first batch's" + ); + assert_eq!( + text.lines().last(), + Some("Migration total: 27 rows (26 this run)"), + "the total is the manifest's, beside this run's, and ends the stream" + ); } // --------------------------------------------------------------------------------------- @@ -1214,13 +1483,15 @@ fn indexed_event(index: u64) -> MigrationRow { MigrationRow::Event(record) } -/// The two summary lines, parsed. +/// The closing block, parsed: the three lines the run has always printed plus the migration's +/// total. Read from the end of the stream, so the progress lines before them do not have to be +/// counted, and a line landing after the total fails the last line's shape. fn summary(text: &str) -> (u64, u64, u64, String) { - let mut lines = text.lines(); - let first = lines.next().expect("the rows line"); - let second = lines.next().expect("the throughput line"); + let mut lines = text.lines().rev(); + let fourth = lines.next().expect("the migration total line"); let third = lines.next().expect("the store line"); - assert_eq!(lines.next(), None, "exactly three summary lines"); + let second = lines.next().expect("the throughput line"); + let first = lines.next().expect("the rows line"); let (rows_text, rest) = first .strip_prefix("Migrated ") @@ -1231,14 +1502,29 @@ fn summary(text: &str) -> (u64, u64, u64, String) { .strip_prefix("Events throughput: ") .and_then(|rest| rest.strip_suffix(" events/s")) .expect("the throughput line's shape"); - let store = third .strip_prefix("Store: ") .expect("the store line's shape") .to_owned(); + let (migrated_text, this_run_text) = fourth + .strip_prefix("Migration total: ") + .and_then(|rest| rest.split_once(" rows (")) + .and_then(|(migrated, rest)| { + rest.strip_suffix(" this run)") + .map(|this_run| (migrated, this_run)) + }) + .expect("the migration total line's shape"); + + let rows: u64 = rows_text.parse().expect("a row count"); + let _migrated: u64 = migrated_text.parse().expect("the migration's total"); + assert_eq!( + this_run_text.parse::().expect("this run's count"), + rows, + "the total line's own count is the rows line's" + ); ( - rows_text.parse().expect("a row count"), + rows, ms_text.parse().expect("a millisecond count"), rate_text.parse().expect("a rate"), store, From 13efc8b203f73bce4d6f7c8952d0f5c66adc6b0d Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 5 Dec 2026 11:43:15 -0500 Subject: [PATCH 2/6] docs(cli): record the migration's progress output --- .changeset/migration-progress-output.md | 2 + .../decisions/0013-pg-to-lmdb-migration.md | 40 ++++++++++++++++++- docs/rewrite/migrating.md | 39 ++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 .changeset/migration-progress-output.md diff --git a/.changeset/migration-progress-output.md b/.changeset/migration-progress-output.md new file mode 100644 index 00000000..a845151c --- /dev/null +++ b/.changeset/migration-progress-output.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 aa16aa63..34f129bc 100644 --- a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md +++ b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md @@ -19,7 +19,7 @@ is a filtered query — and every write is shaped like "a new row now": `create` inserts mint fresh ids. A trait-only copy would be both lossy and partial, which is the one thing a cutover tool must not be. -This document records the twelve decisions the tool rests on, each with the reason it was +This document records the thirteen decisions the tool rests on, each with the reason it was taken. ## The copy goes through a migration-only seam (D1) @@ -267,6 +267,9 @@ Migrated {total} rows in {ms} ms Events throughput: {rate} events/s ``` +D13 adds progress lines before these two and a total line after the `Store:` line; these two +are unchanged and stay first. + `total` is the rows this invocation wrote, and the rate is `events * 1000 / max(ms, 1)` over the `events` table only. Both numbers are plain digits so a reader can recompute the rate exactly, and the rate comes from the same integers that were printed. @@ -316,6 +319,41 @@ 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. +## Progress is reported as it happens (D13) + +A copy that prints nothing until its last row cannot be told from a hung one, so the copy +prints one line per table as it moves, on the same stream as its summary: + +``` +Resuming {table} from {rows}/{source_rows} rows, after {cursor} +{table}: {rows}/{source_rows} rows, after {cursor} +``` + +The first is printed once per table the manifest records progress for, before that table's +first read; it is what tells a resumed run which table it continues and from which key. The +second is printed after the manifest write for a table's first batch, for a batch that carries +the table's row count across a multiple of 100 000 rows, for the read that completes it, and +for a table the source holds no rows in — never before the write, so the numbers on the line +are the ones a resume would read. `rows` and `source_rows` are the manifest's two counts and +the cursor is the manifest's `after` in its hexadecimal spelling. `invite_codes`' cursor is the +invite code itself (D5), so its lines print `after redacted`; a table with no cursor yet prints +`after none`. + +The summary gains one line after `Store:`, which is the migration's own total rather than this +run's: + +``` +Migration total: {rows} rows ({total} this run) +``` + +`rows` is the sum the manifest's nine entries carry and `total` is D8's. No field is added to +the manifest (D7): the total is a sum over entries it already holds. D8's two lines are +unchanged, keep their text, and stay the first two lines the summary prints. + +A write to a closed stdout now ends the copy at the first progress line rather than after its +last row: the failure is an `io::Error` like any other and exits 1, the manifest keeps every +batch that was durable, and the next run resumes. + ## What this record does not decide - No throughput floor: the benchmark rig owns that number. diff --git a/docs/rewrite/migrating.md b/docs/rewrite/migrating.md index 45ed5602..b37cd7d1 100644 --- a/docs/rewrite/migrating.md +++ b/docs/rewrite/migrating.md @@ -177,6 +177,45 @@ 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 rests on the manifest's fields (`:7-10`, `:427-436`). +## What a copy prints + +The copy prints as it goes, on stdout, and the closing lines come last. The formats below are +ADR 0013's D13, taken from the in-process harness +(`crates/nostream-cli/tests/migrate_cli.rs`), not from a terminal transcript: no Postgres +exists in this sandbox to copy. + +For every table the manifest records progress for, before its first read: + +``` +Resuming {table} from {rows}/{source_rows} rows, after {cursor} +``` + +and for a table's first batch, each crossing of 100 000 rows, the read that completes it, and +the one read of an empty table: + +``` +{table}: {rows}/{source_rows} rows, after {cursor} +``` + +`{cursor}` is the manifest's `after` in hex, `none` before a table's first batch, and +`after redacted` for `invite_codes`, whose cursor is the invite code itself (ADR 0013, D5). + +The closing block is four lines, in this order: + +``` +Migrated {rows} rows in {ms} ms +Events throughput: {rate} events/s +Store: {path} +Migration total: {rows} rows ({total} this run) +``` + +The first three are ADR 0013 D8's and D6's; the last is the migration's own total, the sum the +manifest's entries carry, beside this run's count. + +A closed stdout (`… | head`) ends the copy at the first progress line that fails to write, with +exit 1 and `Migration failed: unable to write the migration's output: …`; the manifest keeps +every batch that was durable, so re-running the same command resumes. + ## Verify `--verify` reads the store and compares it to the manifest, table by table, and to the source From f2e94b7b6925c90c09a5969445b6182d10232bf4 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 5 Dec 2026 11:44:46 -0500 Subject: [PATCH 3/6] test(cli): mark the staged resume state as a ceiling --- crates/nostream-cli/tests/migrate_cli.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/nostream-cli/tests/migrate_cli.rs b/crates/nostream-cli/tests/migrate_cli.rs index 931966e8..984cf94b 100644 --- a/crates/nostream-cli/tests/migrate_cli.rs +++ b/crates/nostream-cli/tests/migrate_cli.rs @@ -827,6 +827,9 @@ async fn a_resumed_invite_code_table_redacts_its_resumed_cursor() { // Mark the tables the interrupted run never reached as the completed empty tables it would // have recorded, so the resumed run visits invite_codes alone — the state the criterion is // about. Their rows stay zero, so the migration's total is events' 3 plus invite_codes' 3. + // shortcut: the manifest is staged here rather than reached by real runs, because + // `invite_codes` is copied third, so no interruption inside it leaves the later tables + // complete; upgrade when a resume fixture can build the state through copies alone. let mut staged = interrupted; for table in MigratedTable::ALL { if table != MigratedTable::InviteCodes { From c27d3596241393367a2ebd6ed643f6a74c6e074c Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 5 Dec 2026 12:07:50 -0500 Subject: [PATCH 4/6] refactor(migration): decide a table's credential status beside its key --- crates/nostream-cli/src/commands/migrate.rs | 22 ++++++++---- crates/nostream-storage/src/migration.rs | 37 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index 0b2cec4e..cc621c1b 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -243,7 +243,7 @@ pub async fn migrate_with( let mut after = decode_key(&entry.after)?; // D13: what a resumed run continues from, printed before this table's first read. - if entry.rows != 0 || !entry.after.is_empty() { + if entry.records_progress() { writeln!( out, "Resuming {} from {rows}/{source_rows} rows, after {}", @@ -450,9 +450,7 @@ impl Manifest { /// so a fresh store beside it is honest; one that records progress is only meaningful /// beside the store the progress went into. fn records_progress(&self) -> bool { - self.tables - .values() - .any(|entry| entry.rows != 0 || !entry.after.is_empty() || entry.complete) + self.tables.values().any(TableEntry::records_progress) } /// This table's entry, as the empty one when the manifest carries none. @@ -492,6 +490,15 @@ struct TableEntry { complete: bool, } +impl TableEntry { + /// Whether this entry records that a run did anything: a row written, a cursor moved, or the + /// table finished. The resume line asks it too, where the entry is incomplete by the skip + /// above it, so the two readings cannot drift. + fn records_progress(&self) -> bool { + self.rows != 0 || !self.after.is_empty() || self.complete + } +} + impl Default for TableEntry { fn default() -> Self { Self { @@ -1318,12 +1325,13 @@ fn reports_progress(rows: u64, written: u64, complete: bool) -> bool { } /// A cursor as a progress line prints it: the manifest's hexadecimal spelling, `none` before the -/// table's first batch, and `redacted` for `invite_codes`, whose key is the invite code itself — -/// a NIP-43 bearer credential (ADR 0013, D5). +/// table's first batch, and `redacted` for a table whose key is a credential — `invite_codes`, +/// whose key is the invite code itself (ADR 0013, D5), as `MigratedTable::key_is_credential` +/// decides beside `name` and `key`. fn format_cursor(table: MigratedTable, after: Option<&[u8]>) -> String { match after { None => "none".to_owned(), - Some(_) if table == MigratedTable::InviteCodes => "redacted".to_owned(), + Some(_) if table.key_is_credential() => "redacted".to_owned(), Some(key) => hex::encode(key), } } diff --git a/crates/nostream-storage/src/migration.rs b/crates/nostream-storage/src/migration.rs index baccc849..11e3cd5f 100644 --- a/crates/nostream-storage/src/migration.rs +++ b/crates/nostream-storage/src/migration.rs @@ -78,6 +78,25 @@ impl MigratedTable { Self::Users => "users", } } + + /// Whether this table's key is a credential that a progress line must never print. + /// + /// `invite_codes` is the one: [`MigrationRow::key`] is the invite code itself, which NIP-43 + /// accepts as a bearer credential (ADR 0013, D5). The decision sits beside `name` and `key` + /// so a table added to this enum must decide here before it can print. + pub const fn key_is_credential(self) -> bool { + match self { + Self::InviteCodes => true, + Self::DvmJobs + | Self::Events + | Self::Invoices + | Self::Nip05Verifications + | Self::NotificationDeliveryLog + | Self::NotificationOutbox + | Self::Reports + | Self::Users => false, + } + } } /// A `users` row with the one column the seam's [`User`] omits. @@ -268,3 +287,21 @@ use crate::keys::micros; fn report_key(id: i32) -> [u8; 4] { crate::keys::i32_key(id) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Exactly one table's key is a credential: the invite code, which NIP-43 accepts as a + /// bearer credential (ADR 0013, D5). A new variant is a compile error in + /// [`MigratedTable::key_is_credential`] until it is listed; this pins the one `true`. + #[test] + fn only_the_invite_code_key_is_a_credential() { + let credentials: Vec<&str> = MigratedTable::ALL + .iter() + .filter(|table| table.key_is_credential()) + .map(|table| table.name()) + .collect(); + assert_eq!(credentials, ["invite_codes"]); + } +} From f96a291cd29ab8e1fb1078eeb9b70572c50a9e2a Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 5 Dec 2026 12:07:50 -0500 Subject: [PATCH 5/6] test(cli): drive the resumed invite redaction from the literal run --- crates/nostream-cli/tests/migrate_cli.rs | 43 ++++++++++-------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/crates/nostream-cli/tests/migrate_cli.rs b/crates/nostream-cli/tests/migrate_cli.rs index 984cf94b..6b94613f 100644 --- a/crates/nostream-cli/tests/migrate_cli.rs +++ b/crates/nostream-cli/tests/migrate_cli.rs @@ -824,24 +824,9 @@ async fn a_resumed_invite_code_table_redacts_its_resumed_cursor() { assert_eq!(interrupted["tables"]["invite_codes"]["rows"], 1); assert_eq!(interrupted["tables"]["invite_codes"]["complete"], false); - // Mark the tables the interrupted run never reached as the completed empty tables it would - // have recorded, so the resumed run visits invite_codes alone — the state the criterion is - // about. Their rows stay zero, so the migration's total is events' 3 plus invite_codes' 3. - // shortcut: the manifest is staged here rather than reached by real runs, because - // `invite_codes` is copied third, so no interruption inside it leaves the later tables - // complete; upgrade when a resume fixture can build the state through copies alone. - let mut staged = interrupted; - for table in MigratedTable::ALL { - if table != MigratedTable::InviteCodes { - staged["tables"][table.name()]["complete"] = json!(true); - } - } - std::fs::write( - directory.path().join("migration-manifest.json"), - serde_json::to_vec(&staged).expect("the manifest serialises"), - ) - .expect("the manifest is rewritten"); - + // The resumed run over the full source: the six tables the interrupted run never reached are + // incomplete, so it copies them too; `events` is complete and skipped, and its rows stay in + // the manifest's total. let resumed = StubSource::new(source_rows()); let mut out = Vec::new(); migrate::migrate_with(&resumed, &target, &options.target, &options, &mut out) @@ -852,8 +837,8 @@ async fn a_resumed_invite_code_table_redacts_its_resumed_cursor() { let lines: Vec<&str> = text.lines().collect(); assert_eq!( lines.len(), - 6, - "a resume line, a completing line and the four closing lines" + 18, + "a resume line, thirteen progress lines and the four closing lines" ); assert_eq!( lines[0], "Resuming invite_codes from 1/3 rows, after redacted", @@ -875,12 +860,20 @@ async fn a_resumed_invite_code_table_redacts_its_resumed_cursor() { !text.contains("code-"), "no invite code, and no prefix of one, reached the output" ); - assert!(lines[2].starts_with("Migrated 2 rows in "), "{}", lines[2]); - assert!(lines[3].starts_with("Events throughput: "), "{}", lines[3]); - assert!(lines[4].starts_with("Store: "), "{}", lines[4]); + assert!( + lines[14].starts_with("Migrated 20 rows in "), + "{}", + lines[14] + ); + assert!( + lines[15].starts_with("Events throughput: "), + "{}", + lines[15] + ); + assert!(lines[16].starts_with("Store: "), "{}", lines[16]); assert_eq!( - lines[5], "Migration total: 6 rows (2 this run)", - "the total counts events, which this run never visited" + lines[17], "Migration total: 24 rows (20 this run)", + "the total includes events' 3 rows, which this run never visited" ); assert_eq!( manifest(directory.path())["tables"]["invite_codes"]["after"], From 342b59fcbff7988d2f7a142d28ff151912c0e9b1 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 5 Dec 2026 12:07:50 -0500 Subject: [PATCH 6/6] docs(cli): clarify the migration's progress output --- .../decisions/0013-pg-to-lmdb-migration.md | 19 +++++++++++-------- docs/rewrite/migrating.md | 9 +++++---- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md index 34f129bc..956e6b2f 100644 --- a/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md +++ b/docs/rewrite/decisions/0013-pg-to-lmdb-migration.md @@ -267,8 +267,8 @@ Migrated {total} rows in {ms} ms Events throughput: {rate} events/s ``` -D13 adds progress lines before these two and a total line after the `Store:` line; these two -are unchanged and stay first. +D13 adds progress lines before this block and a total line after the `Store:` line; within the +block these two are unchanged and first. `total` is the rows this invocation wrote, and the rate is `events * 1000 / max(ms, 1)` over the `events` table only. Both numbers are plain digits so a reader can recompute the rate @@ -329,15 +329,16 @@ Resuming {table} from {rows}/{source_rows} rows, after {cursor} {table}: {rows}/{source_rows} rows, after {cursor} ``` -The first is printed once per table the manifest records progress for, before that table's +The first is printed once per incomplete table the manifest records progress for, before that first read; it is what tells a resumed run which table it continues and from which key. The second is printed after the manifest write for a table's first batch, for a batch that carries the table's row count across a multiple of 100 000 rows, for the read that completes it, and for a table the source holds no rows in — never before the write, so the numbers on the line are the ones a resume would read. `rows` and `source_rows` are the manifest's two counts and -the cursor is the manifest's `after` in its hexadecimal spelling. `invite_codes`' cursor is the -invite code itself (D5), so its lines print `after redacted`; a table with no cursor yet prints -`after none`. +the cursor is the manifest's `after` in its hexadecimal spelling. Whether a table's key is a +credential is decided beside `name()` and `key()` (`MigratedTable::key_is_credential`), so a +table added there must decide before it can print: `invite_codes`' cursor is the invite code +itself (D5), so its lines print `after redacted`; a table with no cursor yet prints `after none`. The summary gains one line after `Store:`, which is the migration's own total rather than this run's: @@ -348,11 +349,13 @@ Migration total: {rows} rows ({total} this run) `rows` is the sum the manifest's nine entries carry and `total` is D8's. No field is added to the manifest (D7): the total is a sum over entries it already holds. D8's two lines are -unchanged, keep their text, and stay the first two lines the summary prints. +unchanged, keep their text, and stay first in this closing block. A write to a closed stdout now ends the copy at the first progress line rather than after its last row: the failure is an `io::Error` like any other and exits 1, the manifest keeps every -batch that was durable, and the next run resumes. +batch that was durable, and the next run resumes. `import` takes the opposite policy — it keeps +copying and reports the failed write at the end — so the difference here is deliberate: the +copy stops at the line that failed, as it already does when a batch's own write fails. ## What this record does not decide diff --git a/docs/rewrite/migrating.md b/docs/rewrite/migrating.md index b37cd7d1..9db90cd5 100644 --- a/docs/rewrite/migrating.md +++ b/docs/rewrite/migrating.md @@ -184,7 +184,7 @@ ADR 0013's D13, taken from the in-process harness (`crates/nostream-cli/tests/migrate_cli.rs`), not from a terminal transcript: no Postgres exists in this sandbox to copy. -For every table the manifest records progress for, before its first read: +For every incomplete table the manifest records progress for, before its first read: ``` Resuming {table} from {rows}/{source_rows} rows, after {cursor} @@ -203,14 +203,15 @@ the one read of an empty table: The closing block is four lines, in this order: ``` -Migrated {rows} rows in {ms} ms +Migrated {total} rows in {ms} ms Events throughput: {rate} events/s Store: {path} Migration total: {rows} rows ({total} this run) ``` The first three are ADR 0013 D8's and D6's; the last is the migration's own total, the sum the -manifest's entries carry, beside this run's count. +manifest's entries carry, beside this run's count. `{total}` is this run's own row count — D8's — +and the last line's `{rows}` is the migration's sum. A closed stdout (`… | head`) ends the copy at the first progress line that fails to write, with exit 1 and `Migration failed: unable to write the migration's output: …`; the manifest keeps @@ -262,7 +263,7 @@ 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 50 tests in that file. +describes this tree: the copy and verify passes are driven by the 53 tests in that file. 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: