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

@@ -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) =