feat: say why a restore failed, and add the user_schemas reset mode
- the agent reports the client's primary ERROR/FATAL line with a failed restore step; the hub keeps it as failure_reason (administrators only), logs it and audits restore.failed. psql runs with VERBOSITY=terse and DETAIL/CONTEXT/statement text is dropped so row data never travels - reset mode user_schemas empties every non-system schema in the restore transaction, so multi-schema databases restore without DROP DATABASE; proven against a real PostgreSQL server Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -412,6 +412,10 @@ impl Lab {
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
fn audit_log(&self) -> Vec<(String, String)> {
|
||||
self.state.db.audit_log_events()
|
||||
}
|
||||
|
||||
fn restore_jobs(&self) -> i64 {
|
||||
self.scalar("SELECT COUNT(*) FROM restore_jobs")
|
||||
}
|
||||
@@ -1518,3 +1522,125 @@ async fn only_an_administrator_can_change_a_profile() {
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
|
||||
// ---- why a restore failed ----
|
||||
|
||||
impl Lab {
|
||||
async fn report_with_reason(
|
||||
&self,
|
||||
job: &str,
|
||||
token: &str,
|
||||
progress: &str,
|
||||
reason: &str,
|
||||
) -> StatusCode {
|
||||
self.agent_json(
|
||||
"POST",
|
||||
&format!("/api/v1/wormhole/restore/{job}/report"),
|
||||
&[
|
||||
("x-tessera-restore-token", token.to_string()),
|
||||
("x-tessera-failure-reason", reason.to_string()),
|
||||
],
|
||||
json!(progress),
|
||||
)
|
||||
.await
|
||||
.0
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_restore_says_why_to_administrators_only() {
|
||||
let lab = fresh().await;
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let run = lab.start(&qa, "why").await.1["id"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
lab.capture(&Lab::production_identity(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
lab.tick().await;
|
||||
let (job, token) = lab.restore_until_ready().await.unwrap();
|
||||
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
|
||||
let reason = "psql failed (exit status: 3): ERROR: schema \"drizzle\" already exists";
|
||||
assert_eq!(
|
||||
lab.report_with_reason(&job, &token, "apply_failed", reason)
|
||||
.await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
|
||||
let (status, view) = lab
|
||||
.send(
|
||||
&lab.admin(),
|
||||
"GET",
|
||||
&format!("/api/v1/restore-jobs/{job}"),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(view["phase"], "apply_failed");
|
||||
// whitespace is normalised on the way in (psql pads "ERROR: ")
|
||||
assert_eq!(
|
||||
view["failure_reason"],
|
||||
"psql failed (exit status: 3): ERROR: schema \"drizzle\" already exists"
|
||||
);
|
||||
assert!(lab
|
||||
.audit_log()
|
||||
.iter()
|
||||
.any(|(event, detail)| event == "restore.failed" && detail.contains("drizzle")));
|
||||
|
||||
// the person who started the refresh sees that it failed, never the database's own words
|
||||
lab.tick().await;
|
||||
let (_, seen) = lab
|
||||
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{run}"), None)
|
||||
.await;
|
||||
assert_eq!(seen["status"], "recovery_required", "{seen}");
|
||||
assert!(
|
||||
!seen.to_string().contains("drizzle") && seen.get("failure_reason").is_none(),
|
||||
"{seen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failure_reason_is_only_kept_for_failures_and_is_cleaned_and_bounded() {
|
||||
let lab = fresh().await;
|
||||
lab.start(&lab.admin(), "clean").await;
|
||||
lab.capture(&Lab::production_identity(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
lab.tick().await;
|
||||
let (job, token) = lab.restore_until_ready().await.unwrap();
|
||||
// a heartbeat that carries a reason does not create one
|
||||
assert_eq!(
|
||||
lab.report_with_reason(&job, &token, "heartbeat", "ignored")
|
||||
.await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
let admin = lab.admin();
|
||||
let uri = format!("/api/v1/restore-jobs/{job}");
|
||||
assert!(lab
|
||||
.send(&admin, "GET", &uri, None)
|
||||
.await
|
||||
.1
|
||||
.get("failure_reason")
|
||||
.is_none());
|
||||
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
|
||||
let long = format!("ERROR:\t{}\tend", "x".repeat(2000));
|
||||
assert_eq!(
|
||||
lab.report_with_reason(&job, &token, "apply_failed", &long)
|
||||
.await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
let reason = lab.send(&admin, "GET", &uri, None).await.1["failure_reason"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(
|
||||
reason.len() <= 300 && reason.starts_with("ERROR: xxx"),
|
||||
"{}",
|
||||
reason.len()
|
||||
);
|
||||
assert!(
|
||||
reason.chars().all(|c| c.is_ascii() && !c.is_control()),
|
||||
"{reason:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -365,13 +365,22 @@ async fn report(
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let (outpost, token) = auth(&state, &headers)?;
|
||||
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
// Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not
|
||||
// with what ends up in the database and the log.
|
||||
let reason = headers
|
||||
.get(tessera_core::restore::FAILURE_REASON_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(tessera_core::restore::clean_failure_reason);
|
||||
if !state
|
||||
.db
|
||||
.report_restore(outpost, id, token, progress, now())
|
||||
.report_restore(outpost, id, token, progress, reason.as_deref(), now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
if let Some(reason) = &reason {
|
||||
tracing::warn!(job = %id, ?progress, %reason, "restore step failed");
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -27,17 +27,20 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
lease_token TEXT,
|
||||
lease_until INTEGER,
|
||||
attempt_safety_id TEXT,
|
||||
safety_id TEXT
|
||||
safety_id TEXT,
|
||||
failure_reason 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);",
|
||||
)?;
|
||||
// databases created before failure reasons existed
|
||||
ensure_column(conn, "restore_jobs", "failure_reason", "TEXT")?;
|
||||
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
|
||||
j.updated_at, j.artifact, j.attempt_safety_id, j.failure_reason
|
||||
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
|
||||
|
||||
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
|
||||
@@ -63,6 +66,7 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
|
||||
.map_err(|err| invalid_column(6, err))?,
|
||||
created_at: row.get(7)?,
|
||||
updated_at: row.get(8)?,
|
||||
failure_reason: row.get(11)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -319,6 +323,7 @@ impl Db {
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
progress: RestoreProgress,
|
||||
reason: Option<&str>,
|
||||
now: i64,
|
||||
) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
@@ -348,6 +353,24 @@ impl Db {
|
||||
if !matches!(progress, RestoreProgress::Heartbeat) {
|
||||
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
|
||||
}
|
||||
let failed = matches!(
|
||||
progress,
|
||||
RestoreProgress::InvalidPayload
|
||||
| RestoreProgress::WrongTarget
|
||||
| RestoreProgress::SafetyFailed
|
||||
| RestoreProgress::ApplyFailed
|
||||
);
|
||||
if let (true, Some(reason)) = (failed, reason) {
|
||||
tx.execute(
|
||||
"UPDATE restore_jobs SET failure_reason = ?2 WHERE id = ?1",
|
||||
params![id.to_string(), reason],
|
||||
)?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.failed",
|
||||
&format!("job={id} phase={phase} reason={reason}"),
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
}
|
||||
@@ -568,10 +591,24 @@ mod tests {
|
||||
.authorize_apply(outpost, job.id, lease.token, 104)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
|
||||
.report_restore(
|
||||
outpost,
|
||||
job.id,
|
||||
lease.token,
|
||||
RestoreProgress::Checking,
|
||||
None,
|
||||
104
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
|
||||
.report_restore(
|
||||
outpost,
|
||||
job.id,
|
||||
lease.token,
|
||||
RestoreProgress::Safety,
|
||||
None,
|
||||
105
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
|
||||
|
||||
Reference in New Issue
Block a user