fix: restore safety copies no longer compete with production captures in retention

A safety copy of a restore target was stored in the application's orbit and weighed by the same
retention as captures, so the newest copy (the target's) could push the production capture that had
just been restored out of the keep set, whatever the rule (GFS, count or age). Safety copies are now
separated: they have their own per-target rule (newest three plus anything under seven days) and
never count for or against captures. Proven red on the old behaviour with a real refresh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 12:35:28 +07:00
parent 43709aeeab
commit b104aa8053
6 changed files with 206 additions and 3 deletions

View File

@@ -111,6 +111,43 @@ pub fn evaluate_capture_retention(
.collect() .collect()
} }
/// A restore safety copy, for its own retention.
#[derive(Debug, Clone)]
pub struct SafetyRef {
pub id: Uuid,
pub taken_at: DateTime<Utc>,
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<SafetyRef>, now: DateTime<Utc>) -> Vec<Uuid> {
let mut targets: std::collections::BTreeMap<String, Vec<SafetyRef>> = 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. /// Keep the newest snapshot in each of the most recent occupied UTC periods.
pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> { pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
if !policy.has_tiers() { if !policy.has_tiers() {
@@ -333,4 +370,75 @@ mod tests {
let forget = evaluate_decay(&policy, snaps); let forget = evaluate_decay(&policy, snaps);
assert_eq!(forget.len(), 3); 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"));
}
} }

View File

@@ -13,6 +13,23 @@ pub struct SnapshotManifest {
pub restore_hints: serde_json::Value, 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<String> {
self.restore_hints
.get("target_id")
.and_then(|id| id.as_str())
.map(str::to_string)
}
}
pub fn manifest_hash(manifest: &SnapshotManifest) -> String { pub fn manifest_hash(manifest: &SnapshotManifest) -> String {
let json = serde_json::to_vec(manifest).expect("manifest serializes"); let json = serde_json::to_vec(manifest).expect("manifest serializes");
let digest = Sha256::digest(&json); let digest = Sha256::digest(&json);

View File

@@ -1644,3 +1644,61 @@ async fn a_failure_reason_is_only_kept_for_failures_and_is_cleaned_and_bounded()
"{reason:?}" "{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());
}

View File

@@ -5,7 +5,8 @@ use std::collections::{HashMap, HashSet};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use tessera_core::decay::{ 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; use tessera_core::job::CaptureProfile;
@@ -210,15 +211,28 @@ impl HubState {
let Some(profile) = profile else { let Some(profile) = profile else {
return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref()); return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref());
}; };
let snapshots = vault let (safety, captures): (Vec<_>, Vec<_>) = vault
.list_snapshots()? .list_snapshots()?
.into_iter() .into_iter()
.filter(|snapshot| snapshot.manifest.orbit_id == orbit_id) .filter(|snapshot| snapshot.manifest.orbit_id == orbit_id)
.partition(|snapshot| snapshot.manifest.is_restore_safety());
let snapshots = captures
.into_iter()
.map(|snapshot| SnapshotRef { .map(|snapshot| SnapshotRef {
id: snapshot.id, id: snapshot.id,
taken_at: snapshot.taken_at, taken_at: snapshot.taken_at,
}) })
.collect(); .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) { let expired = match ManagedRetention::resolve(&profile, retention) {
ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots), ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots),
ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => { ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => {
@@ -226,6 +240,9 @@ impl HubState {
} }
}; };
let mut deletable = Vec::new(); let mut deletable = Vec::new();
let expired = expired
.into_iter()
.chain(evaluate_safety_retention(safety, chrono::Utc::now()));
for id in expired { for id in expired {
if !active_exports.contains(&id) if !active_exports.contains(&id)
&& !db.offsite_pending(id)? && !db.offsite_pending(id)?

View File

@@ -745,6 +745,7 @@ impl Vault {
snaps.into_iter().filter(|snapshot| { snaps.into_iter().filter(|snapshot| {
snapshot.manifest.provider != "legacy-history" snapshot.manifest.provider != "legacy-history"
&& snapshot.manifest.restore_hints.get("job_id").is_none() && snapshot.manifest.restore_hints.get("job_id").is_none()
&& !snapshot.manifest.is_restore_safety()
}), }),
) )
} }
@@ -761,7 +762,7 @@ impl Vault {
retention, retention,
snaps snaps
.into_iter() .into_iter()
.filter(|s| s.manifest.orbit_id == orbit_id), .filter(|s| s.manifest.orbit_id == orbit_id && !s.manifest.is_restore_safety()),
) )
} }

View File

@@ -39,6 +39,8 @@ To change a profile's schedule or retention later, send `PUT /api/v1/capture-pro
Downloads are named `<orbit>_<time>_<engine>_<id8>.<ext>`, for example `lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump`. The orbit name is reduced to `[a-z0-9_-]`, the time is when the backup was taken in the profile's schedule zone (UTC with `Z` when there is no schedule), and the first eight characters of the snapshot id keep backups from the same minute apart. The header carries both `filename` and the RFC 5987 `filename*`. Downloads are named `<orbit>_<time>_<engine>_<id8>.<ext>`, for example `lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump`. The orbit name is reduced to `[a-z0-9_-]`, the time is when the backup was taken in the profile's schedule zone (UTC with `Z` when there is no schedule), and the first eight characters of the snapshot id keep backups from the same minute apart. The header carries both `filename` and the RFC 5987 `filename*`.
The safety copy that a restore takes of its target (label `restore-safety`) is not a backup of the application, so retention never counts it against captures: it can neither push a production capture out nor be pushed out by one. Safety copies have their own rule, per restore target: the newest three are kept, plus any younger than seven days, and a copy that a restore still depends on is never forgotten.
A schedule is optional. Scheduled jobs catch up from the time the profile was registered and stay queued while the outpost is offline. Retention defaults to 14 days and keeps the newest archive. Use `"retention": {"mode": "count"}` for five archives or set its `keep` value explicitly. An orbit's custom GFS policy applies when the profile has no explicit retention override. The offline CLI decay command only processes legacy snapshots. A schedule is optional. Scheduled jobs catch up from the time the profile was registered and stay queued while the outpost is offline. Retention defaults to 14 days and keeps the newest archive. Use `"retention": {"mode": "count"}` for five archives or set its `keep` value explicitly. An orbit's custom GFS policy applies when the profile has no explicit retention override. The offline CLI decay command only processes legacy snapshots.
Set the same application UUID in the agent's local JSON file. Each entry has a `source` and an optional `timeout_seconds` (default 3600). The password file contains one line and should be readable only by the service account. Set the same application UUID in the agent's local JSON file. Each entry has a `source` and an optional `timeout_seconds` (default 3600). The password file contains one line and should be readable only by the service account.