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

@@ -71,25 +71,73 @@ struct RunView {
snapshot_id: Option<String>,
/// This run put a target back from the safety copy of an earlier restore.
undo: bool,
/// A completed restore that can still be undone: the newest restore of its target, with its safety copy in
/// the vault. Never says where the copy is.
/// For an undo, the run whose restore it puts back; the Activity log shows the undo under it.
#[serde(skip_serializing_if = "Option::is_none")]
undo_of: Option<String>,
/// The restore job this run queued, which is how the Activity log ties a restore to its run.
#[serde(skip_serializing_if = "Option::is_none")]
restore_job_id: Option<String>,
/// This restore can be put back right now: it is the newest of its target and its safety copy is in the vault.
/// Never says where the copy is.
undo_available: bool,
/// Why it can or cannot be put back, for a restore that took a safety copy: `available`, `superseded` (something
/// was restored onto the target after it) or `expired` (retention has forgotten the copy).
#[serde(skip_serializing_if = "Option::is_none")]
undo_state: Option<&'static str>,
/// While it can be undone: when the safety copy is first at risk of being forgotten. Retention keeps a copy a
/// week, and longer while it is one of the target's newest few.
#[serde(skip_serializing_if = "Option::is_none")]
undo_kept_until: Option<i64>,
}
/// Can this run still be undone: see `Db::undo_candidate`, and the safety copy must still exist.
async fn can_undo(state: &HubState, run: &RefreshRun) -> bool {
if run.status != "completed" {
return false;
}
match state.db.undo_candidate(&run.id, &run.relation_id) {
Ok(Ok(safety)) => snapshot_fits(state, &run.relation_id, safety)
.await
.unwrap_or(false),
_ => false,
}
/// What `undo_views` found out about one run.
#[derive(Clone, Copy)]
struct Undo {
state: &'static str,
kept_until: Option<i64>,
}
async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
/// For every run in the list that took a safety copy, whether it can be put back. The database answers for all of
/// them in one go; the vault is only asked whether a copy still exists (a file lookup), and read only for the one
/// restore per target that could still be undone.
async fn undo_views(
state: &HubState,
runs: &[RefreshRun],
) -> Result<std::collections::HashMap<String, Undo>, StatusCode> {
let infos = state.db.undo_infos(runs).map_err(internal)?;
let mut views = std::collections::HashMap::new();
if infos.is_empty() {
return Ok(views);
}
let vault = state.vault.read().await;
for run in runs {
let Some(info) = infos.get(&run.id) else {
continue;
};
// Safety copies are forgotten by retention: the restore stays in the log, but there is nothing to go back to.
if !vault.has_published_snapshot(info.safety).map_err(internal)? {
views.insert(run.id.clone(), Undo { state: "expired", kept_until: None });
} else if !info.latest {
views.insert(run.id.clone(), Undo { state: "superseded", kept_until: None });
} else if let Some(taken) = fitting_snapshot(state, &vault, &run.relation_id, info.safety)? {
let kept = taken + tessera_core::decay::SAFETY_KEEP_DAYS * 86_400;
views.insert(run.id.clone(), Undo { state: "available", kept_until: Some(kept) });
}
}
Ok(views)
}
async fn view_one(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
let undo = undo_views(state, std::slice::from_ref(run)).await?;
view(state, run, admin, undo.get(&run.id))
}
fn view(
state: &HubState,
run: &RefreshRun,
admin: bool,
undo: Option<&Undo>,
) -> Result<RunView, StatusCode> {
let Progress {
capture_status,
capture_phase,
@@ -117,7 +165,11 @@ async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView
requested_by: admin.then(|| run.requester.clone()),
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
undo: run.is_undo(),
undo_available: can_undo(state, run).await,
undo_of: state.db.undo_parent(run).map_err(internal)?,
restore_job_id: run.restore_job_id.clone(),
undo_available: undo.is_some_and(|undo| undo.state == "available"),
undo_state: undo.map(|undo| undo.state),
undo_kept_until: undo.and_then(|undo| undo.kept_until),
})
}
@@ -168,39 +220,46 @@ fn valid_key(key: &str) -> bool {
}
/// Is this snapshot one that a relation may restore: a database capture of the relation's own source orbit,
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)?
async fn snapshot_fits(
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)? When it is,
/// when it was taken (seconds since the epoch).
fn fitting_snapshot(
state: &HubState,
vault: &tessera_store::Vault,
relation: &str,
snapshot: Uuid,
) -> Result<bool, StatusCode> {
) -> Result<Option<i64>, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
return Ok(false);
return Ok(None);
};
let manifest = state
.vault
.read()
.await
.get_snapshot(snapshot)
.map_err(internal)?
.map(|s| s.manifest);
let Some(stored) = vault.get_snapshot(snapshot).map_err(internal)? else {
return Ok(None);
};
let manifest = &stored.manifest;
let target = match state.db.relation_target(relation).map_err(internal)? {
Some(id) => Uuid::parse_str(&id)
.ok()
.and_then(|id| state.db.restore_target(id).ok().flatten()),
None => None,
};
Ok(manifest.is_some_and(|manifest| {
manifest.orbit_id.to_string() == source
&& if manifest.is_restore_safety() {
// a safety copy only ever goes back onto the target it was taken from
target.as_ref().is_some_and(|target| {
crate::api::rollback_artifact(&manifest, target).is_some()
})
} else {
crate::api::artifact(&manifest).is_some()
}
}))
let fits = manifest.orbit_id.to_string() == source
&& if manifest.is_restore_safety() {
// a safety copy only ever goes back onto the target it was taken from
target
.as_ref()
.is_some_and(|target| crate::api::rollback_artifact(manifest, target).is_some())
} else {
crate::api::artifact(manifest).is_some()
};
Ok(fits.then(|| stored.taken_at.timestamp()))
}
async fn snapshot_fits(
state: &HubState,
relation: &str,
snapshot: Uuid,
) -> Result<bool, StatusCode> {
let vault = state.vault.read().await;
Ok(fitting_snapshot(state, &vault, relation, snapshot)?.is_some())
}
async fn start(
@@ -217,7 +276,7 @@ async fn start(
let relation = body.relation_id.to_string();
// What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
// a fresh capture.
let mut chosen: Option<(Uuid, bool)> = None;
let mut chosen: Option<(Uuid, Option<String>)> = None;
if let Some(of) = body.undo_of {
if body.snapshot_id.is_some() {
return Err(StatusCode::BAD_REQUEST);
@@ -233,7 +292,7 @@ async fn start(
if !snapshot_fits(&state, &relation, safety).await? {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
}
chosen = Some((safety, true));
chosen = Some((safety, Some(of.to_string())));
} else if let Some(snapshot) = body.snapshot_id {
if !snapshot_fits(&state, &relation, snapshot).await? {
return Ok(reason(
@@ -241,7 +300,7 @@ async fn start(
"snapshot_unusable",
));
}
chosen = Some((snapshot, false));
chosen = Some((snapshot, None));
}
// What authorised this run, recorded so it can be checked again before anything is overwritten.
let authorized_by = if actor.subject.admin {
@@ -270,7 +329,7 @@ async fn start(
actor.subject.user_id.as_deref(),
&authorized_by,
&body.idempotency_key,
chosen,
chosen.as_ref().map(|(snapshot, of)| (*snapshot, of.as_deref())),
state.refresh.ttl_secs,
state.refresh.max_active,
now(),
@@ -293,10 +352,13 @@ async fn start(
Ok((
status,
no_store(),
Json(view(&state, &run, actor.subject.admin).await?),
Json(view_one(&state, &run, actor.subject.admin).await?),
)
.into_response())
}
Err(StartError::NothingToUndo) => {
Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"))
}
Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND),
Err(StartError::Unusable(why)) => Ok((
StatusCode::CONFLICT,
@@ -343,9 +405,10 @@ async fn list(
}
}
.map_err(internal)?;
let undo = undo_views(&state, &runs).await?;
let mut views = Vec::with_capacity(runs.len());
for run in &runs {
views.push(view(&state, run, actor.subject.admin).await?);
views.push(view(&state, run, actor.subject.admin, undo.get(&run.id))?);
}
Ok((no_store(), Json(views)))
}
@@ -380,7 +443,7 @@ async fn show(
let run = run.ok_or(StatusCode::NOT_FOUND)?;
Ok((
no_store(),
Json(view(&state, &run, actor.subject.admin).await?),
Json(view_one(&state, &run, actor.subject.admin).await?),
))
}
@@ -429,7 +492,7 @@ async fn cancel(
crate::refresh::audit_run(&state, &run.id, "cancelled");
Ok((
no_store(),
Json(view(&state, &run, actor.subject.admin).await?),
Json(view_one(&state, &run, actor.subject.admin).await?),
)
.into_response())
}

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}");
}

View File

@@ -79,6 +79,8 @@ pub enum StartError {
KeyReused,
/// Too many refreshes are running at once.
TooManyRuns,
/// The restore to undo is not one that can be undone (any more).
NothingToUndo,
}
/// What the confirmation must say: it names exactly what the person saw, including the version.
@@ -99,55 +101,119 @@ impl RefreshRun {
}
}
/// A relation's source orbit, for checking that a snapshot belongs to it.
/// The safety copy a restore took before it overwrote its target, and whether it is still the newest restore there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UndoInfo {
pub safety: Uuid,
/// Nothing was restored onto the target after it. Undoing an older restore would also undo what came later.
pub latest: bool,
}
/// Does this run have a safety copy that puts its target back? A restore that finished, one an administrator
/// has since reconciled, and one whose apply failed (the agent says it stopped, so nothing is still writing) all
/// do: in the last case, rolling back is the recovery. An apply whose agent went silent may still be running, so
/// it waits for an administrator to reconcile it.
fn undo_info(conn: &Connection, run: &RefreshRun) -> Result<Option<UndoInfo>> {
if !matches!(run.status.as_str(), "completed" | "reconciled" | "recovery_required") {
return Ok(None);
}
let Some(job) = &run.restore_job_id else {
return Ok(None);
};
let row: Option<(String, String, Option<String>)> = conn
.query_row(
"SELECT status, phase, safety_id FROM restore_jobs WHERE id = ?1",
params![job],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let Some((status, phase, Some(safety))) = row else {
return Ok(None);
};
let sound = match status.as_str() {
"completed" | "reconciled" => true,
"recovery_required" => phase == "apply_failed",
_ => false,
};
if !sound {
return Ok(None);
}
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','reconciled','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
Ok(Some(UndoInfo {
safety: Uuid::parse_str(&safety)?,
latest: !later,
}))
}
fn undo_check(
conn: &Connection,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
let Some(run) = get(conn, run)?.filter(|r| r.relation_id == relation) else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
Ok(match undo_info(conn, &run)? {
None => Err(UndoRefusal::NothingToUndo),
Some(info) if !info.latest => Err(UndoRefusal::NotTheLatest),
Some(info) => Ok(info.safety),
})
}
/// Why a restore cannot be undone.
#[derive(Debug, PartialEq, Eq)]
pub enum UndoRefusal {
/// No such run, not of this relation, not completed, or it took no safety copy.
/// No such run, not of this relation, not a restore that can be put back, or it took no safety copy.
NothingToUndo,
/// Something else was restored onto the target after it. Undoing an older restore would also undo that.
NotTheLatest,
}
impl Db {
/// The safety copy that undoes `run`, if the run is a completed restore of this relation and the newest
/// restore of its target. Whether the copy still exists in the vault is for the caller to check.
/// The safety copy that undoes `run`, if the run is a restore of this relation that can be put back and the
/// newest restore of its target. Whether the copy still exists in the vault is for the caller to check.
pub fn undo_candidate(
&self,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
undo_check(&self.conn.lock().unwrap(), run, relation)
}
/// What can be done about each run's restore, for a whole list under one lock: only runs that took a safety
/// copy appear. See `UndoInfo`.
pub fn undo_infos(&self, runs: &[RefreshRun]) -> Result<std::collections::HashMap<String, UndoInfo>> {
let conn = self.conn.lock().unwrap();
let Some(run) =
get(&conn, run)?.filter(|r| r.relation_id == relation && r.status == "completed")
else {
return Ok(Err(UndoRefusal::NothingToUndo));
let mut infos = std::collections::HashMap::new();
for run in runs {
if let Some(info) = undo_info(&conn, run)? {
infos.insert(run.id.clone(), info);
}
}
Ok(infos)
}
/// The restore this undo puts back: the run whose restore took the safety copy that `run` restores.
pub fn undo_parent(&self, run: &RefreshRun) -> Result<Option<String>> {
let Some(safety) = run.snapshot_id.as_deref().filter(|_| run.is_undo()) else {
return Ok(None);
};
let Some(job) = &run.restore_job_id else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
let safety: Option<Option<String>> = conn
let conn = self.conn.lock().unwrap();
Ok(conn
.query_row(
"SELECT safety_id FROM restore_jobs WHERE id = ?1 AND status = 'completed'",
params![job],
"SELECT r.id FROM refresh_runs r JOIN restore_jobs j ON j.id = r.restore_job_id
WHERE j.safety_id = ?1 AND r.target_id = ?2 AND r.id <> ?3",
params![safety, run.target_id, run.id],
|r| r.get(0),
)
.optional()?;
let Some(Some(safety)) = safety else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
if later {
return Ok(Err(UndoRefusal::NotTheLatest));
}
Ok(Ok(Uuid::parse_str(&safety)?))
.optional()?)
}
pub fn relation_target(&self, relation: &str) -> Result<Option<String>> {
@@ -350,8 +416,8 @@ impl Db {
requester_user_id: Option<&str>,
authorized_by: &str,
idempotency_key: &str,
// a snapshot to restore instead of capturing one, and whether it is an undo of an earlier restore
snapshot: Option<(Uuid, bool)>,
// a snapshot to restore instead of capturing one, and the run it undoes when it is the safety copy of one
snapshot: Option<(Uuid, Option<&str>)>,
ttl_secs: i64,
max_active: i64,
now: i64,
@@ -379,8 +445,10 @@ impl Db {
if confirmation != confirmation_text(&source, &target, relation.version) {
return Ok(Err(StartError::StaleConfirmation));
}
let undoing = snapshot.and_then(|(_, of)| of);
// The run being undone does not count as busy: if its apply failed, undoing it is how it is recovered.
let busy: Option<String> = tx
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required')", params![relation.target_id], |r| r.get(0))
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required') AND id IS NOT ?2", params![relation.target_id, undoing], |r| r.get(0))
.optional()?;
if let Some(id) = busy {
return Ok(Err(StartError::TargetBusy(id)));
@@ -389,12 +457,34 @@ impl Db {
if running >= max_active {
return Ok(Err(StartError::TooManyRuns));
}
if let Some((safety, Some(of))) = snapshot {
// Checked again inside this transaction: what was true when the request was read may not be now.
if !matches!(undo_check(&tx, of, relation_id)?, Ok(found) if found == safety) {
return Ok(Err(StartError::NothingToUndo));
}
if let Some(parent) = get(&tx, of)?.filter(|r| r.status == "recovery_required") {
// The failed apply no longer fences the target: this undo takes over from it, and puts back what
// the restore replaced. What it leaves behind is kept as this undo's own safety copy.
if let Some(job) = &parent.restore_job_id {
tx.execute(
"UPDATE restore_jobs SET status='reconciled', phase='rolled_back', updated_at=?2
WHERE id=?1 AND status='recovery_required' AND phase='apply_failed'",
params![job, now],
)?;
}
finish(&tx, &parent.id, "reconciled", None, now)?;
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), 'restore.rolled_back', ?1)",
params![format!("run={} by={requester}", parent.id)],
)?;
}
}
let id = Uuid::new_v4().to_string();
// A run either takes a fresh backup first, or restores a snapshot the person picked: then it has
// no capture job, only a placeholder, and the snapshot is recorded from the start.
let capture = match snapshot {
Some((_, true)) => format!("{UNDO}{id}"),
Some((_, false)) => format!("{EXISTING}{id}"),
Some((_, Some(_))) => format!("{UNDO}{id}"),
Some((_, None)) => format!("{EXISTING}{id}"),
None => {
let application = Uuid::parse_str(&relation.source_application_id)?;
let Some(capture) =