diff --git a/crates/tessera-core/src/decay.rs b/crates/tessera-core/src/decay.rs index bfea5cc..04c89ba 100644 --- a/crates/tessera-core/src/decay.rs +++ b/crates/tessera-core/src/decay.rs @@ -111,6 +111,43 @@ pub fn evaluate_capture_retention( .collect() } +/// A restore safety copy, for its own retention. +#[derive(Debug, Clone)] +pub struct SafetyRef { + pub id: Uuid, + pub taken_at: DateTime, + pub target: String, +} + +/// Safety copies kept per restore target regardless of age. +pub const SAFETY_KEEP_PER_TARGET: usize = 3; +/// Safety copies younger than this are always kept, however many there are. +pub const SAFETY_KEEP_DAYS: i64 = 7; + +/// Which safety copies to forget. Each target keeps its newest few and everything from the last week, so the +/// newest copy of a target is never forgotten here, and a burst of restores cannot erase the way back from +/// the previous one. (A copy that a restore still depends on is protected separately, by the caller.) +pub fn evaluate_safety_retention(snapshots: Vec, now: DateTime) -> Vec { + let mut targets: std::collections::BTreeMap> = Default::default(); + for snapshot in snapshots { + targets + .entry(snapshot.target.clone()) + .or_default() + .push(snapshot); + } + let mut forget = Vec::new(); + for (_, mut copies) in targets { + copies.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id))); + for (index, copy) in copies.into_iter().enumerate() { + let recent = now.signed_duration_since(copy.taken_at).num_days() < SAFETY_KEEP_DAYS; + if index >= SAFETY_KEEP_PER_TARGET && !recent { + forget.push(copy.id); + } + } + } + forget +} + /// Keep the newest snapshot in each of the most recent occupied UTC periods. pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec) -> Vec { if !policy.has_tiers() { @@ -333,4 +370,75 @@ mod tests { let forget = evaluate_decay(&policy, snaps); assert_eq!(forget.len(), 3); } + + fn safety(day: u32, target: &str) -> SafetyRef { + SafetyRef { + id: Uuid::new_v4(), + taken_at: Utc.with_ymd_and_hms(2026, 11, day, 4, 0, 0).unwrap(), + target: target.into(), + } + } + + #[test] + fn safety_snapshots_keep_the_newest_few_per_target_and_anything_recent() { + let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap(); + let old: Vec<_> = (1..=6).map(|d| safety(d, "staging")).collect(); // all older than a week + let recent = safety(28, "staging"); + let mut all = old.clone(); + all.push(recent.clone()); + let forgotten = evaluate_safety_retention(all, now); + // newest three overall (recent, day 6, day 5) stay; days 1..=4 go + assert_eq!(forgotten.len(), 4); + assert!(!forgotten.contains(&recent.id)); + assert!(!forgotten.contains(&old[5].id) && !forgotten.contains(&old[4].id)); + assert!(old[..4].iter().all(|s| forgotten.contains(&s.id))); + } + + #[test] + fn a_recent_safety_snapshot_is_never_forgotten_even_beyond_the_count() { + let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap(); + let burst: Vec<_> = (24..=29).map(|d| safety(d, "staging")).collect(); // six in the last week + assert!(evaluate_safety_retention(burst, now).is_empty()); + } + + #[test] + fn targets_are_counted_separately_and_each_keeps_at_least_its_newest() { + let now = Utc.with_ymd_and_hms(2027, 6, 1, 0, 0, 0).unwrap(); // everything is very old + let all = vec![safety(1, "staging"), safety(2, "staging"), safety(1, "dev")]; + let forgotten = evaluate_safety_retention(all.clone(), now); + assert!( + forgotten.is_empty(), + "three or fewer per target are always kept" + ); + let many: Vec<_> = (1..=5) + .map(|d| safety(d, "staging")) + .chain([safety(1, "dev")]) + .collect(); + let forgotten = evaluate_safety_retention(many.clone(), now); + assert_eq!(forgotten.len(), 2); + assert!( + !forgotten.contains(&many[5].id), + "the only snapshot of another target stays" + ); + } + + #[test] + fn a_manifest_knows_whether_it_is_a_restore_safety_copy() { + let mut manifest = crate::manifest::SnapshotManifest { + snapshot_id: Uuid::nil(), + orbit_id: Uuid::nil(), + orbit_name: "x".into(), + labels: vec!["postgres".into()], + provider: "postgres".into(), + paths: vec![], + restore_hints: serde_json::json!({"job_id": "j"}), + }; + assert!(!manifest.is_restore_safety()); + manifest.labels = vec!["restore-safety".into()]; + assert!(manifest.is_restore_safety()); + manifest.labels = vec![]; + manifest.restore_hints = serde_json::json!({"safety_for": "job", "target_id": "t"}); + assert!(manifest.is_restore_safety()); + assert_eq!(manifest.safety_target().as_deref(), Some("t")); + } } diff --git a/crates/tessera-core/src/manifest.rs b/crates/tessera-core/src/manifest.rs index 362a9f9..0933c5d 100644 --- a/crates/tessera-core/src/manifest.rs +++ b/crates/tessera-core/src/manifest.rs @@ -13,6 +13,23 @@ pub struct SnapshotManifest { pub restore_hints: serde_json::Value, } +impl SnapshotManifest { + /// A copy of a restore target's database taken before it was overwritten. It belongs to the target, not + /// to the application's backup history: retention must never weigh it against real captures. + pub fn is_restore_safety(&self) -> bool { + self.labels.iter().any(|label| label == "restore-safety") + || self.restore_hints.get("safety_for").is_some() + } + + /// The restore target a safety copy was taken from. + pub fn safety_target(&self) -> Option { + self.restore_hints + .get("target_id") + .and_then(|id| id.as_str()) + .map(str::to_string) + } +} + pub fn manifest_hash(manifest: &SnapshotManifest) -> String { let json = serde_json::to_vec(manifest).expect("manifest serializes"); let digest = Sha256::digest(&json); diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 0476108..69f9427 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -1644,3 +1644,61 @@ async fn a_failure_reason_is_only_kept_for_failures_and_is_cleaned_and_bounded() "{reason:?}" ); } + +// ---- retention: a safety copy of the target is not a backup of production ---- + +#[tokio::test] +async fn a_restore_safety_copy_never_pushes_a_production_capture_out_of_retention() { + use tessera_core::decay::CaptureRetention; + let lab = fresh().await; + // the harshest rule: only the newest archive is kept + lab.state + .db + .update_capture_profile( + lab.application, + crate::db::ProfileChange { + schedule: None, + retention: Some(Some(CaptureRetention::Count { keep: 1 })), + }, + now(), + ) + .unwrap() + .unwrap(); + lab.start(&lab.admin(), "safety-retention").await; + let capture = lab + .capture(&Lab::production_identity(), false) + .await + .unwrap(); + lab.tick().await; + // the target's safety copy is taken later than the production capture + tokio::time::sleep(std::time::Duration::from_millis(1200)).await; + let (job, token) = lab.restore_until_ready().await.unwrap(); + assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT); + lab.report_applied(&job, &token).await; + lab.tick().await; + + let snapshots = lab.state.vault.read().await.list_snapshots().unwrap(); + let safety: Vec<_> = snapshots + .iter() + .filter(|s| s.manifest.is_restore_safety()) + .map(|s| s.id) + .collect(); + assert_eq!( + safety.len(), + 1, + "one safety copy exists next to the capture" + ); + + let forgotten = lab.state.prune_orbit(lab.orbit).await.unwrap(); + assert!( + !forgotten.contains(&capture), + "the production capture survived: {forgotten:?}" + ); + assert!( + forgotten.is_empty(), + "and the fresh safety copy is kept too: {forgotten:?}" + ); + let vault = lab.state.vault.read().await; + assert!(vault.get_snapshot(capture).unwrap().is_some()); + assert!(vault.get_snapshot(safety[0]).unwrap().is_some()); +} diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index 965f1c1..2cf5b8b 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -5,7 +5,8 @@ use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::Arc; use tessera_core::decay::{ - evaluate_capture_retention, evaluate_gfs, CaptureRetention, RetentionPolicy, SnapshotRef, + evaluate_capture_retention, evaluate_gfs, evaluate_safety_retention, CaptureRetention, + RetentionPolicy, SafetyRef, SnapshotRef, }; use tessera_core::job::CaptureProfile; @@ -210,15 +211,28 @@ impl HubState { let Some(profile) = profile else { return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref()); }; - let snapshots = vault + let (safety, captures): (Vec<_>, Vec<_>) = vault .list_snapshots()? .into_iter() .filter(|snapshot| snapshot.manifest.orbit_id == orbit_id) + .partition(|snapshot| snapshot.manifest.is_restore_safety()); + let snapshots = captures + .into_iter() .map(|snapshot| SnapshotRef { id: snapshot.id, taken_at: snapshot.taken_at, }) .collect(); + // Safety copies of restore targets have their own retention: they never count as a backup of + // the application, so they can neither displace a capture nor be displaced by one. + let safety: Vec<_> = safety + .into_iter() + .map(|snapshot| SafetyRef { + id: snapshot.id, + taken_at: snapshot.taken_at, + target: snapshot.manifest.safety_target().unwrap_or_default(), + }) + .collect(); let expired = match ManagedRetention::resolve(&profile, retention) { ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots), ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => { @@ -226,6 +240,9 @@ impl HubState { } }; let mut deletable = Vec::new(); + let expired = expired + .into_iter() + .chain(evaluate_safety_retention(safety, chrono::Utc::now())); for id in expired { if !active_exports.contains(&id) && !db.offsite_pending(id)? diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index 9c0f11d..3dcef97 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -745,6 +745,7 @@ impl Vault { snaps.into_iter().filter(|snapshot| { snapshot.manifest.provider != "legacy-history" && snapshot.manifest.restore_hints.get("job_id").is_none() + && !snapshot.manifest.is_restore_safety() }), ) } @@ -761,7 +762,7 @@ impl Vault { retention, snaps .into_iter() - .filter(|s| s.manifest.orbit_id == orbit_id), + .filter(|s| s.manifest.orbit_id == orbit_id && !s.manifest.is_restore_safety()), ) } diff --git a/docs/DATABASE-CAPTURE.md b/docs/DATABASE-CAPTURE.md index 6a0ace4..ad74fda 100644 --- a/docs/DATABASE-CAPTURE.md +++ b/docs/DATABASE-CAPTURE.md @@ -39,6 +39,8 @@ To change a profile's schedule or retention later, send `PUT /api/v1/capture-pro Downloads are named `_