From 062efa6583b7fea292a4f485659661d266461611 Mon Sep 17 00:00:00 2001 From: aur-build Date: Wed, 18 Nov 2026 15:48:02 +0000 Subject: review: a database failure is never reported to a reviewer as a stale review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `approve()` returned `Result` and then collapsed every inner failure into `Stale::NotPending { state: e.to_string() }`, so a SQLite error reached the human as "review is no longer pending (state: sqlite: …)". That is the one message that tells a reviewer to look again when the truth is that the write failed — and the transaction had already rolled back, so their review was still pending and nothing on screen explained why. `bulk()` bent the same variant to mean "high risk", "unknown decision" and "the database failed", and handed back a fabricated `Approval { id: 0 }` for a rejection that recorded no approval at all. `approve()` now returns `Result` with two families: `Stale(Stale)` — what is stored is not what was displayed, look again — and `System(Error)` — the write failed, nothing about the review is at fault. The UI answers the first with the 409 and fresh diff it already gave, and the second with a 500 that names the cause; the CLI exits 2 for the first and propagates the second as an error. `bulk()` got its own vocabulary — `BulkOutcome::{Approved, Rejected, Refused(BulkRefusal)}` with `HighRiskUnconfirmed`, `UnknownDecision`, `NotFound`, `Stale` and `System` — and returns no approval row for a rejection, because there is none. The invented `id: 0` is gone. The web handler had its own copy of the bulk loop; it now calls `approve::bulk`, so the page and the library cannot disagree about what §7.4 says. Three tests: a dropped `audit` table mid-transaction must surface as `System` and must leave the review pending and the approval table empty; bulk refusals must name the risk, the unknown decision, and (after a real approval) the genuine staleness as three different things; a bulk rejection must record a `rejected` row and hand back nothing. --- src/http/routes.rs | 59 ++++++++++++------- src/main.rs | 3 +- src/review/approve.rs | 160 ++++++++++++++++++++++++++++++++++++-------------- tests/approve.rs | 77 ++++++++++++++++++++++-- 4 files changed, 228 insertions(+), 71 deletions(-) diff --git a/src/http/routes.rs b/src/http/routes.rs index f4ab2ca..d3b184b 100644 --- a/src/http/routes.rs +++ b/src/http/routes.rs @@ -362,7 +362,16 @@ fn review_approve(state: &State, req: &Req, id: &str) -> Res { } page_to_res(ReviewsPage { page, rows: review_rows(state) }, 200) } - Err(stale) => { + Err(ap::ApproveError::System(e)) => { + // The database refused. Telling the reviewer their review went stale + // would be a lie about the one thing they cannot check themselves. + let mut page = chrome(state, req, "Review failed", "nav_reviews"); + page.flash = format!("the approval could not be recorded: {e}"); + page.has_flash = true; + page.flash_err = true; + page_to_res(ReviewsPage { page, rows: review_rows(state) }, 500) + } + Err(ap::ApproveError::Stale(stale)) => { // §7.1a: refuse, re-render what it is now, and say why. Never // silently retarget the approval onto the newer state. let mut page = chrome(state, req, "Review changed", "nav_reviews"); @@ -441,7 +450,7 @@ fn reviews_bulk(state: &State, req: &Req) -> Res { .find(|(k, _)| k == "decision") .map(|(_, v)| v.clone()) .unwrap_or_default(); - let confirmed: std::collections::BTreeSet = form + let confirmed: Vec = form .iter() .filter(|(k, _)| k == "confirm") .filter_map(|(_, v)| v.parse().ok()) @@ -453,30 +462,36 @@ fn reviews_bulk(state: &State, req: &Req) -> Res { page.flash_err = true; return page_to_res(ReviewsPage { page, rows: review_rows(state) }, 400); } + // The rule itself lives in `review::approve::bulk`, so the page and the + // library cannot disagree about what a bulk decision means (§7.4). + let items: Vec<(i64, String, String)> = ids + .iter() + .filter_map(|id| { + candidates::candidate_by_id(db, *id).ok().flatten().map(|c| (*id, c.identity_hash, c.diff_digest)) + }) + .collect(); + let outcomes = match ap::bulk(db, actor(state, req), &items, &decision, &confirmed) { + Ok(outcomes) => outcomes, + Err(e) => { + let mut page = chrome(state, req, "Reviews", "nav_reviews"); + page.flash = format!("the decisions could not be recorded: {e}"); + page.has_flash = true; + page.flash_err = true; + return page_to_res(ReviewsPage { page, rows: review_rows(state) }, 500); + } + }; let mut done = Vec::new(); let mut refused = Vec::new(); - for id in ids { - let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else { continue }; - if decision == "approve" && c.risk_level == risk::level::HIGH && !confirmed.contains(&id) { - refused.push(format!("{} (high risk: confirm it individually)", c.pkgbase)); - continue; - } - let res = if decision == "approve" { - ap::approve(db, actor(state, req), id, &c.identity_hash, &c.diff_digest, Some("bulk")) - .map(|_| ()) - .map_err(|e| e.to_string()) - } else { - let note = req.form_get("note").unwrap_or_else(|| "bulk reject".into()); - ap::reject(db, actor(state, req), id, ¬e).map_err(|e| e.to_string()) - }; - match res { - Ok(()) => { - if decision == "approve" { - let _ = pipeline::enqueue_for_candidate(&state.cfg, db, &c); + for item in outcomes { + match &item.outcome { + ap::BulkOutcome::Approved(_) => { + if let Some(c) = &item.candidate { + let _ = pipeline::enqueue_for_candidate(&state.cfg, db, c); + done.push(c.pkgbase.clone()); } - done.push(c.pkgbase); } - Err(e) => refused.push(format!("{}: {e}", c.pkgbase)), + ap::BulkOutcome::Rejected => done.push(item.pkgbase().to_string()), + ap::BulkOutcome::Refused(r) => refused.push(format!("{}: {r}", item.pkgbase())), } } let mut page = chrome(state, req, "Reviews", "nav_reviews"); diff --git a/src/main.rs b/src/main.rs index 6df2bd7..40956c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -270,10 +270,11 @@ fn main() -> anyhow::Result<()> { println!("run it with: aur-build run {id}"); Ok(()) } - Err(stale) => { + Err(ap::ApproveError::Stale(stale)) => { eprintln!("refused: {stale}"); std::process::exit(2) } + Err(ap::ApproveError::System(e)) => Err(e.into()), } } Cmd::Reject { candidate, note } => { diff --git a/src/review/approve.rs b/src/review/approve.rs index 704166c..a76eeac 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -11,34 +11,19 @@ use crate::time; /// Why an approval was refused (§7.1a). Rendered as HTTP 409 with the current /// diff, plus a CLI message. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Stale { + #[error("review is no longer pending (state: {state})")] NotPending { state: String }, + #[error("the candidate changed while you were looking: you were shown {expected}, it is now {actual}")] Identity { expected: String, actual: String }, + #[error("the diff changed while you were looking (shown {expected}, now {actual})")] Diff { expected: String, actual: String }, + /// The base moved: a newer version was accepted while the review was open. + #[error("a newer version was accepted since this review was opened")] Base { expected: Option, actual: Option }, } -impl std::fmt::Display for Stale { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Stale::NotPending { state } => write!(f, "review is no longer pending (state: {state})"), - Stale::Identity { expected, actual } => write!( - f, - "the candidate changed while you were looking: you were shown {expected}, it is now {actual}" - ), - Stale::Diff { expected, actual } => write!( - f, - "the diff changed while you were looking (shown {expected}, now {actual})" - ), - Stale::Base { .. } => write!( - f, - "a newer version was accepted since this review was opened" - ), - } - } -} - #[derive(Debug, Clone)] pub struct Approval { pub id: i64, @@ -49,6 +34,26 @@ pub struct Approval { pub identity_hash: String, } +/// Why a decision did not happen (§7.1a, §6 M-3). +/// +/// Two families, and the difference is the whole point. `Stale` means the +/// reviewer's screen no longer matches the database: the answer is to look +/// again, and the UI says so with a 409 and a fresh diff. `System` means the +/// database itself refused: looking again changes nothing, and the operator has +/// a broken thing to fix. They used to be the same variant — every failure, +/// SQLite included, arrived as "review is no longer pending (state: sqlite: +/// …)", which told a reviewer their eyes were wrong when the truth was that +/// the write failed. +#[derive(Debug, thiserror::Error)] +pub enum ApproveError { + /// What is stored is not what was displayed. + #[error(transparent)] + Stale(#[from] Stale), + /// The write itself failed. Nothing about the review is at fault. + #[error("the decision could not be recorded: {0}")] + System(#[from] Error), +} + /// Approve a candidate. Returns the approval row on success, or the reason the /// approval was refused. pub fn approve( @@ -58,14 +63,14 @@ pub fn approve( identity_hash: &str, diff_digest: &str, note: Option<&str>, -) -> std::result::Result { +) -> std::result::Result { let actor = actor.to_string(); let ih = identity_hash.to_string(); let dd = diff_digest.to_string(); let note = note.map(|s| s.to_string()); let at = time::now(); - db.writer.tx(move |tx| -> Result> { + db.writer.tx(move |tx| -> Result> { let subject = candidates::review_subject_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; let id = subject.id; @@ -74,19 +79,19 @@ pub fn approve( // 1. still open if subject.state != candidate_state::PENDING { - return Ok(Err(Stale::NotPending { state: subject.state })); + return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state }))); } // 2. same candidate bytes if subject.identity_hash != ih { - return Ok(Err(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash })); + return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash }))); } // 3. same rendered diff if subject.diff_digest != dd { - return Ok(Err(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest })); + return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }))); } // 4. base is still the accepted release (I2, end to end) if base != current_base { - return Ok(Err(Stale::Base { expected: base, actual: current_base })); + return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base }))); } let approval_id = approvals::record_in( @@ -124,7 +129,8 @@ pub fn approve( identity_hash: ih, })) }) - .map_err(|e| Stale::NotPending { state: e.to_string() })? + // A failure of the transaction is a system failure, never a stale review. + .map_err(ApproveError::System)? } /// Reject a candidate. Rejection is remembered per identity so the watcher stops @@ -159,30 +165,98 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> }) } -/// §7.4 bulk decision. High-risk items are refused unless confirmed individually. +/// One item of a bulk decision, and what happened to it (§7.4). +#[derive(Debug)] +pub struct BulkItem { + /// The review this outcome is about; `None` when the id matched nothing — + /// which is exactly the case a caller must be able to report, so the row + /// cannot be the key. + pub candidate: Option, + pub outcome: BulkOutcome, +} + +impl BulkItem { + /// The pkgbase to name in a summary line. + pub fn pkgbase(&self) -> &str { + self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)") + } +} + +/// What a bulk decision did with one item (§7.4). +#[derive(Debug)] +pub enum BulkOutcome { + /// Approved; the approval row is here so the caller can queue the build. + Approved(Approval), + /// Rejected. A rejection records no approval, so there is no row to hand + /// back — the old code fabricated `Approval { id: 0 }`, which a caller + /// could not tell from a real one (§6 M-3). + Rejected, + /// Not decided, and why. + Refused(BulkRefusal), +} + +/// Why a bulk decision skipped one of its items (§7.4). +/// +/// Each reason is its own variant because they are different answers to give a +/// human: one wants a confirmation click, one is a form bug, one means the +/// review moved while the page was open, one means the database is broken. They +/// used to all be `Stale::NotPending`, which made the flash message the only +/// place the truth survived. +#[derive(Debug, thiserror::Error)] +pub enum BulkRefusal { + /// High-risk items need their own confirmation, per item (§7.4). + #[error("high risk: confirm it individually")] + HighRiskUnconfirmed, + /// The form said neither approve nor reject. + #[error("unknown decision `{0}`")] + UnknownDecision(String), + /// The review is gone — deleted, or never existed. + #[error("no such review")] + NotFound, + /// The review no longer matches what was displayed. + #[error(transparent)] + Stale(Stale), + /// The write itself failed. + #[error("{0}")] + System(Error), +} + +/// §7.4 bulk decision. High-risk items are refused unless confirmed individually, +/// and one refused item never rolls back the ones that were decided. +/// +/// `items` carries the identity and diff each review was displayed with, so the +/// approval-echo rule applies to bulk exactly as it does to a single approval. pub fn bulk( db: &Db, actor: &str, items: &[(i64, String, String)], // (candidate_id, identity_hash, diff_digest) decision: &str, - confirm_high_risk: bool, -) -> Result>> { + confirmed: &[i64], +) -> Result> { let mut out = Vec::new(); for (id, ih, dd) in items { - let risk = candidates::risk_level(db, *id)?.unwrap_or_default(); - if decision == "approve" && risk == "high" && !confirm_high_risk { - out.push(Err(Stale::NotPending { - state: "high-risk: needs individual confirmation".into(), - })); + let candidate = candidates::by_id(db, *id)?; + let mut push = |candidate, outcome| out.push(BulkItem { candidate, outcome }); + let Some(c) = &candidate else { + push(None, BulkOutcome::Refused(BulkRefusal::NotFound)); continue; + }; + if decision == "approve" && c.risk_level == crate::review::risk::level::HIGH && !confirmed.contains(id) { + push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)); + continue; + } + match decision { + "approve" => match approve(db, actor, *id, ih, dd, Some("bulk")) { + Ok(a) => push(Some(c.clone()), BulkOutcome::Approved(a)), + Err(ApproveError::Stale(s)) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::Stale(s))), + Err(ApproveError::System(e)) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::System(e))), + }, + "reject" => match reject(db, actor, *id, "bulk") { + Ok(()) => push(Some(c.clone()), BulkOutcome::Rejected), + Err(e) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::System(e))), + }, + other => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::UnknownDecision(other.to_string()))), } - out.push(match decision { - "approve" => approve(db, actor, *id, ih, dd, Some("bulk")), - "reject" => reject(db, actor, *id, "bulk") - .map(|_| Approval { id: 0, candidate_id: *id, base_release_id: None, decision: "rejected".into(), diff_digest: dd.clone(), identity_hash: ih.clone() }) - .map_err(|e| Stale::NotPending { state: e.to_string() }), - other => Err(Stale::NotPending { state: format!("unknown decision {other}") }), - }); } Ok(out) } diff --git a/tests/approve.rs b/tests/approve.rs index 5a515eb..61e42c2 100644 --- a/tests/approve.rs +++ b/tests/approve.rs @@ -75,7 +75,7 @@ fn a_stale_identity_hash_is_refused() { assert_ne!(now.identity_hash, c.identity_hash, "identity should have moved"); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); - assert!(matches!(err, Stale::Identity { .. }), "{err:?}"); + assert!(matches!(err, ApproveError::Stale(Stale::Identity { .. })), "{err:?}"); assert_eq!( env.query_i64("SELECT count(*) FROM approval", &[]), Some(0), @@ -92,7 +92,7 @@ fn a_stale_diff_digest_is_refused() { let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); let err = approve(&env.db, "tester", c.id, &c.identity_hash, "sha256:whatever", None).unwrap_err(); - assert!(matches!(err, Stale::Diff { .. }), "{err:?}"); + assert!(matches!(err, ApproveError::Stale(Stale::Diff { .. })), "{err:?}"); assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); let _ = dd; } @@ -103,10 +103,77 @@ fn approving_twice_is_refused_not_duplicated() { let (c, dd) = open_review(&env, "plain-make"); approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); - assert!(matches!(err, Stale::NotPending { .. }), "{err:?}"); + assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}"); assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); } +#[test] +fn a_broken_database_is_not_reported_as_a_stale_review() { + // What this pins: every failure inside the approval transaction used to be + // mapped into `Stale::NotPending`, so a SQLite error reached the reviewer as + // "review is no longer pending (state: sqlite: …)" — the one message that + // tells them to look again when the truth is that the write failed (§6 M-3). + let (env, _fx) = env_with_fixture("plain-make"); + let (c, dd) = open_review(&env, "plain-make"); + // Make the write impossible halfway through the transaction: the approval + // row and the candidate update succeed, then the audit append has nowhere + // to go. + env.exec("DROP TABLE audit", &[]); + let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); + assert!(matches!(err, ApproveError::System(_)), "a broken database was reported as a stale review: {err:?}"); + assert!(err.to_string().contains("could not be recorded"), "the message hides the cause: {err}"); + // And the refusal is atomic: the half-written approval rolled back with it. + assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); + let after = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); + assert_eq!(after.state, "pending_review", "a failed approval must not resolve the review"); +} + +#[test] +fn bulk_refusals_are_their_own_reasons() { + // Bulk used to bend `Stale::NotPending` into "high risk", "unknown decision" + // and "the database failed", and to hand back a fabricated `Approval { id: 0 }` + // for a rejection that recorded no approval at all (§6 M-3). + let (env, _fx) = env_with_fixture("plain-make"); + let (c, dd) = open_review(&env, "plain-make"); + candidates::set_risk(&env.db, c.id, "high", &["new source host".into()]).unwrap(); + let items = [(c.id, c.identity_hash.clone(), dd.clone())]; + + // High risk without the individual confirmation: the reason is the risk. + let out = bulk(&env.db, "tester", &items, "approve", &[]).unwrap(); + assert!( + matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)), + "{:?}", + out[0].outcome + ); + // A decision the form should never have sent is its own reason. + let out = bulk(&env.db, "tester", &items, "ship-it", &[]).unwrap(); + assert!( + matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))), + "{:?}", + out[0].outcome + ); + // Confirming it individually is the answer to the first refusal. + let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap(); + assert!(matches!(out[0].outcome, BulkOutcome::Approved(_)), "{:?}", out[0].outcome); + // Now it is no longer pending, and *that* is a staleness — the two reasons + // stay distinguishable in both directions. + let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap(); + assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::Stale(_))), "{:?}", out[0].outcome); + assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); +} + +#[test] +fn a_bulk_rejection_hands_back_no_invented_approval() { + let (env, _fx) = env_with_fixture("plain-make"); + let (c, dd) = open_review(&env, "plain-make"); + let out = bulk(&env.db, "tester", &[(c.id, c.identity_hash.clone(), dd)], "reject", &[]).unwrap(); + assert!(matches!(out[0].outcome, BulkOutcome::Rejected), "{:?}", out[0].outcome); + // A rejection records a `rejected` row; there is no approval to return, and + // the old `Approval { id: 0 }` sentinel is gone. + assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1)); + assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='approved'", &[]), Some(0)); +} + #[test] fn collapse_in_place_bumps_revision_without_a_new_row() { let (env, fx) = env_with_fixture("plain-make"); @@ -145,7 +212,7 @@ fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() { // The frozen one can no longer be approved: approving it would build a // version nobody is looking at. let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err(); - assert!(matches!(err, Stale::NotPending { .. }), "{err:?}"); + assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}"); } #[test] @@ -158,7 +225,7 @@ fn a_rejected_identity_is_not_re_raised() { assert!(candidates::pending_candidates(&env.db).unwrap().is_empty()); // A different identity is a different question, and gets its own review. let err = approve(&env.db, "tester", c.id, &c.identity_hash, &c.diff_digest, None).unwrap_err(); - assert!(matches!(err, Stale::NotPending { .. })); + assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. }))); } #[test] -- cgit v1.2.3