diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 16:31:58 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 16:31:58 +0000 |
| commit | 101f077200e80c7869e4549db645ed94b01acb1b (patch) | |
| tree | f8560d143ef2afe1a3d675a203c693a09cbc451b | |
| parent | f8370b48f3e4464a1454d0ff7af1819b5448c619 (diff) | |
| download | aur-build-101f077200e80c7869e4549db645ed94b01acb1b.tar.gz aur-build-101f077200e80c7869e4549db645ed94b01acb1b.zip | |
db: the build state machine is an enum, and a state write is a compare-and-swap
`build_state` was seven `&str` constants and `set_state(&str)` would write any
string a caller invented, so the machine existed only as `WHERE state IN (...)`
clauses scattered across six modules and nothing could say that
`succeeded → running` is nonsense. It is `db::model::BuildState` now: parsed
where a row is read (a state the code cannot name is an error, not an empty
string — which also retires m-12's `current_state` returning `""`), and
`set_state` takes the variant and writes only if the row's current state is one
of `to`'s legal predecessors. A refused transition writes nothing and says why.
Writing the machine down surfaced three things that were true of the flows but
of nobody's documentation. The step loop re-asserts `Running` at every step
boundary, so a self-write is a no-op and not a move — every state accepts its
own name. A failed build is resumed *on its own row* (I5: the step checkpoints
say where to continue), so `failed → running` is a real transition. And
`builds::retry` — the UI's requeue button — moved any row to `queued`
unconditionally, including one that had already published, re-queueing a build
whose every step was checkpointed as done; it goes through the machine now and
is refused with a reason. `requeue_transient` likewise.
What the CAS buys is the zombie case, which no test covered: a worker's lease
expires mid-step, the reaper returns the build to the queue, and the original
worker — still running — comes back and writes `succeeded` over whatever the new
owner has since done. That write now fails loudly and the queue keeps ownership.
`builds_for_pkgbase` had a second, hand-copied row mapper that dropped unreadable
rows with `filter_map(|r| r.ok())`; it shares `row_to_build` now and a bad row
fails the query instead of vanishing from the package page (m-9's policy,
applied where it bit).
`tests/state_machine.rs` pins the whole table, the zombie refusal, the unknown
state, the terminal build that does not move, and the requeue-of-a-published-
build refusal. `tests/live.rs` walks a build through `running` before succeeding
instead of teleporting it.
| -rw-r--r-- | src/db/builds.rs | 122 | ||||
| -rw-r--r-- | src/db/model.rs | 132 | ||||
| -rw-r--r-- | src/db/queries.rs | 14 | ||||
| -rw-r--r-- | src/http/routes.rs | 12 | ||||
| -rw-r--r-- | src/http/sse.rs | 6 | ||||
| -rw-r--r-- | src/main.rs | 2 | ||||
| -rw-r--r-- | src/pipeline/mod.rs | 8 | ||||
| -rw-r--r-- | tests/crash.rs | 14 | ||||
| -rw-r--r-- | tests/dispatch.rs | 24 | ||||
| -rw-r--r-- | tests/invariants.rs | 2 | ||||
| -rw-r--r-- | tests/live.rs | 8 | ||||
| -rw-r--r-- | tests/pipeline.rs | 2 | ||||
| -rw-r--r-- | tests/staleness.rs | 10 | ||||
| -rw-r--r-- | tests/state_machine.rs | 170 | ||||
| -rw-r--r-- | tests/surfaces.rs | 2 |
15 files changed, 422 insertions, 106 deletions
diff --git a/src/db/builds.rs b/src/db/builds.rs index 5c4d1d4..a41308e 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -2,8 +2,8 @@ use rusqlite::{params, Connection, OptionalExtension}; -use crate::db::Db; -use crate::error::Result; +use crate::db::{BuildState, Db}; +use crate::error::{Error, Result}; use crate::time; #[derive(Debug, Clone)] @@ -15,7 +15,7 @@ pub struct BuildRow { pub kind: String, pub world_snapshot_id: Option<i64>, pub build_profile: String, - pub state: String, + pub state: BuildState, pub blocked_on_json: String, pub current_step: Option<String>, pub lease_owner: Option<String>, @@ -30,7 +30,18 @@ const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_ build_profile, state, blocked_on_json, current_step, lease_owner, lease_expires_at, \ attempt, priority, cancel_requested, error"; -fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> { +pub(crate) fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> { + 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:?}"), + )), + ) + })?; Ok(BuildRow { id: r.get(0)?, pkgbase_id: r.get(1)?, @@ -39,7 +50,7 @@ fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> { kind: r.get(4)?, world_snapshot_id: r.get(5)?, build_profile: r.get(6)?, - state: r.get(7)?, + state, blocked_on_json: r.get(8)?, current_step: r.get(9)?, lease_owner: r.get(10)?, @@ -95,8 +106,8 @@ pub fn get(db: &Db, id: &str) -> Result<Option<BuildRow>> { }) } -pub fn list(db: &Db, states: &[&str], limit: i64) -> Result<Vec<BuildRow>> { - let states = states.iter().map(|s| s.to_string()).collect::<Vec<_>>(); +pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>> { + let states = states.iter().map(|s| s.as_str().to_string()).collect::<Vec<_>>(); db.read(move |c| { let placeholders = states.iter().map(|_| "?").collect::<Vec<_>>().join(","); let sql = format!( @@ -192,30 +203,57 @@ pub fn reap_expired(db: &Db) -> Result<usize> { }) } -pub fn set_state(db: &Db, id: &str, state: &str, error: Option<&str>) -> Result<()> { - let (id, state) = (id.to_string(), state.to_string()); - let error = error.map(|e| e.to_string()); +/// The one way a build changes state, usable inside a transaction. +/// +/// The write is a compare-and-swap: only a row currently in one of `to`'s legal +/// predecessor states is updated, so two workers cannot both land a terminal +/// state, and a zombie worker whose lease was reaped gets an error instead of +/// silently rewriting a build that has since been handed to somebody else. +fn transition_in_tx( + tx: &mut rusqlite::Transaction<'_>, + id: &str, + to: BuildState, + error: Option<&str>, +) -> Result<()> { + let froms = BuildState::predecessors(to); + let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE build SET state=?1, error=?2, updated_at=?3, lease_owner=NULL, + lease_expires_at=NULL WHERE id=?4 AND state IN ({placeholders})" + ); let at = time::now(); - db.writer.tx(move |tx| { - tx.execute( - "UPDATE build SET state=?1, error=?2, updated_at=?3, lease_owner=NULL, - lease_expires_at=NULL WHERE id=?4", - params![state, error, at, id], - )?; - Ok(()) - }) + let state = to.as_str(); + let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &error, &at, &id]; + for f in &froms { + args.push(f); + } + let n = tx.execute(&sql, rusqlite::params_from_iter(args))?; + if n == 0 { + let was: Option<String> = tx + .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) + .optional()?; + return Err(match was { + Some(s) => Error::invalid(format!("illegal build transition {s} → {to} for build {id}")), + None => Error::invalid(format!("no build {id} to move to {to}")), + }); + } + Ok(()) +} + +/// Move a build to `to`, refusing any transition [`BuildState`] forbids. +pub fn set_state(db: &Db, id: &str, to: BuildState, error: Option<&str>) -> Result<()> { + let id = id.to_string(); + let error = error.map(|e| e.to_string()); + db.writer + .tx(move |tx| transition_in_tx(tx, &id, to, error.as_deref())) } pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { let id = id.to_string(); let json = serde_json::to_string(blocked_on)?; - let at = time::now(); db.writer.tx(move |tx| { - tx.execute( - "UPDATE build SET state='blocked_missing_dep', blocked_on_json=?1, updated_at=?2, - lease_owner=NULL, lease_expires_at=NULL WHERE id=?3", - params![json, at, id], - )?; + transition_in_tx(tx, &id, BuildState::BlockedMissingDep, None)?; + tx.execute("UPDATE build SET blocked_on_json=?1 WHERE id=?2", params![json, id])?; Ok(()) }) } @@ -455,10 +493,16 @@ pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } -pub fn current_state(c: &Connection, id: &str) -> Result<String> { - Ok(c.query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) - .optional()? - .unwrap_or_default()) +pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> { + let s: Option<String> = c + .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) + .optional()?; + match s { + None => Ok(None), + Some(text) => BuildState::parse(&text) + .map(Some) + .ok_or_else(|| Error::invalid(format!("build {id} has a state outside the state machine: {text:?}"))), + } } /// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and @@ -512,15 +556,8 @@ pub fn cancel_superseded(db: &Db) -> Result<usize> { /// count so the retry cap can bite (§8.4). pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); - let at = time::now(); - db.writer.tx(move |tx| { - tx.execute( - "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL, - error=NULL, updated_at=?1 WHERE id=?2", - params![at, id], - )?; - Ok(()) - }) + db.writer + .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } /// Explicitly retry a failed build (§8.4). This is a human decision, not a @@ -528,18 +565,17 @@ pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { /// that succeeded stays checkpointed, and the attempt counter keeps counting. pub fn retry(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); - let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE build_step SET status='pending', error=NULL, started_at=NULL, finished_at=NULL WHERE build_id=?1 AND status IN ('failed','interrupted')", params![id], )?; - tx.execute( - "UPDATE build SET state='queued', error=NULL, cancel_requested=0, - lease_owner=NULL, lease_expires_at=NULL, updated_at=?2 WHERE id=?1", - params![id, at], - )?; + // The move itself goes through the machine, so requeueing a build that + // already published is refused with a reason instead of silently + // re-queueing a row whose every step is checkpointed as done. + transition_in_tx(tx, &id, BuildState::Queued, None)?; + tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?; Ok(()) }) } diff --git a/src/db/model.rs b/src/db/model.rs index dfc1f8b..bf3e017 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -112,14 +112,130 @@ pub mod release_state { pub const FAILED_UNBUILT: &str = "failed_unbuilt"; } -pub mod build_state { - pub const QUEUED: &str = "queued"; - pub const LEASED: &str = "leased"; - pub const RUNNING: &str = "running"; - pub const BLOCKED_MISSING_DEP: &str = "blocked_missing_dep"; - pub const SUCCEEDED: &str = "succeeded"; - pub const FAILED: &str = "failed"; - pub const CANCELLED: &str = "cancelled"; +/// The build state machine (§7.1, §8.2). +/// +/// This used to be seven `&str` constants and a `set_state(&str)` that wrote any +/// string a caller invented, so the machine existed only as `WHERE state IN +/// (...)` clauses scattered across six modules — nothing could tell you that +/// `succeeded → running` is nonsense. The enum is the machine: a state is one +/// of these seven, it is parsed where a row is read, and `can_transition` is +/// the only way a write happens. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum BuildState { + /// Approved and waiting for a worker. + Queued, + /// Claimed by a worker with a lease (§8.2). + Leased, + /// A step is executing. + Running, + /// Waiting for packages another build must publish first (§10.4). + BlockedMissingDep, + Succeeded, + Failed, + Cancelled, +} + +impl BuildState { + pub const ALL: &'static [BuildState] = &[ + BuildState::Queued, + BuildState::Leased, + BuildState::Running, + BuildState::BlockedMissingDep, + BuildState::Succeeded, + BuildState::Failed, + BuildState::Cancelled, + ]; + + /// The text in the `state` column. The spelling is part of the schema: the + /// reaper, the dispatcher and the UI all speak it. + pub fn as_str(&self) -> &'static str { + match self { + BuildState::Queued => "queued", + BuildState::Leased => "leased", + BuildState::Running => "running", + BuildState::BlockedMissingDep => "blocked_missing_dep", + BuildState::Succeeded => "succeeded", + BuildState::Failed => "failed", + BuildState::Cancelled => "cancelled", + } + } + + /// The only way in from the database text. An unrecognised state is `None`, + /// and the row boundary turns that into an error rather than a silent + /// fallback: a state we cannot name is a state we must not act on. + pub fn parse(s: &str) -> Option<BuildState> { + BuildState::ALL.iter().copied().find(|b| b.as_str() == s) + } + + /// Nothing happens to a finished build by itself. `Succeeded` is final — + /// the release is published and the row is history (§15). `Failed` and + /// `Cancelled` end a worker's involvement, and only an explicit human + /// requeue or resume moves them again ([`BuildState::can_transition`]). + pub fn is_terminal(&self) -> bool { + matches!( + self, + BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled + ) + } + + /// May a row in this state be written to `to`? + /// + /// Writing the state a row already has is always allowed: it is a no-op, not + /// a move. The step loop re-asserts `Running` at every step boundary (§8.3), + /// and re-running a finished build must stay harmless rather than turn into + /// an error. + /// + /// Everything else is refused by [`crate::db::builds::set_state`], and the + /// refusals are the point: nothing revives a `Succeeded` build, and a build + /// reaped back to `Queued` cannot be completed by the zombie worker that + /// lost its lease — that refusal is the alarm. + pub fn can_transition(&self, to: BuildState) -> bool { + use BuildState::*; + if *self == to { + return true; + } + match self { + // The dispatcher claims queued builds; `aur-build run <id>` runs one + // in the foreground without a lease, so `Running` is legal from here + // too. A dependency can be discovered before a worker ever starts. + Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled), + Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), + Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), + BlockedMissingDep => matches!(to, Queued | Cancelled), + // A failed build is resumed on the same row — that is I5 (the step + // checkpoints say where to continue) and §8.4's human requeue. + Failed => matches!(to, Queued | Running), + // §8.4: requeue is a human decision, not a policy. + Cancelled => to == Queued, + Succeeded => false, + } + } + + /// Every state that may legally move to `to` — the `WHERE state IN (...)` + /// that makes a state write a compare-and-swap. + pub fn predecessors(to: BuildState) -> Vec<&'static str> { + BuildState::ALL + .iter() + .filter(|from| from.can_transition(to)) + .map(|from| from.as_str()) + .collect() + } + + /// The states the queue considers "in flight" for metrics and the index. + pub fn active() -> &'static [BuildState] { + &[ + BuildState::Queued, + BuildState::Running, + BuildState::Leased, + BuildState::BlockedMissingDep, + ] + } +} + +impl std::fmt::Display for BuildState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } } pub mod step_state { diff --git a/src/db/queries.rs b/src/db/queries.rs index b768f83..e1f25b7 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -661,16 +661,10 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr priority, cancel_requested, error FROM build WHERE pkgbase_id=?1 ORDER BY rowid DESC LIMIT ?2", )?; - let rows = st.query_map(params![pkgbase_id, limit], |r| { - Ok(crate::db::builds::BuildRow { - id: r.get(0)?, pkgbase_id: r.get(1)?, candidate_id: r.get(2)?, release_id: r.get(3)?, - kind: r.get(4)?, world_snapshot_id: r.get(5)?, build_profile: r.get(6)?, state: r.get(7)?, - blocked_on_json: r.get(8)?, current_step: r.get(9)?, lease_owner: r.get(10)?, - lease_expires_at: r.get(11)?, attempt: r.get(12)?, priority: r.get(13)?, - cancel_requested: r.get::<_, i64>(14)? != 0, error: r.get(15)?, - }) - })?; - Ok(rows.filter_map(|r| r.ok()).collect()) + let rows = st.query_map(params![pkgbase_id, limit], crate::db::builds::row_to_build)?; + // A row we cannot read is an error, not a build that quietly disappears + // from the package page. + rows.collect::<::rusqlite::Result<Vec<_>>>().map_err(Into::into) }) } diff --git a/src/http/routes.rs b/src/http/routes.rs index d3b184b..926d2a8 100644 --- a/src/http/routes.rs +++ b/src/http/routes.rs @@ -720,7 +720,7 @@ fn package_detail(state: &State, req: &Req, name: &str) -> Res { id_short: short(&b.id), id: b.id, kind: b.kind, - state: b.state, + state: b.state.to_string(), step: b.current_step.unwrap_or_default(), }) .collect(); @@ -828,7 +828,7 @@ fn build_version(db: &Db, b: &builds::BuildRow) -> String { fn build_rows(state: &State) -> Vec<BuildRow> { builds::list( &state.db, - &[build_state::QUEUED, build_state::RUNNING, build_state::LEASED, build_state::BLOCKED_MISSING_DEP], + BuildState::active(), 100, ) .unwrap_or_default() @@ -846,7 +846,7 @@ fn build_rows(state: &State) -> Vec<BuildRow> { pkgbase, version, kind: b.kind, - state: b.state, + state: b.state.to_string(), step: b.current_step.unwrap_or_default(), lease: b.lease_expires_at.unwrap_or_else(|| "—".into()), cancel: b.cancel_requested, @@ -870,7 +870,7 @@ fn builds_page(state: &State, req: &Req) -> Res { } fn recent_rows(state: &State) -> Vec<BuildRow> { - builds::list(&state.db, &[build_state::FAILED, build_state::SUCCEEDED], 10) + builds::list(&state.db, &[BuildState::Failed, BuildState::Succeeded], 10) .unwrap_or_default() .into_iter() .map(|b| { @@ -882,7 +882,7 @@ fn recent_rows(state: &State) -> Vec<BuildRow> { pkgbase, version, kind: b.kind, - state: b.state, + state: b.state.to_string(), step: b.current_step.unwrap_or_default(), lease: String::new(), cancel: b.cancel_requested, @@ -931,7 +931,7 @@ fn build_detail(state: &State, req: &Req, id: &str) -> Res { pkgbase, version: build_version(db, &b), kind: b.kind, - state: b.state, + state: b.state.to_string(), error: b.error.clone().unwrap_or_default(), blocked_on, steps, diff --git a/src/http/sse.rs b/src/http/sse.rs index e141926..5bfb75b 100644 --- a/src/http/sse.rs +++ b/src/http/sse.rs @@ -15,7 +15,6 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use crate::db::builds; -use crate::db::model::build_state; /// How long a tail will wait for a build that never finishes. A viewer that /// outlives this gets a clean end and can reconnect. @@ -53,10 +52,7 @@ impl LogTail { fn terminal(&self) -> bool { match builds::get(&self.db, &self.build_id) { - Ok(Some(b)) => matches!( - b.state.as_str(), - build_state::SUCCEEDED | build_state::FAILED | build_state::CANCELLED - ), + Ok(Some(b)) => b.state.is_terminal(), // A build row that vanished is not going to produce more output. Ok(None) => true, // A database hiccup should not end the stream; the next poll tries diff --git a/src/main.rs b/src/main.rs index 40956c2..1aacfac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -314,7 +314,7 @@ fn main() -> anyhow::Result<()> { } }, Cmd::Builds => { - for b in builds::list(&ctx.db, &[build_state::QUEUED, build_state::RUNNING, build_state::LEASED, build_state::BLOCKED_MISSING_DEP], 50)? { + for b in builds::list(&ctx.db, BuildState::active(), 50)? { println!("{:<66} {:<20} {}", b.id, b.state, b.current_step.unwrap_or_default()); } Ok(()) diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 279ec0f..01c9bc5 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -199,7 +199,7 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { std::fs::create_dir_all(&ctx.staging)?; for step in crate::db::model::BUILD_STEPS { if crate::db::builds::cancel_requested(&ctx.db, &ctx.build.id)? { - builds::set_state(&ctx.db, &ctx.build.id, build_state::CANCELLED, Some("cancelled"))?; + builds::set_state(&ctx.db, &ctx.build.id, BuildState::Cancelled, Some("cancelled"))?; return Ok(Outcome::Cancelled); } let status = builds::step_status(&ctx.db, &ctx.build.id, step)?; @@ -207,7 +207,7 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { continue; // checkpoint says we already did this } builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?; - builds::set_state(&ctx.db, &ctx.build.id, build_state::RUNNING, None)?; + builds::set_state(&ctx.db, &ctx.build.id, BuildState::Running, None)?; ctx.log_line(&format!("==> step {step} (attempt {})", ctx.attempt)); match steps::run_step(ctx, step) { Ok(StepResult::Done(digest)) => { @@ -230,7 +230,7 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { builds::set_state( &ctx.db, &ctx.build.id, - build_state::FAILED, + BuildState::Failed, Some(&format!("{step}: {e}")), )?; ctx.log_line(&format!("!! {step} failed: {e}")); @@ -248,7 +248,7 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { let release_id = ctx .release_id() .ok_or_else(|| Error::other("publish produced no release"))?; - builds::set_state(&ctx.db, &ctx.build.id, build_state::SUCCEEDED, None)?; + builds::set_state(&ctx.db, &ctx.build.id, BuildState::Succeeded, None)?; db::audit_system( &ctx.db.writer, "build.succeeded", diff --git a/tests/crash.rs b/tests/crash.rs index 8d8ba35..0510aab 100644 --- a/tests/crash.rs +++ b/tests/crash.rs @@ -62,7 +62,7 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work // The database survived, because no transaction ever spans a build step. let b = builds::get(&env.db, &id).unwrap().expect("build row survived the kill"); assert!( - b.state == build_state::LEASED || b.state == build_state::RUNNING, + b.state == BuildState::Leased || b.state == BuildState::Running, "a killed build must still look claimed, not finished: {}", b.state ); @@ -112,7 +112,7 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work "no duplicate release from the resume" ); assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::SUCCEEDED); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Succeeded); } #[test] @@ -124,7 +124,7 @@ fn a_cancelled_build_stops_at_a_step_boundary_and_publishes_nothing() { builds::request_cancel(&env.db, &id).unwrap(); let out = pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert!(matches!(out, pipeline::Outcome::Cancelled), "{out:?}"); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::CANCELLED); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Cancelled); // Nothing ran, so nothing to undo. let shim = env.cfg.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shim, "repo-add", ""), 0); @@ -179,18 +179,18 @@ fn a_transient_failure_retries_but_a_deterministic_one_never_does() { let (mut env, _fx) = env_with_fixture("build-fails"); let id = queued(&env, "build-fails"); let pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(env.cfg.clone()), env.db.clone()); - let mut state = String::new(); + let mut state = BuildState::Queued; for _ in 0..400 { if let Some(b) = builds::get(&env.db, &id).unwrap() { - state = b.state.clone(); - if state == build_state::FAILED { + state = b.state; + if state == BuildState::Failed { break; } } std::thread::sleep(std::time::Duration::from_millis(25)); } pool.shutdown(); - assert_eq!(state, build_state::FAILED); + assert_eq!(state, BuildState::Failed); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().attempt, 1, "a deterministic failure must not retry"); // The release stays approved_but_unbuilt rather than vanishing. assert_eq!(db::approved_but_unbuilt(&env.db).unwrap().len(), 1); diff --git a/tests/dispatch.rs b/tests/dispatch.rs index c70dd6b..6721fc8 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -103,7 +103,7 @@ fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { // A fresh dispatcher (as after a restart) reaps it before claiming anything. let reaped = builds::reap_expired(&env.db).unwrap(); assert_eq!(reaped, 1, "the expired lease was not requeued"); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::QUEUED); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued); assert_eq!( builds::step_status(&env.db, &id, "build").unwrap().as_deref(), Some("interrupted"), @@ -129,7 +129,7 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { // run() honours it at the step boundary rather than mid-step. let out = pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert!(matches!(out, pipeline::Outcome::Cancelled), "run ignored the cancellation"); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::CANCELLED); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Cancelled); } #[test] @@ -140,9 +140,9 @@ fn a_deterministic_build_failure_is_not_retried() { let (env, _fx) = env_with_fixture("build-fails"); let id = queued_build(&env, "build-fails"); let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone()); - let state = wait_for(&env, &id, &["failed", "succeeded"]); + let state = wait_for(&env, &id, &[BuildState::Failed, BuildState::Succeeded]); pool.shutdown(); - assert_eq!(state, build_state::FAILED, "a deterministic failure should not succeed"); + assert_eq!(state, BuildState::Failed, "a deterministic failure should not succeed"); let b = builds::get(&env.db, &id).unwrap().unwrap(); assert_eq!(b.attempt, 1, "a deterministic failure must not be retried"); assert!(b.error.unwrap_or_default().contains("build"), "no step named in the error"); @@ -165,7 +165,7 @@ fn a_transient_failure_is_retried_up_to_the_cap() { // attempt count reaching the cap with the build left failed. let b = wait_attempt(&env, &id, 3); pool.shutdown(); - assert_eq!(b.state, build_state::FAILED); + assert_eq!(b.state, BuildState::Failed); assert_eq!(b.attempt, 3, "a transient failure should retry up to the cap"); } @@ -177,9 +177,9 @@ fn the_pool_takes_a_queued_build_all_the_way_to_publication() { let id = queued_build(&env, "plain-make"); let cfg = Arc::new(env.cfg.clone()); let pool = dispatch::Pool::spawn(cfg, env.db.clone()); - let state = wait_for(&env, &id, &["succeeded", "failed"]); + let state = wait_for(&env, &id, &[BuildState::Succeeded, BuildState::Failed]); pool.shutdown(); - assert_eq!(state, build_state::SUCCEEDED, "the pool did not finish the build"); + assert_eq!(state, BuildState::Succeeded, "the pool did not finish the build"); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_some(), "nothing was published"); assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); } @@ -218,9 +218,9 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { ); let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone()); - let state = wait_for(&env, &id, &["succeeded", "failed"]); + let state = wait_for(&env, &id, &[BuildState::Succeeded, BuildState::Failed]); pool.shutdown(); - assert_eq!(state, build_state::SUCCEEDED, "the resumed build did not finish"); + assert_eq!(state, BuildState::Succeeded, "the resumed build did not finish"); assert_eq!( aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", ""), @@ -255,7 +255,7 @@ fn queued_candidate(env: &Env, name: &str) -> CandidateRow { fn wait_attempt(env: &Env, id: &str, n: i64) -> builds::BuildRow { for _ in 0..600 { if let Some(b) = builds::get(&env.db, id).unwrap() { - if b.attempt >= n && b.state == build_state::FAILED { + if b.attempt >= n && b.state == BuildState::Failed { return b; } } @@ -265,10 +265,10 @@ fn wait_attempt(env: &Env, id: &str, n: i64) -> builds::BuildRow { } /// Poll until the build reaches one of `want` (or the test gives up). -fn wait_for(env: &Env, id: &str, want: &[&str]) -> String { +fn wait_for(env: &Env, id: &str, want: &[BuildState]) -> BuildState { for _ in 0..600 { if let Some(b) = builds::get(&env.db, id).unwrap() { - if want.contains(&b.state.as_str()) { + if want.contains(&b.state) { return b.state; } } diff --git a/tests/invariants.rs b/tests/invariants.rs index a083a89..ceaddc4 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -442,7 +442,7 @@ fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { store_before, "the store must be untouched by a refused build" ); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::FAILED); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Failed); assert!(db::index_version(&env.db, "plain-make").unwrap().is_none(), "nothing publishes from a failed build"); // And the database itself is intact — the build read it, it did not become it. assert!(secret.exists()); diff --git a/tests/live.rs b/tests/live.rs index 60d757b..16b68c5 100644 --- a/tests/live.rs +++ b/tests/live.rs @@ -7,7 +7,8 @@ mod common; use std::io::Read; use std::time::{Duration, Instant}; -use aur_build::db::{builds, model::build_state}; +use aur_build::db::model::BuildState; +use aur_build::db::builds; use aur_build::pipeline; use aur_build::review::{candidates, diff}; use common::*; @@ -62,7 +63,10 @@ fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() { std::thread::sleep(Duration::from_millis(400)); append(&log2, "==> step publish\n"); std::thread::sleep(Duration::from_millis(200)); - builds::set_state(&db, &id2, build_state::SUCCEEDED, None).unwrap(); + // Walk the machine the way a real build does: a queued build runs + // before it succeeds. + builds::set_state(&db, &id2, BuildState::Running, None).unwrap(); + builds::set_state(&db, &id2, BuildState::Succeeded, None).unwrap(); }); let resp = ureq::get(&web.url(&format!("/builds/{id}/log.stream"))).call().expect("stream"); diff --git a/tests/pipeline.rs b/tests/pipeline.rs index 5a2fa5a..01ae5f7 100644 --- a/tests/pipeline.rs +++ b/tests/pipeline.rs @@ -302,7 +302,7 @@ fn an_unresolvable_dependency_blocks_instead_of_failing() { } let (bid, _name, blocked_on) = builds::blocked_builds(&env.db).unwrap().remove(0); assert_eq!(blocked_on, vec!["dep-partner".to_string()]); - assert_eq!(builds::get(&env.db, &bid).unwrap().unwrap().state, build_state::BLOCKED_MISSING_DEP); + assert_eq!(builds::get(&env.db, &bid).unwrap().unwrap().state, BuildState::BlockedMissingDep); assert!(in_index(&env).is_empty(), "a blocked build publishes nothing"); } diff --git a/tests/staleness.rs b/tests/staleness.rs index c99c666..bebceb4 100644 --- a/tests/staleness.rs +++ b/tests/staleness.rs @@ -90,7 +90,7 @@ fn a_missing_dependency_blocks_the_build_and_names_the_blocker_everywhere() { assert!(matches!(out, pipeline::Outcome::Blocked { .. }), "{out:?}"); let b = builds::get(&env.db, &id).unwrap().unwrap(); - assert_eq!(b.state, build_state::BLOCKED_MISSING_DEP); + assert_eq!(b.state, BuildState::BlockedMissingDep); let blocked_on: Vec<String> = serde_json::from_str(&b.blocked_on_json).unwrap(); assert_eq!(blocked_on, vec!["dep-partner".to_string()]); // Blocked is not failed: nothing went wrong with the build itself. @@ -111,12 +111,12 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() { let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); let _ = fx; pipeline::run(&env.cfg, &env.db, &id).unwrap(); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::BLOCKED_MISSING_DEP); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::BlockedMissingDep); // The dispatcher sweeps blocked builds every pass. Requeueing one that will // immediately block again is a busy loop, so it must stay put. assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::BLOCKED_MISSING_DEP); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::BlockedMissingDep); // Publishing dep-partner is what unblocks it. A build that was blocked and // can now run is not a new decision — a human already approved it (§10). @@ -128,12 +128,12 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() { ); // Publishing the blocker requeues what was waiting on it — the publish path // sweeps blocked builds itself, so an explicit call afterwards is a no-op. - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::QUEUED, "the blocker arrived and the build stayed blocked"); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued, "the blocker arrived and the build stayed blocked"); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "nothing left to requeue"); // And it now runs to completion. pipeline::run(&env.cfg, &env.db, &id).unwrap(); - assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::SUCCEEDED); + assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Succeeded); assert!(aur_build::db::index_version(&env.db, "missing-dep").unwrap().is_some()); } diff --git a/tests/state_machine.rs b/tests/state_machine.rs new file mode 100644 index 0000000..c5203d7 --- /dev/null +++ b/tests/state_machine.rs @@ -0,0 +1,170 @@ +//! The build state machine (§6 M-8). +//! +//! Before this was an enum, `set_state(&str)` wrote any string a caller +//! invented and the machine lived only in `WHERE state IN (...)` clauses. These +//! tests are the ones that would have failed then. + +mod common; + +use aur_build::db::{builds, model::BuildState}; +use common::Env; + +fn build(env: &Env, id: &str) -> String { + env.exec( + "INSERT INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", + &[], + ); + let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).expect("pkgbase id"); + builds::enqueue(&env.db, id, pb, None, "manual", None, "default", 0).unwrap(); + id.to_string() +} + +fn state(env: &Env, id: &str) -> BuildState { + builds::get(&env.db, id).unwrap().expect("build").state +} + +#[test] +fn every_state_round_trips_through_its_column_text() { + for s in BuildState::ALL { + assert_eq!(BuildState::parse(s.as_str()), Some(*s), "{s:?} does not round-trip"); + } + assert_eq!(BuildState::parse("exploded"), None); + assert_eq!(BuildState::parse(""), None); +} + +#[test] +fn the_machine_refuses_a_transition_it_does_not_define() { + let env = Env::new(); + let id = build(&env, "b1"); + assert_eq!(state(&env, "b1"), BuildState::Queued); + + // Queued → Succeeded: a build cannot finish without running. Before the + // enum this wrote happily and produced a succeeded build that never built. + let err = builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap_err(); + assert!(err.to_string().contains("illegal build transition"), "{err}"); + assert_eq!(state(&env, "b1"), BuildState::Queued, "a refused transition writes nothing"); + + // And a build that does not exist is named as such, not silently updated. + let err = builds::set_state(&env.db, "nope", BuildState::Cancelled, None).unwrap_err(); + assert!(err.to_string().contains("no build nope"), "{err}"); +} + +#[test] +fn a_terminal_build_is_history_and_does_not_move() { + let env = Env::new(); + let id = build(&env, "b1"); + builds::claim(&env.db, "worker-1", &id, 90).unwrap(); + builds::set_state(&env.db, &id, BuildState::Running, None).unwrap(); + builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap(); + assert_eq!(state(&env, "b1"), BuildState::Succeeded); + + for to in [BuildState::Running, BuildState::Queued, BuildState::Failed] { + assert!( + !BuildState::Succeeded.can_transition(to), + "succeeded must not transition to {to:?}" + ); + assert!(builds::set_state(&env.db, &id, to, None).is_err(), "accepted {to:?} after success"); + } + assert_eq!(state(&env, "b1"), BuildState::Succeeded); + // Rows are never deleted (§15); a finished build stays what it was. + assert_eq!(env.query_i64("SELECT count(*) FROM build", &[]), Some(1)); +} + +#[test] +fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { + // The failure this pins: a worker's lease expires mid-step, the reaper hands + // the build back to the queue, and the original worker — still running — + // comes back and writes `succeeded` over whatever the new owner did. The + // compare-and-swap in `set_state` is what makes that an error. + let env = Env::new(); + let id = build(&env, "b1"); + builds::claim(&env.db, "worker-1", &id, 90).unwrap(); + builds::set_state(&env.db, &id, BuildState::Running, None).unwrap(); + + env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", &[common::P::S(id.clone())]); + assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); + assert_eq!(state(&env, &id), BuildState::Queued); + + let err = builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap_err(); + assert!(err.to_string().contains("illegal build transition"), "the zombie was allowed to write: {err}"); + assert_eq!(state(&env, &id), BuildState::Queued, "the queue still owns this build"); +} + +#[test] +fn a_state_the_code_does_not_know_is_an_error_not_an_empty_string() { + // A row written by an older binary, a hand-edit, or a future migration the + // code has not caught up with must stop the process, not render as a build + // in no state at all. + let env = Env::new(); + let id = build(&env, "b1"); + env.exec("UPDATE build SET state='exploded' WHERE id=?1", &[common::P::S(id.clone())]); + let err = builds::get(&env.db, &id).unwrap_err(); + assert!(err.to_string().contains("outside the state machine"), "{err}"); + // The package page lists a pkgbase's builds with no state filter: an + // unreadable row must fail the query, not vanish from the list. + let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap(); + assert!(aur_build::db::builds_for_pkgbase(&env.db, pb, 10).is_err()); +} + +#[test] +fn the_transition_table_is_the_machine_the_code_actually_uses() { + // Every state may be re-written with its own name — that is a no-op, not a + // move (the step loop re-asserts Running at each boundary). What matters is + // what else is reachable, and this table is the whole machine. + let reachable = |from: BuildState| -> Vec<&'static str> { + BuildState::ALL + .iter() + .filter(|to| from.can_transition(**to)) + .map(|to| to.as_str()) + .collect() + }; + assert_eq!(reachable(BuildState::Queued), ["queued", "leased", "running", "blocked_missing_dep", "cancelled"]); + assert_eq!( + reachable(BuildState::Leased), + ["queued", "leased", "running", "blocked_missing_dep", "succeeded", "failed", "cancelled"] + ); + assert_eq!( + reachable(BuildState::Running), + ["queued", "running", "blocked_missing_dep", "succeeded", "failed", "cancelled"] + ); + assert_eq!(reachable(BuildState::BlockedMissingDep), ["queued", "blocked_missing_dep", "cancelled"]); + // A failed build is resumed on its own row (I5) or requeued by a human (§8.4). + assert_eq!(reachable(BuildState::Failed), ["queued", "running", "failed"]); + assert_eq!(reachable(BuildState::Cancelled), ["queued", "cancelled"]); + // A published build is history. Nothing revives it; a new version is a new + // build id (§8.1), not a resurrection. + assert_eq!(reachable(BuildState::Succeeded), ["succeeded"]); +} + +#[test] +fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { + // `builds::retry` resets the failed steps and moves the row back to the + // queue. On a build that already published there is nothing to retry, and + // the old unconditional UPDATE happily requeued it anyway. + let env = Env::new(); + let id = build(&env, "b1"); + builds::claim(&env.db, "worker-1", &id, 90).unwrap(); + builds::set_state(&env.db, &id, BuildState::Running, None).unwrap(); + builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap(); + let err = builds::retry(&env.db, &id).unwrap_err(); + assert!(err.to_string().contains("illegal build transition succeeded"), "{err}"); + assert_eq!(state(&env, "b1"), BuildState::Succeeded); +} + +#[test] +fn a_failed_build_is_resumed_on_its_own_row() { + // I5: the resume happens on the same row, because the step checkpoints say + // where to continue. The machine has to know that, or the resume is a bug. + let env = Env::new(); + let id = build(&env, "b1"); + builds::claim(&env.db, "worker-1", &id, 90).unwrap(); + builds::set_state(&env.db, &id, BuildState::Running, None).unwrap(); + builds::set_state(&env.db, &id, BuildState::Failed, Some("publish: injected")).unwrap(); + builds::retry(&env.db, &id).unwrap(); + assert_eq!(state(&env, &id), BuildState::Queued); + builds::set_state(&env.db, &id, BuildState::Running, None).unwrap(); + assert_eq!(state(&env, &id), BuildState::Running); + builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap(); + assert_eq!(state(&env, &id), BuildState::Succeeded); +} + diff --git a/tests/surfaces.rs b/tests/surfaces.rs index 659123f..b13cc9d 100644 --- a/tests/surfaces.rs +++ b/tests/surfaces.rs @@ -116,7 +116,7 @@ fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() { .unwrap(); pipeline::run(&web.env.cfg, &web.env.db, &id).unwrap(); let b = builds::get(&web.env.db, &id).unwrap().unwrap(); - assert_eq!(b.state, build_state::SUCCEEDED, "rebuild failed: {:?}", b.error); + assert_eq!(b.state, BuildState::Succeeded, "rebuild failed: {:?}", b.error); assert_eq!( web.env.query_i64("SELECT count(*) FROM approval", &[]).unwrap(), approvals_before, |
