Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/migration-resume-hint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

fix(cli): tell operators a failed migration resumes from the manifest (#1328)
50 changes: 49 additions & 1 deletion crates/nostream-cli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,8 +838,14 @@ fn failure_lines(error: CliError) -> Failure {
),
CliError::Import(message) => (vec![format!("Import failed: {message}")], 1),
CliError::Migrate(message) => (vec![format!("Migration failed: {message}")], 1),
CliError::MigrateResumable(message) => (
vec![format!(
"Migration failed: {message} — the manifest records the last committed batch; run \
the same command to resume"
)],
1,
),
};

Failure::Lines { lines, code }
}

Expand Down Expand Up @@ -869,3 +875,45 @@ pub(crate) fn print_error_lines(lines: &[String]) -> std::io::Result<()> {

Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_resumable_migrate_failure_line_names_the_manifest_and_resume_instruction() {
match failure_lines(CliError::MigrateResumable(
"events: connection reset".to_owned(),
)) {
Failure::Lines { lines, code } => {
assert_eq!(code, 1);
assert_eq!(lines.len(), 1);
assert!(lines[0].starts_with("Migration failed: events: connection reset"));
assert!(lines[0].contains("manifest"));
assert!(lines[0].contains(
"the manifest records the last committed batch; run the same command to resume"
));
}
Failure::ReportedFirst { .. } => {
unreachable!("CliError::MigrateResumable returns Failure::Lines");
}
}
}

#[test]
fn a_refused_migrate_failure_line_keeps_existing_recovery_advice_without_resume_hint() {
let message =
"No store at /tmp/lmdb: the manifest records progress. To start over, use a fresh --target"
.to_owned();
match failure_lines(CliError::Migrate(message.clone())) {
Failure::Lines { lines, code } => {
assert_eq!(code, 1);
assert_eq!(lines, vec![format!("Migration failed: {message}")]);
assert!(!lines[0].contains("run the same command to resume"));
}
Failure::ReportedFirst { .. } => {
unreachable!("CliError::Migrate returns Failure::Lines");
}
}
}
}
38 changes: 28 additions & 10 deletions crates/nostream-cli/src/commands/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,23 @@ fn run_with(
// acquire timeout, so only a direct connection answers with the reason. Then the
// master-only backend, because the copy reads the master and nothing else and a
// replica that is down during a cutover must not stop it.
let has_resumable_store = existing
.as_ref()
.is_some_and(|manifest| manifest.records_progress());
let source_failure = |error: &dyn std::fmt::Display| {
let failure =
CliError::Migrate(format!("could not read the source at {described}: {error}"));
if has_resumable_store {
as_resumable(failure)
} else {
failure
}
};
PostgresBackend::probe_master_from_env(probe_budget())
.await
.map_err(|error| {
CliError::Migrate(format!("could not read the source at {described}: {error}"))
})?;
let source = PostgresBackend::master_only_from_env().map_err(|error| {
CliError::Migrate(format!("could not read the source at {described}: {error}"))
})?;
.map_err(|error| source_failure(&error))?;
let source =
PostgresBackend::master_only_from_env().map_err(|error| source_failure(&error))?;
let pin = create_target(&options)?;
after_pin();
let root = pin.root();
Expand Down Expand Up @@ -231,16 +240,16 @@ pub async fn migrate_with(
let batch = source
.read_batch(table, after.as_deref(), options.batch_size)
.await
.map_err(|error| table_failed(table, &error))?;
.map_err(|error| as_resumable(table_failed(table, &error)))?;
let count = batch.len();
let written = target
.write_batch(&batch)
.await
.map_err(|error| table_failed(table, &error))?;
.map_err(|error| as_resumable(table_failed(table, &error)))?;
measured = Some(started.elapsed());

for row in &batch {
sum.add(row)?;
sum.add(row).map_err(as_resumable)?;
}
rows += written;
total += written;
Expand All @@ -257,7 +266,7 @@ pub async fn migrate_with(
entry.checksum = sum.to_hex();
entry.after = after.as_deref().map(hex::encode).unwrap_or_default();
entry.complete = complete;
write_manifest(root, &options.target, &manifest)?;
write_manifest(root, &options.target, &manifest).map_err(as_resumable)?;

if complete {
break;
Expand Down Expand Up @@ -1217,6 +1226,15 @@ fn table_failed(table: MigratedTable, error: &dyn std::fmt::Display) -> CliError
CliError::Migrate(format!("{}: {error}", table.name()))
}

/// Marks a failure during a copy whose manifest remains intact on disk as resumable by re-running
/// the same command.
fn as_resumable(error: CliError) -> CliError {
match error {
CliError::Migrate(message) => CliError::MigrateResumable(message),
other => other,
}
}

/// One hex resume cursor, or `None` before the table's first batch.
fn decode_key(text: &str) -> Result<Option<Vec<u8>>, CliError> {
if text.is_empty() {
Expand Down
5 changes: 5 additions & 0 deletions crates/nostream-cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ pub enum CliError {
/// not open.
#[error("{0}")]
Migrate(String),

/// A migration failure where an intact manifest remains on disk, so re-running the same
/// command resumes from the last committed batch.
#[error("{0}")]
MigrateResumable(String),
}

impl CliError {
Expand Down
77 changes: 67 additions & 10 deletions crates/nostream-cli/tests/migrate_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,8 +627,8 @@ async fn an_interrupted_run_resumes_to_the_clean_run_manifest() {
.await
.expect_err("the second read fails");
assert!(
matches!(error, nostream_cli::CliError::Migrate(_)),
"a migration failure is the variant `main` prints as `Migration failed:` and exits 1 for"
matches!(error, nostream_cli::CliError::MigrateResumable(_)),
"a failed copy during migration produces the resumable failure variant"
);
assert_eq!(
error.to_string(),
Expand Down Expand Up @@ -985,8 +985,8 @@ async fn a_crash_between_the_first_batch_and_the_manifest_write_resumes_to_the_c
.await
.expect_err("the first read fails");
assert!(
matches!(error, nostream_cli::CliError::Migrate(_)),
"a source failure is the variant `main` reports as `Migration failed:`"
matches!(error, nostream_cli::CliError::MigrateResumable(_)),
"a source failure during copy produces the resumable failure variant"
);

let fresh = manifest_bytes(crashed.path());
Expand Down Expand Up @@ -1303,8 +1303,8 @@ async fn a_refused_row_stops_the_run_and_keeps_the_resume_point() {
.await
.expect_err("the refused key fails the batch");
assert!(
matches!(error, nostream_cli::CliError::Migrate(_)),
"a migration failure is the variant `main` prints as `Migration failed:` and exits 1 for"
matches!(error, nostream_cli::CliError::MigrateResumable(_)),
"a refused row during copy produces the resumable failure variant"
);
assert!(
error.to_string().starts_with("events: "),
Expand Down Expand Up @@ -1815,7 +1815,7 @@ fn a_manifest_that_records_progress_over_a_missing_store_is_refused() {
.await
});
assert!(
matches!(error, Err(nostream_cli::CliError::Migrate(_))),
matches!(error, Err(nostream_cli::CliError::MigrateResumable(_))),
"the stub fails the second read_batch"
);
let manifest: Value = serde_json::from_slice(&manifest_bytes(partial.path()))
Expand Down Expand Up @@ -1849,6 +1849,10 @@ fn a_manifest_that_records_progress_over_a_missing_store_is_refused() {
stderr.contains("a fresh --target"),
"the refusal names the remedy: {stderr}"
);
assert!(
!stderr.contains("run the same command to resume"),
"a refused resume target must not tell the operator to re-run the same command: {stderr}"
);

// Half two: the manifest R6 writes, with no progress in it, over an empty directory.
let fresh = tempfile::tempdir().expect("a temporary directory");
Expand Down Expand Up @@ -1915,9 +1919,8 @@ fn a_manifest_that_records_progress_over_a_missing_store_is_refused() {
assert!(complete, "every table is complete");
}

/// The process boundary the two failure tests above stop at: `main` prints
/// `Migration failed: {message}` and exits 1. No source is reachable here, so the run fails on
/// the way to the copy, which is the same arm.
/// The process boundary the failure tests stop at: `main` prints `Migration failed: {message}`
/// and exits 1. No manifest exists on an empty directory, so no resume instruction is appended.
#[test]
fn a_failed_run_reports_migration_failed_and_exits_1() {
let directory = tempfile::tempdir().expect("a temporary directory");
Expand All @@ -1937,6 +1940,60 @@ fn a_failed_run_reports_migration_failed_and_exits_1() {
stderr.starts_with("Migration failed: "),
"the failure is reported as one: {stderr}"
);
assert!(
!stderr.contains("run the same command to resume"),
"a run with no saved manifest does not tell the operator to resume: {stderr}"
);
}

#[test]
fn a_failed_resumable_run_prints_the_manifest_resume_instruction() {
let directory = tempfile::tempdir().expect("a temporary directory");
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("the test runtime builds");
let partial_options = options(directory.path(), 2);
let error = runtime.block_on(async {
let target = LmdbBackend::open(directory.path())
.await
.expect("the store opens");
migrate::migrate_with(
&StubSource::failing_at(source_rows(), 1),
&target,
&partial_options.target,
&partial_options,
&mut Vec::new(),
)
.await
});
assert!(
matches!(error, Err(nostream_cli::CliError::MigrateResumable(_))),
"a mid-copy failure returns the resumable error variant"
);

let output = Command::new(env!("CARGO_BIN_EXE_nostream-cli"))
.args(["migrate", "pg-to-lmdb", "--target"])
.arg(directory.path())
.env("DB_URI", "postgres://127.0.0.1:1/nostream")
.env("DB_ACQUIRE_CONNECTION_TIMEOUT", "1000")
.output()
.expect("the binary runs");

assert_eq!(output.status.code(), Some(1));
let stderr = String::from_utf8_lossy(&output.stderr);
let failure_line = stderr.lines().next().unwrap_or("");
assert!(
failure_line.starts_with("Migration failed: "),
"the failure line begins with Migration failed: {stderr}"
);
assert!(
failure_line.contains("manifest")
&& failure_line.contains(
"the manifest records the last committed batch; run the same command to resume"
),
"the failure line tells the operator a re-run resumes from the manifest: {stderr}"
);
}

// ---------------------------------------------------------------------------------------
Expand Down
Loading