diff --git a/docs/incidents/ya_overview_signals_recorded.md b/docs/incidents/ya_overview_signals_recorded.md new file mode 100644 index 00000000..1ac86a8b --- /dev/null +++ b/docs/incidents/ya_overview_signals_recorded.md @@ -0,0 +1,7 @@ +# 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. + +Anything the backfilled history can answer is answered from it, with no nightly snapshots: the cycle time of every merged pull request over 90 days, the open pull requests per stage per day over 12 weeks (rebuilt from each one's opened and closed times and stage change log; days the change log doesn't reach count in the total only, and the answer says from which day the split is complete), the strip's week-over-week change and the review flow. "Not enough history yet" is kept for what CoderHelm records going forward; too few events to rate say "too few yet". 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..f4ea008c 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,23 +274,29 @@ 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; /// A repository's pull request template as the description's structure. pub mod pr_template; +pub mod pr_trends; pub mod pr_view; pub mod preview; pub mod preview_access; diff --git a/services/common/src/pr_ci.rs b/services/common/src/pr_ci.rs new file mode 100644 index 00000000..1a149763 --- /dev/null +++ b/services/common/src/pr_ci.rs @@ -0,0 +1,712 @@ +//! 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 only when a later head is green as a whole: every check +//! suite on it has completed and nothing failed ([`rollup`]). A fast check +//! passing while a slower one hasn't been created yet doesn't end it. +//! Episodes are kept [`EPISODE_KEEP_SECS`]. +//! - Queue samples are one per job, from `workflow_job`: the job's own +//! queued (`created_at`) to `started_at`, so a wait on `needs:` or an +//! approval isn't counted. 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 { + /// The job's id: one sample per job, however often it's delivered. + pub id: String, + 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, + /// The head's check suites, by id: true once the suite has completed. + /// A head is green only when every suite on it has completed. + pub suites: 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 head: red on any failing check; green +/// only when every check reported is done and every suite known on the head +/// has completed (so a check not created yet still holds it pending). +pub fn rollup( + checks: &BTreeMap, + suites: &BTreeMap, +) -> &'static str { + if checks.values().any(MainCheck::failing) { + "red" + } else if !checks.is_empty() + && checks.values().all(MainCheck::done) + && suites.values().all(|done| *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() + } + + /// Moves to `sha` when it's newer than the head held; false for an + /// older head's late report. + fn head(&mut self, sha: &str, at: i64) -> bool { + if sha == self.sha { + return true; + } + 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(); + self.suites.clear(); + true + } + + /// A suite seen on the head: pending until it completes. + fn note_suite(&mut self, id: &str, completed: bool) -> bool { + if id.is_empty() { + return false; + } + let was = self.suites.get(id).copied(); + let now = completed || was == Some(true); + self.suites.insert(id.to_string(), now); + was != Some(now) + } + + fn note_check( + &mut self, + sha: &str, + at: i64, + name: &str, + c: MainCheck, + suite: Option<(String, bool)>, + ) -> bool { + if sha.is_empty() || name.is_empty() || !self.head(sha, at) { + return false; + } + let mut changed = match suite { + Some((id, completed)) => self.note_suite(&id, completed), + None => false, + }; + if self.checks.get(name) != Some(&c) + && (self.checks.len() < MAX_CHECKS || self.checks.contains_key(name)) + { + self.checks.insert(name.to_string(), c); + changed = true; + } + if changed { + self.settle(at); + } + changed + } + + /// 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, &self.suites) { + "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 || s.id.is_empty() || self.queue.iter().any(|q| q.id == s.id) { + 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 suite = &run["check_suite"]; + if !on_default(suite["head_branch"].as_str().unwrap_or("")) { + return false; + } + let at = [ts(&run["completed_at"]), ts(&run["started_at"]), now] + .into_iter() + .find(|t| *t > 0) + .unwrap_or(now); + let suite_id = suite["id"] + .as_u64() + .map(|n| n.to_string()) + .unwrap_or_default(); + 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, + }, + (!suite_id.is_empty()).then(|| (suite_id, suite["status"] == "completed")), + ) + } + "check_suite" => { + let suite = &payload["check_suite"]; + if !on_default(suite["head_branch"].as_str().unwrap_or("")) { + return false; + } + let sha = suite["head_sha"].as_str().unwrap_or(""); + let id = suite["id"] + .as_u64() + .map(|n| n.to_string()) + .unwrap_or_default(); + let at = [ts(&suite["updated_at"]), ts(&suite["created_at"]), now] + .into_iter() + .find(|t| *t > 0) + .unwrap_or(now); + if sha.is_empty() || id.is_empty() || !self.head(sha, at) { + return false; + } + let changed = self.note_suite(&id, suite["status"] == "completed"); + if changed { + self.settle(at); + } + changed + } + "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, + }, + None, + ) + } + "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 { + id: job["id"] + .as_u64() + .map(|n| n.to_string()) + .unwrap_or_default(), + 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": {"id": 1, "head_branch": "main", "status": if conclusion.is_some() { "completed" } else { "in_progress" }, "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": {"id": 9001, "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 an_episode_stays_open_while_the_fixing_head_still_has_checks_to_come() { + let mut m = MainCi::new("acme/web"); + m.apply_event( + "check_run", + &run("b2", "test", Some("failure"), "2026-01-05T11:00:00Z"), + 0, + ); + // The next head: lint passes first while its suite is still running + // (test hasn't been created yet: it needs lint). + let mut lint = run("c3", "lint", Some("success"), "2026-01-05T12:00:00Z"); + lint["check_run"]["check_suite"] = + json!({"id": 7, "head_branch": "main", "status": "in_progress"}); + m.apply_event("check_run", &lint, 0); + assert!( + m.red_now().is_some(), + "a subset of the head's checks is not green" + ); + // Its test fails later: the same episode, not a second one. + let mut test = run("c3", "test", Some("failure"), "2026-01-05T12:20:00Z"); + test["check_run"]["check_suite"] = + json!({"id": 7, "head_branch": "main", "status": "in_progress"}); + m.apply_event("check_run", &test, 0); + assert_eq!(m.episodes.len(), 1); + // A later head: both pass, then its suite completes; only then it ends. + for (name, at) in [ + ("lint", "2026-01-05T13:00:00Z"), + ("test", "2026-01-05T13:30:00Z"), + ] { + let mut r = run("d4", name, Some("success"), at); + r["check_run"]["check_suite"] = + json!({"id": 8, "head_branch": "main", "status": "in_progress"}); + m.apply_event("check_run", &r, 0); + } + assert!(m.red_now().is_some(), "its suite hasn't completed"); + let done = json!({"action": "completed", "repository": {"default_branch": "main"}, + "check_suite": {"id": 8, "head_sha": "d4", "head_branch": "main", "status": "completed", + "conclusion": "success", "updated_at": "2026-01-05T13:31:00Z"}}); + assert!(m.apply_event("check_suite", &done, 0)); + assert!(m.red_now().is_none()); + assert_eq!(m.episodes.len(), 1); + assert_eq!(m.episodes[0].fixed_sha, "d4"); + assert_eq!(m.episodes[0].secs(0), 2 * 3600 + 31 * 60); + } + + #[test] + fn queue_samples_are_one_per_job_from_its_own_queued_time() { + let mut m = MainCi::new("acme/web"); + // A check run's suite was created long before: never a queue sample. + m.apply_event( + "check_run", + &run("a1", "test", None, "2026-01-05T10:30:00Z"), + 0, + ); + assert!(m.queue.is_empty()); + let job = |action: &str, started: &str| { + json!({"action": action, "repository": {"default_branch": "main"}, + "workflow_job": {"id": 42, "created_at": "2026-01-05T10:28:00Z", "started_at": started, + "labels": ["ubuntu-latest"]}}) + }; + assert!(m.apply_event( + "workflow_job", + &job("in_progress", "2026-01-05T10:30:00Z"), + 0 + )); + assert!( + !m.apply_event( + "workflow_job", + &job("in_progress", "2026-01-05T10:30:05Z"), + 0 + ), + "the same job counts once" + ); + assert_eq!(m.queue.len(), 1); + assert_eq!( + m.queue[0].secs, 120, + "from the job's queued time, not the suite's" + ); + } + + #[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..6e91d419 --- /dev/null +++ b/services/common/src/pr_findings.rs @@ -0,0 +1,433 @@ +//! 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; + +/// The sort key of a per-pull-request item: `owner/repo#000318`. +pub fn pr_sk(prefix: &str, repo: &str, number: u64) -> String { + format!("{prefix}{repo}#{number:06}") +} + +pub fn findings_sk(repo: &str, number: u64) -> String { + pr_sk(PREFIX, repo, number) +} + +/// `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("