Files
tessera/crates/tessera-hub/src/db/restore.rs
Adnan Zahir da46453c13 feat: durable refresh runs from a source to a staging target (auth M6c)
A refresh captures a new dump of the relation's source, then restores exactly that
snapshot onto the relation's target through the existing restore path.

- refresh_runs in SQLite, one active run per target, per-requester idempotency keys,
  a cap on concurrent runs and a TTL that only applies until the restore starts overwriting
- the run and its capture job are created in one transaction; the run follows its own
  capture job, never the latest snapshot, and pins that snapshot until it ends
- the restore is queued and linked in one guarded transaction; every step is safe to repeat
  after a crash; a background driver only reads the database
- authorize_apply re-checks, in the transaction that allows the overwrite, that the relation
  is still usable, the requester is still active, the authorising grant still exists, the
  deadline has not passed and the target is not the source; otherwise the restore is
  cancelled, the run is blocked and the agent gets 409. Administrator restores are untouched
- POST/GET/DELETE /api/v1/refresh-runs: confirmation names source, target and version;
  non-administrators never see the snapshot id, the requester or the database identity
- audit refresh.* per run

Tests drive the agent through the real Outpost endpoints and cover revocation at every
stage; the access matrix gains a RunRow kind.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:23:13 +07:00

599 lines
24 KiB
Rust

