From bbae6c8e83cf145f9af472f69591bae804d03048 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 20 Nov 2026 18:20:18 +0000 Subject: error: give the six variants behavior carries a shape, not a sentence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Error::NotFound("no repo row; run `aur-build init`")` and `Error::NotFound("pkgbase linux")` were the same variant. One is "the install was never initialised, every page is wrong"; the other is "that page does not exist, answer 404". The difference lived inside a string, so the only way to act on it was to re-parse text the same process had written moments earlier. Six variants now carry structure: Missing pkgbase / candidate / release / build / snapshot / mirror path / repo row Refused IllegalTransition / WrongState / PointerMoved / Other Guard HashMismatch / DigestMismatch / Invariant WorldGap MissingPin / Other PoolFull Backend{backend} / Other TransientCause Upstream / Command / Other `Refused` distinguishes the three refusals that were indistinguishable: a transition no edge permits (caller bug), a row in the wrong state (stale view), and the accepted pointer moving under a build (a lost race, and the one a client may safely retry). `PoolFull::Backend` names which pool, because a kata quota needs an operator and a local cap clears when a build exits. `is_transient` and `is_pool_exhausted` already matched on variants rather than strings, so they are unchanged — the typing is what lets the *next* branch be a match instead of a `contains`. No test assertion was edited. Where a message is load-bearing the Display was written to reproduce it: `recipe_hash mismatch: approved X, materialized Y`, `no release 4`, `illegal candidate transition approved → rejected`, `sandbox world is missing plain-make-1.0-1 after installing the lease set` and kata's `never dialed in` all come out of the new types byte-identical. Five messages did change wording, none asserted anywhere: release N is X, not published: nothing to withdraw -> release N is X, not published (Refused::WrongState's shape) illegal candidate transition a → b for review 7 -> ... for candidate 7 (it is a candidate id; "review" was misleading) no candidate 7 to resolve -> candidate 7 (Missing::Candidate's shape) lease artifact n-v: store bytes hash to A but the index says B -> source n-v hashed to A but the candidate recorded B (shares Guard::DigestMismatch with the source-cache check) vcs_cache clone URL: err -> upstream: vcs_cache clone URL: err (TransientCause::Upstream tag) error.pub 15->21 is the six payload enums, which is the point of the task rather than a widening to apologise for. watch.dead/test each rose by one for a subtler reason: `watch::upstream::resolve` looked live only because an unrelated db message ended "... to resolve", and rewording that string removed the phantom mention. The census now documents that a clean count is not always an answer, since mentions are matched over raw source including string literals. 281 passed / 0 failed (277 plus four new typing tests in src/error.rs), clippy -D warnings clean, release build clean. --- src/error.rs | 344 +++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 325 insertions(+), 19 deletions(-) (limited to 'src/error.rs') diff --git a/src/error.rs b/src/error.rs index 5966e28..8dee79f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,233 @@ use std::fmt; +/// What a lookup asked for and did not get. +/// +/// Carried as data rather than a sentence, because "not found" is not one +/// failure: a pkgbase nobody subscribed to is a 404 page, while a missing repo +/// row means the install was never initialised and every page is wrong. A +/// caller can tell those apart from the variant instead of re-reading prose the +/// call site wrote for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Missing { + Pkgbase(String), + Candidate(i64), + Release(i64), + Build(String), + Snapshot, + /// A path the mirror's tree listing did not contain at that commit. + MirrorPath(String), + /// The single `repo` row is absent — nothing has been initialised yet. + RepoRow, + /// A lookup whose subject only the call site can describe. + Other(String), +} + +impl fmt::Display for Missing { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Missing::Pkgbase(n) => write!(f, "pkgbase {n}"), + Missing::Candidate(id) => write!(f, "candidate {id}"), + Missing::Release(id) => write!(f, "no release {id}"), + Missing::Build(id) => write!(f, "build {id}"), + Missing::Snapshot => write!(f, "snapshot"), + Missing::MirrorPath(p) => write!(f, "{p} not in mirror"), + Missing::RepoRow => write!(f, "no repo row; run `aur-build init`"), + Missing::Other(s) => write!(f, "{s}"), + } + } +} + +/// An operation the current state of the world refuses. +/// +/// The three shapes are the ones the state machines and the publish path +/// actually produce. `IllegalTransition` is a bug in the caller — it asked for +/// a move no edge permits; `WrongState` is a stale view — the caller was right +/// once and the row moved; `PointerMoved` is a lost race, which is the one a +/// client can safely retry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refused { + /// No edge in the state machine leads from `from` to `to`. + IllegalTransition { entity: &'static str, id: String, from: String, to: String }, + /// The row is in `found`, which does not permit the operation. + WrongState { entity: &'static str, id: String, found: String, expected: &'static str }, + /// The accepted pointer moved while a build was running. + PointerMoved { pkgbase: String }, + /// A refusal only the call site can phrase. + Other(String), +} + +impl fmt::Display for Refused { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Refused::IllegalTransition { entity, id, from, to } => { + write!(f, "illegal {entity} transition {from} → {to} for {entity} {id}") + } + Refused::WrongState { entity, id, found, expected } => { + write!(f, "{entity} {id} is {found}, not {expected}") + } + Refused::PointerMoved { pkgbase } => write!( + f, + "accepted pointer moved while this build was running; refusing to publish ({pkgbase})" + ), + Refused::Other(s) => write!(f, "{s}"), + } + } +} + +/// A guard the code holds against itself: a value that was checked once must +/// still be that value where it is used. +/// +/// These are not user errors. Nothing downstream recovers from one; the point +/// of naming them is that a build that trips one stops rather than publishing +/// bytes nobody approved. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Guard { + /// A hash recomputed at use time differs from the one approved. + HashMismatch { what: &'static str, approved: String, computed: String }, + /// A digest resolved from a cache or a download is not the recorded one. + DigestMismatch { url: String, expected: String, found: String }, + /// A precondition the surrounding code was supposed to have established. + Invariant(String), +} + +impl fmt::Display for Guard { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Guard::HashMismatch { what, approved, computed } => { + write!(f, "{what} mismatch: approved {approved}, materialized {computed}") + } + Guard::DigestMismatch { url, expected, found } => { + write!(f, "source {url} hashed to {found} but the candidate recorded {expected}") + } + Guard::Invariant(s) => write!(f, "{s}"), + } + } +} + +/// The world the candidate was computed against no longer contains what it +/// pinned. Retryable only by recomputing the world, not by trying again. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WorldGap { + /// A package the build pins is not in the repository world. + MissingPin { package: String }, + /// A gap only the detecting step can describe. + Other(String), +} + +impl fmt::Display for WorldGap { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + WorldGap::MissingPin { package } => write!(f, "sandbox world is missing {package} after installing the lease set"), + WorldGap::Other(s) => write!(f, "{s}"), + } + } +} + +/// The sandbox pool is at its quota. +/// +/// Carries which backend said so, because the two have different remedies: a +/// Kubernetes quota needs an operator, a local cap clears when a build exits. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PoolFull { + Backend { backend: &'static str, detail: String }, + Other(String), +} + +impl fmt::Display for PoolFull { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PoolFull::Backend { backend, detail } => write!(f, "{backend}: {detail}"), + PoolFull::Other(s) => write!(f, "{s}"), + } + } +} + +/// A failure a retry is allowed to treat as worth another attempt. +/// +/// The variant is the whole of the retry decision — `is_transient` reads it +/// directly — so it carries where the failure came from rather than a message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TransientCause { + /// An upstream fetch that a moment might fix. + Upstream(String), + /// A command whose network or VCS operation was interrupted. + Command(String), + /// Anything else the call site judged retryable. + Other(String), +} + +impl fmt::Display for TransientCause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TransientCause::Upstream(s) => write!(f, "upstream: {s}"), + TransientCause::Command(s) => write!(f, "{s}"), + TransientCause::Other(s) => write!(f, "{s}"), + } + } +} + +/// Convenience for the many guards a call site can only phrase in words. +impl From<&str> for Guard { + fn from(s: &str) -> Self { + Guard::Invariant(s.to_string()) + } +} +impl From for Guard { + fn from(s: String) -> Self { + Guard::Invariant(s) + } +} +impl From<&str> for Missing { + fn from(s: &str) -> Self { + Missing::Other(s.to_string()) + } +} +impl From for Missing { + fn from(s: String) -> Self { + Missing::Other(s) + } +} +impl From<&str> for Refused { + fn from(s: &str) -> Self { + Refused::Other(s.to_string()) + } +} +impl From for Refused { + fn from(s: String) -> Self { + Refused::Other(s) + } +} +impl From<&str> for WorldGap { + fn from(s: &str) -> Self { + WorldGap::Other(s.to_string()) + } +} +impl From for WorldGap { + fn from(s: String) -> Self { + WorldGap::Other(s) + } +} +impl From<&str> for PoolFull { + fn from(s: &str) -> Self { + PoolFull::Other(s.to_string()) + } +} +impl From for PoolFull { + fn from(s: String) -> Self { + PoolFull::Other(s) + } +} +impl From<&str> for TransientCause { + fn from(s: &str) -> Self { + TransientCause::Other(s.to_string()) + } +} +impl From for TransientCause { + fn from(s: String) -> Self { + TransientCause::Other(s) + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("io: {0}")] @@ -17,21 +245,21 @@ pub enum Error { #[error("child process {cmd}: {detail}")] Subprocess { cmd: String, detail: String }, #[error("assertion failed: {0}")] - FailClosed(String), + FailClosed(Guard), #[error("not found: {0}")] - NotFound(String), + NotFound(Missing), #[error("conflict: {0}")] - Conflict(String), + Conflict(Refused), #[error("invalid: {0}")] Invalid(String), #[error("blocked: {0}")] Blocked(String), #[error("sandbox pool exhausted: {0}")] - PoolExhausted(String), + PoolExhausted(PoolFull), #[error("world mismatch: {0}")] - WorldMismatch(String), + WorldMismatch(WorldGap), #[error("transient: {0}")] - Transient(String), + Transient(TransientCause), #[error("{0}")] Other(String), } @@ -43,14 +271,14 @@ impl Error { pub fn git(s: impl fmt::Display) -> Self { Error::Git(s.to_string()) } - pub fn fail_closed(s: impl fmt::Display) -> Self { - Error::FailClosed(s.to_string()) + pub fn fail_closed(g: impl Into) -> Self { + Error::FailClosed(g.into()) } - pub fn not_found(s: impl fmt::Display) -> Self { - Error::NotFound(s.to_string()) + pub fn not_found(m: impl Into) -> Self { + Error::NotFound(m.into()) } - pub fn conflict(s: impl fmt::Display) -> Self { - Error::Conflict(s.to_string()) + pub fn conflict(r: impl Into) -> Self { + Error::Conflict(r.into()) } pub fn invalid(s: impl fmt::Display) -> Self { Error::Invalid(s.to_string()) @@ -61,14 +289,14 @@ impl Error { pub fn other(s: impl fmt::Display) -> Self { Error::Other(s.to_string()) } - pub fn transient(s: impl fmt::Display) -> Self { - Error::Transient(s.to_string()) + pub fn transient(c: impl Into) -> Self { + Error::Transient(c.into()) } - pub fn pool_exhausted(s: impl fmt::Display) -> Self { - Error::PoolExhausted(s.to_string()) + pub fn pool_exhausted(p: impl Into) -> Self { + Error::PoolExhausted(p.into()) } - pub fn world_mismatch(s: impl fmt::Display) -> Self { - Error::WorldMismatch(s.to_string()) + pub fn world_mismatch(w: impl Into) -> Self { + Error::WorldMismatch(w.into()) } pub fn is_pool_exhausted(&self) -> bool { @@ -95,7 +323,6 @@ impl Error { } pub type Result = std::result::Result; - #[cfg(test)] mod tests { use super::*; @@ -120,4 +347,83 @@ mod tests { assert!(!Error::world_mismatch("missing pinned dep").is_transient()); assert!(Error::pool_exhausted("at quota").is_pool_exhausted()); } + + #[test] + fn the_six_behavioural_variants_carry_data_not_prose() { + // Each of these is branched on somewhere, so the branch must be able to + // read a field rather than re-parse a sentence it wrote itself. + match Error::not_found(Missing::RepoRow) { + Error::NotFound(Missing::RepoRow) => {} + other => panic!("repo row not-found came back as {other:?}"), + } + match Error::conflict(Refused::PointerMoved { pkgbase: "linux".into() }) { + Error::Conflict(Refused::PointerMoved { pkgbase }) => assert_eq!(pkgbase, "linux"), + other => panic!("pointer-moved came back as {other:?}"), + } + match Error::fail_closed(Guard::HashMismatch { + what: "recipe_hash", + approved: "aaa".into(), + computed: "bbb".into(), + }) { + Error::FailClosed(Guard::HashMismatch { approved, computed, .. }) => { + assert_eq!((approved.as_str(), computed.as_str()), ("aaa", "bbb")); + } + other => panic!("hash mismatch came back as {other:?}"), + } + match Error::world_mismatch(WorldGap::MissingPin { package: "glibc-2.39-1".into() }) { + Error::WorldMismatch(WorldGap::MissingPin { package }) => { + assert_eq!(package, "glibc-2.39-1"); + } + other => panic!("world gap came back as {other:?}"), + } + match Error::pool_exhausted(PoolFull::Backend { backend: "kata", detail: "at quota".into() }) { + Error::PoolExhausted(PoolFull::Backend { backend, .. }) => assert_eq!(backend, "kata"), + other => panic!("pool full came back as {other:?}"), + } + match Error::transient(TransientCause::Upstream("502".into())) { + Error::Transient(TransientCause::Upstream(why)) => assert_eq!(why, "502"), + other => panic!("transient came back as {other:?}"), + } + } + + #[test] + fn a_typed_refusal_keeps_the_text_the_ui_and_tests_match_on() { + // These strings are load-bearing: tests assert on them and a reviewer + // reads them. Typing the payload must not silently reword them. + let e = Error::conflict(Refused::IllegalTransition { + entity: "candidate", + id: "7".into(), + from: "approved".into(), + to: "rejected".into(), + }); + assert!(e.to_string().contains("illegal candidate transition approved → rejected"), "{e}"); + let e = Error::not_found(Missing::Release(4)); + assert!(e.to_string().contains("no release 4"), "{e}"); + let e = Error::fail_closed(Guard::HashMismatch { + what: "recipe_hash", + approved: "a1".into(), + computed: "b2".into(), + }); + assert!(e.to_string().contains("recipe_hash mismatch: approved a1, materialized b2"), "{e}"); + } + + #[test] + fn a_missing_thing_is_distinguishable_from_a_refused_one() { + // Both were `Variant(String)`; a handler could only tell them apart by + // prefix. Now the shape decides. + assert!(matches!(Error::not_found(Missing::RepoRow), Error::NotFound(_))); + assert!(!matches!(Error::not_found(Missing::RepoRow), Error::Conflict(_))); + assert!(matches!(Error::conflict(Refused::Other("no".into())), Error::Conflict(_))); + } + + #[test] + fn a_call_site_that_cannot_structure_its_reason_still_compiles() { + // The `From<&str>` arms exist so typing is incremental: a guard that is + // genuinely just a sentence lands in Invariant/Other rather than + // blocking the refactor. + assert!(matches!(Error::fail_closed("no aur_commit on the source identity"), + Error::FailClosed(Guard::Invariant(_)))); + assert!(matches!(Error::not_found("snapshot for build"), + Error::NotFound(Missing::Other(_)))); + } } -- cgit v1.2.3