From 97c62d13ee96e89787ff453df5f83795f0910239 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 3 Dec 2026 21:18:13 -0500 Subject: [PATCH] The review session API returns the checks the review ran, its model cost, and whether it goes on in parts A review's session page could say what was decided but not what was verified or what it cost. The verification run existed only as markdown in the review body, and per-review spend wasn't kept anywhere. - common::review_session keeps the verification run as data (one row per command: passed, failed, couldnt_run or skipped, with a reason), the model cost in whole millionths of a dollar, and goes_on for a session that read one part of a large pull request. - common::usage gains a SpendTally task-local; every model call adds to it, whatever allowance it runs under. - The review dispatch runs each job under the tally. The worker records the run (or "off" when checks are turned off), adds the job's spend before its session closes, and marks a part that goes on. - GET /api/reviewer/session returns verification, cost_usd and goes_on; older sessions return null, null and false. openapi.json regenerated. --- docs/api/openapi.json | 125 +++++++- services/common/src/review_session.rs | 297 ++++++++++++++++++++ services/common/src/usage.rs | 64 ++++- services/gateway/src/routes/reviewer.rs | 119 ++++++++ services/worker/src/main.rs | 6 +- services/worker/src/passes/review_pr.rs | 61 +++- services/worker/src/passes/review_verify.rs | 58 +++- 7 files changed, 722 insertions(+), 8 deletions(-) diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 5fd099816..ac26ecf39 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3680,6 +3680,17 @@ "null" ] }, + "cost_usd": { + "description": "What the review's model calls cost, in US dollars. Null on sessions\nfrom before it was kept.", + "examples": [ + 0.84 + ], + "format": "double", + "type": [ + "number", + "null" + ] + }, "findings": { "description": "How many findings the review kept, once there is a verdict.", "examples": [ @@ -3699,6 +3710,13 @@ ], "type": "string" }, + "goes_on": { + "description": "This session read one part of a large pull request and the review\ngoes on in a new session; the verdict comes with the last part.", + "examples": [ + false + ], + "type": "boolean" + }, "head_sha": { "description": "The commit reviewed.", "examples": [ @@ -3819,6 +3837,17 @@ "REQUEST_CHANGES" ], "type": "string" + }, + "verification": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/SessionVerification", + "description": "The checks the review ran on the change in a sandbox, once they ran.\nNull while it runs, when it ran none, and on older sessions." + } + ] } }, "required": [ @@ -3839,7 +3868,8 @@ "review_url", "steps", "activity", - "activity_dropped" + "activity_dropped", + "goes_on" ], "type": "object" }, @@ -6508,6 +6538,54 @@ ], "type": "object" }, + "SessionCheck": { + "description": "One command of the verification run.", + "properties": { + "cmd": { + "description": "The command, as it ran in the package's folder.", + "examples": [ + "npx vitest run src/auth/limits.test.ts" + ], + "type": "string" + }, + "dir": { + "description": "The package's folder, `.` for the root.", + "examples": [ + "." + ], + "type": "string" + }, + "kind": { + "description": "`install`, `check` or `test`.", + "examples": [ + "test" + ], + "type": "string" + }, + "result": { + "description": "`passed`, `failed`, `couldnt_run` or `skipped`.", + "examples": [ + "passed" + ], + "type": "string" + }, + "why": { + "description": "Why it failed or couldn't run; empty when it passed.", + "examples": [ + "" + ], + "type": "string" + } + }, + "required": [ + "kind", + "dir", + "cmd", + "result", + "why" + ], + "type": "object" + }, "SessionStep": { "description": "One step a review went through.", "properties": { @@ -6540,6 +6618,51 @@ ], "type": "object" }, + "SessionVerification": { + "description": "The review's verification run: each command it ran on the change, and\nwhat it left to the pull request's CI.", + "properties": { + "checks": { + "description": "Each command the review ran, in order.", + "items": { + "$ref": "#/components/schemas/SessionCheck" + }, + "type": "array" + }, + "left_out": { + "description": "What wasn't run here, and why.", + "examples": [ + [ + "`e2e/login.spec.ts`: end-to-end tests run against a preview, so the pull request's CI result stands for them" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "note": { + "description": "Why the run as a whole couldn't run; empty when it ran.", + "examples": [ + "" + ], + "type": "string" + }, + "outcome": { + "description": "`passed`, `failed` (a check the change made fail; it holds the\nmerge), `incomplete` (some of it couldn't run: CoderHelm's own\nproblem, never a hold) or `off` (the repository's reviews don't run\nchecks).", + "examples": [ + "incomplete" + ], + "type": "string" + } + }, + "required": [ + "outcome", + "checks", + "note", + "left_out" + ], + "type": "object" + }, "SnsEnvelope": { "description": "An Amazon SNS message, as SNS posts it to an HTTPS subscription.", "examples": [ diff --git a/services/common/src/review_session.rs b/services/common/src/review_session.rs index ac1cadf9a..a558e5f18 100644 --- a/services/common/src/review_session.rs +++ b/services/common/src/review_session.rs @@ -503,6 +503,214 @@ pub fn session_id_of(item: &HashMap) -> Option { .cloned() } +// ---- The verification run and the model spend --------------------------- + +/// The verification run's outcome words: every step passed, one the change +/// made fail, or some of it couldn't run (CoderHelm's own problem). +pub const VERIFY_PASSED: &str = "passed"; +pub const VERIFY_FAILED: &str = "failed"; +pub const VERIFY_INCOMPLETE: &str = "incomplete"; +/// The repository's reviews don't run its checks (a setting). +pub const VERIFY_OFF: &str = "off"; + +/// One command's result words. `couldnt_run` is CoderHelm's own problem +/// (a missing runner, the sandbox), never the change's; `skipped` didn't run +/// because the install before it didn't finish. +pub const CHECK_PASSED: &str = "passed"; +pub const CHECK_FAILED: &str = "failed"; +pub const CHECK_COULDNT_RUN: &str = "couldnt_run"; +pub const CHECK_SKIPPED: &str = "skipped"; + +/// At most this many commands are kept; a run has a handful. +pub const MAX_CHECKS: usize = 40; + +/// One command of the review's verification run. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CheckRun { + /// `install`, `check` or `test`. + pub kind: String, + /// The package's folder, `.` for the root. + pub dir: String, + /// What ran. + pub cmd: String, + /// One of the `CHECK_*` words. + pub result: String, + /// Why it failed or couldn't run, in words; empty when it passed. + pub why: String, +} + +/// The verification run of one review, as its session keeps it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct VerificationRecord { + /// One of the `VERIFY_*` words. + pub outcome: String, + pub checks: Vec, + /// Why the run as a whole couldn't run; empty when it ran. + pub note: String, + /// What wasn't run here, and why (an end-to-end spec runs against a + /// preview, so the pull request's CI stands for it). + pub left_out: Vec, +} + +/// Attribute holding the verification run. +pub const VERIFICATION: &str = "verification"; + +/// Pure: the record as a DynamoDB map, every text bounded. +pub fn verification_value(v: &VerificationRecord) -> AttributeValue { + let checks = v + .checks + .iter() + .take(MAX_CHECKS) + .map(|c| { + AttributeValue::M(HashMap::from([ + ("kind".to_string(), s(crate::truncate_str(&c.kind, 20))), + ("dir".to_string(), s(crate::truncate_str(&c.dir, 300))), + ("cmd".to_string(), s(crate::truncate_str(&c.cmd, 500))), + ("result".to_string(), s(crate::truncate_str(&c.result, 20))), + ("why".to_string(), s(crate::truncate_str(&c.why, 500))), + ])) + }) + .collect(); + let left_out = v + .left_out + .iter() + .take(MAX_CHECKS) + .map(|l| s(crate::truncate_str(l, 500))) + .collect(); + AttributeValue::M(HashMap::from([ + ( + "outcome".to_string(), + s(crate::truncate_str(&v.outcome, 20)), + ), + ("checks".to_string(), AttributeValue::L(checks)), + ("note".to_string(), s(crate::truncate_str(&v.note, 500))), + ("left_out".to_string(), AttributeValue::L(left_out)), + ])) +} + +/// Pure: the verification run a session holds; `None` before one ran and on +/// older sessions. +pub fn verification_of(item: &HashMap) -> Option { + let m = item.get(VERIFICATION)?.as_m().ok()?; + let text = |m: &HashMap, k: &str| { + m.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let outcome = text(m, "outcome"); + if outcome.is_empty() { + return None; + } + let checks = m + .get("checks") + .and_then(|v| v.as_l().ok()) + .map(|l| { + l.iter() + .filter_map(|v| v.as_m().ok()) + .map(|c| CheckRun { + kind: text(c, "kind"), + dir: text(c, "dir"), + cmd: text(c, "cmd"), + result: text(c, "result"), + why: text(c, "why"), + }) + .collect() + }) + .unwrap_or_default(); + let left_out = m + .get("left_out") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default(); + Some(VerificationRecord { + outcome, + checks, + note: text(m, "note"), + left_out, + }) +} + +/// Record the verification run of `job`'s review. +pub async fn note_verification( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + job: &str, + v: &VerificationRecord, +) { + let update = "SET #verification = :v, #updated_at = :at"; + let req = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&record_sk(job))) + .update_expression(update) + .condition_expression(EXISTS) + .expression_attribute_values(":v", verification_value(v)) + .expression_attribute_values(":at", s(&chrono::Utc::now().to_rfc3339())); + log_unless_missing(named(req, update).send().await.err(), job, "verification"); +} + +/// Attribute holding what the job's model calls cost, in millionths of a +/// dollar (a whole number, so each invocation adds to it exactly). +pub const COST_MICRO_USD: &str = "cost_micro_usd"; + +/// Pure: millionths of a dollar for `usd`; nothing for no spend. +pub fn micro_usd(usd: f64) -> Option { + let micro = (usd * 1e6).round(); + (micro.is_finite() && micro >= 1.0).then_some(micro.min(9e15) as i64) +} + +/// Add `usd` of model spend to `job`'s session. +pub async fn add_cost(dynamo: &DynamoClient, table: &str, team_id: &str, job: &str, usd: f64) { + let Some(micro) = micro_usd(usd) else { return }; + let update = "ADD #cost_micro_usd :c SET #updated_at = :at"; + let req = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&record_sk(job))) + .update_expression(update) + .condition_expression(EXISTS) + .expression_attribute_values(":c", n(micro)) + .expression_attribute_values(":at", s(&chrono::Utc::now().to_rfc3339())); + log_unless_missing(named(req, update).send().await.err(), job, "cost"); +} + +/// Pure: what a session's model calls cost in dollars; `None` on sessions +/// from before it was kept. +pub fn cost_usd_of(item: &HashMap) -> Option { + item.get(COST_MICRO_USD) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .map(|m| m.max(0) as f64 / 1e6) +} + +/// Attribute set on a session whose job read one part of a large pull +/// request and handed the rest to the next job (`review_parts`). +pub const GOES_ON: &str = "goes_on"; + +/// Mark `job`'s session as one part of a review that goes on in its next job. +pub async fn note_goes_on(dynamo: &DynamoClient, table: &str, team_id: &str, job: &str) { + let update = "SET #goes_on = :t, #updated_at = :at"; + let req = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&record_sk(job))) + .update_expression(update) + .condition_expression(EXISTS) + .expression_attribute_values(":t", AttributeValue::Bool(true)) + .expression_attribute_values(":at", s(&chrono::Utc::now().to_rfc3339())); + log_unless_missing(named(req, update).send().await.err(), job, "goes on"); +} + +/// Pure: the session read one part of the review and the next job goes on. +pub fn goes_on_of(item: &HashMap) -> bool { + matches!(item.get(GOES_ON), Some(AttributeValue::Bool(true))) +} + /// A condition miss is a job that never opened a session (it stopped before /// real work); anything else is logged and dropped. fn log_unless_missing( @@ -559,6 +767,95 @@ pub fn steps_of(item: &HashMap) -> Vec { mod tests { use super::*; + #[test] + fn the_verification_run_reads_back_as_it_was_kept() { + let v = VerificationRecord { + outcome: VERIFY_INCOMPLETE.into(), + checks: vec![ + CheckRun { + kind: "check".into(), + dir: ".".into(), + cmd: "npx tsc --noEmit".into(), + result: CHECK_PASSED.into(), + why: String::new(), + }, + CheckRun { + kind: "test".into(), + dir: "web".into(), + cmd: "npx vitest run src/cart.test.ts".into(), + result: CHECK_COULDNT_RUN.into(), + why: "the test runner isn't installed in the package".into(), + }, + ], + note: String::new(), + left_out: vec!["`e2e/cart.spec.ts`: end-to-end tests run against a preview".into()], + }; + let item = HashMap::from([(VERIFICATION.to_string(), verification_value(&v))]); + assert_eq!(verification_of(&item), Some(v)); + // Older sessions and a record without an outcome have none. + assert_eq!(verification_of(&HashMap::new()), None); + let blank = HashMap::from([( + VERIFICATION.to_string(), + verification_value(&VerificationRecord::default()), + )]); + assert_eq!(verification_of(&blank), None); + } + + #[test] + fn the_verification_run_is_bounded() { + let many = VerificationRecord { + outcome: VERIFY_PASSED.into(), + checks: vec![ + CheckRun { + cmd: "x".repeat(2_000), + result: CHECK_PASSED.into(), + ..Default::default() + }; + MAX_CHECKS + 5 + ], + ..Default::default() + }; + let item = HashMap::from([(VERIFICATION.to_string(), verification_value(&many))]); + let back = verification_of(&item).unwrap(); + assert_eq!(back.checks.len(), MAX_CHECKS); + assert!(back.checks[0].cmd.len() <= 500); + } + + #[test] + fn spend_is_kept_in_whole_millionths_and_read_as_dollars() { + assert_eq!(micro_usd(0.0), None); + assert_eq!(micro_usd(-1.0), None); + assert_eq!(micro_usd(f64::NAN), None); + assert_eq!(micro_usd(0.000_000_4), None); + assert_eq!(micro_usd(0.84), Some(840_000)); + let item = HashMap::from([(COST_MICRO_USD.to_string(), n(840_000))]); + assert_eq!(cost_usd_of(&item), Some(0.84)); + assert_eq!(cost_usd_of(&HashMap::new()), None); + } + + #[test] + fn a_session_read_in_parts_says_so() { + assert!(!goes_on_of(&HashMap::new())); + let item = HashMap::from([(GOES_ON.to_string(), AttributeValue::Bool(true))]); + assert!(goes_on_of(&item)); + } + + #[test] + fn the_new_updates_name_every_placeholder() { + for expr in [ + "SET #verification = :v, #updated_at = :at", + "ADD #cost_micro_usd :c SET #updated_at = :at", + "SET #goes_on = :t, #updated_at = :at", + ] { + let names = placeholders(expr); + assert!(names.len() == 2, "{expr}: {names:?}"); + } + assert_eq!( + placeholders("ADD #cost_micro_usd :c SET #updated_at = :at")[0], + COST_MICRO_USD + ); + } + #[test] fn keys_and_ids() { let id = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; diff --git a/services/common/src/usage.rs b/services/common/src/usage.rs index 07f4165b2..918792933 100644 --- a/services/common/src/usage.rs +++ b/services/common/src/usage.rs @@ -131,8 +131,50 @@ pub async fn with_run_allowance( RUN_ALLOWANCE.scope(allowance, fut).await } -/// A model call's cost, against the current allowance. +/// What one piece of work's model calls cost, whatever allowance holds +/// them: a review job reads it when it ends, for its session page. +#[derive(Default)] +pub struct SpendTally { + /// Millionths of a dollar. + micro: std::sync::atomic::AtomicU64, +} + +impl SpendTally { + /// Dollars spent so far. + pub fn usd(&self) -> f64 { + self.micro.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6 + } +} + +tokio::task_local! { + static SPEND_TALLY: std::sync::Arc; +} + +/// Dollars the current tally counted since this was last asked, and zero +/// outside one: a review job adds it to its session as it ends. +pub fn take_spend_tally() -> f64 { + SPEND_TALLY + .try_with(|t| t.micro.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / 1e6) + .unwrap_or(0.0) +} + +/// Runs `fut` with what its model calls cost added to `tally`. +pub async fn with_spend_tally( + tally: std::sync::Arc, + fut: F, +) -> F::Output { + SPEND_TALLY.scope(tally, fut).await +} + +/// A model call's cost, against the current allowance (and the current +/// tally, when there is one). pub fn note_run_spend(cost_usd: f64) { + let _ = SPEND_TALLY.try_with(|t| { + t.micro.fetch_add( + (cost_usd.max(0.0) * 1e6) as u64, + std::sync::atomic::Ordering::Relaxed, + ); + }); let _ = RUN_ALLOWANCE.try_with(|a| { let micro = (cost_usd.max(0.0) * 1e6) as u64; a.left @@ -1492,6 +1534,26 @@ pub fn counts_cache_enabled(team_setting: Option, env_default: Option<&str #[cfg(test)] mod tests { use super::*; + + #[tokio::test] + async fn a_tally_counts_what_its_work_spent_inside_any_allowance() { + let tally = std::sync::Arc::new(SpendTally::default()); + with_spend_tally(tally.clone(), async { + note_run_spend(0.25); + let allowance = std::sync::Arc::new(RunAllowance::new(10.0)); + with_run_allowance(allowance, async { note_run_spend(0.5) }).await; + note_run_spend(-1.0); + assert!((take_spend_tally() - 0.75).abs() < 1e-9); + assert_eq!(take_spend_tally(), 0.0); + note_run_spend(0.75); + }) + .await; + assert_eq!(take_spend_tally(), 0.0); + assert!((tally.usd() - 0.75).abs() < 1e-9, "{}", tally.usd()); + // Spend outside it isn't its own. + note_run_spend(3.0); + assert!((tally.usd() - 0.75).abs() < 1e-9); + } use serde_json::json; /// A store whose first `conflicts` writes lose a transaction race. diff --git a/services/gateway/src/routes/reviewer.rs b/services/gateway/src/routes/reviewer.rs index b4544a532..130dfdac6 100644 --- a/services/gateway/src/routes/reviewer.rs +++ b/services/gateway/src/routes/reviewer.rs @@ -1275,6 +1275,77 @@ pub struct ReviewSession { /// Null while it runs, when it ended without one, and on older sessions. #[schema(example = "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00")] pub review_sk: Option, + /// The checks the review ran on the change in a sandbox, once they ran. + /// Null while it runs, when it ran none, and on older sessions. + pub verification: Option, + /// What the review's model calls cost, in US dollars. Null on sessions + /// from before it was kept. + #[schema(example = 0.84)] + pub cost_usd: Option, + /// This session read one part of a large pull request and the review + /// goes on in a new session; the verdict comes with the last part. + #[schema(example = false)] + pub goes_on: bool, +} + +/// The review's verification run: each command it ran on the change, and +/// what it left to the pull request's CI. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct SessionVerification { + /// `passed`, `failed` (a check the change made fail; it holds the + /// merge), `incomplete` (some of it couldn't run: CoderHelm's own + /// problem, never a hold) or `off` (the repository's reviews don't run + /// checks). + #[schema(example = "incomplete")] + pub outcome: String, + /// Each command the review ran, in order. + pub checks: Vec, + /// Why the run as a whole couldn't run; empty when it ran. + #[schema(example = "")] + pub note: String, + /// What wasn't run here, and why. + #[schema(example = json!(["`e2e/login.spec.ts`: end-to-end tests run against a preview, so the pull request's CI result stands for them"]))] + pub left_out: Vec, +} + +/// One command of the verification run. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct SessionCheck { + /// `install`, `check` or `test`. + #[schema(example = "test")] + pub kind: String, + /// The package's folder, `.` for the root. + #[schema(example = ".")] + pub dir: String, + /// The command, as it ran in the package's folder. + #[schema(example = "npx vitest run src/auth/limits.test.ts")] + pub cmd: String, + /// `passed`, `failed`, `couldnt_run` or `skipped`. + #[schema(example = "passed")] + pub result: String, + /// Why it failed or couldn't run; empty when it passed. + #[schema(example = "")] + pub why: String, +} + +/// Pure: the verification run a session holds, as the API returns it. +fn verification_of(item: &HashMap) -> Option { + common::review_session::verification_of(item).map(|v| SessionVerification { + outcome: v.outcome, + checks: v + .checks + .into_iter() + .map(|c| SessionCheck { + kind: c.kind, + dir: c.dir, + cmd: c.cmd, + result: c.result, + why: c.why, + }) + .collect(), + note: v.note, + left_out: v.left_out, + }) } /// Pure: the session in `item` as `team_id` sees it. `None` for a record @@ -1329,6 +1400,9 @@ fn session_of( activity_dropped: common::review_session::activity_dropped(item), overview: overview_of(item), review_sk: common::review_session::review_sk_of(item), + verification: verification_of(item), + cost_usd: common::review_session::cost_usd_of(item), + goes_on: common::review_session::goes_on_of(item), }) } @@ -1779,6 +1853,51 @@ mod tests { assert!(s["review_sk"].is_null()); } + #[test] + fn a_session_returns_its_checks_its_cost_and_whether_it_goes_on() { + use common::review_session as rs; + let old = serde_json::to_value( + session_of(&session_item("t", "done", 2_000), "t", 9_999).unwrap(), + ) + .unwrap(); + // Older sessions: null, never missing, and not a part. + assert!(old["verification"].is_null()); + assert!(old["cost_usd"].is_null()); + assert_eq!(old["goes_on"], false); + + let mut it = session_item("t", "done", 2_000); + it.insert( + rs::VERIFICATION.into(), + rs::verification_value(&rs::VerificationRecord { + outcome: rs::VERIFY_INCOMPLETE.into(), + checks: vec![rs::CheckRun { + kind: "test".into(), + dir: ".".into(), + cmd: "npx vitest run a.test.ts".into(), + result: rs::CHECK_COULDNT_RUN.into(), + why: "the test runner isn't installed".into(), + }], + note: String::new(), + left_out: vec!["e2e/a.spec.ts: runs against a preview".into()], + }), + ); + it.insert(rs::COST_MICRO_USD.into(), attr_n(840_000)); + it.insert(rs::GOES_ON.into(), AttributeValue::Bool(true)); + let s = serde_json::to_value(session_of(&it, "t", 9_999).unwrap()).unwrap(); + assert_eq!(s["verification"]["outcome"], "incomplete"); + assert_eq!(s["verification"]["checks"][0]["result"], "couldnt_run"); + assert_eq!( + s["verification"]["checks"][0]["cmd"], + "npx vitest run a.test.ts" + ); + assert_eq!( + s["verification"]["left_out"][0], + "e2e/a.spec.ts: runs against a preview" + ); + assert_eq!(s["cost_usd"], 0.84); + assert_eq!(s["goes_on"], true); + } + #[test] fn a_session_returns_its_activity_in_groups_and_its_overview() { use common::review_activity::Event; diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index a0b4d04f7..96dfe3f07 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -684,7 +684,11 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe } models::WorkerMessage::Review(msg) => { info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), pr = msg.pr_number, "Reviewing PR from label"); - if let Err(e) = passes::review_pr::run(&state, msg).await { + // The job's model spend, for its session page. + let tally = std::sync::Arc::new(common::usage::SpendTally::default()); + if let Err(e) = + common::usage::with_spend_tally(tally, passes::review_pr::run(&state, msg)).await + { error!("Review failed: {e:?}"); } } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index ed186b205..fbb6b900a 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -968,6 +968,35 @@ impl LiveJob { self.session().opened = true; } + /// Add what the job's model calls cost since it last did to its session. + async fn add_cost(&self, state: &WorkerState, team_id: &str) { + common::review_session::add_cost( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &self.id, + common::usage::take_spend_tally(), + ) + .await; + } + + /// The verification run, on the session page. + async fn verification( + &self, + state: &WorkerState, + msg: &ReviewMessage, + v: &common::review_session::VerificationRecord, + ) { + common::review_session::note_verification( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + &self.id, + v, + ) + .await; + } + /// One more step in the session. `detail` may be empty. async fn step(&self, state: &WorkerState, msg: &ReviewMessage, text: &str, detail: &str) { common::review_session::step( @@ -1312,7 +1341,7 @@ impl LiveJob { Finished::Continuing { reason, .. } => ( rs::STATUS_DONE, Some(*reason), - format!("This step's part is done; the review goes on: {reason}"), + format!("Read this part; the review goes on in its next part: {reason}"), CheckEnd::Retrying { reason }, ), }; @@ -1344,6 +1373,18 @@ impl LiveJob { reason, }; } + // What it cost, and that a review read in parts goes on, are on the + // session before it reads as ended. + self.add_cost(state, &msg.team_id).await; + if matches!(how, Finished::Continuing { .. }) { + rs::note_goes_on( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + &self.id, + ) + .await; + } rs::close( &state.dynamo, &state.config.settings_table_name, @@ -1446,8 +1487,12 @@ pub async fn run( return Ok(()); } let job = LiveJob::start(); + let team_id = msg.team_id.clone(); let mut reviewed_head = msg.head_sha.clone(); - match run_budgeted(state, msg.clone(), &mut reviewed_head, &job).await { + // What the job spends is added to its session as it ends (the caller + // holds the tally); what it spent after that, such as a reply posted + // after the review, is added here. + let out = match run_budgeted(state, msg.clone(), &mut reviewed_head, &job).await { Ok(Outcome::Done { posted, .. }) => { job.finished(state, &msg, common::review_live::Finished::Done) .await; @@ -1509,7 +1554,9 @@ pub async fn run( review_failed(state, &carried, &reviewed_head, &e.to_string(), limit, &job).await; Ok(()) } - } + }; + job.add_cost(state, &team_id).await; + out } /// The job that goes on with a review read in parts: pinned to the head it @@ -4358,8 +4405,16 @@ async fn run_once( // Only a check or test the change made fail holds the merge; a // run CoderHelm couldn't make is said once, as its own problem. verify_failed = v.blocks(); + live_job.verification(state, &msg, &v.record).await; verify_md = v.md; } + } else { + // The session page says checks are off, not that none were found. + let off = common::review_session::VerificationRecord { + outcome: common::review_session::VERIFY_OFF.to_string(), + ..Default::default() + }; + live_job.verification(state, &msg, &off).await; } // Verdict: always APPROVE or REQUEST_CHANGES. Changes are requested for diff --git a/services/worker/src/passes/review_verify.rs b/services/worker/src/passes/review_verify.rs index 465666c4c..508187688 100644 --- a/services/worker/src/passes/review_verify.rs +++ b/services/worker/src/passes/review_verify.rs @@ -643,6 +643,8 @@ pub struct Verification { pub outcome: Outcome, /// The review's Verification section. pub md: String, + /// The same run as data, for the review's session page. + pub record: common::review_session::VerificationRecord, } impl Verification { @@ -664,10 +666,49 @@ impl Verification { Self { outcome: Outcome::Incomplete, md, + record: common::review_session::VerificationRecord { + outcome: Outcome::Incomplete.word().to_string(), + checks: Vec::new(), + note: why.trim().trim_end_matches('.').to_string(), + left_out: left_out.to_vec(), + }, } } } +impl Outcome { + /// The outcome's word on the session record: `passed`, `failed` or + /// `incomplete`. + pub fn word(&self) -> &'static str { + match self { + Outcome::Passed => common::review_session::VERIFY_PASSED, + Outcome::Failed => common::review_session::VERIFY_FAILED, + Outcome::Incomplete => common::review_session::VERIFY_INCOMPLETE, + } + } +} + +/// One step's result as the session page shows it. +fn check_run(step: &Step, read: &StepRead) -> common::review_session::CheckRun { + use common::review_session as rs; + let (result, why) = match read { + StepRead::Passed => (rs::CHECK_PASSED, String::new()), + StepRead::Failed(code) => (rs::CHECK_FAILED, format!("it exited with code {code}")), + StepRead::Own(why) => (rs::CHECK_COULDNT_RUN, why.clone()), + StepRead::Skipped => ( + rs::CHECK_SKIPPED, + "its install didn't finish, so it didn't run".to_string(), + ), + }; + rs::CheckRun { + kind: step.kind.word().to_string(), + dir: step.dir.clone(), + cmd: step.cmd.clone(), + result: result.to_string(), + why, + } +} + fn notes(md: &mut String, left_out: &[String]) { if !left_out.is_empty() { md.push_str("\n\nNot run here:"); @@ -730,8 +771,11 @@ pub fn judge(plan: &Plan, changed: &[String], output: &str) -> Verification { let mut passed: Vec<&Step> = Vec::new(); let mut failed: Vec<(&Step, i32, String)> = Vec::new(); let mut own: Vec<(&Step, String)> = Vec::new(); + let mut checks = Vec::new(); for (step, (code, text)) in plan.steps.iter().zip(&results) { - match read_step(step.kind, &step.deps, *code, text, changed) { + let read = read_step(step.kind, &step.deps, *code, text, changed); + checks.push(check_run(step, &read)); + match read { StepRead::Passed => passed.push(step), StepRead::Own(why) => own.push((step, why)), StepRead::Skipped => {} @@ -782,7 +826,17 @@ pub fn judge(plan: &Plan, changed: &[String], output: &str) -> Verification { } } notes(&mut md, &plan.left_out); - Verification { outcome, md } + let record = common::review_session::VerificationRecord { + outcome: outcome.word().to_string(), + checks, + note: String::new(), + left_out: plan.left_out.clone(), + }; + Verification { + outcome, + md, + record, + } } #[cfg(test)]