From 41fa1684de8eb13c5b76c3a3e174fece04ac5afa Mon Sep 17 00:00:00 2001 From: aur-build Date: Wed, 18 Nov 2026 16:49:40 +0000 Subject: db: the review, step, release and subscription states are enums too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M-8 named four more machines after `build_state`, and each had the same defect in miniature: `&str` constants, a writer that took any `&str`, and a rule that lived only in the caller's discipline. They are `CandidateState`, `StepState`, `ReleaseState` and `SubscriptionState` now, all parsed through one `db::state_col` at the row boundary — a column value the code cannot name fails the read rather than becoming a state it did not ask for. The one that mattered is the review machine. `resolve_in(tx, id, &str)` would move a candidate to any state from any state, so an approval racing a rejection, or a stale worker resolving a review that had already been superseded, silently overwrote what a human had decided — the direct route to breaking I2 and I3 with no symptom anywhere. It is a compare-and-swap on `CandidateState` now: a decided review is only ever frozen, never re-decided, and a refusal names both states. `supersede_in` goes through it, so the freeze cannot resurrect a superseded review either. `StepState` gives I5 teeth. `begin_step` upserted over any existing checkpoint, including one recorded `succeeded`, so a resume that asked to re-run a finished step could rewrite the very row that told it to skip; the upsert now refuses to touch a done checkpoint and `finish_step` is a CAS. The blocked path (`running → pending`) and the reaper's `running → interrupted` are unchanged, and both are in the table. Two behaviour changes, both for the better and both tested: the UI's pause button now says "orphaned: nothing to pause" instead of rewriting an orphaned subscription back to a pausable state, and a step checkpoint that is already done makes `begin_step` an error rather than a quiet overwrite. Five tests in `tests/state_machine.rs` cover the review CAS in both directions, the frozen checkpoint, the interrupted/blocked transitions, and the unknown value in a candidate and a step row. --- src/db/builds.rs | 90 +++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 63 insertions(+), 27 deletions(-) (limited to 'src/db/builds.rs') diff --git a/src/db/builds.rs b/src/db/builds.rs index a41308e..c1d65db 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -2,7 +2,7 @@ use rusqlite::{params, Connection, OptionalExtension}; -use crate::db::{BuildState, Db}; +use crate::db::{BuildState, Db, StepState}; use crate::error::{Error, Result}; use crate::time; @@ -31,17 +31,7 @@ const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_ attempt, priority, cancel_requested, error"; pub(crate) fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result { - let state_text: String = r.get(7)?; - let state = BuildState::parse(&state_text).ok_or_else(|| { - rusqlite::Error::FromSqlConversionFailure( - 7, - rusqlite::types::Type::Text, - Box::new(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("build has a state outside the state machine: {state_text:?}"), - )), - ) - })?; + let state = crate::db::state_col::(7, &r.get::<_, String>(7)?)?; Ok(BuildRow { id: r.get(0)?, pkgbase_id: r.get(1)?, @@ -324,7 +314,7 @@ pub fn cancel_requested(db: &Db, id: &str) -> Result { #[derive(Debug, Clone)] pub struct StepRow { pub step: String, - pub status: String, + pub status: StepState, pub attempt: i64, pub error: Option, } @@ -336,7 +326,12 @@ pub fn steps(db: &Db, id: &str) -> Result> { "SELECT step, status, attempt, error FROM build_step WHERE build_id=?1 ORDER BY rowid", )?; let rows = stmt.query_map(params![id], |r| { - Ok(StepRow { step: r.get(0)?, status: r.get(1)?, attempt: r.get(2)?, error: r.get(3)? }) + Ok(StepRow { + step: r.get(0)?, + status: crate::db::state_col::(1, &r.get::<_, String>(1)?)?, + attempt: r.get(2)?, + error: r.get(3)?, + }) })?; let mut out = Vec::new(); for r in rows { @@ -346,15 +341,16 @@ pub fn steps(db: &Db, id: &str) -> Result> { }) } -pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result> { +pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result> { let (b, s) = (build_id.to_string(), step.to_string()); db.read(move |c| { - Ok(c.query_row( + c.query_row( "SELECT status FROM build_step WHERE build_id=?1 AND step=?2", params![b, s], - |r| r.get(0), + |r| crate::db::state_col::(0, &r.get::<_, String>(0)?), ) - .optional()?) + .optional() + .map_err(Into::into) }) } @@ -362,29 +358,69 @@ pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<( let (b, s) = (build_id.to_string(), step.to_string()); let at = time::now(); db.writer.tx(move |tx| { - tx.execute( + // The `WHERE` is I5 with teeth: a step already checkpointed as done is + // frozen, so a resume that asks to re-run it cannot overwrite the record + // that told it to skip. The insert path is unaffected. + let n = tx.execute( "INSERT INTO build_step (build_id, step, status, attempt, started_at) VALUES (?1,?2,'running',?3,?4) ON CONFLICT(build_id, step) DO UPDATE SET status='running', attempt=?3, started_at=?4, - error=NULL", + error=NULL + WHERE build_step.status NOT IN ('succeeded','skipped')", params![b, s, attempt, at], )?; + if n == 0 { + return Err(Error::invalid(format!( + "step {s} of build {b} is already checkpointed as done and must not re-run (I5)" + ))); + } tx.execute("UPDATE build SET current_step=?1 WHERE id=?2", params![s, b])?; Ok(()) }) } -pub fn finish_step(db: &Db, build_id: &str, step: &str, status: &str, output_digest: Option<&str>, error: Option<&str>) -> Result<()> { - let (b, s, st) = (build_id.to_string(), step.to_string(), status.to_string()); +/// Record what a step produced. Refuses a transition [`StepState`] forbids — +/// above all, writing over a checkpoint a resume is relying on. +pub fn finish_step( + db: &Db, + build_id: &str, + step: &str, + to: StepState, + output_digest: Option<&str>, + error: Option<&str>, +) -> Result<()> { + let (b, s) = (build_id.to_string(), step.to_string()); let od = output_digest.map(|s| s.to_string()); let err = error.map(|s| s.to_string()); let at = time::now(); + let froms = StepState::predecessors(to); + let placeholders = froms.iter().map(|_| "?").collect::>().join(","); + let sql = format!( + "UPDATE build_step SET status=?1, output_digest=?2, error=?3, finished_at=?4 + WHERE build_id=?5 AND step=?6 AND status IN ({placeholders})" + ); db.writer.tx(move |tx| { - tx.execute( - "UPDATE build_step SET status=?1, output_digest=?2, error=?3, finished_at=?4 - WHERE build_id=?5 AND step=?6", - params![st, od, err, at, b, s], - )?; + let status = to.as_str(); + let mut args: Vec<&dyn rusqlite::ToSql> = vec![&status, &od, &err, &at, &b, &s]; + for f in &froms { + args.push(f); + } + let n = tx.execute(&sql, rusqlite::params_from_iter(args))?; + if n == 0 { + let was: Option = tx + .query_row( + "SELECT status FROM build_step WHERE build_id=?1 AND step=?2", + params![b, s], + |r| r.get(0), + ) + .optional()?; + return Err(match was { + Some(w) => Error::invalid(format!( + "illegal step transition {w} → {to} for step {s} of build {b}" + )), + None => Error::invalid(format!("no checkpoint for step {s} of build {b}")), + }); + } Ok(()) }) } -- cgit v1.2.3