feat: undo a restore from the safety copy it took
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled

- POST /refresh-runs accepts undo_of: restores the safety copy of a completed restore back onto the same
  target through the normal run engine (checks, countdown, progress, and a new safety copy so the undo can be
  undone); refused when something was restored after it or the copy is gone
- a safety copy is accepted as a source only for the target it was taken from (hub and agent both check)
- run views carry undo and undo_available; audited as refresh.undo_started
- the modal offers Undo last restore and, after a restore, Undo this restore
- proven with a real agent and PostgreSQL: restore, undo back to the original contents, undo of the undo

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 16:47:02 +07:00
parent 854e3572e9
commit 648c8c6a2a
16 changed files with 457 additions and 41 deletions

View File

@@ -24,5 +24,5 @@ mod session;
pub use orbit::run_orbit_internal;
pub(crate) use relations::identity_facts;
pub(crate) use restore::artifact;
pub(crate) use restore::{artifact, rollback_artifact};
pub use routes::router;

View File

@@ -69,9 +69,27 @@ struct RunView {
requested_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
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.
undo_available: bool,
}
fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
/// 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,
}
}
async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
let Progress {
capture_status,
capture_phase,
@@ -98,6 +116,8 @@ fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, Stat
expires_at: run.expires_at,
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,
})
}
@@ -134,6 +154,10 @@ struct Start {
/// relation's own source.
#[serde(default)]
snapshot_id: Option<Uuid>,
/// Put the target back as it was before this earlier restore: restore that restore's safety copy onto the same
/// target. The run must be a completed restore of this relation and the newest one of its target.
#[serde(default)]
undo_of: Option<Uuid>,
}
fn valid_key(key: &str) -> bool {
@@ -160,10 +184,22 @@ async fn snapshot_fits(
.get_snapshot(snapshot)
.map_err(internal)?
.map(|s| s.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
&& !manifest.is_restore_safety()
&& crate::api::artifact(&manifest).is_some()
&& 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()
}
}))
}
@@ -179,13 +215,33 @@ async fn start(
}
super::gate::relation(&state, &actor, body.relation_id)?;
let relation = body.relation_id.to_string();
if let Some(snapshot) = body.snapshot_id {
// 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;
if let Some(of) = body.undo_of {
if body.snapshot_id.is_some() {
return Err(StatusCode::BAD_REQUEST);
}
let candidate = state
.db
.undo_candidate(&of.to_string(), &relation)
.map_err(internal)?;
let Ok(safety) = candidate else {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
};
// the copy may have been removed since
if !snapshot_fits(&state, &relation, safety).await? {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
}
chosen = Some((safety, true));
} else if let Some(snapshot) = body.snapshot_id {
if !snapshot_fits(&state, &relation, snapshot).await? {
return Ok(reason(
StatusCode::UNPROCESSABLE_ENTITY,
"snapshot_unusable",
));
}
chosen = Some((snapshot, false));
}
// What authorised this run, recorded so it can be checked again before anything is overwritten.
let authorized_by = if actor.subject.admin {
@@ -214,7 +270,7 @@ async fn start(
actor.subject.user_id.as_deref(),
&authorized_by,
&body.idempotency_key,
body.snapshot_id,
chosen,
state.refresh.ttl_secs,
state.refresh.max_active,
now(),
@@ -223,7 +279,11 @@ async fn start(
match started {
Ok((run, created)) => {
if created {
crate::refresh::audit_run(&state, &run.id, "capturing");
crate::refresh::audit_run(
&state,
&run.id,
if run.is_undo() { "undo" } else { "capturing" },
);
}
let status = if created {
StatusCode::ACCEPTED
@@ -233,7 +293,7 @@ async fn start(
Ok((
status,
no_store(),
Json(view(&state, &run, actor.subject.admin)?),
Json(view(&state, &run, actor.subject.admin).await?),
)
.into_response())
}
@@ -283,10 +343,10 @@ async fn list(
}
}
.map_err(internal)?;
let views = runs
.iter()
.map(|run| view(&state, run, actor.subject.admin))
.collect::<Result<Vec<_>, _>>()?;
let mut views = Vec::with_capacity(runs.len());
for run in &runs {
views.push(view(&state, run, actor.subject.admin).await?);
}
Ok((no_store(), Json(views)))
}
@@ -318,7 +378,10 @@ async fn show(
)
.map_err(internal)?;
let run = run.ok_or(StatusCode::NOT_FOUND)?;
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)))
Ok((
no_store(),
Json(view(&state, &run, actor.subject.admin).await?),
))
}
async fn cancel(
@@ -364,7 +427,11 @@ async fn cancel(
{
Ok(run) => {
crate::refresh::audit_run(&state, &run.id, "cancelled");
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response())
Ok((
no_store(),
Json(view(&state, &run, actor.subject.admin).await?),
)
.into_response())
}
Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND),
Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")),

View File

@@ -2188,3 +2188,180 @@ async fn the_screens_get_what_they_need_to_offer_restore_for_an_orbit() {
"{kinds:?}"
);
}
// ---- undoing a restore: put the target back from the safety copy the restore took ----
impl Lab {
async fn start_undo(&self, caller: &Caller, key: &str, run: &str) -> (StatusCode, Value) {
self.send(
caller,
"POST",
"/api/v1/refresh-runs",
Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key, "undo_of": run})),
)
.await
}
/// A completed restore of a fresh capture, with its safety copy in the vault.
async fn restored_once(&self, key: &str) -> 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;
self.finish_restore().await;
assert_eq!(self.run(&run).status, "completed");
run
}
}
#[tokio::test]
async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can_be_undone() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let first = lab.restored_once("first").await;
let (_, view) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
assert_eq!(view["undo_available"], true, "{view}");
assert!(
view.get("safety_snapshot_id").is_none(),
"no snapshot id reaches a non-administrator: {view}"
);
let (status, undo) = lab.start_undo(&qa, "undo-1", &first).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
assert_eq!(undo["undo"], true);
let undo_id = undo["id"].as_str().unwrap().to_string();
let captures = lab.capture_jobs();
lab.tick().await;
// the restore job takes the first restore's safety copy back onto the same target
let (job, _) = lab
.restore_until_ready()
.await
.expect("an undo job is waiting");
let artifact: Value = serde_json::from_str(&lab.scalar::<String>(&format!(
"SELECT artifact FROM restore_jobs WHERE id='{job}'"
)))
.unwrap();
assert_eq!(artifact["rollback"], true, "{artifact}");
assert_eq!(lab.capture_jobs(), captures, "an undo captures nothing");
let (_, token) = (
job.clone(),
lab.scalar::<String>(&format!(
"SELECT lease_token FROM restore_jobs WHERE id='{job}'"
)),
);
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
lab.report_applied(&job, &token).await;
lab.tick().await;
assert_eq!(lab.run(&undo_id).status, "completed");
// only the newest restore of a target can be undone: the first one no longer can, the undo can
let (_, old) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
let (_, new) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
.await;
assert_eq!(
(old["undo_available"].clone(), new["undo_available"].clone()),
(json!(false), json!(true))
);
assert!(lab
.audit_log()
.iter()
.any(|(event, _)| event == "restore.queued"));
}
#[tokio::test]
async fn an_undo_is_refused_when_there_is_nothing_sound_to_go_back_to() {
let lab = fresh().await;
let admin = lab.admin();
// a run that has not finished, and one that does not exist
let (_, running) = lab.start(&admin, "running").await;
let running = running["id"].as_str().unwrap().to_string();
for (what, id) in [
("unfinished", running.clone()),
("unknown", Uuid::new_v4().to_string()),
] {
let (status, body) = lab.start_undo(&admin, &format!("u-{what}"), &id).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{what}: {body}");
assert_eq!(body["reason"], "nothing_to_undo", "{what}");
}
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
lab.finish_restore().await;
// the safety copy has been removed from the vault
let safety = lab.scalar::<String>("SELECT safety_id FROM restore_jobs LIMIT 1");
lab.state
.vault
.write()
.await
.forget(&[Uuid::parse_str(&safety).unwrap()])
.unwrap();
let (status, body) = lab.start_undo(&admin, "gone", &running).await;
assert_eq!(
(status, body["reason"].clone()),
(StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")),
"{body}"
);
assert_eq!(
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"),
1,
"nothing was started"
);
}
#[tokio::test]
async fn a_safety_copy_is_only_ever_restored_onto_the_target_it_came_from() {
let lab = fresh().await;
let admin = lab.admin();
let first = lab.restored_once("first").await;
let own_safety =
Uuid::parse_str(&lab.scalar::<String>("SELECT safety_id FROM restore_jobs LIMIT 1"))
.unwrap();
let hints = lab
.state
.vault
.read()
.await
.get_snapshot(own_safety)
.unwrap()
.unwrap()
.manifest
.restore_hints;
// the same kind of copy, but taken from some other target
let mut foreign_hints = hints.clone();
foreign_hints["target_id"] = json!(Uuid::new_v4());
let foreign = lab
.plant_snapshot(lab.orbit, &["restore-safety"], foreign_hints)
.await;
let (status, body) = lab.start_snapshot(&admin, "foreign", foreign).await;
assert_eq!(
(status, body["reason"].clone()),
(StatusCode::UNPROCESSABLE_ENTITY, json!("snapshot_unusable")),
"{body}"
);
// its own copy is fine, through the plain snapshot route as well
let (status, body) = lab.start_snapshot(&admin, "own", own_safety).await;
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
let _ = first;
}
#[tokio::test]
async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
let lab = fresh().await;
let first = lab.restored_once("first").await;
let stranger = lab.person("stranger");
let status = lab.start_undo(&stranger, "s", &first).await.0;
assert!(
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
"{status}"
);
assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1);
}

