feat: roll back a failed restore and say when a safety copy is gone

- a restore whose apply failed can be undone from its safety copy, which is its recovery: the failed apply stops
  fencing the target in the transaction that starts the undo (job phase rolled_back, audited restore.rolled_back);
  an apply whose agent went silent still waits for an administrator to reconcile it; reconciled restores can be undone
- run views carry undo_state (available, superseded, expired), undo_kept_until, undo_of and restore_job_id
- undo state for a list is worked out in one database pass and a file lookup per copy; the vault is read only for the
  newest restore of each target
- eligibility is checked again inside the transaction that creates the run

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 20:37:21 +07:00
parent 648c8c6a2a
commit 62f0c68e89
5 changed files with 374 additions and 87 deletions

View File

@@ -2257,6 +2257,16 @@ async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can
lab.report_applied(&job, &token).await;
lab.tick().await;
assert_eq!(lab.run(&undo_id).status, "completed");
// the undo says which restore it puts back, and the restore says which job it queued
let (_, child) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
.await;
assert_eq!(child["undo_of"], json!(first), "{child}");
assert!(child["restore_job_id"].is_string(), "{child}");
let (_, parent) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
assert!(parent.get("undo_of").is_none(), "{parent}");
// only the newest restore of a target can be undone: the first one no longer can, the undo can
let (_, old) = lab
@@ -2365,3 +2375,118 @@ async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
);
assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1);
}
// ---- why a restore can or cannot be put back, and rolling back a restore that failed ----
impl Lab {
async fn run_view(&self, run: &str) -> Value {
self.send(&self.admin(), "GET", &format!("/api/v1/refresh-runs/{run}"), None)
.await
.1
}
fn safety_of(&self, run: &str) -> Uuid {
Uuid::parse_str(&self.scalar::<String>(&format!(
"SELECT safety_id FROM restore_jobs WHERE id=(SELECT restore_job_id FROM refresh_runs WHERE id='{run}')"
)))
.unwrap()
}
/// A restore that got as far as overwriting the target and then failed, as the agent reports it.
async fn failed_apply(&self, key: &str) -> (String, String) {
let (_, run) = self.start(&self.admin(), key).await;
let run = run["id"].as_str().unwrap().to_string();
self.capture(&Lab::production_identity(), false).await.unwrap();
self.tick().await;
let (job, token) = self.restore_until_ready().await.expect("a restore job is waiting");
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
let (status, _) = self
.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&[("x-tessera-restore-token", token)],
json!("apply_failed"),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
self.tick().await;
assert_eq!(self.run(&run).status, "recovery_required");
(run, job)
}
}
#[tokio::test]
async fn a_restore_says_why_it_can_or_cannot_be_put_back_and_how_long_for() {
let lab = fresh().await;
let first = lab.restored_once("first").await;
let view = lab.run_view(&first).await;
assert_eq!((view["undo_available"].clone(), view["undo_state"].clone()), (json!(true), json!("available")), "{view}");
let until = view["undo_kept_until"].as_i64().expect("a date while it can be undone");
assert!(until > chrono::Utc::now().timestamp() + 6 * 86_400, "a week from when it was taken: {view}");
// a later restore of the same target supersedes it; only the newest can be undone
let second = lab.restored_once("second").await;
let (old, new) = (lab.run_view(&first).await, lab.run_view(&second).await);
assert_eq!((old["undo_state"].clone(), old["undo_available"].clone()), (json!("superseded"), json!(false)), "{old}");
assert_eq!(new["undo_state"], "available", "{new}");
// retention forgets the newest copy: it says so, instead of offering something that would be refused
lab.state.vault.write().await.forget(&[lab.safety_of(&second)]).unwrap();
let new = lab.run_view(&second).await;
assert_eq!((new["undo_state"].clone(), new["undo_available"].clone()), (json!("expired"), json!(false)), "{new}");
assert!(new.get("undo_kept_until").is_none(), "{new}");
// expired wins over superseded, so nobody is told to look for a copy that is gone
lab.state.vault.write().await.forget(&[lab.safety_of(&first)]).unwrap();
assert_eq!(lab.run_view(&first).await["undo_state"], "expired");
// the list says the same, for a person who may only use the relation
let (qa, _) = lab.refresher("qa");
let (_, list) = lab.send(&qa, "GET", "/api/v1/refresh-runs", None).await;
let states: Vec<_> = list.as_array().unwrap().iter().map(|r| r["undo_state"].clone()).collect();
assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}");
}
#[tokio::test]
async fn a_restore_whose_apply_failed_is_rolled_back_from_its_safety_copy() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let (run, job) = lab.failed_apply("broken").await;
let view = lab.run_view(&run).await;
assert_eq!(view["undo_available"], true, "rolling back is offered: {view}");
// while the failed apply fences the target nothing else may start, but the rollback may
let (status, other) = lab.start(&qa, "other").await;
assert_eq!((status, other["reason"].clone()), (StatusCode::CONFLICT, json!("run_active")), "{other}");
let (status, undo) = lab.start_undo(&qa, "rollback", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
assert_eq!(undo["undo_of"], json!(run));
assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.scalar::<String>(&format!("SELECT phase FROM restore_jobs WHERE id='{job}'")), "rolled_back");
assert!(lab.audit_log().iter().any(|(event, _)| event == "restore.rolled_back"));
// it goes through the same engine and puts the copy back
lab.tick().await;
lab.finish_restore().await;
assert_eq!(lab.run(undo["id"].as_str().unwrap()).status, "completed");
assert_eq!(lab.run_view(&run).await["undo_state"], "superseded", "it is not offered twice");
}
#[tokio::test]
async fn an_apply_that_lost_its_agent_waits_for_an_administrator_before_it_can_be_rolled_back() {
let lab = fresh().await;
let (run, job) = lab.failed_apply("silent").await;
// the agent did not say it stopped: the apply may still be writing
lab.conn()
.execute("UPDATE restore_jobs SET phase='lease_lost' WHERE id=?1", [&job])
.unwrap();
assert_eq!(lab.run_view(&run).await["undo_available"], false);
let (status, body) = lab.start_undo(&lab.admin(), "early", &run).await;
assert_eq!((status, body["reason"].clone()), (StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")), "{body}");
// once an administrator has verified it, the same safety copy can put the target back
assert!(lab.state.db.reconcile_restore(Uuid::parse_str(&job).unwrap(), "admin", now()).unwrap());
lab.tick().await;
assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.run_view(&run).await["undo_available"], true);
let (status, undo) = lab.start_undo(&lab.admin(), "after", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
}