use super::{jobs::invalid_column, *};
use rusqlite::{Row, Transaction, TransactionBehavior};
use tessera_core::{
job::CAPTURE_LEASE_SECONDS,
restore::{RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreTarget},
};
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS restore_targets (
id TEXT PRIMARY KEY,
application_id TEXT NOT NULL,
outpost_id TEXT NOT NULL,
identity TEXT NOT NULL UNIQUE,
profile TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS restore_jobs (
id TEXT PRIMARY KEY,
snapshot_id TEXT NOT NULL,
target_id TEXT NOT NULL,
actor TEXT NOT NULL,
artifact TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
phase TEXT NOT NULL DEFAULT 'queued',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
lease_token TEXT,
lease_until INTEGER,
attempt_safety_id TEXT,
safety_id TEXT
);
CREATE INDEX IF NOT EXISTS restore_jobs_target ON restore_jobs(target_id, status);
CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_id, status);",
)?;
Ok(())
}
const VIEW: &str =
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at,
j.updated_at, j.artifact, j.attempt_safety_id
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn json<T: serde::de::DeserializeOwned>(row: &Row<'_>, index: usize) -> rusqlite::Result<T> {
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
Ok(RestoreJob {
id: uuid(row, 0)?,
snapshot_id: uuid(row, 1)?,
target: json(row, 2)?,
actor: row.get(3)?,
status: row.get(4)?,
phase: row.get(5)?,
safety_snapshot_id: row
.get::<_, Option<String>>(6)?
.map(|id| Uuid::parse_str(&id))
.transpose()
.map_err(|err| invalid_column(6, err))?,
created_at: row.get(7)?,
updated_at: row.get(8)?,
})
}
pub(crate) fn restore_target_mismatch(
target: &RestoreTarget,
artifact: &RestoreArtifact,
) -> Option<&'static str> {
if Some(target.engine) != artifact.format.engine() {
Some("Database engine differs from the snapshot")
} else if target.identity == artifact.identity {
Some("Target is the source database")
} else {
None
}
}
impl Db {
pub fn register_restore_target(&self, target: &RestoreTarget) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?6)
ON CONFLICT DO NOTHING",
params![
target.id.to_string(),
target.application_id.to_string(),
target.outpost_id.to_string(),
serde_json::to_string(&(target.engine, &target.identity))?,
serde_json::to_string(target)?,
chrono::Utc::now().timestamp(),
],
)?;
Ok(changed == 1)
}
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
Ok(self.restore_targets_with_activity(application)?
.into_iter().map(|(target, _)| target).collect())
}
pub fn restore_targets_with_activity(&self, application: Uuid) -> Result<Vec<(RestoreTarget, bool)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials
WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?2)
FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
)?;
let rows = stmt.query_map(params![application.to_string(), chrono::Utc::now().timestamp()], |row| Ok((json(row, 0)?, row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn enqueue_restore(
&self,
snapshot: Uuid,
application: Uuid,
target: Uuid,
actor: &str,
artifact: &RestoreArtifact,
now: i64,
) -> Result<Option<RestoreJob>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let job = enqueue_restore_in(&tx, snapshot, application, target, actor, artifact, now)?;
tx.commit()?;
Ok(job)
}
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
Ok(conn
.query_row(
&format!("{VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)
.optional()?)
}
pub fn restore_history(&self, snapshot: Uuid, now: i64) -> Result<Vec<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
let mut stmt = conn.prepare(&format!(
"{VIEW} WHERE j.snapshot_id = ?1 ORDER BY j.rowid DESC LIMIT 25"
))?;
let rows = stmt.query_map([snapshot.to_string()], read_job)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The newest restore jobs across every snapshot, newest first, for the activity log.
pub fn restore_recent(&self, limit: u32, now: i64) -> Result<Vec<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
let mut stmt = conn.prepare(&format!("{VIEW} ORDER BY j.rowid DESC LIMIT ?1"))?;
let rows = stmt.query_map([limit], read_job)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn snapshot_in_restore(&self, id: Uuid) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1)
AND status IN ('queued','running','applying','recovery_required'))
-- a refresh run pins its own snapshot from the moment it starts: the snapshot id is its capture job id
OR EXISTS(SELECT 1 FROM refresh_runs WHERE capture_job_id = ?1
AND status IN ('capturing','restoring','recovery_required'))",
[id.to_string()], |row| row.get(0),
)?)
}
pub fn claim_restore(
&self,
outpost: Uuid,
target: Uuid,
now: i64,
) -> Result<Option<RestoreLease>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
expire_destructive(&tx, now)?;
let selected = tx.query_row(
&format!("{VIEW} WHERE t.id = ?1 AND t.outpost_id = ?2
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
AND NOT EXISTS (
SELECT 1 FROM restore_jobs active JOIN restore_targets owner ON owner.id = active.target_id
WHERE owner.application_id = t.application_id
AND (active.status IN ('applying','recovery_required')
OR (active.status = 'running' AND active.lease_until > ?3))
)
AND NOT EXISTS (
SELECT 1 FROM capture_jobs c WHERE c.application_id = t.application_id
AND c.status = 'running' AND c.lease_until > ?3
)
ORDER BY j.created_at, j.rowid LIMIT 1"),
params![target.to_string(), outpost.to_string(), now],
|row| Ok((read_job(row)?, json(row, 9)?)),
).optional()?;
let Some((mut job, artifact)) = selected else {
tx.commit()?;
return Ok(None);
};
let token = Uuid::new_v4();
tx.execute(
"UPDATE restore_jobs SET status = 'running', phase = 'claimed', lease_token = ?2, lease_until = ?3,
attempt_safety_id = ?4, safety_id = NULL, updated_at = ?5 WHERE id = ?1",
params![job.id.to_string(), token.to_string(), now + CAPTURE_LEASE_SECONDS,
Uuid::new_v4().to_string(), now],
)?;
job.status = "running".into();
job.phase = "claimed".into();
job.safety_snapshot_id = None;
job.updated_at = now;
tx.commit()?;
Ok(Some(RestoreLease {
job,
token,
artifact,
}))
}
pub fn restore_access(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
restore_access(&self.conn.lock().unwrap(), outpost, id, token, now)
}
pub fn record_safety(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
publish: impl FnOnce(Uuid) -> Result<()>,
) -> Result<Option<Uuid>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, expected)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(None);
};
if job.status != "running" {
return Ok(None);
}
if let Some(safety) = job.safety_snapshot_id {
return Ok(Some(safety));
}
if job.phase != "safety" {
return Ok(None);
}
publish(expected)?;
tx.execute("UPDATE restore_jobs SET phase = 'ready', safety_id = ?2, updated_at = ?3 WHERE id = ?1",
params![id.to_string(), expected.to_string(), now])?;
audit(
&tx,
"restore.safety_committed",
&format!("job={id} snapshot={expected}"),
)?;
tx.commit()?;
Ok(Some(expected))
}
pub fn authorize_apply(&self, outpost: Uuid, id: Uuid, token: Uuid, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(false);
};
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
return Ok(false);
}
// A refresh is only allowed to overwrite its target while what authorised it still holds. The check
// and the flip to `applying` are one transaction, and the agent applies nothing without this answer.
// Restores an administrator queued directly have no run and behave exactly as before.
if let Some(run) = super::refresh::run_for_restore(&tx, &id.to_string())? {
if let Some(reason) = super::refresh::invalid_reason(&tx, &run, now)? {
super::refresh::block(&tx, &run, reason, now)?;
tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status='running'", params![id.to_string(), now])?;
audit(&tx, "restore.apply_refused", &format!("job={id} run={} reason={reason}", run.id))?;
tx.commit()?;
return Ok(false);
}
}
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
audit(
&tx,
"restore.apply_authorized",
&format!("job={id} target={}", job.target.id),
)?;
tx.commit()?;
Ok(true)
}
pub fn report_restore(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
progress: RestoreProgress,
now: i64,
) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(false);
};
let (status, phase) = match progress {
RestoreProgress::Heartbeat => (job.status.as_str(), job.phase.as_str()),
RestoreProgress::Checking if job.phase == "claimed" => ("running", "checking"),
RestoreProgress::Safety if job.phase == "checking" => ("running", "safety"),
RestoreProgress::InvalidPayload if job.phase == "checking" => {
("failed", "invalid_payload")
}
RestoreProgress::WrongTarget if job.phase == "checking" => ("failed", "wrong_target"),
RestoreProgress::SafetyFailed if matches!(job.phase.as_str(), "safety" | "ready") => {
("failed", "safety_failed")
}
RestoreProgress::Applied if job.status == "applying" => ("completed", "completed"),
RestoreProgress::ApplyFailed if job.status == "applying" => {
("recovery_required", "apply_failed")
}
_ => return Ok(false),
};
tx.execute("UPDATE restore_jobs SET status = ?2, phase = ?3, updated_at = ?4, lease_until = ?5 WHERE id = ?1",
params![id.to_string(), status, phase, now, now + CAPTURE_LEASE_SECONDS])?;
if !matches!(progress, RestoreProgress::Heartbeat) {
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
}
tx.commit()?;
Ok(true)
}
pub fn reconcile_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
expire_destructive(&tx, now)?;
let changed = tx.execute(
"UPDATE restore_jobs SET status = 'reconciled', phase = 'reconciled', updated_at = ?2
WHERE id = ?1 AND status = 'recovery_required'",
params![id.to_string(), now],
)?;
if changed == 1 {
audit(
&tx,
"restore.reconciled",
&format!("actor={actor} job={id}"),
)?;
}
tx.commit()?;
Ok(changed == 1)
}
pub fn cancel_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let changed = tx.execute(
"UPDATE restore_jobs SET status = 'cancelled', phase = 'cancelled', updated_at = ?2
WHERE id = ?1 AND status IN ('queued','running')",
params![id.to_string(), now],
)?;
if changed == 1 {
audit(&tx, "restore.cancelled", &format!("actor={actor} job={id}"))?;
}
tx.commit()?;
Ok(changed == 1)
}
}
/// Queue a restore inside a transaction the caller owns, so a refresh run can link it atomically.
pub(super) fn enqueue_restore_in(
tx: &Transaction<'_>,
snapshot: Uuid,
application: Uuid,
target: Uuid,
actor: &str,
artifact: &RestoreArtifact,
now: i64,
) -> Result<Option<RestoreJob>> {
let registered: Option<RestoreTarget> = tx.query_row(
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)",
params![target.to_string(), application.to_string(), now],
|row| json(row, 0),
).optional()?;
let Some(registered) = registered else {
return Ok(None);
};
if restore_target_mismatch(&registered, artifact).is_some() {
return Ok(None);
}
let id = Uuid::new_v4();
tx.execute(
"INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
params![id.to_string(), snapshot.to_string(), target.to_string(), actor,
serde_json::to_string(artifact)?, now],
)?;
audit(
&tx,
"restore.queued",
&format!("actor={actor} job={id} snapshot={snapshot} target={target}"),
)?;
let job = tx.query_row(
&format!("{VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)?;
Ok(Some(job))
}
fn restore_access(
conn: &Connection,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
Ok(conn
.query_row(
&format!(
"{VIEW} WHERE j.id = ?1 AND t.outpost_id = ?2 AND j.lease_token = ?3
AND j.lease_until > ?4 AND j.status IN ('running', 'applying')"
),
params![id.to_string(), outpost.to_string(), token.to_string(), now],
|row| Ok((read_job(row)?, json(row, 9)?, uuid(row, 10)?)),
)
.optional()?)
}
fn expire_destructive(conn: &Connection, now: i64) -> Result<()> {
conn.execute(
"UPDATE restore_jobs SET status = 'recovery_required', phase = 'lease_lost', updated_at = ?1
WHERE status = 'applying' AND lease_until <= ?1",
[now],
)?;
Ok(())
}
fn audit(tx: &Transaction<'_>, event: &str, detail: &str) -> Result<()> {
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), ?1, ?2)",
params![event, detail],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::{
job::{CaptureFormat, CaptureProfile},
restore::{DatabaseIdentity, Engine},
};
#[tokio::test]
async fn expired_apply_survives_restart_and_fences_the_target_until_reconciled() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("restore.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_test_credential("synthetic-token", &outpost.to_string(), "agent");
let orbit = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit,
name: "fixture".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
let app = Uuid::new_v4();
assert!(db
.register_capture_profile(
&CaptureProfile {
application_id: app,
orbit_id: orbit,
outpost_id: outpost,
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
},
100
)
.unwrap());
let target = Uuid::new_v4();
assert!(db
.register_restore_target(&RestoreTarget {
id: target,
application_id: app,
outpost_id: outpost,
name: "target".into(),
engine: Engine::Postgres,
identity: DatabaseIdentity {
instance: "123".into(),
database: "target".into()
},
})
.unwrap());
let snapshot = Uuid::new_v4();
let artifact = RestoreArtifact {
format: CaptureFormat::PostgresCustom,
sha256: "0".repeat(64),
identity: DatabaseIdentity {
instance: "123".into(),
database: "source".into(),
},
};
let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap();
assert!(registered.1);
let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() };
assert_eq!(restore_target_mismatch(&registered.0, &same_source), Some("Target is the source database"));
assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none());
let job = db
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
.unwrap()
.unwrap();
let next_snapshot = Uuid::new_v4();
let next = db
.enqueue_restore(next_snapshot, app, target, "fixture", &artifact, 101)
.unwrap()
.unwrap();
let lease = db.claim_restore(outpost, target, 102).unwrap().unwrap();
assert_eq!(lease.job.id, job.id);
assert!(db.claim_restore(outpost, target, 103).unwrap().is_none());
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 104)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
.unwrap());
assert!(db
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
"synthetic write failure"
))
.is_err());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 107)
.unwrap());
let safety = db
.record_safety(outpost, job.id, lease.token, 108, |_| Ok(()))
.unwrap()
.unwrap();
assert!(db
.authorize_apply(outpost, job.id, lease.token, 109)
.unwrap());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 110)
.unwrap());
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let late = 109 + CAPTURE_LEASE_SECONDS;
assert!(db.claim_restore(outpost, target, late).unwrap().is_none());
assert!(db
.restore_access(outpost, job.id, lease.token, late)
.unwrap()
.is_none());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, late)
.unwrap());
let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
assert_eq!(interrupted.status, "recovery_required");
let recent = db.restore_recent(10, late).unwrap();
assert_eq!(recent.iter().map(|item| item.id).collect::<Vec<_>>(), vec![next.id, job.id]);
assert_eq!(db.restore_recent(1, late).unwrap().len(), 1);
assert_eq!(interrupted.safety_snapshot_id, Some(safety));
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(db.snapshot_in_restore(safety).unwrap());
assert!(db.reconcile_restore(job.id, "fixture", late + 1).unwrap());
assert!(!db.snapshot_in_restore(snapshot).unwrap());
assert!(!db.snapshot_in_restore(safety).unwrap());
let retry = db
.claim_restore(outpost, target, late + 2)
.unwrap()
.unwrap();
assert_eq!(retry.job.id, next.id);
assert_ne!(retry.token, lease.token);
}
}