View File

@@ -234,10 +234,42 @@ pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArti
format,
identity,
sha256,
rollback: false,
},
))
}
/// The artifact for putting a target back from the safety copy a restore took of it, or `None` when the
/// snapshot is not such a copy, was taken from some other target, or lacks what a restore needs. The copy is a
/// dump of the target itself, so its source identity is the target's own.
pub(crate) fn rollback_artifact(
manifest: &SnapshotManifest,
target: &tessera_core::restore::RestoreTarget,
) -> Option<RestoreArtifact> {
if !manifest.is_restore_safety() || manifest.safety_target()? != target.id.to_string() {
return None;
}
let format = match (
manifest.provider.as_str(),
manifest.restore_hints.get("format")?.as_str()?,
) {
("postgres", "custom") => CaptureFormat::PostgresCustom,
("postgres", "plain") => CaptureFormat::PostgresSql,
("mysql", "plain") => CaptureFormat::MysqlSql,
_ => return None,
};
let sha256 = manifest.restore_hints.get("sha256")?.as_str()?.to_owned();
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
(format.engine() == Some(target.engine)).then(|| RestoreArtifact {
format,
identity: target.identity.clone(),
sha256,
rollback: true,
})
}
async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,

View File

@@ -84,9 +84,77 @@ pub enum StartError {
/// What the confirmation must say: it names exactly what the person saw, including the version.
/// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one.
const EXISTING: &str = "existing:";
/// Same, for a run that puts a target back from the safety copy of an earlier restore.
const UNDO: &str = "undo:";
/// Does this run take its snapshot from the request instead of from a capture of its own?
fn picked_snapshot(run: &RefreshRun) -> bool {
run.capture_job_id.starts_with(EXISTING) || run.capture_job_id.starts_with(UNDO)
}
impl RefreshRun {
/// This run put a target back from a safety copy.
pub fn is_undo(&self) -> bool {
self.capture_job_id.starts_with(UNDO)
}
}
/// A relation's source orbit, for checking that a snapshot belongs to it.
/// 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.
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.
pub fn undo_candidate(
&self,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
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 Some(job) = &run.restore_job_id else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
let safety: Option<Option<String>> = conn
.query_row(
"SELECT safety_id FROM restore_jobs WHERE id = ?1 AND status = 'completed'",
params![job],
|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)?))
}
pub fn relation_target(&self, relation: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(relation_of(&conn, relation)?.map(|r| r.target_id))
}
pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id))
@@ -282,7 +350,8 @@ impl Db {
requester_user_id: Option<&str>,
authorized_by: &str,
idempotency_key: &str,
snapshot: Option<Uuid>,
// a snapshot to restore instead of capturing one, and whether it is an undo of an earlier restore
snapshot: Option<(Uuid, bool)>,
ttl_secs: i64,
max_active: i64,
now: i64,
@@ -324,7 +393,8 @@ impl Db {
// 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(_) => format!("{EXISTING}{id}"),
Some((_, true)) => format!("{UNDO}{id}"),
Some((_, false)) => format!("{EXISTING}{id}"),
None => {
let application = Uuid::parse_str(&relation.source_application_id)?;
let Some(capture) =
@@ -340,7 +410,7 @@ impl Db {
authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)",
params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id,
requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|s| s.to_string()), now, now + ttl_secs],
requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|(s, _)| s.to_string()), now, now + ttl_secs],
)?;
Ok(Ok((get(&tx, &id)?.expect("just inserted"), true)))
})()?;
@@ -446,7 +516,7 @@ impl Db {
if run.status != "capturing" || run.restore_job_id.is_some() {
return Ok(Linked::NotReady);
}
let snapshot = if run.capture_job_id.starts_with(EXISTING) {
let snapshot = if picked_snapshot(&run) {
let Some(snapshot) = run.snapshot_id.clone() else {
return Ok(Linked::NotReady);
};
@@ -613,7 +683,7 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
Ok(Sync::Moved(status.into()))
};
match run.status.as_str() {
"capturing" if run.capture_job_id.starts_with(EXISTING) => {
"capturing" if picked_snapshot(&run) => {
// Nothing to capture: the snapshot was chosen when the run was started.
match (&run.snapshot_id, &run.restore_job_id) {
(Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())),

View File

@@ -76,7 +76,7 @@ pub(crate) fn restore_target_mismatch(
) -> Option<&'static str> {
if Some(target.engine) != artifact.format.engine() {
Some("Database engine differs from the snapshot")
} else if target.identity == artifact.identity {
} else if target.identity == artifact.identity && !artifact.rollback {
Some("Target is the source database")
} else {
None
@@ -562,6 +562,7 @@ mod tests {
let artifact = RestoreArtifact {
format: CaptureFormat::PostgresCustom,
sha256: "0".repeat(64),
rollback: false,
identity: DatabaseIdentity {
instance: "123".into(),
database: "source".into(),

View File

@@ -47,6 +47,7 @@ fn now() -> i64 {
pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) {
match status {
"capturing" => ("refresh.started", AuditOutcome::Succeeded),
"undo" => ("refresh.undo_started", AuditOutcome::Succeeded),
"restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded),
"completed" => ("refresh.completed", AuditOutcome::Succeeded),
"reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded),
@@ -104,10 +105,18 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
.await
.get_snapshot(snapshot_id)?
.map(|s| s.manifest);
let artifact = manifest
.as_ref()
.and_then(crate::api::artifact)
.map(|(_, artifact)| artifact);
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
// A safety copy is restorable only onto the target it was taken from (an undo); anything else must be a
// capture with its source identity.
let artifact = manifest.as_ref().and_then(|manifest| {
if manifest.is_restore_safety() {
target
.as_ref()
.and_then(|target| crate::api::rollback_artifact(manifest, target))
} else {
crate::api::artifact(manifest).map(|(_, artifact)| artifact)
}
});
let Some(artifact) = artifact else {
// The snapshot is missing or lacks what a restore needs (format, checksum, source identity).
state
@@ -117,9 +126,9 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
return Ok(true);
};
// The driver looks again: a run that was told to restore a snapshot only restores one of its own source.
let belongs = manifest.as_ref().is_some_and(|manifest| {
manifest.orbit_id.to_string() == run.source_orbit_id && !manifest.is_restore_safety()
});
let belongs = manifest
.as_ref()
.is_some_and(|manifest| manifest.orbit_id.to_string() == run.source_orbit_id);
if !belongs {
state
.db
@@ -127,7 +136,6 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
audit_run(state, &run.id, "blocked");
return Ok(true);
}
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
let clash = match target {
Some(target) => {
let source = Uuid::parse_str(&run.source_orbit_id)?;