From d5e6390c1dda88ffce149148aab2576f08f313bf Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 22:18:50 -0500 Subject: [PATCH 1/3] Pull requests overview: record every signal at the source, and the opt-in digest and nudges The overview no longer says "not recorded yet". Each signal is recorded where it happens, for every pull request and repository: - default-branch check runs, statuses and job waits from the webhook, into one record per repository with red episodes and runner waits (common::pr_ci); pull requests blocked by a red main - CoderHelm's findings, each time the reviewer stores a review, from raised to verified fixed at a later head (common::pr_findings) - every run's end state, stop reason and cost on the pull request's history, at close and nightly (common::pr_runs), with a test that every ending maps to exactly one of six states - closed pull requests' files, for single-reviewer paths and sensitive-path merges against each repository's list, defaulting to auth, payments, secrets, infra and migrations (common::pr_settings, GET/PUT /api/prs/settings) - open Dependabot alerts with no pull request; code scanning says it needs the security events permission The overview read moves into common::pr_overview_read so the page and the weekly digest share it. The digest (Monday, to the team's channels or its members by email) and private nudges (at the stage's p85, then two and four working days later, then never) are both off until a team turns them on. Incident case ya_overview_signals_recorded pins it. --- .../incidents/ya_overview_signals_recorded.md | 5 + docs/pull-requests/api_contract.md | 15 +- services/common/src/lib.rs | 6 + services/common/src/pr_ci.rs | 564 ++++++++++++++++++ services/common/src/pr_findings.rs | 371 ++++++++++++ services/common/src/pr_history.rs | 7 + services/common/src/pr_notify.rs | 459 ++++++++++++++ services/common/src/pr_overview.rs | 344 +++++++++-- services/common/src/pr_overview_read.rs | 477 +++++++++++++++ services/common/src/pr_runs.rs | 228 +++++++ services/common/src/pr_settings.rs | 283 +++++++++ services/gateway/src/main.rs | 4 + services/gateway/src/permissions.rs | 2 + services/gateway/src/routes/github_webhook.rs | 1 + services/gateway/src/routes/prs.rs | 214 ++----- services/gateway/src/routes/prs_overview.rs | 202 +++---- services/worker/src/main.rs | 5 + .../xw_every_open_pr_has_one_state.rs | 3 +- .../incidents/xz_org_overview_facts_only.rs | 38 +- .../incidents/ya_overview_signals_recorded.rs | 126 ++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/pr_notify.rs | 356 +++++++++++ services/worker/src/passes/pr_records.rs | 56 ++ services/worker/src/passes/review_pr.rs | 43 ++ 24 files changed, 3431 insertions(+), 379 deletions(-) create mode 100644 docs/incidents/ya_overview_signals_recorded.md create mode 100644 services/common/src/pr_ci.rs create mode 100644 services/common/src/pr_findings.rs create mode 100644 services/common/src/pr_notify.rs create mode 100644 services/common/src/pr_overview_read.rs create mode 100644 services/common/src/pr_runs.rs create mode 100644 services/common/src/pr_settings.rs create mode 100644 services/worker/src/passes/incidents/ya_overview_signals_recorded.rs create mode 100644 services/worker/src/passes/pr_notify.rs diff --git a/docs/incidents/ya_overview_signals_recorded.md b/docs/incidents/ya_overview_signals_recorded.md new file mode 100644 index 00000000..9404b25e --- /dev/null +++ b/docs/incidents/ya_overview_signals_recorded.md @@ -0,0 +1,5 @@ +# ya. `ya_overview_signals_recorded` + +**What happened:** The org overview said "not recorded yet" for eight signals: how long main was red and which pull requests it blocked, how long jobs waited for a runner, what became of CoderHelm's findings, how its runs ended, what they cost, which paths one reviewer covers, which merges touched a sensitive path, and open security alerts with no pull request. The weekly digest and the per-pull-request nudges didn't exist. + +**The guarantee:** Each signal is recorded where it happens, for every pull request and repository. Default-branch check runs, statuses and job waits go from the webhook into one record per repository (`pr_ci`), with red episodes and runner waits. Each stored review records its findings and moves earlier ones on (`pr_findings`); only the reviewer finding a concern gone at a later head counts as verified. A pull request's runs end in exactly one of six states with their cost, written when it closes and again nightly (`pr_runs`). Closed pull requests keep their files, for single-reviewer paths and sensitive-path merges against each repository's list (`pr_settings`, defaulting to auth, payments, secrets, infra and migrations). Open Dependabot alerts with no pull request are counted; code scanning says it needs the security events permission. The digest and nudges stay off until a team turns them on; a digest goes only to the team's members or its own channels, and a nudge goes privately to the person whose turn it is, three times a stage at most, then never. diff --git a/docs/pull-requests/api_contract.md b/docs/pull-requests/api_contract.md index 4ab3857e..f44fa712 100644 --- a/docs/pull-requests/api_contract.md +++ b/docs/pull-requests/api_contract.md @@ -129,9 +129,20 @@ On the history row (`History`): - `bypass`: the rule a merge went past ("merged before the required review", "merged with changes requested", "merged with required checks failing: ...", "merged while the branch's rules blocked it") or null; `merged_by_type` (`person` | `coderhelm` | `bot`), so CoderHelm's own bypasses show. - `follow_ups[] {repo, number, at, reason}`: suspects, never cause, each with its reason; `reverted_by` is the certain link. - `category`, `severity`, `flaky_checks[]`, `drift_behind`, `drift_overlap`. -- `run_outcome` (the last run's status) and `stop_reason` (its hand-off code when a person had to act). +- `run_outcome`: one of `first_try`, `after_fixes`, `rerun_only`, `gave_up`, `blocked`, `stopped` (`common::pr_runs::outcome`, from the run's recorded ending), and `stop_reason`, its ending code. Written when the pull request closes and again by the nightly reconcile for a run that ends later. +- `cost_micro_usd`: the pull request's runs' recorded cost together; `files[]` (up to 300), for single-reviewer paths and sensitive-path merges. -Not stored yet (follow-ups): CODEOWNERS file versions and sensitive-path lists (so `non_owner_on_owned` reads only GitHub's review decision today), policy events from the rule-suites API and audit log, Dependabot and code-scanning alerts with KEV and EPSS, default-branch CI episodes, a nightly flaky-check index, review comment counts and comments followed by a change, run cost and findings per pull request, the event feed, and the SLA and working-agreement settings. +## Recorded at the source (`ya_overview_signals_recorded`) +- Default-branch CI `PRMAINCI#owner/repo` (`pr_ci::MainCi`), one per repository, from every `check_run`, `status` and `workflow_job` webhook on the default branch: the current head's checks, red `episodes[] {from, to, sha, checks, fixed_sha}` (newest 500, 400 days) and runner waits `queue[] {at, secs, label}` (`started_at` minus `created_at`, newest 2,000). A pull request is blocked by main when a check failing on it is failing on main now (`pr_ci::blocked_by_main`). +- Findings `PRFINDINGS#owner/repo#000318` (`pr_findings::PrFindings`), written by the reviewer each time it stores a review: each finding's tier (p0 blocking, p1 high, p2 other), when it was raised, acknowledged by a person, followed by a change to its lines, verified fixed (the reviewer found it gone at a later head), or dismissed (answered without a change). +- Settings `PRSETTINGS` (`pr_settings::PrSettings`), `GET`/`PUT /api/prs/settings` (changing needs agent settings): sensitive path patterns per repository (default `**/auth/**`, `**/payments/**`, `**/secrets/**`, `**/infra/**`, `**/migrations/**`), the SLA days, `digest {enabled, channel: slack|teams|email, to[]}` and `nudges {enabled}`, both off by default. +- Security alerts: open Dependabot findings with no pull request, from the security findings CoderHelm already keeps (`SECFINDING#`). Code scanning reads as `needs_permission` until the app holds the security events permission. + +## Digest and nudges (`worker::passes::pr_notify`, both opt-in) +- Weekly digest: Monday from 13:00 UTC, once per ISO week (`PRDIGEST#` claim), the overview read through the same `pr_overview_read::read` the page uses. Slack or Teams go to the team's update channels; email only to listed addresses that belong to team members. +- Nudges: a private email to the member whose GitHub login holds the turn, at the stage's p85 (the latest repository snapshot), then two and four working days later, then never again for that stage (`PRNUDGE#owner/repo#000318`); skipped when a person acted in the last working day. + +Not stored yet (follow-ups): CODEOWNERS file versions (so `non_owner_on_owned` reads only GitHub's review decision today), policy events from the rule-suites API and audit log, KEV and EPSS beyond what security findings carry, a nightly flaky-check index, and review comment counts. ## Ordering and freshness (since the review of #985) - `PrRecord.head_repo`: the head branch's repository. Stack links join head and base inside the same repository only, so a fork's branch never stacks the repository's pull requests. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 4566f790..66fbfbe9 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -265,6 +265,7 @@ pub mod plan_sync; /// Every body CoderHelm sends GitHub fits GitHub's limit. pub mod pr_body; pub mod pr_body_fit; +pub mod pr_ci; /// A description checked against the recorded facts, sentence by sentence. pub mod pr_claims; /// What is recorded about a pull request at one head, and the lead rendered @@ -273,18 +274,23 @@ pub mod pr_conventions; /// A dependency pull request's facts, from what the pipeline records. pub mod pr_dependency; pub mod pr_facts; +pub mod pr_findings; pub mod pr_history; /// Where each part of a description goes, and how a reader would judge it. pub mod pr_layout; pub mod pr_needs; +pub mod pr_notify; /// What happened to a PR CoderHelm opened, read from GitHub. pub mod pr_outcome; pub mod pr_overview; +pub mod pr_overview_read; /// The last read of a description before it is saved, verified. pub mod pr_reader; pub mod pr_record; /// The final read of a description before it is posted. pub mod pr_review; +pub mod pr_runs; +pub mod pr_settings; /// The work around a pull request that is not in its diff, each step with /// one owner and one state. pub mod pr_steps; diff --git a/services/common/src/pr_ci.rs b/services/common/src/pr_ci.rs new file mode 100644 index 00000000..34fd1ebf --- /dev/null +++ b/services/common/src/pr_ci.rs @@ -0,0 +1,564 @@ +//! Each repository's default branch, as CI sees it: when its checks turned +//! red and green again (the red-main episodes), which checks are failing on +//! it now, and how long jobs waited for a runner. +//! +//! - One settings-table item per repository (`pk` = team id, `sk` = +//! [`main_sk`]), its body a JSON document ([`MainCi`]) written with a +//! version check, from the `check_run`, `check_suite`, `status` and +//! `workflow_job` events GitHub already sends for every repository the +//! app is installed on. No GitHub read is spent. +//! - An episode starts when the default branch's newest head has a failing +//! check and ends when a later head has its checks green again +//! ([`MainCi::rollup`]). Episodes are kept [`EPISODE_KEEP_SECS`]. +//! - Queue samples are job waits (queued to started) on any branch: +//! capacity, never counted as a failure. +//! +//! The pure parts ([`MainCi::apply_event`], [`blocked_by_main`]) are what the +//! tests and the incident cases drive. + +use std::collections::BTreeMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::pr_record::PrRecord; + +/// Sort-key prefix of the per-repository default-branch record. +pub const MAIN_PREFIX: &str = "PRMAINCI#"; +/// How long an ended episode is kept. +pub const EPISODE_KEEP_SECS: i64 = 400 * 86_400; +/// Most episodes kept per repository (the newest). +pub const MAX_EPISODES: usize = 500; +/// Most queue samples kept per repository (the newest). +pub const MAX_QUEUE: usize = 2_000; +/// Most checks tracked for one head. +pub const MAX_CHECKS: usize = 200; + +pub fn main_sk(repo: &str) -> String { + format!("{MAIN_PREFIX}{repo}") +} + +/// One check on the default branch's head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct MainCheck { + /// `queued`, `in_progress`, `completed`. + pub status: String, + pub conclusion: String, + pub at: i64, +} + +impl MainCheck { + fn failing(&self) -> bool { + self.status == "completed" + && matches!( + self.conclusion.as_str(), + "failure" | "timed_out" | "startup_failure" | "error" | "action_required" + ) + } + fn done(&self) -> bool { + self.status == "completed" + } +} + +/// The default branch was red from `from` until `to` (0 while still red). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Episode { + pub from: i64, + pub to: i64, + /// The head that turned it red, and the checks failing on it. + pub sha: String, + pub checks: Vec, + /// The head that turned it green again. + pub fixed_sha: String, +} + +impl Episode { + /// Seconds red, up to `now` while still open. + pub fn secs(&self, now: i64) -> i64 { + let end = if self.to > 0 { self.to } else { now }; + (end - self.from).max(0) + } + /// Seconds of the episode inside `[a, b]`. + pub fn secs_within(&self, a: i64, b: i64) -> i64 { + let end = if self.to > 0 { self.to } else { b }; + (end.min(b) - self.from.max(a)).max(0) + } +} + +/// One job's wait for a runner. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct QueueSample { + pub at: i64, + pub secs: i64, + /// The runner label it asked for (`ubuntu-latest`, a self-hosted label). + pub label: String, +} + +/// A repository's default branch. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct MainCi { + pub repo: String, + pub branch: String, + /// The newest head CI reported on, and its checks. + pub sha: String, + pub sha_at: i64, + pub checks: BTreeMap, + pub episodes: Vec, + pub queue: Vec, + pub updated_at: i64, +} + +fn ts(v: &Value) -> i64 { + v.as_str() + .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) + .map(|d| d.timestamp()) + .unwrap_or(0) +} + +/// `red`, `green` or `pending` for a set of checks. +pub fn rollup(checks: &BTreeMap) -> &'static str { + if checks.values().any(MainCheck::failing) { + "red" + } else if !checks.is_empty() && checks.values().all(MainCheck::done) { + "green" + } else { + "pending" + } +} + +impl MainCi { + pub fn new(repo: &str) -> MainCi { + MainCi { + repo: repo.to_string(), + ..Default::default() + } + } + + /// The open episode, if the default branch is red now. + pub fn red_now(&self) -> Option<&Episode> { + self.episodes.last().filter(|e| e.to == 0) + } + + /// The checks failing on the default branch's head now. + pub fn failing_now(&self) -> Vec { + self.checks + .iter() + .filter(|(_, c)| c.failing()) + .map(|(n, _)| n.clone()) + .collect() + } + + fn note_check(&mut self, sha: &str, at: i64, name: &str, c: MainCheck) -> bool { + if sha.is_empty() || name.is_empty() { + return false; + } + if sha != self.sha { + // An older head's late report changes nothing. + if at > 0 && at < self.sha_at && !self.sha.is_empty() { + return false; + } + self.sha = sha.to_string(); + self.sha_at = at; + self.checks.clear(); + } + if self.checks.get(name) == Some(&c) { + return false; + } + if self.checks.len() >= MAX_CHECKS && !self.checks.contains_key(name) { + return false; + } + self.checks.insert(name.to_string(), c); + self.settle(at); + true + } + + /// Opens an episode when the head turns red, closes it when a head is + /// green again. + fn settle(&mut self, at: i64) { + match rollup(&self.checks) { + "red" => { + let failing = self.failing_now(); + match self.episodes.last_mut().filter(|e| e.to == 0) { + Some(open) => { + for f in failing { + if !open.checks.contains(&f) { + open.checks.push(f); + } + } + } + None => self.episodes.push(Episode { + from: at, + to: 0, + sha: self.sha.clone(), + checks: failing, + fixed_sha: String::new(), + }), + } + } + "green" => { + if let Some(open) = self.episodes.last_mut().filter(|e| e.to == 0) { + open.to = at.max(open.from); + open.fixed_sha = self.sha.clone(); + } + } + _ => {} + } + if self.episodes.len() > MAX_EPISODES { + let cut = self.episodes.len() - MAX_EPISODES; + self.episodes.drain(..cut); + } + self.episodes + .retain(|e| e.to == 0 || e.to > at - EPISODE_KEEP_SECS); + } + + fn note_queue(&mut self, s: QueueSample) -> bool { + if s.secs < 0 || s.at == 0 || self.queue.iter().any(|q| q == &s) { + return false; + } + self.queue.push(s); + if self.queue.len() > MAX_QUEUE { + let cut = self.queue.len() - MAX_QUEUE; + self.queue.drain(..cut); + } + true + } + + /// One webhook. True when the record changed. + pub fn apply_event(&mut self, event_type: &str, payload: &Value, now: i64) -> bool { + let default = payload["repository"]["default_branch"] + .as_str() + .unwrap_or(""); + if !default.is_empty() { + self.branch = default.to_string(); + } + self.updated_at = now; + let on_default = |b: &str| !b.is_empty() && b == default; + match event_type { + "check_run" => { + let run = &payload["check_run"]; + let mut changed = false; + // Capacity: queued (its suite created) to started, any branch. + let started = ts(&run["started_at"]); + let created = ts(&run["check_suite"]["created_at"]); + if started > 0 && created > 0 && payload["action"] == "created" { + changed |= self.note_queue(QueueSample { + at: started, + secs: started - created, + label: String::new(), + }); + } + if !on_default(run["check_suite"]["head_branch"].as_str().unwrap_or("")) { + return changed; + } + let at = [ts(&run["completed_at"]), started, now] + .into_iter() + .find(|t| *t > 0) + .unwrap_or(now); + changed + | self.note_check( + run["head_sha"].as_str().unwrap_or(""), + at, + run["name"].as_str().unwrap_or(""), + MainCheck { + status: run["status"].as_str().unwrap_or("").to_string(), + conclusion: run["conclusion"].as_str().unwrap_or("").to_string(), + at, + }, + ) + } + "status" => { + let on = payload["branches"].as_array().is_some_and(|b| { + b.iter() + .any(|x| on_default(x["name"].as_str().unwrap_or(""))) + }); + let sha = payload["sha"].as_str().unwrap_or(""); + if !on && sha != self.sha { + return false; + } + let state = payload["state"].as_str().unwrap_or(""); + let at = ts(&payload["updated_at"]).max(ts(&payload["created_at"])); + let at = if at > 0 { at } else { now }; + let (status, conclusion) = match state { + "pending" => ("in_progress", ""), + "success" => ("completed", "success"), + "failure" => ("completed", "failure"), + _ => ("completed", "error"), + }; + self.note_check( + sha, + at, + payload["context"].as_str().unwrap_or(""), + MainCheck { + status: status.into(), + conclusion: conclusion.into(), + at, + }, + ) + } + "workflow_job" => { + let job = &payload["workflow_job"]; + let created = ts(&job["created_at"]); + let started = ts(&job["started_at"]); + if payload["action"] != "in_progress" || created == 0 || started == 0 { + return false; + } + let label = job["labels"] + .as_array() + .and_then(|l| l.first()) + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + self.note_queue(QueueSample { + at: started, + secs: started - created, + label, + }) + } + _ => false, + } + } + + /// Seconds red inside `[a, b]`, and the episodes that overlap it. + pub fn red_within(&self, a: i64, b: i64) -> (i64, Vec<&Episode>) { + let eps: Vec<&Episode> = self + .episodes + .iter() + .filter(|e| e.from <= b && (e.to == 0 || e.to >= a)) + .collect(); + (eps.iter().map(|e| e.secs_within(a, b)).sum(), eps) + } +} + +/// An open pull request whose failing checks include one failing on its +/// base branch's head now: main broke under it, it didn't break main. +pub fn blocked_by_main(rec: &PrRecord, main: &MainCi) -> bool { + if main.red_now().is_none() || (!main.branch.is_empty() && rec.base_ref != main.branch) { + return false; + } + let failing_main = main.failing_now(); + rec.checks.iter().any(|(name, c)| { + c.status == "completed" + && matches!( + c.conclusion.as_str(), + "failure" | "timed_out" | "startup_failure" | "error" | "action_required" + ) + && failing_main.contains(name) + }) +} + +// ─── Storage ──────────────────────────────────────────────────────────────── + +type Err = Box; + +/// Read, change and write one repository's record under a version check; +/// two events at once never lose each other's change. +pub async fn update( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + f: impl Fn(&mut MainCi) -> bool, +) -> Result { + for _ in 0..4 { + let got = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(main_sk(repo))) + .consistent_read(true) + .send() + .await?; + let item = got.item(); + let version: i64 = item + .and_then(|i| i.get("version")) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + let mut ci: MainCi = item + .and_then(|i| i.get("doc")) + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str(d).ok()) + .unwrap_or_else(|| MainCi::new(repo)); + if !f(&mut ci) { + return Ok(false); + } + let mut put = dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(main_sk(repo))) + .item("doc", AttributeValue::S(serde_json::to_string(&ci)?)) + .item("version", AttributeValue::N((version + 1).to_string())); + put = if version == 0 { + put.condition_expression("attribute_not_exists(sk)") + } else { + put.condition_expression("version = :v") + .expression_attribute_values(":v", AttributeValue::N(version.to_string())) + }; + match put.send().await { + Ok(_) => return Ok(true), + Err(e) => { + let conflict = e + .as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()); + if !conflict { + return Err(e.into()); + } + } + } + } + Err("default-branch record: too many concurrent writes".into()) +} + +/// Every repository's default-branch record of a team (the items read). +pub fn from_items(team_id: &str, items: &[crate::pr_record::Item]) -> Vec { + items + .iter() + .filter(|i| i.get("pk").and_then(|v| v.as_s().ok()).map(String::as_str) == Some(team_id)) + .filter(|i| { + i.get("sk") + .and_then(|v| v.as_s().ok()) + .is_some_and(|s| s.starts_with(MAIN_PREFIX)) + }) + .filter_map(|i| i.get("doc").and_then(|v| v.as_s().ok())) + .filter_map(|d| serde_json::from_str(d).ok()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn run(sha: &str, name: &str, conclusion: Option<&str>, at: &str) -> Value { + json!({ + "action": if conclusion.is_some() { "completed" } else { "created" }, + "repository": {"full_name": "acme/web", "default_branch": "main"}, + "check_run": { + "name": name, "head_sha": sha, + "status": if conclusion.is_some() { "completed" } else { "in_progress" }, + "conclusion": conclusion, + "started_at": at, "completed_at": conclusion.map(|_| at), + "check_suite": {"head_branch": "main", "created_at": "2026-01-05T10:00:00Z"} + } + }) + } + + #[test] + fn a_red_head_opens_an_episode_and_a_green_head_closes_it() { + let mut m = MainCi::new("acme/web"); + assert!(m.apply_event( + "check_run", + &run("a1", "test", Some("success"), "2026-01-05T10:05:00Z"), + 0 + )); + assert!(m.red_now().is_none()); + m.apply_event( + "check_run", + &run("b2", "test", Some("failure"), "2026-01-05T11:00:00Z"), + 0, + ); + let open = m.red_now().expect("red"); + assert_eq!(open.checks, vec!["test".to_string()]); + assert_eq!(open.sha, "b2"); + // A later head goes green: the episode closes, with its fix. + m.apply_event( + "check_run", + &run("c3", "test", Some("success"), "2026-01-05T14:10:00Z"), + 0, + ); + assert!(m.red_now().is_none()); + let e = &m.episodes[0]; + assert_eq!(e.fixed_sha, "c3"); + assert_eq!(e.secs(0), 3 * 3600 + 600); + } + + #[test] + fn checks_on_other_branches_never_count_and_a_late_old_report_changes_nothing() { + let mut m = MainCi::new("acme/web"); + let mut feature = run("f1", "test", Some("failure"), "2026-01-05T11:00:00Z"); + feature["check_run"]["check_suite"]["head_branch"] = json!("feature/cart"); + m.apply_event("check_run", &feature, 0); + assert!(m.episodes.is_empty()); + m.apply_event( + "check_run", + &run("b2", "test", Some("success"), "2026-01-05T12:00:00Z"), + 0, + ); + m.apply_event( + "check_run", + &run("a1", "test", Some("failure"), "2026-01-05T09:00:00Z"), + 0, + ); + assert!( + m.red_now().is_none(), + "an older head's late failure doesn't turn main red" + ); + } + + #[test] + fn a_status_on_the_default_branch_counts_like_a_check() { + let mut m = MainCi::new("acme/web"); + let p = json!({"repository": {"default_branch": "main"}, "sha": "d4", "state": "error", "context": "ci/legacy", + "branches": [{"name": "main"}], "updated_at": "2026-01-05T12:00:00Z"}); + m.apply_event("status", &p, 0); + assert_eq!(m.failing_now(), vec!["ci/legacy".to_string()]); + } + + #[test] + fn a_job_wait_is_a_queue_sample_on_any_branch() { + let mut m = MainCi::new("acme/web"); + let p = json!({"action": "in_progress", "repository": {"default_branch": "main"}, + "workflow_job": {"created_at": "2026-01-05T10:00:00Z", "started_at": "2026-01-05T10:04:00Z", + "labels": ["ubuntu-latest"], "head_branch": "feature/cart"}}); + assert!(m.apply_event("workflow_job", &p, 0)); + assert_eq!(m.queue[0].secs, 240); + assert_eq!(m.queue[0].label, "ubuntu-latest"); + assert!( + !m.apply_event("workflow_job", &p, 0), + "a redelivery is the same sample" + ); + } + + #[test] + fn a_pull_request_failing_the_check_main_fails_is_blocked_by_main() { + let mut m = MainCi::new("acme/web"); + m.apply_event( + "check_run", + &run( + "b2", + "payments_test", + Some("failure"), + "2026-01-05T11:00:00Z", + ), + 0, + ); + let mut r = PrRecord::new("acme/web", 7); + r.base_ref = "main".into(); + r.checks.insert( + "payments_test".into(), + crate::pr_record::Check { + status: "completed".into(), + conclusion: "failure".into(), + at: 1, + }, + ); + assert!(blocked_by_main(&r, &m)); + r.checks.clear(); + r.checks.insert( + "lint".into(), + crate::pr_record::Check { + status: "completed".into(), + conclusion: "failure".into(), + at: 1, + }, + ); + assert!(!blocked_by_main(&r, &m), "its own failure, not main's"); + } +} diff --git a/services/common/src/pr_findings.rs b/services/common/src/pr_findings.rs new file mode 100644 index 00000000..16e06c19 --- /dev/null +++ b/services/common/src/pr_findings.rs @@ -0,0 +1,371 @@ +//! What became of each of CoderHelm's review findings on a pull request: +//! raised, acknowledged by a person, followed by a change to the flagged +//! lines, verified fixed on a later head, or dismissed. Resolving a thread +//! alone never counts as fixed: only the reviewer finding the concern gone +//! at a later head does. +//! +//! One settings-table item per pull request (`pk` = team id, `sk` = +//! [`findings_sk`]), written by the reviewer each time it stores a review, +//! kept [`KEEP_SECS`] like the pull request's history. + +use std::collections::BTreeMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde::{Deserialize, Serialize}; + +pub const PREFIX: &str = "PRFINDINGS#"; +pub const KEEP_SECS: i64 = 400 * 86_400; +/// Most findings kept per pull request. +pub const MAX_FINDINGS: usize = 300; + +pub fn findings_sk(repo: &str, number: u64) -> String { + format!("{PREFIX}{repo}#{number:06}") +} + +/// `p0` (blocking), `p1` (high) or `p2` (everything else). +pub fn tier(severity: &str) -> &'static str { + match severity.to_ascii_lowercase().as_str() { + "blocking" | "critical" => "p0", + "high" => "p1", + _ => "p2", + } +} + +/// Words of a title or a comment's first line, lower case, no punctuation. +pub fn words(text: &str) -> String { + let first = text + .lines() + .map(str::trim) + .find(|l| !l.is_empty() && !l.starts_with("