From b2d5e4d71a4fcbc0b5f67c016042842c8667c4bb Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 20:55:13 +0700 Subject: [PATCH 1/7] test: add trait seams to the agent restore flow (no behaviour change) RestoreTarget, RestoreHub and BackupSource let the destructive restore sequence be driven by fakes. poll takes the heartbeat interval as a parameter instead of reading the constant. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/tessera-agent/Cargo.toml | 1 + crates/tessera-agent/src/jobs.rs | 12 +- crates/tessera-agent/src/restore.rs | 183 +++++++++++++++++++--------- 4 files changed, 140 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d626b56..d81c6a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3083,6 +3083,7 @@ name = "tessera-agent" version = "0.1.0" dependencies = [ "anyhow", + "async-trait", "base64 0.22.1", "clap", "hex", diff --git a/crates/tessera-agent/Cargo.toml b/crates/tessera-agent/Cargo.toml index 84a3abb..ff943a5 100644 --- a/crates/tessera-agent/Cargo.toml +++ b/crates/tessera-agent/Cargo.toml @@ -13,6 +13,7 @@ path = "src/main.rs" tessera-core = { path = "../tessera-core" } tessera-providers = { path = "../tessera-providers" } anyhow.workspace = true +async-trait.workspace = true clap.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/tessera-agent/src/jobs.rs b/crates/tessera-agent/src/jobs.rs index b9dbeb2..bf4467d 100644 --- a/crates/tessera-agent/src/jobs.rs +++ b/crates/tessera-agent/src/jobs.rs @@ -46,8 +46,15 @@ pub(super) enum Source { Mysql(MysqlSource), } -impl Source { - pub(super) async fn identity(&self) -> Result { +/// The local backup source, as far as the restore guard cares: which database it is. +#[async_trait::async_trait] +pub(super) trait BackupSource: Sync { + async fn identity(&self) -> Result; +} + +#[async_trait::async_trait] +impl BackupSource for Source { + async fn identity(&self) -> Result { match self { Self::Postgres(source) => source.identity().await, Self::Mysql(source) => source.identity().await, @@ -119,6 +126,7 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> { profile.source.as_ref(), &profile.targets, profile.timeout_seconds, + Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS), ) .await?; if !restored && (profile.source.is_some() || !profile.paths.is_empty()) { diff --git a/crates/tessera-agent/src/restore.rs b/crates/tessera-agent/src/restore.rs index 0c0cef8..db4235b 100644 --- a/crates/tessera-agent/src/restore.rs +++ b/crates/tessera-agent/src/restore.rs @@ -1,12 +1,13 @@ use crate::{ http, - jobs::{digest_file, Hub, Source}, + jobs::{digest_file, BackupSource, Hub}, }; use anyhow::{ensure, Context, Result}; +use async_trait::async_trait; use serde::Deserialize; use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; use tessera_core::{ - job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS}, + job::CaptureFormat, restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, }; use tessera_providers::{MysqlRestore, PostgresRestore}; @@ -19,7 +20,108 @@ pub(super) enum Target { Mysql(MysqlRestore), } -impl Target { +/// The local database a restore is applied to. A seam so the destructive sequence in `run` can be driven +/// by fakes in tests; the real implementation is `Target`. +#[async_trait] +pub(super) trait RestoreTarget: Sync { + async fn identity(&self) -> Result; + async fn prepare(&self, input: File, lease: &RestoreLease) -> Result; + async fn safety(&self, stage: File) -> Result<()>; + async fn apply(&self, script: File) -> Result<()>; +} + +/// What the restore flow needs from the hub. A seam for tests; the real implementation is `Arc`. +#[async_trait] +pub(super) trait RestoreHub: Sync { + async fn send( + &self, + path: String, + body: serde_json::Value, + restore: Option, + ) -> Result; + async fn send_with_reason( + &self, + path: String, + body: serde_json::Value, + restore: Uuid, + reason: Option, + ) -> Result; + async fn upload_safety( + &self, + lease: &RestoreLease, + stage: File, + timeout: Duration, + ) -> Result<()>; + async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result; +} + +#[async_trait] +impl RestoreHub for Arc { + async fn send( + &self, + path: String, + body: serde_json::Value, + restore: Option, + ) -> Result { + self.post(path, body, restore).await + } + + async fn send_with_reason( + &self, + path: String, + body: serde_json::Value, + restore: Uuid, + reason: Option, + ) -> Result { + self.post_with_reason(path, body, restore, reason).await + } + + async fn upload_safety( + &self, + lease: &RestoreLease, + stage: File, + timeout: Duration, + ) -> Result<()> { + self.upload( + format!("restore/{}/safety", lease.job.id), + stage, + timeout, + "x-tessera-restore-token", + lease.token, + None, + ) + .await + } + + async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result { + let hub = self.clone(); + let id = lease.job.id; + let token = lease.token.to_string(); + let digest = lease.artifact.sha256.clone(); + tokio::task::spawn_blocking(move || { + let mut file = tempfile::tempfile().context("create private restore staging")?; + let size = http::get_file( + &format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url), + &mut file, + &[ + ("x-tessera-upload-token", &hub.token), + ("x-tessera-restore-token", &token), + ], + timeout, + )?; + let (bytes, computed) = digest_file(&mut file)?; + ensure!( + size == bytes && computed == digest, + "restore payload checksum mismatch" + ); + Ok(file) + }) + .await? + } +} + +#[async_trait] +impl RestoreTarget for Target { async fn identity(&self) -> Result { match self { Self::Postgres(target) => target.connection.identity().await, @@ -59,16 +161,17 @@ impl Target { } } -pub(super) async fn poll( - hub: &Arc, +pub(super) async fn poll( + hub: &H, application: Uuid, - source: Option<&Source>, - targets: &HashMap, + source: Option<&S>, + targets: &HashMap, timeout_seconds: u64, + heartbeat: Duration, ) -> Result { for (target_id, target) in targets { let reply = hub - .post( + .send( format!("restore-targets/{target_id}/claim"), serde_json::Value::Null, None, @@ -93,7 +196,7 @@ pub(super) async fn poll( tokio::select! { biased; result = &mut work => return result.map(|()| true), - _ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => { + _ = tokio::time::sleep(heartbeat) => { report(hub, &lease, RestoreProgress::Heartbeat).await?; } } @@ -102,16 +205,16 @@ pub(super) async fn poll( Ok(false) } -async fn run( - hub: &Arc, +async fn run( + hub: &H, lease: &RestoreLease, - target: &Target, - source: Option<&Source>, + target: &T, + source: Option<&S>, timeout: Duration, ) -> Result<()> { report(hub, lease, RestoreProgress::Checking).await?; let downloaded = tokio::time::timeout(timeout, async { - let input = download(hub, lease, timeout).await?; + let input = hub.download(lease, timeout).await?; target.prepare(input, lease).await }) .await; @@ -159,15 +262,7 @@ async fn run( target.identity().await? == identity, "target changed during safety capture" ); - hub.upload( - format!("restore/{}/safety", lease.job.id), - stage, - timeout, - "x-tessera-restore-token", - lease.token, - None, - ) - .await?; + hub.upload_safety(lease, stage, timeout).await?; Ok::<_, anyhow::Error>(()) }) .await; @@ -177,7 +272,7 @@ async fn run( } // The permit is single-use. A lost response leaves the target locked for reconciliation. - hub.post( + hub.send( format!("restore/{}/apply", lease.job.id), serde_json::Value::Null, Some(lease.token), @@ -198,13 +293,13 @@ fn why(result: Result, tokio::time::error::Elapsed>) -> String { } } -async fn report_failed( - hub: &Arc, +async fn report_failed( + hub: &H, lease: &RestoreLease, progress: RestoreProgress, reason: String, ) -> Result<()> { - hub.post_with_reason( + hub.send_with_reason( format!("restore/{}/report", lease.job.id), serde_json::to_value(progress)?, lease.token, @@ -214,8 +309,12 @@ async fn report_failed( Ok(()) } -async fn report(hub: &Arc, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> { - hub.post( +async fn report( + hub: &H, + lease: &RestoreLease, + progress: RestoreProgress, +) -> Result<()> { + hub.send( format!("restore/{}/report", lease.job.id), serde_json::to_value(progress)?, Some(lease.token), @@ -223,29 +322,3 @@ async fn report(hub: &Arc, lease: &RestoreLease, progress: RestoreProgress) .await?; Ok(()) } - -async fn download(hub: &Arc, lease: &RestoreLease, timeout: Duration) -> Result { - let hub = hub.clone(); - let id = lease.job.id; - let token = lease.token.to_string(); - let digest = lease.artifact.sha256.clone(); - tokio::task::spawn_blocking(move || { - let mut file = tempfile::tempfile().context("create private restore staging")?; - let size = http::get_file( - &format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url), - &mut file, - &[ - ("x-tessera-upload-token", &hub.token), - ("x-tessera-restore-token", &token), - ], - timeout, - )?; - let (bytes, computed) = digest_file(&mut file)?; - ensure!( - size == bytes && computed == digest, - "restore payload checksum mismatch" - ); - Ok(file) - }) - .await? -} From 30ec7623242c3e8284c3b1990a34c2f3d82c3de9 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 20:58:32 +0700 Subject: [PATCH 2/7] test: cover the agent restore sequence with fakes Safety failure never applies, identity and source guards, rollback exception, per-step timeouts, lost apply permit, crash after permit, poll lease checks, and the heartbeat-failure behaviour. Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-agent/src/restore.rs | 3 + crates/tessera-agent/src/restore/tests.rs | 792 ++++++++++++++++++++++ 2 files changed, 795 insertions(+) create mode 100644 crates/tessera-agent/src/restore/tests.rs diff --git a/crates/tessera-agent/src/restore.rs b/crates/tessera-agent/src/restore.rs index db4235b..63f592a 100644 --- a/crates/tessera-agent/src/restore.rs +++ b/crates/tessera-agent/src/restore.rs @@ -322,3 +322,6 @@ async fn report( .await?; Ok(()) } + +#[cfg(test)] +mod tests; diff --git a/crates/tessera-agent/src/restore/tests.rs b/crates/tessera-agent/src/restore/tests.rs new file mode 100644 index 0000000..ec71da9 --- /dev/null +++ b/crates/tessera-agent/src/restore/tests.rs @@ -0,0 +1,792 @@ +//! The restore sequence is destructive, so these tests drive `run` and `poll` with in-process fakes and +//! assert what the agent does (and above all never does) at each step. Every fake appends to one shared +//! event log so tests can assert on ordering and absence. + +use super::*; +use std::{ + collections::VecDeque, + io::{Read, Write}, + sync::Mutex, +}; +use tessera_core::restore::{RestoreArtifact, RestoreJob, RestoreTarget as JobTarget}; + +type Log = Arc>>; + +fn identity(instance: &str, database: &str) -> DatabaseIdentity { + DatabaseIdentity { + instance: instance.into(), + database: database.into(), + } +} + +fn target_identity() -> DatabaseIdentity { + identity("1", "target") +} + +fn source_identity() -> DatabaseIdentity { + identity("2", "source") +} + +fn lease_for(target: Uuid, application: Uuid, rollback: bool) -> RestoreLease { + RestoreLease { + job: RestoreJob { + id: Uuid::new_v4(), + snapshot_id: Uuid::new_v4(), + target: JobTarget { + id: target, + application_id: application, + outpost_id: Uuid::new_v4(), + name: "target".into(), + engine: tessera_core::restore::Engine::Postgres, + identity: target_identity(), + }, + actor: "admin".into(), + status: "running".into(), + phase: "queued".into(), + safety_snapshot_id: None, + created_at: 0, + updated_at: 0, + failure_reason: None, + }, + token: Uuid::new_v4(), + artifact: RestoreArtifact { + format: CaptureFormat::PostgresCustom, + // A normal restore comes from another database; a rollback comes from the target itself. + identity: if rollback { + target_identity() + } else { + source_identity() + }, + sha256: "00".into(), + rollback, + }, + } +} + +fn lease() -> RestoreLease { + lease_for(Uuid::new_v4(), Uuid::new_v4(), false) +} + +#[derive(Clone, Copy, PartialEq)] +enum Step { + Ok, + Fail, + Hang, +} + +impl Step { + async fn run(self, what: &str) -> Result<()> { + match self { + Step::Ok => Ok(()), + Step::Fail => anyhow::bail!("{what} exploded"), + Step::Hang => std::future::pending().await, + } + } +} + +type Answer = Result; + +struct FakeTarget { + log: Log, + /// Answers for successive `identity` calls; the last one repeats. + identities: Mutex>, + hang_identity: bool, + prepare: Step, + safety: Step, + apply: Step, +} + +impl FakeTarget { + fn new(log: &Log) -> Self { + Self { + log: log.clone(), + identities: Mutex::new(VecDeque::from([Ok(target_identity())])), + hang_identity: false, + prepare: Step::Ok, + safety: Step::Ok, + apply: Step::Ok, + } + } + + fn identities(self, answers: Vec) -> Self { + *self.identities.lock().unwrap() = answers.into(); + self + } +} + +#[async_trait] +impl RestoreTarget for FakeTarget { + async fn identity(&self) -> Result { + self.log.lock().unwrap().push("target.identity".into()); + if self.hang_identity { + std::future::pending::<()>().await; + } + let answer = { + let mut answers = self.identities.lock().unwrap(); + if answers.len() > 1 { + answers.pop_front().unwrap() + } else { + answers.front().cloned().unwrap() + } + }; + answer.map_err(|why| anyhow::anyhow!(why)) + } + + async fn prepare(&self, mut input: File, _: &RestoreLease) -> Result { + self.log.lock().unwrap().push("target.prepare".into()); + self.prepare.run("prepare").await?; + let mut script = tempfile::tempfile()?; + let mut body = Vec::new(); + input.read_to_end(&mut body)?; + script.write_all(&body)?; + Ok(script) + } + + async fn safety(&self, _: File) -> Result<()> { + self.log.lock().unwrap().push("target.safety".into()); + self.safety.run("safety dump").await + } + + async fn apply(&self, _: File) -> Result<()> { + self.log.lock().unwrap().push("target.apply".into()); + self.apply.run("apply").await + } +} + +struct FakeSource(Answer); + +#[async_trait] +impl BackupSource for FakeSource { + async fn identity(&self) -> Result { + self.0.clone().map_err(|why| anyhow::anyhow!(why)) + } +} + +struct FakeHub { + log: Log, + /// Queue of claim replies; empty means "nothing to restore". + claims: Mutex>, + download: Step, + upload: Step, + /// A request whose path ends with this fails (the response is "lost"). + fail_path: Option<&'static str>, + /// Reports with this progress fail (used to break heartbeats). + fail_progress: Option<&'static str>, +} + +impl FakeHub { + fn new(log: &Log) -> Self { + Self { + log: log.clone(), + claims: Mutex::default(), + download: Step::Ok, + upload: Step::Ok, + fail_path: None, + fail_progress: None, + } + } +} + +#[async_trait] +impl RestoreHub for FakeHub { + async fn send( + &self, + path: String, + body: serde_json::Value, + restore: Option, + ) -> Result { + if path.ends_with("/claim") { + return Ok(self + .claims + .lock() + .unwrap() + .pop_front() + .unwrap_or_else(|| "null".into())); + } + if path.ends_with("/apply") { + assert!(restore.is_some(), "the apply permit needs the lease token"); + self.log.lock().unwrap().push("hub.apply-permit".into()); + } else { + let progress = body.as_str().unwrap_or("?").to_owned(); + self.log.lock().unwrap().push(format!("report:{progress}")); + if self.fail_progress == Some(progress.as_str()) { + anyhow::bail!("hub unreachable"); + } + } + if self.fail_path.is_some_and(|suffix| path.ends_with(suffix)) { + anyhow::bail!("response lost"); + } + Ok(String::new()) + } + + async fn send_with_reason( + &self, + _: String, + body: serde_json::Value, + _: Uuid, + reason: Option, + ) -> Result { + self.log.lock().unwrap().push(format!( + "failed:{}:{}", + body.as_str().unwrap_or("?"), + reason.unwrap_or_default() + )); + Ok(String::new()) + } + + async fn upload_safety(&self, _: &RestoreLease, _: File, _: Duration) -> Result<()> { + self.log.lock().unwrap().push("hub.safety-upload".into()); + self.upload.run("upload").await + } + + async fn download(&self, _: &RestoreLease, _: Duration) -> Result { + self.log.lock().unwrap().push("hub.download".into()); + self.download.run("download").await?; + Ok(tempfile::tempfile()?) + } +} + +const SHORT: Duration = Duration::from_millis(60); + +struct Outcome { + result: Result<()>, + log: Vec, +} + +impl Outcome { + fn did(&self, event: &str) -> bool { + self.log.iter().any(|entry| entry == event) + } + + fn failed(&self, progress: &str) -> Option<&str> { + self.log + .iter() + .find_map(|entry| entry.strip_prefix(&format!("failed:{progress}:"))) + } + + /// The agent never reached the destructive step. + fn never_applied(&self) -> bool { + !self.did("hub.apply-permit") && !self.did("target.apply") + } +} + +async fn drive( + lease: &RestoreLease, + log: &Log, + hub: FakeHub, + target: FakeTarget, + source: Option, +) -> Outcome { + let result = run(&hub, lease, &target, source.as_ref(), SHORT).await; + let log = log.lock().unwrap().clone(); + Outcome { result, log } +} + +fn log() -> Log { + Log::default() +} + +#[tokio::test] +async fn full_restore_runs_in_order_and_reports_applied() { + let log = log(); + let out = drive( + &lease(), + &log, + FakeHub::new(&log), + FakeTarget::new(&log), + None, + ) + .await; + out.result.as_ref().unwrap(); + let steps: Vec<&str> = out + .log + .iter() + .map(String::as_str) + .filter(|entry| *entry != "target.identity") + .collect(); + assert_eq!( + steps, + [ + "report:checking", + "hub.download", + "target.prepare", + "report:safety", + "target.safety", + "hub.safety-upload", + "hub.apply-permit", + "target.apply", + "report:applied", + ] + ); +} + +// ---- safety capture: nothing destructive may happen unless the safety copy is stored ---- + +#[tokio::test] +async fn safety_dump_failure_never_applies() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.safety = Step::Fail; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out.never_applied()); + assert!(out + .failed("safety_failed") + .unwrap() + .contains("safety dump exploded")); + assert!(!out.did("hub.safety-upload")); +} + +#[tokio::test] +async fn safety_upload_failure_never_applies() { + let log = log(); + let mut hub = FakeHub::new(&log); + hub.upload = Step::Fail; + let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await; + out.result.as_ref().unwrap(); + assert!(out.never_applied()); + assert!(out + .failed("safety_failed") + .unwrap() + .contains("upload exploded")); +} + +#[tokio::test] +async fn target_changed_during_safety_capture_never_applies() { + let log = log(); + // Verified as the expected target, then a different database answers after the dump. + let target = + FakeTarget::new(&log).identities(vec![Ok(target_identity()), Ok(source_identity())]); + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out.never_applied()); + assert!(out + .failed("safety_failed") + .unwrap() + .contains("target changed during safety capture")); + assert!( + !out.did("hub.safety-upload"), + "a dump of the wrong database must not be stored" + ); +} + +#[tokio::test] +async fn target_unreachable_after_safety_capture_never_applies() { + let log = log(); + let target = FakeTarget::new(&log).identities(vec![Ok(target_identity()), Err("gone")]); + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out.never_applied()); + assert!(out.failed("safety_failed").is_some()); +} + +// ---- identity checks ---- + +#[tokio::test] +async fn identity_mismatch_refuses_before_any_dump() { + let log = log(); + let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "other"))]); + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out + .failed("wrong_target") + .unwrap() + .contains("identity does not match")); + assert!(out.never_applied()); + assert!( + !out.did("target.safety"), + "must refuse before touching the target" + ); + assert!(!out.did("report:safety")); +} + +#[tokio::test] +async fn identity_probe_error_is_a_wrong_target() { + let log = log(); + let target = FakeTarget::new(&log).identities(vec![Err("connection refused")]); + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out + .failed("wrong_target") + .unwrap() + .contains("connection refused")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn restoring_a_backup_onto_its_own_source_database_is_refused() { + let log = log(); + let mut lease = lease(); + lease.artifact.identity = target_identity(); // artifact was taken from the target itself + let out = drive( + &lease, + &log, + FakeHub::new(&log), + FakeTarget::new(&log), + None, + ) + .await; + out.result.as_ref().unwrap(); + assert!(out.failed("wrong_target").is_some()); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn rollback_may_restore_onto_the_database_the_copy_came_from() { + let log = log(); + let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true); + assert_eq!(lease.artifact.identity, lease.job.target.identity); + let out = drive( + &lease, + &log, + FakeHub::new(&log), + FakeTarget::new(&log), + None, + ) + .await; + out.result.as_ref().unwrap(); + assert!(out.did("report:applied")); +} + +#[tokio::test] +async fn rollback_still_requires_the_target_identity_to_match() { + let log = log(); + let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true); + let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "impostor"))]); + let out = drive(&lease, &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out.failed("wrong_target").is_some()); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn target_that_is_the_local_backup_source_is_refused() { + let log = log(); + let source = FakeSource(Ok(target_identity())); + let out = drive( + &lease(), + &log, + FakeHub::new(&log), + FakeTarget::new(&log), + Some(source), + ) + .await; + out.result.as_ref().unwrap(); + assert!(out + .failed("wrong_target") + .unwrap() + .contains("target resolves to the local backup source")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn a_different_local_source_does_not_block_a_restore() { + let log = log(); + let source = FakeSource(Ok(source_identity())); + let out = drive( + &lease(), + &log, + FakeHub::new(&log), + FakeTarget::new(&log), + Some(source), + ) + .await; + out.result.as_ref().unwrap(); + assert!(out.did("report:applied")); +} + +/// Documented as designed: the source guard is best effort. If the local source cannot be identified (its +/// probe errors), the restore proceeds on the strength of the target identity checks alone. +#[tokio::test] +async fn unidentifiable_local_source_does_not_block_a_restore() { + let log = log(); + let source = FakeSource(Err("source down")); + let out = drive( + &lease(), + &log, + FakeHub::new(&log), + FakeTarget::new(&log), + Some(source), + ) + .await; + out.result.as_ref().unwrap(); + assert!(out.did("report:applied")); +} + +// ---- per-step timeouts map to their own failure state, and never reach apply ---- + +#[tokio::test] +async fn download_timeout_is_invalid_payload() { + let log = log(); + let mut hub = FakeHub::new(&log); + hub.download = Step::Hang; + let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("invalid_payload"), Some("timed out")); + assert!(out.never_applied()); + assert!(!out.did("target.safety")); +} + +#[tokio::test] +async fn prepare_timeout_is_invalid_payload() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.prepare = Step::Hang; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("invalid_payload"), Some("timed out")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn prepare_error_is_invalid_payload_with_its_reason() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.prepare = Step::Fail; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out + .failed("invalid_payload") + .unwrap() + .contains("prepare exploded")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn identity_check_timeout_is_wrong_target() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.hang_identity = true; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("wrong_target"), Some("timed out")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn safety_dump_timeout_is_safety_failed() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.safety = Step::Hang; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("safety_failed"), Some("timed out")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn safety_upload_timeout_is_safety_failed() { + let log = log(); + let mut hub = FakeHub::new(&log); + hub.upload = Step::Hang; + let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("safety_failed"), Some("timed out")); + assert!(out.never_applied()); +} + +#[tokio::test] +async fn apply_timeout_is_apply_failed_after_the_permit() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.apply = Step::Hang; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("apply_failed"), Some("timed out")); + assert!(out.did("hub.apply-permit") && out.did("target.apply")); + assert!(!out.did("report:applied")); +} + +#[tokio::test] +async fn apply_error_is_apply_failed_with_its_reason() { + let log = log(); + let mut target = FakeTarget::new(&log); + target.apply = Step::Fail; + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert!(out + .failed("apply_failed") + .unwrap() + .contains("apply exploded")); + assert!(!out.did("report:applied")); +} + +// ---- the permit ---- + +/// The permit is single-use and the agent does not retry it. If the response is lost (or the hub refuses), +/// `run` returns the error WITHOUT applying and without reporting anything further: the hub has consumed +/// (or may have consumed) the permit, so the target stays locked until the hub reconciles the lease. +#[tokio::test] +async fn lost_apply_permit_response_does_not_apply_and_leaves_the_lease_for_reconciliation() { + let log = log(); + let mut hub = FakeHub::new(&log); + hub.fail_path = Some("/apply"); + let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await; + assert!(out + .result + .as_ref() + .unwrap_err() + .to_string() + .contains("response lost")); + assert!(out.did("hub.apply-permit")); + assert!( + !out.did("target.apply"), + "no permit response, no destructive step" + ); + assert_eq!(out.log.last().map(String::as_str), Some("hub.apply-permit")); + assert!(out + .log + .iter() + .all(|e| !e.starts_with("failed:") && e != "report:applied")); +} + +/// Agent dies (or is cancelled) after the permit but before the restore finishes. The hub has seen the +/// permit but never a terminal report, so the lease is left mid-flight for the hub to expire. +#[tokio::test] +async fn crash_between_permit_and_apply_leaves_no_terminal_report() { + let log = log(); + let hub = FakeHub::new(&log); + let mut target = FakeTarget::new(&log); + target.apply = Step::Hang; + let lease = lease(); + let crashed = tokio::time::timeout( + Duration::from_millis(200), + run( + &hub, + &lease, + &target, + None::<&FakeSource>, + Duration::from_secs(30), + ), + ) + .await; + assert!(crashed.is_err(), "the run was dropped mid-apply"); + let log = log.lock().unwrap().clone(); + assert!(log.contains(&"hub.apply-permit".to_owned())); + assert!(log.contains(&"target.apply".to_owned())); + assert!(log + .iter() + .all(|e| e != "report:applied" && !e.starts_with("failed:"))); +} + +#[tokio::test] +async fn failure_reasons_are_cleaned_before_they_are_reported() { + let log = log(); + let target = FakeTarget::new(&log).identities(vec![Err("line one\nline\ttwo \u{1F4A5}")]); + let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await; + out.result.as_ref().unwrap(); + assert_eq!(out.failed("wrong_target"), Some("line one line two ?")); +} + +// ---- poll ---- + +fn poll_fixture( + log: &Log, + lease: &RestoreLease, + target_id: Uuid, +) -> (FakeHub, HashMap) { + let hub = FakeHub::new(log); + hub.claims + .lock() + .unwrap() + .push_back(serde_json::to_string(lease).unwrap()); + let targets = HashMap::from([(target_id, FakeTarget::new(log))]); + (hub, targets) +} + +#[tokio::test] +async fn poll_with_nothing_to_claim_does_nothing() { + let log = log(); + let hub = FakeHub::new(&log); + let targets = HashMap::from([(Uuid::new_v4(), FakeTarget::new(&log))]); + let did = poll( + &hub, + Uuid::new_v4(), + None::<&FakeSource>, + &targets, + 1, + SHORT, + ) + .await + .unwrap(); + assert!(!did); + assert!(log.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn poll_refuses_a_lease_for_another_target_or_application() { + for swap_target in [true, false] { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = if swap_target { + lease_for(Uuid::new_v4(), application, false) + } else { + lease_for(target_id, Uuid::new_v4(), false) + }; + let (hub, targets) = poll_fixture(&log, &lease, target_id); + let err = poll(&hub, application, None::<&FakeSource>, &targets, 1, SHORT) + .await + .unwrap_err(); + assert!(err.to_string().contains("unexpected restore target")); + assert!( + log.lock().unwrap().is_empty(), + "nothing may run for a mismatched lease" + ); + } +} + +#[tokio::test] +async fn poll_runs_a_matching_lease() { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = lease_for(target_id, application, false); + let (hub, targets) = poll_fixture(&log, &lease, target_id); + let did = poll( + &hub, + application, + None::<&FakeSource>, + &targets, + 5, + Duration::from_secs(60), + ) + .await + .unwrap(); + assert!(did); + assert!(log.lock().unwrap().contains(&"report:applied".to_owned())); +} + +/// Current behaviour, flagged in the report as a risk: a failed heartbeat report abandons the in-flight +/// restore future (and with it the apply, whose child processes are `kill_on_drop`), so a transient hub +/// blip mid-apply can kill a restore half way with no terminal report. Pinned so a deliberate change shows. +#[tokio::test] +async fn failed_heartbeat_abandons_the_in_flight_restore() { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = lease_for(target_id, application, false); + let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + hub.fail_progress = Some("heartbeat"); + targets.get_mut(&target_id).unwrap().apply = Step::Hang; + let err = tokio::time::timeout( + Duration::from_secs(5), + poll( + &hub, + application, + None::<&FakeSource>, + &targets, + 30, + Duration::from_millis(50), + ), + ) + .await + .expect("poll returns once the heartbeat fails") + .unwrap_err(); + assert!(err.to_string().contains("hub unreachable")); + let log = log.lock().unwrap().clone(); + assert!( + log.contains(&"target.apply".to_owned()), + "apply had started" + ); + assert!(log + .iter() + .all(|e| e != "report:applied" && !e.starts_with("failed:"))); +} From ed6296a9c5e945372fc6a72d398f6dcfcbb9c2ed Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:22:52 +0700 Subject: [PATCH 3/7] fix: a failed heartbeat no longer abandons a restore once the apply permit is spent Before the permit the lease is still given up on; after it the failure is logged and the apply runs to its terminal report instead of being killed mid-flight. Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-agent/src/restore.rs | 29 ++++++- crates/tessera-agent/src/restore/tests.rs | 99 +++++++++++++++++++---- 2 files changed, 111 insertions(+), 17 deletions(-) diff --git a/crates/tessera-agent/src/restore.rs b/crates/tessera-agent/src/restore.rs index 63f592a..235ac64 100644 --- a/crates/tessera-agent/src/restore.rs +++ b/crates/tessera-agent/src/restore.rs @@ -5,7 +5,15 @@ use crate::{ use anyhow::{ensure, Context, Result}; use async_trait::async_trait; use serde::Deserialize; -use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; +use std::{ + collections::HashMap, + fs::File, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::Duration, +}; use tessera_core::{ job::CaptureFormat, restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, @@ -184,12 +192,14 @@ pub(super) async fn poll( lease.job.target.id == *target_id && lease.job.target.application_id == application, "hub returned an unexpected restore target" ); + let permit_taken = AtomicBool::new(false); let work = run( hub, &lease, target, source, Duration::from_secs(timeout_seconds), + &permit_taken, ); tokio::pin!(work); loop { @@ -197,7 +207,17 @@ pub(super) async fn poll( biased; result = &mut work => return result.map(|()| true), _ = tokio::time::sleep(heartbeat) => { - report(hub, &lease, RestoreProgress::Heartbeat).await?; + if let Err(error) = report(hub, &lease, RestoreProgress::Heartbeat).await { + // Once the apply permit is spent, dropping `work` would kill the apply + // half way (its children are `kill_on_drop`) and leave the target + // half-restored with no terminal report. Keep going and let the outcome + // report decide. Before the permit nothing destructive has happened, + // so give up and let the lease expire. + if !permit_taken.load(Ordering::SeqCst) { + return Err(error); + } + tracing::warn!(restore = %lease.job.id, %error, "heartbeat failed during apply; letting the restore finish"); + } } } } @@ -211,6 +231,7 @@ async fn run( target: &T, source: Option<&S>, timeout: Duration, + permit_taken: &AtomicBool, ) -> Result<()> { report(hub, lease, RestoreProgress::Checking).await?; let downloaded = tokio::time::timeout(timeout, async { @@ -271,7 +292,9 @@ async fn run( return Ok(()); } - // The permit is single-use. A lost response leaves the target locked for reconciliation. + // The permit is single-use. A lost response leaves the target locked for reconciliation. Mark it + // taken before asking: from here on the hub may consider the apply started. + permit_taken.store(true, Ordering::SeqCst); hub.send( format!("restore/{}/apply", lease.job.id), serde_json::Value::Null, diff --git a/crates/tessera-agent/src/restore/tests.rs b/crates/tessera-agent/src/restore/tests.rs index ec71da9..fe34a46 100644 --- a/crates/tessera-agent/src/restore/tests.rs +++ b/crates/tessera-agent/src/restore/tests.rs @@ -72,6 +72,8 @@ enum Step { Ok, Fail, Hang, + /// Succeeds after this many milliseconds. + Slow(u64), } impl Step { @@ -80,6 +82,10 @@ impl Step { Step::Ok => Ok(()), Step::Fail => anyhow::bail!("{what} exploded"), Step::Hang => std::future::pending().await, + Step::Slow(ms) => { + tokio::time::sleep(Duration::from_millis(ms)).await; + Ok(()) + } } } } @@ -277,7 +283,15 @@ async fn drive( target: FakeTarget, source: Option, ) -> Outcome { - let result = run(&hub, lease, &target, source.as_ref(), SHORT).await; + let result = run( + &hub, + lease, + &target, + source.as_ref(), + SHORT, + &AtomicBool::new(false), + ) + .await; let log = log.lock().unwrap().clone(); Outcome { result, log } } @@ -657,6 +671,7 @@ async fn crash_between_permit_and_apply_leaves_no_terminal_report() { &target, None::<&FakeSource>, Duration::from_secs(30), + &AtomicBool::new(false), ), ) .await; @@ -755,17 +770,16 @@ async fn poll_runs_a_matching_lease() { assert!(log.lock().unwrap().contains(&"report:applied".to_owned())); } -/// Current behaviour, flagged in the report as a risk: a failed heartbeat report abandons the in-flight -/// restore future (and with it the apply, whose child processes are `kill_on_drop`), so a transient hub -/// blip mid-apply can kill a restore half way with no terminal report. Pinned so a deliberate change shows. +/// Before the apply permit nothing destructive has happened, so a failed heartbeat gives up on the lease +/// (the hub will expire it) rather than carrying on unobserved. #[tokio::test] -async fn failed_heartbeat_abandons_the_in_flight_restore() { +async fn failed_heartbeat_before_the_permit_abandons_the_restore() { let log = log(); let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); let lease = lease_for(target_id, application, false); - let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + let (mut hub, targets) = poll_fixture(&log, &lease, target_id); hub.fail_progress = Some("heartbeat"); - targets.get_mut(&target_id).unwrap().apply = Step::Hang; + hub.download = Step::Hang; let err = tokio::time::timeout( Duration::from_secs(5), poll( @@ -782,11 +796,68 @@ async fn failed_heartbeat_abandons_the_in_flight_restore() { .unwrap_err(); assert!(err.to_string().contains("hub unreachable")); let log = log.lock().unwrap().clone(); - assert!( - log.contains(&"target.apply".to_owned()), - "apply had started" - ); - assert!(log - .iter() - .all(|e| e != "report:applied" && !e.starts_with("failed:"))); + assert!(log.contains(&"hub.download".to_owned())); + assert!(log.iter().all(|e| e != "hub.apply-permit" + && e != "target.apply" + && e != "report:applied" + && !e.starts_with("failed:"))); +} + +/// After the permit is spent, dropping the restore would kill the apply half way (its children are +/// `kill_on_drop`). A failed heartbeat is only logged and the apply runs to its terminal report. +#[tokio::test] +async fn failed_heartbeat_after_the_permit_lets_the_apply_finish() { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = lease_for(target_id, application, false); + let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + hub.fail_progress = Some("heartbeat"); + targets.get_mut(&target_id).unwrap().apply = Step::Slow(300); + let did = tokio::time::timeout( + Duration::from_secs(5), + poll( + &hub, + application, + None::<&FakeSource>, + &targets, + 30, + Duration::from_millis(50), + ), + ) + .await + .expect("poll finishes") + .unwrap(); + assert!(did); + let log = log.lock().unwrap().clone(); + let beats = log.iter().filter(|e| *e == "report:heartbeat").count(); + assert!(beats >= 2, "heartbeats kept being attempted: {beats}"); + assert_eq!(log.last().map(String::as_str), Some("report:applied")); +} + +/// If the apply itself fails while heartbeats are failing, the failure is still reported. +#[tokio::test] +async fn failed_apply_is_still_reported_when_heartbeats_fail() { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = lease_for(target_id, application, false); + let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + hub.fail_progress = Some("heartbeat"); + targets.get_mut(&target_id).unwrap().apply = Step::Hang; + let err = tokio::time::timeout( + Duration::from_secs(5), + poll( + &hub, + application, + None::<&FakeSource>, + &targets, + 1, + Duration::from_millis(50), + ), + ) + .await + .expect("apply timeout ends the poll") + .unwrap(); + assert!(err); + let log = log.lock().unwrap().clone(); + assert!(log.iter().any(|e| e.starts_with("failed:apply_failed:"))); } From f4e42178e6cec7810a9e467984a9bebc43d8bbc3 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:24:40 +0700 Subject: [PATCH 4/7] test: boundary and property tests for the retention and decay evaluators Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-core/src/decay.rs | 394 +++++++++++++++++++++++++++++++ 1 file changed, 394 insertions(+) diff --git a/crates/tessera-core/src/decay.rs b/crates/tessera-core/src/decay.rs index 04c89ba..7691bbe 100644 --- a/crates/tessera-core/src/decay.rs +++ b/crates/tessera-core/src/decay.rs @@ -441,4 +441,398 @@ mod tests { assert!(manifest.is_restore_safety()); assert_eq!(manifest.safety_target().as_deref(), Some("t")); } + + // ---- boundaries ---- + + fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, sec: u32) -> DateTime { + Utc.with_ymd_and_hms(y, mo, d, h, mi, sec).unwrap() + } + + fn snap(taken_at: DateTime) -> SnapshotRef { + SnapshotRef { + id: Uuid::new_v4(), + taken_at, + } + } + + #[test] + fn capture_age_boundary_is_a_whole_number_of_days() { + let now = at(2026, 11, 20, 12, 0, 0); + let newest = snap(now); + let exactly = snap(now - Duration::days(14)); + let just_under = snap(now - Duration::days(14) + Duration::seconds(1)); + let policy = CaptureRetention::Age { days: 14 }; + let forgotten = evaluate_capture_retention( + policy, + vec![just_under.clone(), exactly.clone(), newest.clone()], + now, + ); + assert_eq!(forgotten, [exactly.id], "14 days old to the second goes"); + } + + #[test] + fn capture_retention_never_forgets_the_newest_even_when_ancient_or_in_the_future() { + let now = at(2026, 11, 20, 12, 0, 0); + for policy in [ + CaptureRetention::Age { days: 1 }, + CaptureRetention::Count { keep: 1 }, + ] { + let only = snap(now - Duration::days(4000)); + assert!(evaluate_capture_retention(policy, vec![only], now).is_empty()); + // a snapshot stamped in the future (clock skew) has negative age and is never expired + let future = snap(now + Duration::days(3)); + let old = snap(now - Duration::days(30)); + assert_eq!( + evaluate_capture_retention(policy, vec![old.clone(), future], now), + [old.id] + ); + } + assert!(evaluate_capture_retention(CaptureRetention::default(), vec![], now).is_empty()); + } + + #[test] + fn capture_count_boundaries() { + let now = at(2026, 11, 20, 12, 0, 0); + let snaps: Vec<_> = (0..4).map(|i| snap(now - Duration::hours(i))).collect(); + let count = |keep| { + evaluate_capture_retention(CaptureRetention::Count { keep }, snaps.clone(), now).len() + }; + assert_eq!(count(1), 3); + assert_eq!(count(3), 1); + assert_eq!(count(4), 0, "keeping exactly as many as exist forgets none"); + assert_eq!(count(u16::MAX), 0); + // keep 0 is rejected by validation, but must still not forget the newest if it slips through + assert!(!CaptureRetention::Count { keep: 0 }.is_valid()); + assert!(!CaptureRetention::Age { days: 0 }.is_valid()); + let forgotten = + evaluate_capture_retention(CaptureRetention::Count { keep: 0 }, snaps.clone(), now); + assert!(!forgotten.contains(&snaps[0].id)); + } + + #[test] + fn equal_timestamps_are_ordered_by_id_so_the_outcome_is_deterministic() { + let now = at(2026, 11, 20, 12, 0, 0); + let mut twins = vec![snap(now), snap(now), snap(now)]; + let keep_one = CaptureRetention::Count { keep: 1 }; + let first = evaluate_capture_retention(keep_one, twins.clone(), now); + twins.reverse(); + let second = evaluate_capture_retention(keep_one, twins, now); + assert_eq!(set(&first), set(&second)); + assert_eq!(first.len(), 2); + } + + #[test] + fn safety_age_boundary_is_seven_whole_days() { + let now = at(2026, 11, 30, 12, 0, 0); + let copy = |age: Duration| SafetyRef { + id: Uuid::new_v4(), + taken_at: now - age, + target: "t".into(), + }; + // three fresh copies fill the per-target quota, so age alone decides for the next two + let pad: Vec<_> = (1..=3).map(|i| copy(Duration::hours(i))).collect(); + let exactly_seven = copy(Duration::days(7)); + let just_under = copy(Duration::days(7) - Duration::seconds(1)); + let forgotten = evaluate_safety_retention( + pad.into_iter() + .chain([exactly_seven.clone(), just_under.clone()]) + .collect(), + now, + ); + assert_eq!( + forgotten, + [exactly_seven.id], + "exactly 7 days old is no longer recent; one second less still is" + ); + } + + #[test] + fn safety_retention_handles_empty_and_a_lone_ancient_copy() { + let now = at(2030, 1, 1, 0, 0, 0); + assert!(evaluate_safety_retention(vec![], now).is_empty()); + assert!(evaluate_safety_retention(vec![safety(1, "only")], now).is_empty()); + } + + #[test] + fn gfs_period_boundaries_are_utc_midnight_iso_weeks_and_calendar_years() { + let daily = RetentionPolicy { + keep_daily: 2, + ..Default::default() + }; + let last_second = snap(at(2025, 12, 31, 23, 59, 59)); + let first_second = snap(at(2026, 1, 1, 0, 0, 0)); + let earlier = snap(at(2025, 12, 31, 0, 0, 0)); + // 23:59:59 and 00:00:00 straddle a day, so both days count and each keeps its newest + assert_eq!( + evaluate_gfs( + &daily, + vec![earlier.clone(), last_second.clone(), first_second.clone()] + ), + [earlier.id] + ); + // ISO weeks: Sun 2024-12-29 is week 52; Mon 2024-12-30 and Wed 2025-01-01 are week 1 of 2025 + let weekly = RetentionPolicy { + keep_weekly: 2, + ..Default::default() + }; + let sunday = snap(at(2024, 12, 29, 12, 0, 0)); + let monday = snap(at(2024, 12, 30, 0, 0, 0)); + let wednesday = snap(at(2025, 1, 1, 12, 0, 0)); + assert_eq!( + evaluate_gfs(&weekly, vec![sunday, monday.clone(), wednesday]), + [monday.id] + ); + // ISO week 53 of 2020 spans the new year + let a = snap(at(2020, 12, 31, 1, 0, 0)); + let b = snap(at(2021, 1, 1, 1, 0, 0)); + let one_week = RetentionPolicy { + keep_weekly: 1, + ..Default::default() + }; + assert_eq!(evaluate_gfs(&one_week, vec![a.clone(), b]), [a.id]); + let yearly = RetentionPolicy { + keep_yearly: 1, + ..Default::default() + }; + assert_eq!( + evaluate_gfs(&yearly, vec![first_second.clone(), last_second.clone()]), + [last_second.id] + ); + // the same month number in another year is a different month + let monthly = RetentionPolicy { + keep_monthly: 2, + ..Default::default() + }; + let jan25 = snap(at(2025, 1, 15, 0, 0, 0)); + let jan26 = snap(at(2026, 1, 15, 0, 0, 0)); + let jan26_early = snap(at(2026, 1, 2, 0, 0, 0)); + assert_eq!( + evaluate_gfs(&monthly, vec![jan25, jan26, jan26_early.clone()]), + [jan26_early.id] + ); + } + + #[test] + fn gfs_edge_inputs() { + let all_tiers = RetentionPolicy { + keep_daily: 3, + keep_weekly: 3, + keep_monthly: 3, + keep_yearly: 3, + }; + assert!(evaluate_gfs(&all_tiers, vec![]).is_empty()); + assert!(evaluate_gfs(&all_tiers, vec![snap(at(2020, 2, 29, 0, 0, 0))]).is_empty()); + // all tiers zero means no policy, which keeps everything rather than forgetting everything + let many: Vec<_> = (1..=5).map(|d| snap(at(2026, 1, d, 0, 0, 0))).collect(); + assert!(evaluate_gfs(&RetentionPolicy::default(), many.clone()).is_empty()); + let huge = RetentionPolicy { + keep_daily: u32::MAX, + keep_weekly: u32::MAX, + keep_monthly: u32::MAX, + keep_yearly: u32::MAX, + }; + assert!(evaluate_gfs(&huge, many).is_empty()); + } + + // ---- properties, over seeded pseudo-random histories (no extra dependency) ---- + + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + } + + fn history(rng: &mut Rng, now: DateTime) -> Vec { + let n = rng.below(60); + (0..n) + .map(|_| { + // about three years at second resolution, with some collisions on whole hours + let secs = rng.below(3 * 365 * 86_400) as i64; + let secs = if rng.below(4) == 0 { + secs - secs % 3600 + } else { + secs + }; + snap(now - Duration::seconds(secs)) + }) + .collect() + } + + fn random_policy(rng: &mut Rng) -> RetentionPolicy { + RetentionPolicy { + keep_daily: rng.below(10) as u32, + keep_weekly: rng.below(10) as u32, + keep_monthly: rng.below(14) as u32, + keep_yearly: rng.below(5) as u32, + } + } + + fn survivors(all: &[SnapshotRef], forgotten: &[Uuid]) -> Vec { + all.iter() + .filter(|s| !forgotten.contains(&s.id)) + .cloned() + .collect() + } + + fn shuffled(rng: &mut Rng, mut v: Vec) -> Vec { + for i in (1..v.len()).rev() { + v.swap(i, rng.below(i as u64 + 1) as usize); + } + v + } + + fn set(ids: &[Uuid]) -> HashSet { + ids.iter().copied().collect() + } + + fn newest(all: &[SnapshotRef]) -> Option<&SnapshotRef> { + all.iter().max_by_key(|s| (s.taken_at, s.id)) + } + + #[test] + fn gfs_properties_hold_for_random_histories() { + let now = at(2026, 11, 20, 12, 0, 0); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + for _ in 0..400 { + let all = history(&mut rng, now); + let policy = random_policy(&mut rng); + let forgotten = evaluate_gfs(&policy, all.clone()); + let ids: Vec<_> = all.iter().map(|s| s.id).collect(); + // only names snapshots it was given, each at most once + assert!(set(&forgotten).is_subset(&set(&ids))); + assert_eq!(set(&forgotten).len(), forgotten.len()); + // the newest survives whenever any tier is switched on + if policy.has_tiers() { + if let Some(newest) = newest(&all) { + assert!(!forgotten.contains(&newest.id), "{policy:?}"); + } + } else { + assert!(forgotten.is_empty()); + } + // input order is irrelevant + let again = evaluate_gfs(&policy, shuffled(&mut rng, all.clone())); + assert_eq!(set(&forgotten), set(&again)); + // applying the policy to what is left forgets nothing more + let left = survivors(&all, &forgotten); + assert!(evaluate_gfs(&policy, left).is_empty(), "{policy:?}"); + // keeping more of any tier never forgets more + let wider = RetentionPolicy { + keep_daily: policy.keep_daily + rng.below(3) as u32, + keep_weekly: policy.keep_weekly + rng.below(3) as u32, + keep_monthly: policy.keep_monthly + rng.below(3) as u32, + keep_yearly: policy.keep_yearly + rng.below(3) as u32, + }; + assert!(set(&evaluate_gfs(&wider, all)).is_subset(&set(&forgotten))); + } + } + + #[test] + fn capture_retention_properties_hold_for_random_histories() { + let now = at(2026, 11, 20, 12, 0, 0); + let mut rng = Rng(0xD1B5_4A32_D192_ED03); + for _ in 0..400 { + let all = history(&mut rng, now); + let policy = if rng.below(2) == 0 { + CaptureRetention::Age { + days: 1 + rng.below(400) as u16, + } + } else { + CaptureRetention::Count { + keep: 1 + rng.below(20) as u16, + } + }; + let forgotten = evaluate_capture_retention(policy, all.clone(), now); + assert_eq!(set(&forgotten).len(), forgotten.len()); + if let Some(newest) = newest(&all) { + assert!(!forgotten.contains(&newest.id)); + } + let left = survivors(&all, &forgotten); + assert!(evaluate_capture_retention(policy, left, now).is_empty()); + let again = evaluate_capture_retention(policy, shuffled(&mut rng, all.clone()), now); + assert_eq!(set(&forgotten), set(&again)); + if let CaptureRetention::Count { keep } = policy { + assert_eq!( + all.len() - forgotten.len(), + all.len().min(usize::from(keep)) + ); + } + } + } + + #[test] + fn safety_retention_properties_hold_for_random_histories() { + let now = at(2026, 11, 30, 12, 0, 0); + let mut rng = Rng(0x2545_F491_4F6C_DD1D); + for _ in 0..400 { + let all: Vec = (0..rng.below(30)) + .map(|_| SafetyRef { + id: Uuid::new_v4(), + taken_at: now - Duration::seconds(rng.below(60 * 86_400) as i64), + target: format!("t{}", rng.below(3)), + }) + .collect(); + let forgotten = evaluate_safety_retention(all.clone(), now); + assert_eq!(set(&forgotten).len(), forgotten.len()); + for copy in all.iter().filter(|c| forgotten.contains(&c.id)) { + // forgotten means old AND outside its target's newest three + assert!(now.signed_duration_since(copy.taken_at).num_days() >= SAFETY_KEEP_DAYS); + let newer = all + .iter() + .filter(|o| { + o.target == copy.target && (o.taken_at, o.id) > (copy.taken_at, copy.id) + }) + .count(); + assert!(newer >= SAFETY_KEEP_PER_TARGET); + } + for target in ["t0", "t1", "t2"] { + let newest = all + .iter() + .filter(|c| c.target == target) + .max_by_key(|c| (c.taken_at, c.id)); + if let Some(newest) = newest { + assert!(!forgotten.contains(&newest.id)); + } + } + let left: Vec<_> = all + .iter() + .filter(|c| !forgotten.contains(&c.id)) + .cloned() + .collect(); + assert!(evaluate_safety_retention(left, now).is_empty()); + } + } + + #[test] + fn legacy_decay_properties_hold_for_random_histories() { + let now = at(2026, 11, 20, 12, 0, 0); + let mut rng = Rng(0xA076_1D64_78BD_642F); + for _ in 0..400 { + let all = history(&mut rng, now); + let policy = DecayPolicy { + keep_daily: rng.below(10) as usize, + keep_weekly: rng.below(8) as usize, + keep_monthly: rng.below(14) as usize, + }; + let forgotten = evaluate_decay(&policy, all.clone()); + assert_eq!(set(&forgotten).len(), forgotten.len()); + let ids: Vec<_> = all.iter().map(|s| s.id).collect(); + assert!(set(&forgotten).is_subset(&set(&ids))); + if policy.keep_daily + policy.keep_weekly + policy.keep_monthly > 0 { + if let Some(newest) = newest(&all) { + assert!(!forgotten.contains(&newest.id)); + } + } + let left = survivors(&all, &forgotten); + assert!(evaluate_decay(&policy, left).is_empty()); + } + } } From 460f6f4db6d8e093d45a468df2cd1eb554462681 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:26:32 +0700 Subject: [PATCH 5/7] fix: reserve disk for admitted exports so concurrent downloads cannot share the same free space Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-hub/src/exports.rs | 93 ++++++++++++++++++++++++++++--- 1 file changed, 86 insertions(+), 7 deletions(-) diff --git a/crates/tessera-hub/src/exports.rs b/crates/tessera-hub/src/exports.rs index c12ced0..31fa1db 100644 --- a/crates/tessera-hub/src/exports.rs +++ b/crates/tessera-hub/src/exports.rs @@ -10,7 +10,10 @@ use axum::body::Bytes; use futures_core::Stream; use std::io; use std::pin::Pin; -use std::sync::Arc; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; use std::task::{Context, Poll}; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use uuid::Uuid; @@ -170,6 +173,26 @@ pub struct ExportGate { permits: Arc, /// Free space that must remain after the export has been written. min_free: u64, + /// Bytes promised to exports that are admitted and not finished yet. Free space alone cannot say + /// that, because an export that has only just started has barely written anything. + reserved: Arc, +} + +/// The most one export may reserve: 64 of them (the concurrency ceiling) still fit in a `u64`. +const MAX_RESERVATION: u64 = 1 << 57; + +/// An admitted export: its place among the running ones and the disk it was promised. Both are given +/// back when this is dropped. +pub struct Admission { + _permit: OwnedSemaphorePermit, + reserved: Arc, + size: u64, +} + +impl Drop for Admission { + fn drop(&mut self) { + self.reserved.fetch_sub(self.size, Ordering::SeqCst); + } } pub enum Refused { @@ -184,6 +207,7 @@ impl ExportGate { Self { permits: Arc::new(Semaphore::new(concurrency)), min_free, + reserved: Arc::default(), } } @@ -200,17 +224,31 @@ impl ExportGate { ) } - /// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body. - pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result { + /// Admit one export of about `size` bytes into `dir`. The slot and the bytes are held for as long as the + /// response body, so exports admitted together cannot each count on the same free space. + pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result { let permit = self .permits .clone() .try_acquire_owned() .map_err(|_| Refused::Busy)?; + // No disk is that large, and the cap keeps the running total from overflowing. + let size = size.min(MAX_RESERVATION); + // Reserve first, then check: concurrent callers can only over-refuse, never over-admit. + let earlier = self.reserved.fetch_add(size, Ordering::SeqCst); + let admission = Admission { + _permit: permit, + reserved: self.reserved.clone(), + size, + }; match free_bytes(dir) { // `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies. - Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace), - _ => Ok(permit), + // Bytes already written by running exports are no longer free and are counted again in `earlier`; being + // that cautious is deliberate. + Some(free) if free < earlier.saturating_add(size).saturating_add(self.min_free) => { + Err(Refused::NoSpace) + } + _ => Ok(admission), } } } @@ -248,7 +286,7 @@ pub fn sweep_stale(data_dir: &std::path::Path) -> usize { /// the client went away, or the response was discarded) releases the permit and deletes the export. pub struct Guarded { inner: Pin>, - _permit: OwnedSemaphorePermit, + _permit: Admission, _dir: tempfile::TempDir, db: Db, principal: Principal, @@ -261,7 +299,7 @@ pub struct Guarded { impl Guarded { pub fn new( inner: S, - permit: OwnedSemaphorePermit, + permit: Admission, dir: tempfile::TempDir, db: Db, principal: Principal, @@ -596,4 +634,45 @@ mod tests { "a snapshot bigger than the disk" ); } + + #[test] + fn concurrent_exports_cannot_each_count_on_the_same_free_space() { + let dir = tempfile::tempdir().unwrap(); + let free = free_bytes(dir.path()).expect("statvfs works on the temp dir"); + // each export needs a bit over a third of what is free, so two fit on paper but not together + // (the disk may move under us a little, which is why the margin is generous) + let size = free / 3 + free / 20; + let gate = ExportGate::new(8, 0); + let first = gate.admit(dir.path(), size).ok().expect("one fits"); + let second = gate.admit(dir.path(), size).ok().expect("two fit"); + assert!( + matches!(gate.admit(dir.path(), size), Err(Refused::NoSpace)), + "the third would need more than the disk has once the first two are counted" + ); + drop(first); + assert!( + gate.admit(dir.path(), size).is_ok(), + "a finished export gives its bytes back" + ); + drop(second); + } + + #[test] + fn a_refused_export_leaves_nothing_reserved() { + let dir = tempfile::tempdir().unwrap(); + let gate = ExportGate::new(2, 0); + for _ in 0..3 { + assert!(matches!( + gate.admit(dir.path(), u64::MAX), + Err(Refused::NoSpace) + )); + } + assert_eq!(gate.reserved.load(Ordering::SeqCst), 0); + let busy = ExportGate::new(1, 0); + let held = busy.admit(dir.path(), 5).ok().unwrap(); + assert!(matches!(busy.admit(dir.path(), 7), Err(Refused::Busy))); + assert_eq!(busy.reserved.load(Ordering::SeqCst), 5); + drop(held); + assert_eq!(busy.reserved.load(Ordering::SeqCst), 0); + } } From d98d8354db246415870403f49a4cee0a3b6d73f4 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:28:19 +0700 Subject: [PATCH 6/7] test: pairing negatives (auth, bad names, malformed bodies, replay, expiry, audit) Co-Authored-By: Claude Sonnet 5.5 --- .../tessera-hub/src/api/credentials_tests.rs | 272 ++++++++++++++++++ 1 file changed, 272 insertions(+) diff --git a/crates/tessera-hub/src/api/credentials_tests.rs b/crates/tessera-hub/src/api/credentials_tests.rs index 8a9b4b9..f89183d 100644 --- a/crates/tessera-hub/src/api/credentials_tests.rs +++ b/crates/tessera-hub/src/api/credentials_tests.rs @@ -582,3 +582,275 @@ async fn sso_endpoints_are_rate_limited_per_source() { ); assert!(h.state.limits.oidc_login_allowed(other)); } + +// ---- pairing, the ways it must say no ---- + +const START: &str = "/api/v1/wormhole/pairing"; +const CLAIM: &str = "/api/v1/wormhole/claim"; + +/// A different source address each time, so the per-source claim limit does not interfere. +fn fresh_peer() -> String { + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + format!("192.0.{}.{}", (n >> 8) & 255, n & 255) +} + +impl Harness { + async fn start_code(&self) -> String { + let start = self + .call(request("POST", START, "127.0.0.1", Some(ADMIN), None)) + .await; + assert_eq!(start.status(), StatusCode::OK); + json_of(start).await["code"].as_str().unwrap().to_string() + } + + async fn claim(&self, _peer: &str, body: Value) -> Response { + self.call(request("POST", CLAIM, &fresh_peer(), None, Some(body))) + .await + } + + fn outposts(&self) -> i64 { + self.scalar("SELECT COUNT(*) FROM outposts") + } + + fn credentials(&self) -> i64 { + self.scalar("SELECT COUNT(*) FROM outpost_credentials") + } +} + +#[tokio::test] +async fn only_an_admin_can_start_a_pairing() { + let h = harness().await; + for auth in [None, Some("wrong-token"), Some("")] { + let status = h + .status(request("POST", START, "127.0.0.1", auth, None)) + .await; + assert!( + status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN, + "{auth:?} must not start a pairing, got {status}" + ); + } + // a paired agent's upload token is not an operator credential either + let (_, token) = h.pair("agent").await; + let status = h + .status(as_outpost( + request("POST", START, "198.51.100.20", None, None), + &token, + )) + .await; + assert!( + status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN, + "an outpost token must not start a pairing, got {status}" + ); + let codes: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes WHERE consumed_at IS NULL"); + assert_eq!(codes, 0, "a refused request leaves no code behind"); +} + +#[tokio::test] +async fn a_started_code_is_twelve_unambiguous_characters_valid_for_about_ten_minutes() { + let h = harness().await; + let start = h + .call(request("POST", START, "127.0.0.1", Some(ADMIN), None)) + .await; + let body = json_of(start).await; + let code = body["code"].as_str().unwrap(); + assert_eq!(code.len(), 12); + assert!( + code.chars() + .all(|c| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(c)), + "no 0/O/1/I lookalikes: {code}" + ); + let expires = chrono::DateTime::parse_from_rfc3339(body["expires_at"].as_str().unwrap()) + .unwrap() + .timestamp(); + let in_secs = expires - chrono::Utc::now().timestamp(); + assert!((595..=600).contains(&in_secs), "expires in {in_secs}s"); + assert_ne!(code, h.start_code().await, "codes are not repeated"); +} + +#[tokio::test] +async fn a_claim_that_is_refused_creates_no_outpost_and_no_credential() { + let h = harness().await; + let code = h.start_code().await; + let lower = code.to_lowercase(); + let spaced = format!(" {code} "); + let truncated = code[..11].to_string(); + for wrong in [ + lower.as_str(), + spaced.as_str(), + truncated.as_str(), + "", + "AAAAAAAAAAAA", + "'; DROP TABLE pairing_codes;--", + ] { + let response = h + .claim("198.51.100.20", json!({"code": wrong, "outpost_name": "x"})) + .await; + assert_eq!(response.status(), StatusCode::GONE, "code {wrong:?}"); + } + assert_eq!((h.outposts(), h.credentials()), (0, 0)); + let failed: i64 = h.scalar( + "SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'", + ); + assert_eq!(failed, 6, "every refusal is audited"); + let leaked: i64 = h.scalar(&format!( + "SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{code}%'" + )); + assert_eq!(leaked, 0, "the code is never written to the audit log"); + // the real code still works afterwards: wrong guesses do not burn it + let ok = h + .claim( + "198.51.100.20", + json!({"code": code, "outpost_name": "real"}), + ) + .await; + assert_eq!(ok.status(), StatusCode::OK); +} + +#[tokio::test] +async fn a_claim_with_a_bad_name_is_refused_before_the_code_is_spent() { + let h = harness().await; + let code = h.start_code().await; + let too_long = "n".repeat(129); + for name in [ + "", + " ", + "\t\n", + "tab\there", + "nul\u{0}byte", + too_long.as_str(), + ] { + let response = h + .claim("198.51.100.20", json!({"code": code, "outpost_name": name})) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "name {name:?}"); + } + assert_eq!(h.outposts(), 0); + let longest = "n".repeat(128); + let ok = h + .claim( + "198.51.100.20", + json!({"code": code, "outpost_name": longest}), + ) + .await; + assert_eq!(ok.status(), StatusCode::OK, "128 characters is allowed"); + assert_eq!(h.outposts(), 1); +} + +#[tokio::test] +async fn malformed_claims_are_client_errors_and_never_touch_a_code() { + let h = harness().await; + let code = h.start_code().await; + for body in [ + json!({}), + json!({"code": code}), + json!({"outpost_name": "x"}), + json!({"code": 12345, "outpost_name": "x"}), + json!({"code": null, "outpost_name": "x"}), + json!({"code": ["a"], "outpost_name": "x"}), + ] { + let status = h.claim("198.51.100.20", body.clone()).await.status(); + assert!( + status.is_client_error() && status != StatusCode::GONE, + "{body} gave {status}" + ); + } + let good = format!(r#"{{"code":"{code}","outpost_name":"x"}}"#); + let raw = |content_type: Option<&str>, body: &str| { + let mut builder = Request::builder() + .method("POST") + .uri(CLAIM) + .extension(ConnectInfo( + format!("{}:4000", fresh_peer()) + .parse::() + .unwrap(), + )); + if let Some(content_type) = content_type { + builder = builder.header(header::CONTENT_TYPE, content_type); + } + builder.body(Body::from(body.to_string())).unwrap() + }; + for request in [ + raw(Some("application/json"), "{not json"), + raw(None, &good), + raw(Some("text/plain"), &good), + ] { + let status = h.status(request).await; + assert!(status.is_client_error(), "got {status}"); + } + assert_eq!((h.outposts(), h.credentials()), (0, 0)); + let ok = h + .claim("198.51.100.20", json!({"code": code, "outpost_name": "x"})) + .await; + assert_eq!( + ok.status(), + StatusCode::OK, + "the code survived every bad request" + ); +} + +#[tokio::test] +async fn an_enormous_code_is_refused_without_trouble() { + let h = harness().await; + let huge = "A".repeat(1 << 20); + let status = h + .claim("198.51.100.20", json!({"code": huge, "outpost_name": "x"})) + .await + .status(); + assert!( + status == StatusCode::GONE || status == StatusCode::PAYLOAD_TOO_LARGE, + "got {status}" + ); + assert_eq!((h.outposts(), h.credentials()), (0, 0)); +} + +#[tokio::test] +async fn a_claimed_code_cannot_be_replayed_and_the_replay_is_audited() { + let h = harness().await; + let code = h.start_code().await; + let first = h + .claim( + "198.51.100.20", + json!({"code": code, "outpost_name": "first"}), + ) + .await; + assert_eq!(first.status(), StatusCode::OK); + let second = h + .claim( + "198.51.100.21", + json!({"code": code, "outpost_name": "second"}), + ) + .await; + assert_eq!(second.status(), StatusCode::GONE); + assert_eq!((h.outposts(), h.credentials()), (1, 1), "no second outpost"); + let failed: i64 = h.scalar( + "SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'", + ); + assert_eq!(failed, 1); +} + +#[tokio::test] +async fn an_expired_code_is_refused_and_old_ones_are_swept_by_the_next_pairing() { + let h = harness().await; + let now = chrono::Utc::now().timestamp(); + h.state + .db + .insert_pairing("old-outpost", "STALECODE234", now - 1) + .unwrap(); + h.state + .db + .insert_pairing("ancient-outpost", "ANCIENTCODE2", now - 200_000) + .unwrap(); + let response = h + .claim( + "198.51.100.20", + json!({"code": "STALECODE234", "outpost_name": "late"}), + ) + .await; + assert_eq!(response.status(), StatusCode::GONE); + assert_eq!((h.outposts(), h.credentials()), (0, 0)); + h.start_code().await; + // a code that expired a moment ago lingers (the claim still refuses it); one a day old is deleted + let rows: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes"); + assert_eq!(rows, 2, "the recent stale code and the fresh one remain"); +} From 6ab788fcda516a57f18875fb059efd4ca73e699a Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:30:24 +0700 Subject: [PATCH 7/7] test: cover legacy-import with a stand-in aws (inventory, import, resume, history) The AWS program becomes a skipped clap field so tests can substitute a fake; run is split into reconcile (returns the report) and a printing wrapper. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-cli/src/legacy_import.rs | 510 +++++++++++++++++++++++- 1 file changed, 505 insertions(+), 5 deletions(-) diff --git a/crates/tessera-cli/src/legacy_import.rs b/crates/tessera-cli/src/legacy_import.rs index 06bb1d4..96744c7 100644 --- a/crates/tessera-cli/src/legacy_import.rs +++ b/crates/tessera-cli/src/legacy_import.rs @@ -33,6 +33,9 @@ pub struct ImportArgs { /// Reconcile counts, times and sizes without downloading or writing snapshots. #[arg(long)] inventory_only: bool, + /// The AWS CLI to run; a field only so tests can substitute a fake one. + #[arg(skip = PathBuf::from("aws"))] + program: PathBuf, } #[derive(Clone, Copy, ValueEnum)] @@ -96,6 +99,12 @@ struct Report { } pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { + let report = reconcile(vault, args)?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) +} + +fn reconcile(vault: &Vault, args: ImportArgs) -> Result { ensure!( !args.prefix.is_empty() && args.prefix.ends_with('/'), "provide a per-application prefix ending in '/'" @@ -173,7 +182,7 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { .map(|path| import_history(vault, path)) .transpose()? }; - let report = Report { + Ok(Report { application: args.application, bucket: args.bucket, prefix: args.prefix, @@ -181,13 +190,11 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { bytes, history_snapshot_id, objects, - }; - println!("{}", serde_json::to_string_pretty(&report)?); - Ok(()) + }) } fn aws(args: &ImportArgs, operation: &str) -> Command { - let mut cmd = Command::new("aws"); + let mut cmd = Command::new(&args.program); cmd.args([ "--no-cli-pager", "--no-cli-auto-prompt", @@ -285,3 +292,496 @@ fn import_history(vault: &Vault, path: &std::path::Path) -> Result { vault.import_legacy_payload(manifest, staged, taken_at)?; Ok(id) } + +/// These drive `reconcile` against a stand-in `aws` (a shell script that serves a local directory), so the +/// listing, conditional download, receipts and history paths all run for real; only S3 is faked. +#[cfg(all(test, unix))] +mod tests { + use super::*; + use serde_json::{json, Value}; + use std::{fs, os::unix::fs::PermissionsExt, path::Path}; + + const ETAG: &str = "\"9b2cf535f27731c974343645a3985328\""; + const WHEN: &str = "2026-01-02T03:04:05+00:00"; + + struct Fixture { + dir: tempfile::TempDir, + vault: Vault, + listing: Vec, + } + + impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let vault = Vault::init(dir.path().join("vault"), "synthetic-passphrase").unwrap(); + let fake = dir.path().join("fake"); + fs::create_dir_all(fake.join("obj")).unwrap(); + fs::create_dir_all(fake.join("meta")).unwrap(); + let script = format!( + r#"#!/bin/sh +D='{}' +op="$6" +echo "$op" >> "$D/calls" +case "$op" in + list-objects-v2) + [ -f "$D/list.fail" ] && exit 1 + cat "$D/list.json" ;; + get-object) + for a in "$@"; do + last="$a" + case "$a" in --key=*) key="${{a#--key=}}" ;; esac + done + name=$(basename "$key") + [ -f "$D/get.fail.$name" ] && exit 1 + cp "$D/obj/$name" "$last" + cat "$D/meta/$name.json" ;; +esac +"#, + fake.display() + ); + let program = dir.path().join("aws"); + fs::write(&program, script).unwrap(); + fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap(); + let fixture = Self { + dir, + vault, + listing: vec![], + }; + fixture.publish(); + fixture + } + + fn fake(&self) -> std::path::PathBuf { + self.dir.path().join("fake") + } + + fn publish(&self) { + fs::write( + self.fake().join("list.json"), + json!({ "Contents": self.listing }).to_string(), + ) + .unwrap(); + } + + /// Put an object in the listing and on the fake bucket, with matching download metadata. + fn add(&mut self, key: &str, body: &[u8]) { + self.add_listed(key, body, body.len() as u64, ETAG); + let name = key.rsplit('/').next().unwrap(); + fs::write(self.fake().join("obj").join(name), body).unwrap(); + self.meta(key, ETAG, body.len() as u64, WHEN); + } + + /// Only the listing entry, for metadata the object itself would not match. + fn add_listed(&mut self, key: &str, _body: &[u8], size: u64, etag: &str) { + self.listing.push(json!({ + "Key": key, "ETag": etag, "Size": size, "LastModified": WHEN + })); + self.publish(); + } + + fn meta(&self, key: &str, etag: &str, length: u64, modified: &str) { + let name = key.rsplit('/').next().unwrap(); + fs::write( + self.fake().join("meta").join(format!("{name}.json")), + json!({"ETag": etag, "ContentLength": length, "LastModified": modified}) + .to_string(), + ) + .unwrap(); + } + + fn calls(&self) -> Vec { + fs::read_to_string(self.fake().join("calls")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } + + fn args(&self) -> ImportArgs { + ImportArgs { + bucket: "legacy-bucket".into(), + prefix: "backups/shop/".into(), + endpoint: None, + orbit_id: Uuid::from_u128(7), + application: "shop".into(), + engine: Engine::Postgres, + history: None, + inventory_only: false, + program: self.dir.path().join("aws"), + } + } + + fn run(&self, args: ImportArgs) -> Result { + reconcile(&self.vault, args) + } + + fn snapshots(&self) -> usize { + self.vault.list_snapshots().unwrap().len() + } + + fn receipts(&self) -> usize { + fs::read_dir(self.vault.root().join("keys/legacy-imports")) + .map(|entries| entries.count()) + .unwrap_or(0) + } + } + + fn gzip_header(rest: &[u8]) -> Vec { + [&[0x1f, 0x8b][..], rest].concat() + } + + fn statuses(report: &Report) -> Vec<&'static str> { + report.objects.iter().map(|o| o.status).collect() + } + + // ---- arguments are validated before anything is listed ---- + + #[test] + fn bad_arguments_are_refused_before_aws_is_run() { + let fx = Fixture::new(); + type Tweak = fn(&mut ImportArgs); + let cases: [(&str, Tweak); 11] = [ + ("empty prefix", |a| a.prefix = String::new()), + ("prefix without a trailing slash", |a| { + a.prefix = "backups/shop".into() + }), + ("blank application", |a| a.application = " ".into()), + ("long application", |a| a.application = "a".repeat(129)), + ("control in application", |a| { + a.application = "sh\nop".into() + }), + ("plain http endpoint", |a| { + a.endpoint = Some("http://s3.example.com".into()) + }), + ("http on another loopback port form", |a| { + a.endpoint = Some("http://localhost:9000".into()) + }), + ("credentials in the endpoint", |a| { + a.endpoint = Some("https://user:pw@s3.example.com".into()) + }), + ("query in the endpoint", |a| { + a.endpoint = Some("https://s3.example.com/?x=1".into()) + }), + ("fragment in the endpoint", |a| { + a.endpoint = Some("https://s3.example.com/#x".into()) + }), + ("newline in the endpoint", |a| { + a.endpoint = Some("https://s3.example.com/\nx".into()) + }), + ]; + for (what, tweak) in cases { + let mut args = fx.args(); + tweak(&mut args); + assert!(fx.run(args).is_err(), "{what} must be refused"); + } + assert!(fx.calls().is_empty(), "aws was never run"); + let mut ok = fx.args(); + ok.endpoint = Some("http://127.0.0.1:9000".into()); + assert!(fx.run(ok).is_ok(), "a local test endpoint is allowed"); + let mut ok = fx.args(); + ok.endpoint = Some("https://s3.example.com".into()); + assert!(fx.run(ok).is_ok()); + } + + // ---- inventory ---- + + #[test] + fn inventory_counts_only_sql_archives_under_the_prefix_and_writes_nothing() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"select 1;"); + fx.add("backups/shop/b.sql.gz", &gzip_header(b"zz")); + fx.add("backups/shop/readme.txt", b"not a dump"); + fx.add("backups/shop/nested/c.sql", b"select 3;"); + fx.add("backups/shop/d.sql.bak", b"select 4;"); + fx.add("backups/other/e.sql", b"another application"); + fx.add("backups/shopping/f.sql", b"prefix lookalike"); + let mut args = fx.args(); + args.inventory_only = true; + let report = fx.run(args).unwrap(); + assert_eq!(report.count, 3, "a, b and nested/c"); + assert_eq!(report.bytes, 9 + 4 + 9); + assert_eq!(statuses(&report), ["inventoried"; 3]); + assert!(report.history_snapshot_id.is_none()); + assert_eq!(fx.snapshots(), 0); + assert_eq!(fx.receipts(), 0); + assert_eq!(fx.calls(), ["list-objects-v2"], "no object was downloaded"); + } + + #[test] + fn inventory_only_ignores_a_history_export() { + let fx = Fixture::new(); + let history = fx.dir.path().join("history.sqlite"); + fs::write(&history, b"SQLite format 3\0 rows").unwrap(); + let mut args = fx.args(); + args.inventory_only = true; + args.history = Some(history); + let report = fx.run(args).unwrap(); + assert!(report.history_snapshot_id.is_none()); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn an_empty_or_missing_listing_is_a_clean_zero() { + let fx = Fixture::new(); + let report = fx.run(fx.args()).unwrap(); + assert_eq!((report.count, report.bytes), (0, 0)); + fs::write(fx.fake().join("list.json"), "{}").unwrap(); + assert_eq!(fx.run(fx.args()).unwrap().count, 0); + } + + #[test] + fn listing_failures_stop_the_run() { + let fx = Fixture::new(); + fs::write(fx.fake().join("list.fail"), "").unwrap(); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("could not list"), "{err:#}"); + fs::remove_file(fx.fake().join("list.fail")).unwrap(); + for broken in [ + "", + "not json", + r#"{"Contents":[{"Key":"x"}]}"#, + r#"{"Contents":"x"}"#, + ] { + fs::write(fx.fake().join("list.json"), broken).unwrap(); + assert!(fx.run(fx.args()).is_err(), "listing {broken:?}"); + } + let missing = ImportArgs { + program: fx.dir.path().join("no-such-aws"), + ..fx.args() + }; + assert!(fx.run(missing).is_err(), "no aws binary is an error"); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn untrustworthy_inventory_metadata_is_refused() { + for (size, etag) in [(0, ETAG), (5, ""), (5, "*")] { + let mut fx = Fixture::new(); + fx.add_listed("backups/shop/a.sql", b"", size, etag); + let err = fx.run(fx.args()).err().unwrap(); + assert!( + format!("{err:#}").contains("invalid legacy archive metadata"), + "size {size} etag {etag:?}: {err:#}" + ); + assert_eq!(fx.snapshots(), 0); + } + } + + #[test] + fn an_inventory_whose_sizes_overflow_is_refused() { + let mut fx = Fixture::new(); + fx.add_listed("backups/shop/a.sql", b"", u64::MAX, ETAG); + fx.add_listed("backups/shop/b.sql", b"", 2, "\"other\""); + let mut args = fx.args(); + args.inventory_only = true; + let err = fx.run(args).err().unwrap(); + assert!(format!("{err:#}").contains("overflow"), "{err:#}"); + } + + // ---- import ---- + + #[test] + fn importing_stores_each_archive_once_and_a_rerun_changes_nothing() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + fx.add("backups/shop/b.sql.gz", &gzip_header(b"compressed")); + let first = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&first), ["imported", "imported"]); + assert_eq!((fx.snapshots(), fx.receipts()), (2, 2)); + let stored = fx + .vault + .get_snapshot(first.objects[0].snapshot_id) + .unwrap() + .expect("stored under the reported id"); + assert_eq!(stored.manifest.orbit_id, Uuid::from_u128(7)); + assert_eq!(stored.manifest.orbit_name, "shop"); + assert_eq!(stored.manifest.provider, "postgres"); + assert_eq!(stored.manifest.labels, ["legacy-import"]); + assert_eq!(stored.manifest.restore_hints["format"], "plain"); + assert_eq!(stored.manifest.restore_hints["legacy"]["etag"], ETAG); + let gz = fx + .vault + .get_snapshot(first.objects[1].snapshot_id) + .unwrap() + .unwrap(); + assert_eq!(gz.manifest.restore_hints["format"], "sql_gzip"); + assert_eq!( + stored.taken_at, + "2026-01-02T03:04:05Z".parse::>().unwrap(), + "the snapshot keeps the original time, not the import time" + ); + let calls_before = fx.calls().len(); + let second = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&second), ["already_imported", "already_imported"]); + assert_eq!( + fx.calls().len(), + calls_before + 1, + "the rerun listed but downloaded nothing" + ); + assert_eq!((fx.snapshots(), fx.receipts()), (2, 2)); + assert_eq!( + first.objects[0].snapshot_id, second.objects[0].snapshot_id, + "ids are derived, so a rerun finds its own work" + ); + } + + #[test] + fn the_engine_orbit_and_endpoint_decide_the_mysql_manifest_and_the_snapshot_id() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + let mut mysql = fx.args(); + mysql.engine = Engine::Mysql; + let first = fx.run(mysql).unwrap(); + let stored = fx + .vault + .get_snapshot(first.objects[0].snapshot_id) + .unwrap() + .unwrap(); + assert_eq!(stored.manifest.provider, "mysql"); + // another orbit is a different import of the same bytes, not a duplicate + let mut other = fx.args(); + other.orbit_id = Uuid::from_u128(8); + let second = fx.run(other).unwrap(); + assert_ne!(first.objects[0].snapshot_id, second.objects[0].snapshot_id); + assert_eq!(statuses(&second), ["imported"]); + // so is another endpoint + let mut elsewhere = fx.args(); + elsewhere.endpoint = Some("https://s3.example.com".into()); + let third = fx.run(elsewhere).unwrap(); + assert_ne!(first.objects[0].snapshot_id, third.objects[0].snapshot_id); + assert_eq!(fx.snapshots(), 3); + } + + #[test] + fn an_object_that_changed_since_the_inventory_is_not_imported() { + for (what, etag, length, modified) in [ + ("etag", "\"changed\"", 17, WHEN), + ("length", ETAG, 18, WHEN), + ("time", ETAG, 17, "2026-01-02T03:04:06+00:00"), + ] { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + fx.meta("backups/shop/a.sql", etag, length, modified); + let err = fx.run(fx.args()).err().unwrap(); + assert!( + format!("{err:#}").contains("changed since inventory"), + "{what}: {err:#}" + ); + assert_eq!((fx.snapshots(), fx.receipts()), (0, 0), "{what}"); + } + } + + #[test] + fn a_downloaded_file_of_the_wrong_size_is_not_imported() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + // the metadata agrees with the listing but fewer bytes arrived + fs::write(fx.fake().join("obj/a.sql"), b"create").unwrap(); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("changed since inventory")); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn a_gzip_named_archive_must_start_with_the_gzip_signature() { + let mut fx = Fixture::new(); + fx.add("backups/shop/b.sql.gz", b"plainly not gzip"); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("gzip header"), "{err:#}"); + assert_eq!((fx.snapshots(), fx.receipts()), (0, 0)); + // a one-byte file cannot even hold the signature + let mut tiny = Fixture::new(); + tiny.add("backups/shop/t.sql.gz", &[0x1f]); + assert!(tiny.run(tiny.args()).is_err()); + assert_eq!(tiny.snapshots(), 0); + } + + #[test] + fn a_plain_sql_archive_is_not_inspected_for_a_signature() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", &gzip_header(b"gz bytes in a .sql")); + let report = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&report), ["imported"]); + } + + #[test] + fn a_failed_download_stops_the_run_and_a_retry_resumes_where_it_left_off() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + fx.add("backups/shop/b.sql", b"create table b();"); + fs::write(fx.fake().join("get.fail.b.sql"), "").unwrap(); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("download failed"), "{err:#}"); + assert_eq!((fx.snapshots(), fx.receipts()), (1, 1), "a was kept"); + fs::remove_file(fx.fake().join("get.fail.b.sql")).unwrap(); + let retry = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&retry), ["already_imported", "imported"]); + assert_eq!((fx.snapshots(), fx.receipts()), (2, 2)); + } + + #[test] + fn a_receipt_keeps_an_archive_from_returning_after_its_snapshot_is_forgotten() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + let first = fx.run(fx.args()).unwrap(); + let id = first.objects[0].snapshot_id; + assert!(fx.vault.legacy_import_exists(id).unwrap()); + fx.vault.forget(&[id]).unwrap(); + assert_eq!(fx.snapshots(), 0); + let again = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&again), ["already_imported"]); + assert_eq!(fx.snapshots(), 0, "retention's decision is not undone"); + } + + // ---- the operator-history export ---- + + #[test] + fn a_history_export_must_be_a_sqlite_file() { + let fx = Fixture::new(); + let write = |name: &str, bytes: &[u8]| { + let path = fx.dir.path().join(name); + fs::write(&path, bytes).unwrap(); + path + }; + for (name, bytes) in [ + ("empty", &b""[..]), + ("short", b"SQLite"), + ("text", b"just a text file, long enough to read"), + ("near", b"SQLite format 3 not-nul-terminated"), + ("wal", b"SQLite format 4\0 later version"), + ] { + let mut args = fx.args(); + args.history = Some(write(name, bytes)); + assert!(fx.run(args).is_err(), "{name} must be refused"); + } + let mut missing = fx.args(); + missing.history = Some(Path::new("/definitely/not/here.sqlite").into()); + assert!(fx.run(missing).is_err()); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn a_history_export_is_stored_once_and_identified_by_its_content() { + let fx = Fixture::new(); + let path = fx.dir.path().join("history.sqlite"); + fs::write(&path, b"SQLite format 3\0 first export").unwrap(); + let mut args = fx.args(); + args.history = Some(path.clone()); + let first = fx.run(args.clone()).unwrap(); + let id = first.history_snapshot_id.expect("history imported"); + assert_eq!(fx.snapshots(), 1); + let stored = fx.vault.get_snapshot(id).unwrap().unwrap(); + assert_eq!(stored.manifest.provider, "legacy-history"); + assert_eq!(stored.manifest.orbit_id, Uuid::nil()); + assert_eq!(stored.manifest.restore_hints["format"], "sqlite"); + // same bytes: same snapshot, nothing new stored + let second = fx.run(args.clone()).unwrap(); + assert_eq!(second.history_snapshot_id, Some(id)); + assert_eq!(fx.snapshots(), 1); + // different bytes: a different snapshot + fs::write(&path, b"SQLite format 3\0 second export").unwrap(); + let third = fx.run(args).unwrap(); + assert_ne!(third.history_snapshot_id, Some(id)); + assert_eq!(fx.snapshots(), 2); + } +}