diff --git a/docs/incidents/xx_waits_never_outlive_their_event.md b/docs/incidents/xx_waits_never_outlive_their_event.md new file mode 100644 index 00000000..c8bd4686 --- /dev/null +++ b/docs/incidents/xx_waits_never_outlive_their_event.md @@ -0,0 +1,5 @@ +# xx. `xx_waits_never_outlive_their_event` + +**What happened:** Two waits went on after what they waited for had happened. A run stopped because the change it built on closed without merging was told that reopening the change takes it back to waiting by itself. The change was reopened, and the run kept waiting on a person until the 15-minute sweep: the reopen webhook went on to the review triggers and returned, and the check a pull request event sent read only the runs still waiting for a merge, not the runs that change's close had stopped. On an alert route that waits out a quiet window before posting the recovery, the run waiting on a person for that alert stayed waiting after the recovery posted. Only a recovery posted at once closed it; the later post, made by the worker's episode check, never reached the run. + +**The guarantee:** A pull request closed or reopened sends the team's change check before any return a reopen reaches, and the check names that change. It reads the runs still waiting for a merge and the runs stopped by that change's close, so a reopen takes the stopped run back to waiting at once and a merge sends it on. The 15-minute sweep stays the backstop for every team. A recovery closes its waiting run through one path, `common::run_wake::alert_cleared`, whether it posts at once (the gateway's `alert_delivery`) or after the quiet window (the worker's episode check). diff --git a/docs/incidents/xz_org_overview_facts_only.md b/docs/incidents/xz_org_overview_facts_only.md new file mode 100644 index 00000000..5f925c56 --- /dev/null +++ b/docs/incidents/xz_org_overview_facts_only.md @@ -0,0 +1,5 @@ +# xz. `xz_org_overview_facts_only` + +**What happened:** A leader opened the pull requests page to understand the state of the org's pull requests and found only a list: nothing said what was stuck, on whom, or whether that was usual for the org. The overview above the list answers that, and it is the one place a page could rank people, print a number nothing computed, or mix two teams' pull requests. + +**The guarantee:** `GET /api/prs/overview` (`common::pr_overview::build`) covers every pull request in the team's repositories, people's, CoderHelm's and other bots', and returns computed facts only. No per-person ranking, count or duration is ever returned; a GitHub login appears only as the owner of one item under "Needs attention". Every number in the summary is the value of a fact in `facts`, and the words between them carry no numbers of their own. Thresholds are percentiles of the scope's own history (a repo's own from 30 merges in 90 days, else the org's), no rate is shown on fewer than 10 events, and what CoderHelm doesn't store yet is `null` and named in `missing`, never estimated. The Stale tile and the Stale panel's headline are one number. An org with no CoderHelm pull requests gets the whole overview. Every read is keyed by the session's team, and the short cache by the installation, the team and the scope, listed in `bm_teams_never_cross`. diff --git a/services/common/src/change_wait.rs b/services/common/src/change_wait.rs index 4b18ced3..c37e6888 100644 --- a/services/common/src/change_wait.rs +++ b/services/common/src/change_wait.rs @@ -294,6 +294,20 @@ pub fn waits_on_close(action: &str) -> bool { a.starts_with("Reopen ") && a.contains(CLOSED_ASK) } +/// Whether the pull request `pr` of `repo` that moved (a merge, a close, a +/// reopen as GitHub reports it) is the change `dep` waits on. An empty repo +/// or no number (the sweep) reads every dependency. +pub fn moved_is(dep: &Dependency, repo: &str, pr: u64) -> bool { + repo.is_empty() || pr == 0 || (dep.pr == pr && dep.repo.eq_ignore_ascii_case(repo)) +} + +/// Whether a pull request event `action` asks the team's waiting runs to +/// read their change again: a close (merged or not) settles a wait, and a +/// reopen takes a run stopped by that close back to waiting at once. +pub fn event_moves_change(action: &str) -> bool { + matches!(action, "closed" | "reopened") +} + /// The reason a run stops when its dependency closed without merging. pub fn closed_reason(dep: &Dependency) -> String { format!( @@ -328,6 +342,26 @@ mod after_close_tests { assert_eq!(crate::rendered::person_text(&a), None, "{a}"); } + #[test] + fn a_reopen_or_close_reaches_only_the_runs_of_that_change() { + assert!(event_moves_change("reopened")); + assert!(event_moves_change("closed")); + for other in ["opened", "synchronize", "edited", "labeled", ""] { + assert!(!event_moves_change(other), "{other}"); + } + let dep = Dependency { + ticket: "WEB-7".into(), + repo: "acme/bookstore-web".into(), + pr: 12, + ..Default::default() + }; + assert!(moved_is(&dep, "Acme/Bookstore-Web", 12)); + assert!(!moved_is(&dep, "acme/bookstore-web", 13)); + assert!(!moved_is(&dep, "acme/other", 12)); + // The sweep names no change: every dependency is read. + assert!(moved_is(&dep, "", 0)); + } + #[test] fn only_the_closed_change_stop_is_read_as_its_change_closing() { let dep = Dependency { diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 32f2da03..4566f790 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -279,6 +279,7 @@ pub mod pr_layout; pub mod pr_needs; /// What happened to a PR CoderHelm opened, read from GitHub. pub mod pr_outcome; +pub mod pr_overview; /// The last read of a description before it is saved, verified. pub mod pr_reader; pub mod pr_record; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index cc0cb05f..ad3d78a2 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -238,9 +238,11 @@ pub enum WorkerMessage { /// sends one too). #[serde(rename = "role_reads_wait")] RoleReadsWait(RoleReadsWaitMessage), - /// A pull request of the team merged or closed: its runs waiting for - /// another change (`awaiting_change`, `crate::change_wait`) read their - /// dependency again (the self-heal sweep checks every 15 minutes too). + /// A pull request of the team merged, closed or reopened: its runs + /// waiting for another change (`awaiting_change`, `crate::change_wait`) + /// read their dependency again, and a run stopped because that change + /// closed waits for it again (the self-heal sweep checks every 15 + /// minutes too). #[serde(rename = "change_wait_check")] ChangeWaitCheck(ChangeWaitCheckMessage), /// Read a team's open pull requests into their records @@ -965,6 +967,12 @@ pub struct PrRecordsSyncMessage { #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] pub struct ChangeWaitCheckMessage { pub team_id: String, + /// `owner/repo` of the pull request that moved (empty: any). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub repo: String, + /// The pull request that moved (0: any). + #[serde(default)] + pub pr: u64, } /// Re-check the role of a run waiting for the install's "AWS role reads" diff --git a/services/common/src/pr_overview.rs b/services/common/src/pr_overview.rs new file mode 100644 index 00000000..7cf3dd90 --- /dev/null +++ b/services/common/src/pr_overview.rs @@ -0,0 +1,2139 @@ +//! The org's pull requests in one answer: the overview page's summary, +//! stage strip, aging dots, repos, the stale, failure, review and security +//! panels, this week's events and CoderHelm's slice. +//! +//! Every number covers every pull request in the team's repositories: +//! people's, CoderHelm's and other bots'. CoderHelm's are one slice, in +//! `coderhelm` only. +//! +//! - Computed facts only. Thresholds are percentiles of the scope's own +//! history (`pr_history`): a repository uses its own once it has +//! [`pr_history::MIN_MERGED_FOR_OWN`] merges in 90 days, else the org's. +//! Before 8 weeks of history (or while the backfill runs) the external +//! bands stand beside them, labeled as external. +//! - No rate is shown on fewer than [`MIN_EVENTS`] events. +//! - What isn't stored yet is `null` and named in `missing`, with +//! `history` (the store is younger than the comparison) or +//! `not_recorded` (CoderHelm doesn't keep it yet). Nothing is estimated. +//! - No per-person count, ranking or duration is ever returned. A GitHub +//! login appears only as `summary.attention[].owner`, the owner of one +//! pull request's next move ([`owner_of`]). +//! - The summary's sentences are fixed templates over [`Fact`]s; every +//! number in them is a fact's value ([`Builder::num`]). +//! +//! Pure: the gateway reads the rows and calls [`build`]. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{json, Value}; + +use crate::pr_history::{self, Backfill, History, Snapshot, MIN_MERGED_FOR_OWN, MIN_WEEKS_OWN}; +use crate::pr_record::{is_bot, is_coderhelm, PrRecord}; +use crate::pr_view::{rfc3339, Row}; + +const HOUR: i64 = 3_600; +const DAY: i64 = 86_400; + +/// No rate on fewer events than this. +pub const MIN_EVENTS: usize = 10; +/// A stale clock never fires under one day, so tiny repos still signal. +pub const STALE_FLOOR_SECS: i64 = DAY; +/// Abandoned candidates: no author action for at least this long. +pub const ABANDONED_FLOOR_SECS: i64 = 14 * DAY; +/// Archive candidates: idle this long. +pub const ARCHIVE_SECS: i64 = 30 * DAY; +/// Most aging dots sent (the oldest). +pub const MAX_DOTS: usize = 400; +/// Most repositories in the table. +pub const MAX_REPOS: usize = 300; +/// Large PR: more changed lines than this. +pub const LARGE_LINES: u32 = 400; +/// A wait is mentioned only past this. +pub const WAIT_FLOOR_SECS: i64 = DAY; + +/// Security deadlines by severity (days). Known-exploited counts as critical. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Sla { + pub critical: i64, + pub high: i64, + pub medium: i64, + pub low: i64, +} + +impl Default for Sla { + fn default() -> Self { + Sla { + critical: 7, + high: 30, + medium: 90, + low: 180, + } + } +} + +impl Sla { + pub fn days(&self, severity: &str) -> i64 { + match severity { + "critical" | "kev" => self.critical, + "high" => self.high, + "medium" | "moderate" => self.medium, + _ => self.low, + } + } +} + +/// One open pull request: its record and its row (the same decision the +/// list shows). +pub struct Open { + pub rec: PrRecord, + pub row: Row, +} + +/// Everything the overview reads, already scoped to the team. +pub struct Input<'a> { + pub open: &'a [Open], + /// History rows closed in the last ~400 days. + pub hist: &'a [History], + /// The scope's daily snapshots, oldest first (org, or the repo). + pub snaps: &'a [Snapshot], + /// Each repository's snapshots, oldest first (those read). + pub repo_snaps: &'a BTreeMap>, + pub backfill: &'a [Backfill], + pub org: Option<&'a str>, + pub repo: Option<&'a str>, + pub window_days: i64, + pub sla: Sla, + pub now: i64, +} + +/// One computed fact the summary may be written from. +#[derive(Debug, Clone, PartialEq)] +pub struct Fact { + pub id: String, + pub scope: String, + pub value: f64, + pub prev: Option, + pub weight: f64, + pub link: Value, +} + +/// The windows' parsing: `7d`, `14d`, `28d`; anything else is 7. +pub fn window_days(w: Option<&str>) -> Option { + match w.unwrap_or("7d") { + "7d" => Some(7), + "14d" => Some(14), + "28d" => Some(28), + _ => None, + } +} + +fn in_scope(org: Option<&str>, repo: Option<&str>, name: &str) -> bool { + if let Some(r) = repo { + return name.eq_ignore_ascii_case(r); + } + match org { + Some(o) => name + .split('/') + .next() + .is_some_and(|x| x.eq_ignore_ascii_case(o)), + None => true, + } +} + +fn pct(v: &[i64], p: u32) -> Option { + pr_history::percentile(v, p) +} + +fn share(n: usize, d: usize) -> Option { + (d >= MIN_EVENTS).then(|| n as f64 / d as f64) +} + +fn round3(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 +} + +fn median(v: &[i64]) -> Option { + pct(v, 50) +} + +/// The scope's cycle-time percentiles and where they came from. +#[derive(Debug, Clone, Default)] +struct Lines { + cycle: Option<[i64; 3]>, + first_review: Option<[i64; 2]>, + stage_p85: BTreeMap, + merged: usize, + inherited: bool, +} + +fn lines_of(hist: &[&History], now: i64) -> Lines { + let cycles: Vec = hist + .iter() + .filter(|h| h.merged_at > now - 90 * DAY) + .filter_map(|h| h.cycle_secs()) + .collect(); + let first: Vec = hist + .iter() + .filter(|h| h.closed_at > now - 56 * DAY) + .filter_map(|h| h.first_review_secs()) + .collect(); + let mut stages: BTreeMap> = BTreeMap::new(); + for h in hist.iter().filter(|h| h.closed_at > now - 90 * DAY) { + for (i, s) in h.spans.iter().enumerate() { + if s.stage.is_empty() { + continue; + } + let to = h + .spans + .get(i + 1) + .map(|n| n.from) + .unwrap_or(h.closed_at.max(h.merged_at)); + stages + .entry(s.stage.clone()) + .or_default() + .push((to - s.from).max(0)); + } + } + Lines { + cycle: match (pct(&cycles, 50), pct(&cycles, 85), pct(&cycles, 95)) { + (Some(a), Some(b), Some(c)) => Some([a, b, c]), + _ => None, + }, + first_review: match (pct(&first, 50), pct(&first, 85)) { + (Some(a), Some(b)) => Some([a, b]), + _ => None, + }, + stage_p85: stages + .into_iter() + .filter_map(|(k, v)| pct(&v, 85).map(|p| (k, p))) + .collect(), + merged: cycles.len(), + inherited: false, + } +} + +/// The org's lines, or a repository's own once it has enough merges. +fn scope_lines(all: &[&History], org: Option<&str>, repo: Option<&str>, now: i64) -> Lines { + let org_name = repo + .and_then(|r| r.split('/').next()) + .or(org) + .map(str::to_string); + let org_hist: Vec<&History> = all + .iter() + .copied() + .filter(|h| in_scope(org_name.as_deref(), None, &h.repo)) + .collect(); + let org_lines = lines_of(&org_hist, now); + let Some(r) = repo else { return org_lines }; + let own_hist: Vec<&History> = org_hist + .iter() + .copied() + .filter(|h| h.repo.eq_ignore_ascii_case(r)) + .collect(); + let own = lines_of(&own_hist, now); + if own.merged >= MIN_MERGED_FOR_OWN { + own + } else { + Lines { + inherited: true, + ..org_lines + } + } +} + +/// Age since ready (drafts from creation). +fn age(o: &Open, now: i64) -> i64 { + let start = if o.rec.draft { + o.rec.created_at + } else { + o.rec.ready_or_created() + }; + (now - start).max(0) +} + +fn stage(o: &Open) -> &str { + o.row.stage.as_deref().unwrap_or("") +} + +/// The login or team whose move a pull request is, when one person or +/// team holds it: the only place a name appears. +pub fn owner_of(row: &Row) -> (Option, Option<&'static str>) { + for f in &row.next.from { + if let Some(p) = f.strip_prefix("person:") { + if !is_bot(p) { + return (Some(p.to_string()), Some("person")); + } + } + if let Some(t) = f.strip_prefix("team:") { + return (Some(t.to_string()), Some("team")); + } + if f == "author" && !is_bot(&row.author.login) { + return (Some(row.author.login.clone()), Some("person")); + } + } + (None, None) +} + +/// Who holds the turn and how long they have been idle: only people's +/// actions reset the clock, and the author's and reviewers' clocks are +/// kept apart. +fn idle_of(o: &Open, now: i64) -> Option<(&'static str, i64)> { + if o.row.turn != "person" && o.row.turn != "you" { + return None; + } + let on_author = o + .row + .next + .from + .iter() + .any(|f| f == "author" || f == &format!("person:{}", o.rec.author)); + let clock = if on_author { + o.rec.last_author_action_at + } else { + o.rec.last_reviewer_action_at + }; + let since = clock.max(o.rec.ready_or_created()); + Some(( + if on_author { "author" } else { "reviewer" }, + (now - since).max(0), + )) +} + +fn stale_threshold(lines: &Lines, stage: &str) -> i64 { + lines + .stage_p85 + .get(stage) + .copied() + .unwrap_or(STALE_FLOOR_SECS) + .max(STALE_FLOOR_SECS) +} + +fn is_stale(o: &Open, lines: &Lines, now: i64) -> Option<&'static str> { + let st = stage(o); + if st.is_empty() || st == "draft" || st == "blocked" { + return None; + } + let (who, idle) = idle_of(o, now)?; + (idle > stale_threshold(lines, st)).then_some(who) +} + +fn is_abandoned(o: &Open, lines: &Lines, now: i64) -> bool { + if o.rec.draft { + return false; + } + let floor = lines + .cycle + .map(|c| c[2]) + .unwrap_or(0) + .max(ABANDONED_FLOOR_SECS); + let last_author = o.rec.last_author_action_at.max(o.rec.ready_or_created()); + let unanswered = o + .rec + .review_log + .iter() + .any(|r| r.human && r.state == "CHANGES_REQUESTED" && r.at > last_author); + now - last_author > floor && unanswered +} + +fn is_zombie(o: &Open, lines: &Lines, now: i64) -> bool { + let Some(c) = lines.cycle else { return false }; + let last_human = o + .rec + .last_author_action_at + .max(o.rec.last_reviewer_action_at); + age(o, now) > c[2] && now - last_human > c[1] && o.rec.last_bot_event_at > now - c[1] +} + +fn band(age: i64, lines: &Lines) -> Value { + match lines.cycle { + Some([_, _, p95]) if age > p95 => json!("p95"), + Some([_, p85, _]) if age > p85 => json!("p85"), + Some([p50, _, _]) if age > p50 => json!("p50"), + _ => Value::Null, + } +} + +fn past_p85(o: &Open, lines: &Lines, now: i64) -> bool { + !o.rec.draft && lines.cycle.is_some_and(|c| age(o, now) > c[1]) +} + +/// The snapshot nearest to `days` ago, when one exists within two days. +fn snap_at(snaps: &[Snapshot], now: i64, days: i64) -> Option<&Snapshot> { + let want = now - days * DAY; + snaps + .iter() + .filter_map(|s| { + let t = chrono::NaiveDate::parse_from_str(&s.day, "%Y-%m-%d") + .ok()? + .and_hms_opt(12, 0, 0)? + .and_utc() + .timestamp(); + Some((s, (t - want).abs())) + }) + .filter(|(_, d)| *d <= 2 * DAY) + .min_by_key(|(_, d)| *d) + .map(|(s, _)| s) +} + +/// Eight weekly values of a snapshot field, oldest first, when at least two +/// weeks have one. +fn weekly(snaps: &[Snapshot], now: i64, f: impl Fn(&Snapshot) -> u32) -> Option> { + let v: Vec = (0..8) + .rev() + .filter_map(|w| snap_at(snaps, now, w * 7).map(&f)) + .collect(); + (v.len() >= 2).then_some(v) +} + +/// The previous 8 weekly values (not this week), min and max, when all 8 exist. +fn range8(snaps: &[Snapshot], now: i64, f: impl Fn(&Snapshot) -> u32) -> Option<(u32, u32)> { + let v: Vec = (1..=8) + .filter_map(|w| snap_at(snaps, now, w * 7).map(&f)) + .collect(); + (v.len() == 8).then(|| (*v.iter().min().unwrap(), *v.iter().max().unwrap())) +} + +fn author_kind(login: &str) -> &'static str { + pr_history::author_type(login) +} + +fn day_of(t: i64) -> String { + chrono::DateTime::from_timestamp(t, 0) + .map(|d| d.format("%Y-%m-%d").to_string()) + .unwrap_or_default() +} + +fn gh_search(org: &str, q: &str) -> Value { + let query = format!("is:pr org:{org} {q}"); + json!({"github": format!("https://github.com/pulls?q={}", urlencode(&query))}) +} + +fn urlencode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} + +fn list(q: &str) -> Value { + json!({"list": q}) +} + +/// Collects facts while the summary is written, so every number in a +/// sentence is a fact's value. +#[derive(Default)] +pub struct Builder { + pub facts: Vec, +} + +impl Builder { + /// A number in a sentence: records the fact and returns the part. + pub fn num(&mut self, id: &str, scope: &str, value: f64, unit: &str, link: Value) -> Value { + self.fact(id, scope, value, None, 0.0, link.clone()); + json!({"n": value, "unit": unit, "fact": id, "link": link}) + } + + pub fn fact( + &mut self, + id: &str, + scope: &str, + value: f64, + prev: Option, + weight: f64, + link: Value, + ) { + if let Some(f) = self + .facts + .iter_mut() + .find(|f| f.id == id && f.scope == scope) + { + f.weight = f.weight.max(weight); + if prev.is_some() { + f.prev = prev; + } + return; + } + self.facts.push(Fact { + id: id.into(), + scope: scope.into(), + value, + prev, + weight, + link, + }); + } +} + +fn t(s: impl Into) -> Value { + json!({"t": s.into()}) +} + +/// "11h", "3.1d": the words a sentence uses for a duration. +pub fn dur_words(secs: i64) -> String { + if secs < HOUR { + format!("{}m", (secs / 60).max(1)) + } else if secs < DAY { + format!("{}h", (secs + HOUR / 2) / HOUR) + } else { + let d = secs as f64 / DAY as f64; + if d < 10.0 { + format!("{:.1}d", d) + } else { + format!("{}d", d.round() as i64) + } + } +} + +/// The whole overview. +pub fn build(i: &Input) -> Value { + let now = i.now; + let w = i.window_days.max(1) * DAY; + let since = now - w; + let prev_since = now - 2 * w; + let scope_name = i + .repo + .map(str::to_string) + .or(i.org.map(str::to_string)) + .unwrap_or_else(|| "all".into()); + let org_name = i + .repo + .and_then(|r| r.split('/').next()) + .or(i.org) + .unwrap_or("") + .to_string(); + let mut missing: Vec = Vec::new(); + let mut miss = |path: &str, reason: &str, text: &str| { + missing.push(json!({"path": path, "reason": reason, "text": text})); + }; + + let all_hist: Vec<&History> = i.hist.iter().collect(); + let hist: Vec<&History> = i + .hist + .iter() + .filter(|h| in_scope(i.org, i.repo, &h.repo)) + .collect(); + let open: Vec<&Open> = i + .open + .iter() + .filter(|o| in_scope(i.org, i.repo, &o.rec.repo) && o.rec.is_open()) + .collect(); + let lines = scope_lines(&all_hist, i.org, i.repo, now); + + // ── History: how much there is, and whether the backfill is done ── + let first_seen = hist + .iter() + .map(|h| h.created_at) + .chain(open.iter().map(|o| o.rec.created_at)) + .filter(|t| *t > 0) + .min() + .unwrap_or(now); + let backfills: Vec<&Backfill> = i + .backfill + .iter() + .filter(|b| org_name.is_empty() || b.owner.eq_ignore_ascii_case(&org_name)) + .collect(); + let backfill_done = !backfills.is_empty() && backfills.iter().all(|b| b.done); + let history_secs = (now - first_seen).max(0); + let young = !backfill_done || history_secs < MIN_WEEKS_OWN * 7 * DAY; + let bf_repos: BTreeSet = backfills + .iter() + .flat_map(|b| b.repos.keys().cloned()) + .collect(); + let backfill = if backfills.is_empty() { + Value::Null + } else { + let months = pr_history::BACKFILL_MONTHS; + let read = backfills + .iter() + .map(|b| b.months_read.min(months)) + .min() + .unwrap_or(0); + json!({ + "repos": bf_repos.len().max(1), + "repos_read": if backfill_done { bf_repos.len().max(1) } else { bf_repos.len() }, + "months": months, + "months_read": read, + "done": backfill_done, + "days": (months as i64) * 30, + "held": backfills.iter().any(|b| b.paused_until > now), + }) + }; + if !backfill_done { + miss( + "history", + "history", + "Not enough history yet: CoderHelm is still reading merged and closed pull requests back from GitHub.", + ); + } + + // ── Thresholds ── + if lines.cycle.is_none() { + miss( + "thresholds.cycle", + "history", + "Not enough history yet: no merged pull requests in 90 days to take percentiles from.", + ); + } + let thresholds = json!({ + "scope": if i.repo.is_some() && !lines.inherited { "repo" } else { "org" }, + "inherited": lines.inherited, + "min_merged": MIN_MERGED_FOR_OWN, + "min_weeks": MIN_WEEKS_OWN, + "external": young, + "cycle": lines.cycle.map(|c| json!({"p50": c[0], "p85": c[1], "p95": c[2]})), + "first_review": lines.first_review.map(|c| json!({"p50": c[0], "p85": c[1]})), + "bands": [ + {"key": "linearb_elite_cycle", "label": "LinearB elite cycle time (p75)", "secs": 25 * HOUR, "source": "LinearB benchmarks"}, + {"key": "google_review", "label": "Google whole review (median)", "secs": 4 * HOUR, "source": "Sadowski et al."} + ], + "rule": format!("p85 of ready-to-merge over 90 days; a repo with fewer than {MIN_MERGED_FOR_OWN} merges uses the org's; before {MIN_WEEKS_OWN} weeks of history the external bands stand beside it, labeled as external."), + }); + + // ── Strip ── + const STAGES: [(&str, &str); 6] = [ + ("draft", "Draft"), + ("first_review", "Waiting for first review"), + ("in_review", "In review"), + ("blocked", "Blocked"), + ("coderhelm_working", "CoderHelm working"), + ("approved", "Approved, not merged"), + ]; + let week_ago = snap_at(i.snaps, now, 7); + let mut strip = Vec::new(); + for (code, label) in STAGES { + let n = open.iter().filter(|o| stage(o) == code).count() as u32; + let delta = week_ago.map(|s| n as i64 - *s.stages.get(code).unwrap_or(&0) as i64); + if delta.is_none() { + miss(&format!("strip.{code}.delta"), "history", "Not enough history yet: the week-over-week change needs a snapshot from 7 days ago."); + } + strip.push(json!({ + "stage": code, + "label": label, + "count": n, + "delta": delta, + "spark": weekly(i.snaps, now, |s| *s.stages.get(code).unwrap_or(&0)), + "past_p85": open.iter().filter(|o| stage(o) == code && past_p85(o, &lines, now)).count(), + "link": list(&format!("stage={code}")), + })); + } + let open_n = open.iter().filter(|o| !o.rec.draft).count(); + let drafts = open.len() - open_n; + let nobody = open + .iter() + .filter(|o| o.row.next.from.is_empty() || o.row.next.from.iter().all(|f| f == "nobody")) + .count(); + let turns = json!({ + "person": open.iter().filter(|o| o.row.turn == "person" || o.row.turn == "you").count(), + "coderhelm": open.iter().filter(|o| o.row.turn == "coderhelm").count(), + "machines": open.iter().filter(|o| o.row.turn == "machines").count(), + "nobody": nobody, + }); + let decisions: Vec<&&Open> = open + .iter() + .filter(|o| o.row.state == "needs_decision") + .collect(); + let needs_decision = json!({ + "count": decisions.len(), + "oldest_secs": decisions.iter().map(|o| age(o, now)).max(), + "link": list("view=needs_decision"), + }); + + // ── Conditions and the Stale panel ── + let stale: Vec<(&&Open, &str)> = open + .iter() + .filter_map(|o| is_stale(o, &lines, now).map(|w| (o, w))) + .collect(); + let abandoned: Vec<&&Open> = open + .iter() + .filter(|o| is_abandoned(o, &lines, now)) + .collect(); + let zombie = lines + .cycle + .map(|_| open.iter().filter(|o| is_zombie(o, &lines, now)).count()); + if zombie.is_none() { + miss( + "conditions.zombie", + "history", + "Not enough history yet: a zombie is open past the p95 cycle time.", + ); + miss( + "stale.zombie", + "history", + "Not enough history yet: a zombie is open past the p95 cycle time.", + ); + } + let overlaps: Vec = hist + .iter() + .filter(|h| h.merged && h.drift_overlap > 0) + .map(|h| h.drift_overlap as i64) + .collect(); + let drift_p85 = (overlaps.len() >= MIN_EVENTS) + .then(|| pct(&overlaps, 85)) + .flatten(); + let mut drifting: Vec<&&Open> = match drift_p85 { + Some(p) => open + .iter() + .filter(|o| (o.rec.drift_overlap as i64) >= p && o.rec.drift_overlap > 0) + .collect(), + None => Vec::new(), + }; + drifting.sort_by_key(|o| std::cmp::Reverse(o.rec.drift_overlap)); + if drift_p85.is_none() { + miss("conditions.high_drift", "history", "Not enough history yet: drift is judged against the p85 at merge, over 10 or more merges."); + miss("stale.drift", "history", "Not enough history yet: drift is judged against the p85 at merge, over 10 or more merges."); + } + miss( + "conditions.blocked_by_main", + "not_recorded", + "Not recorded yet: CoderHelm doesn't keep the default branch's check history yet.", + ); + let stale_prev = week_ago.map(|_| Value::Null); + let _ = stale_prev; + let on_author = stale.iter().filter(|(_, w)| *w == "author").count(); + let conditions = json!({ + "stale": {"count": stale.len(), "delta": Value::Null, "author": on_author, "reviewer": stale.len() - on_author}, + "abandoned": abandoned.len(), + "zombie": zombie, + "high_drift": drift_p85.map(|_| drifting.len()), + "blocked_by_main": Value::Null, + }); + let drafts_ages: Vec = open + .iter() + .filter(|o| o.rec.draft) + .map(|o| age(o, now)) + .collect(); + let past_usual = open.iter().filter(|o| past_p85(o, &lines, now)).count(); + let stale_panel = json!({ + "stale": stale.len(), + "past_usual": lines.cycle.map(|_| past_usual), + "on_author": on_author, + "on_reviewer": stale.len() - on_author, + "abandoned": {"count": abandoned.len(), "oldest_secs": abandoned.iter().map(|o| age(o, now)).max()}, + "zombie": zombie, + "drift": drift_p85.map(|_| drifting.iter().take(3).map(|o| json!({"key": o.row.key, "overlapping": o.rec.drift_overlap})).collect::>()), + "draft_p85_secs": pct(&drafts_ages, 85), + "archive_candidates": open.iter().filter(|o| !o.rec.draft && idle_of(o, now).is_some_and(|(_, s)| s >= ARCHIVE_SECS)).count(), + }); + + // ── Aging dots ── + let mut by_age: Vec<&&Open> = open.iter().collect(); + by_age.sort_by_key(|o| std::cmp::Reverse(age(o, now))); + let dots: Vec = by_age + .iter() + .take(MAX_DOTS) + .map(|o| { + let a = age(o, now); + json!({ + "key": o.row.key, + "repo": o.rec.repo, + "number": o.rec.number, + "title": o.rec.title, + "stage": stage(o), + "state": o.row.state, + "state_label": o.row.state_label, + "age_secs": a, + "coderhelm": o.rec.author_is_coderhelm(), + "author_type": author_kind(&o.rec.author), + "band": band(a, &lines), + "idle": is_stale(o, &lines, now).is_some(), + "main_blocked": false, + }) + }) + .collect(); + + // ── Windows over history ── + let merged_in = |h: &&History, a: i64, b: i64| h.merged && h.merged_at > a && h.merged_at <= b; + let merged_w: Vec<&History> = hist + .iter() + .copied() + .filter(|h| merged_in(h, since, now)) + .collect(); + let merged_prev: Vec<&History> = hist + .iter() + .copied() + .filter(|h| merged_in(h, prev_since, since)) + .collect(); + let human_share = |v: &[&History]| { + share( + v.iter().filter(|h| h.coverage == "human_approved").count(), + v.len(), + ) + }; + + // ── Repos ── + let mut repo_names: BTreeSet = BTreeSet::new(); + for o in &open { + repo_names.insert(o.rec.repo.clone()); + } + for h in &hist { + if h.closed_at > now - 56 * DAY { + repo_names.insert(h.repo.clone()); + } + } + for r in &bf_repos { + if in_scope(i.org, i.repo, r) { + repo_names.insert(r.clone()); + } + } + let total_open = open.len().max(1); + let mut repos: Vec = Vec::new(); + let mut org_health = ("quiet", 0u8); + let mut obligation_anywhere = false; + let rank = |h: &str| match h { + "slipping" => 3u8, + "at_risk" => 2, + "healthy" => 1, + _ => 0, + }; + for name in repo_names.iter().take(MAX_REPOS) { + let ro: Vec<&&Open> = open + .iter() + .filter(|o| o.rec.repo.eq_ignore_ascii_case(name)) + .collect(); + let rh: Vec<&History> = all_hist + .iter() + .copied() + .filter(|h| h.repo.eq_ignore_ascii_case(name)) + .collect(); + let rl = scope_lines(&all_hist, None, Some(name), now); + let mut stages = BTreeMap::new(); + for o in &ro { + *stages.entry(stage(o).to_string()).or_insert(0u32) += 1; + } + let past = ro.iter().filter(|o| past_p85(o, &rl, now)).count() as u32; + let snaps = i.repo_snaps.get(name).map(Vec::as_slice).unwrap_or(&[]); + let past_delta = snap_at(snaps, now, 7).map(|s| past as i64 - s.past_p85 as i64); + let first: Vec = rh + .iter() + .filter(|h| h.closed_at > now - 56 * DAY) + .filter_map(|h| h.first_review_secs()) + .collect(); + let arrivals = ro + .iter() + .filter(|o| o.rec.ready_or_created() > since) + .count() + + rh.iter().filter(|h| h.ready_at > since).count(); + let rm: Vec<&History> = rh + .iter() + .copied() + .filter(|h| merged_in(h, since, now)) + .collect(); + let rm_prev: Vec<&History> = rh + .iter() + .copied() + .filter(|h| merged_in(h, prev_since, since)) + .collect(); + let reverts = rh + .iter() + .filter(|h| { + h.reverted_by + .as_ref() + .is_some_and(|(_, _, t)| *t > now - 14 * DAY) + }) + .count(); + let reworked = rm.iter().filter(|h| h.reworked()).count(); + let ci_n: Vec<&History> = rh + .iter() + .copied() + .filter(|h| h.closed_at > since && !h.check_log.is_empty()) + .collect(); + let ci_first = share( + ci_n.iter().filter(|h| first_try_green(h)).count(), + ci_n.len(), + ); + let large = share( + rm.iter() + .filter(|h| h.additions + h.deletions > LARGE_LINES) + .count(), + rm.len(), + ); + let sec: Vec<(&str, i64)> = ro + .iter() + .filter(|o| o.rec.category == "security") + .filter(|o| age(o, now) > i.sla.days(&o.rec.severity) * DAY) + .map(|o| (o.rec.severity.as_str(), age(o, now))) + .collect(); + let worst = ["critical", "high", "medium", "low"].into_iter().find(|s| { + sec.iter().any(|(x, _)| { + x == s || (*s == "low" && !["critical", "high", "medium"].contains(x)) + }) + }); + let bypass_unreviewed = rm + .iter() + .filter(|h| h.bypass.is_some() && !reviewed_after(h)) + .count(); + let quiet = ro.is_empty() && arrivals == 0 && rm.is_empty(); + let past_range = range8(snaps, now, |s| s.past_p85); + let merges_range = range8(snaps, now, |s| s.merges); + let obligation = sec.iter().any(|(s, _)| *s == "critical") || bypass_unreviewed > 0; + let out_of_range = past_range.is_some_and(|(_, hi)| past > hi) + || merges_range.is_some_and(|(lo, _)| (rm.len() as u32) < lo); + let health = if quiet { + "quiet" + } else if obligation { + "slipping" + } else if out_of_range { + "at_risk" + } else { + "healthy" + }; + let mut flags: Vec = Vec::new(); + if let Some(wst) = worst { + flags.push(format!("{} {wst} past SLA", sec.len())); + } + if bypass_unreviewed > 0 { + flags.push(format!("{bypass_unreviewed} bypass, no review after")); + } + if reverts > 0 { + flags.push(format!( + "{reverts} revert{}", + if reverts == 1 { "" } else { "s" } + )); + } + if let Some(p) = past_range.filter(|(_, hi)| past > *hi) { + flags.push(format!("{past} past usual (8 wk {} to {})", p.0, p.1)); + } + let short = name.split('/').nth(1).unwrap_or(name); + let why = if quiet { + format!("No pull request activity in {short} in the window.") + } else if flags.is_empty() { + if past_range.is_none() { + format!("Nothing breached; {short} has no 8-week range yet to judge against.") + } else { + format!("Nothing breached, and every number is inside {short}'s 8-week range.") + } + } else { + flags.join("; ") + }; + if obligation { + obligation_anywhere = true; + } + if ro.len() * 10 >= total_open && rank(health) > org_health.1 { + org_health = (health, rank(health)); + } + repos.push(json!({ + "repo": name, + "open": ro.len(), + "stages": stages, + "past_p85": past, + "past_p85_delta": past_delta, + "first_review": match (pct(&first, 50), pct(&first, 85)) { (Some(a), Some(b)) => json!({"p50": a, "p85": b}), _ => Value::Null }, + "arrivals": arrivals, + "merges": rm.len(), + "spark": weekly(snaps, now, |s| s.open), + "oldest_secs": ro.iter().map(|o| age(o, now)).max(), + "reworked": reworked, + "stale": ro.iter().filter(|o| is_stale(o, &rl, now).is_some()).count(), + "abandoned": ro.iter().filter(|o| is_abandoned(o, &rl, now)).count(), + "human_reviewed": human_share(&rm).map(round3), + "human_reviewed_delta": match (human_share(&rm), human_share(&rm_prev)) { (Some(a), Some(b)) => json!(round3(a - b)), _ => Value::Null }, + "ci_first_try": ci_first.map(round3), + "main_red_secs": Value::Null, + "reverts": reverts, + "large_share": large.map(round3), + "security_past_sla": worst.map(|w| json!({"count": sec.len(), "worst": w})), + "bypasses_unreviewed": bypass_unreviewed, + "flags": flags, + "health": health, + "why": why, + "inherited": rl.inherited, + "link": {"overview": format!("repo={name}")}, + })); + } + let hrank = |v: &Value| rank(v["health"].as_str().unwrap_or("")); + repos.sort_by(|a, b| { + hrank(b) + .cmp(&hrank(a)) + .then(b["past_p85"].as_u64().cmp(&a["past_p85"].as_u64())) + .then(b["oldest_secs"].as_i64().cmp(&a["oldest_secs"].as_i64())) + }); + if obligation_anywhere { + org_health = ("slipping", 3); + } + miss( + "repos.main_red_secs", + "not_recorded", + "Not recorded yet: CoderHelm doesn't keep the default branch's check history yet.", + ); + + // ── Review health ── + let human_reviews_in = |a: i64, b: i64| -> Vec<(String, i64)> { + let mut v = Vec::new(); + for (log, _repo) in open + .iter() + .map(|o| (&o.rec.review_log, &o.rec.repo)) + .chain(hist.iter().map(|h| (&h.review_log, &h.repo))) + { + for r in log.iter().filter(|r| r.human && r.at > a && r.at <= b) { + v.push((r.who.to_ascii_lowercase(), r.at)); + } + } + v + }; + let top20 = |rev: &[(String, i64)]| -> Option<(f64, usize)> { + let mut per: BTreeMap<&str, usize> = BTreeMap::new(); + for (who, _) in rev { + *per.entry(who.as_str()).or_default() += 1; + } + if rev.len() < MIN_EVENTS || per.len() < 5 { + return None; + } + let mut counts: Vec = per.values().copied().collect(); + counts.sort_unstable_by(|a, b| b.cmp(a)); + let k = (counts.len() as f64 * 0.2).ceil() as usize; + Some(( + counts.iter().take(k).sum::() as f64 / rev.len() as f64, + per.len(), + )) + }; + let rev30 = human_reviews_in(now - 30 * DAY, now); + let rev30_prev = human_reviews_in(now - 60 * DAY, now - 30 * DAY); + let conc = top20(&rev30); + let conc_prev = top20(&rev30_prev); + if conc.is_none() { + miss("review.concentration", "history", "Not enough history yet: concentration needs 10 or more reviews by people, from 5 or more reviewers, in 30 days."); + } + miss("review.concentration.where", "not_recorded", "Not recorded yet: CoderHelm doesn't keep which paths or CODEOWNERS entries a review covered."); + let requests_w = open + .iter() + .flat_map(|o| o.rec.request_log.iter()) + .chain(hist.iter().flat_map(|h| h.request_log.iter())) + .filter(|r| r.at > since) + .count() as i64; + let done_w = human_reviews_in(since, now).len() as i64; + let flow = weekly(i.snaps, now, |s| s.review_requests).zip(weekly(i.snaps, now, |s| s.reviews_done)).map(|(a, b)| { + a.iter() + .zip(b.iter()) + .enumerate() + .map(|(k, (r, d))| json!({"week": day_of(now - (a.len() as i64 - 1 - k as i64) * 7 * DAY), "requests": r, "done": d})) + .collect::>() + }); + if flow.is_none() { + miss( + "review.flow", + "history", + "Not enough history yet: the weekly flow needs 2 weeks of nightly snapshots.", + ); + } + let mut cov = BTreeMap::from([ + ("human_approved", 0usize), + ("ai_only", 0), + ("non_owner_on_owned", 0), + ("bypass_or_exempt", 0), + ("no_review", 0), + ]); + for h in &merged_w { + *cov.entry(match h.coverage.as_str() { + "human_approved" => "human_approved", + "ai_only" => "ai_only", + "non_owner_on_owned" => "non_owner_on_owned", + "bypass_or_exempt" => "bypass_or_exempt", + _ => "no_review", + }) + .or_default() += 1; + } + let any_first: Vec = hist + .iter() + .filter(|h| h.closed_at > now - 56 * DAY && h.ready_at > 0) + .filter_map(|h| { + h.review_log + .iter() + .filter(|r| r.who != h.author) + .map(|r| r.at) + .min() + .map(|t| (t - h.ready_at).max(0)) + }) + .collect(); + let size_bucket = |n: u32| { + if n < 50 { + "small" + } else if n <= LARGE_LINES { + "medium" + } else { + "large" + } + }; + let mut stamp: BTreeMap<&str, (usize, usize)> = BTreeMap::new(); + let mut waits: BTreeMap<&str, Vec> = BTreeMap::new(); + for h in hist.iter().filter(|h| h.closed_at > now - 90 * DAY) { + for r in h + .review_log + .iter() + .filter(|r| r.human && r.state == "APPROVED") + { + if let Some(req) = h + .request_log + .iter() + .filter(|q| q.at <= r.at) + .map(|q| q.at) + .max() + { + waits + .entry(size_bucket(h.additions + h.deletions)) + .or_default() + .push(r.at - req); + } + } + } + for h in &merged_w { + let b = size_bucket(h.additions + h.deletions); + let p10 = waits + .get(b) + .and_then(|v| (v.len() >= MIN_EVENTS).then(|| pct(v, 10)).flatten()); + for r in h + .review_log + .iter() + .filter(|r| r.human && r.state == "APPROVED") + { + let e = stamp.entry(b).or_default(); + e.1 += 1; + let req = h + .request_log + .iter() + .filter(|q| q.at <= r.at) + .map(|q| q.at) + .max(); + if let (Some(p), Some(q)) = (p10, req) { + if !r.has_body && r.at - q < p { + e.0 += 1; + } + } + } + } + let stamp_of = |b: &str| stamp.get(b).and_then(|(n, d)| share(*n, *d)).map(round3); + let queue_open: Vec = open + .iter() + .filter(|o| stage(o) == "first_review") + .map(|o| age(o, now)) + .collect(); + let sizes = |v: &[&History]| -> Vec { + v.iter() + .map(|h| (h.additions + h.deletions) as i64) + .collect() + }; + let review = json!({ + "flow": flow, + "gap": requests_w - done_w, + "concentration": { + "top_share": conc.map(|c| round3(c.0)), + "reviewers": conc.map(|c| c.1).unwrap_or(0), + "delta": conc.zip(conc_prev).map(|(a, b)| round3(a.0 - b.0)), + "where": Value::Null, + }, + "depth": { + "merged_without_review": share(cov["no_review"], merged_w.len()).map(round3), + "rubber_stamp": Value::Null, + "median_size": median(&sizes(&merged_w)), + "median_size_delta": median(&sizes(&merged_w)).zip(median(&sizes(&merged_prev))).map(|(a, b)| a - b), + }, + "coverage": (!merged_w.is_empty()).then(|| json!({ + "merged": merged_w.len(), + "human": cov["human_approved"], + "ai_only": cov["ai_only"], + "non_owner": cov["non_owner_on_owned"], + "bypass": cov["bypass_or_exempt"], + "none": cov["no_review"], + })), + "first_review_human": lines.first_review.map(|c| json!({"p50": c[0], "p85": c[1]})), + "first_review_any": pct(&any_first, 50).zip(pct(&any_first, 85)).map(|(a, b)| json!({"p50": a, "p85": b})), + "rubber_stamp_by_size": if stamp.is_empty() { Value::Null } else { json!({"small": stamp_of("small"), "medium": stamp_of("medium"), "large": stamp_of("large")}) }, + "queue": { + "under_4h": queue_open.iter().filter(|a| **a < 4 * HOUR).count(), + "h4_24": queue_open.iter().filter(|a| **a >= 4 * HOUR && **a < DAY).count(), + "d1_3": queue_open.iter().filter(|a| **a >= DAY && **a < 3 * DAY).count(), + "over_3d": queue_open.iter().filter(|a| **a >= 3 * DAY).count(), + }, + "single_reviewer_paths": Value::Null, + "funnel": Value::Null, + }); + if merged_w.is_empty() { + miss( + "review.coverage", + "history", + "Not enough history yet: no merges in the window.", + ); + } + if stamp.is_empty() { + miss( + "review.rubber_stamp_by_size", + "history", + "Not enough history yet: fewer than 10 qualifying approvals.", + ); + } + miss( + "review.funnel", + "not_recorded", + "Not recorded yet: CoderHelm's findings aren't joined to pull requests yet.", + ); + + // ── Failures ── + let ci_hist: Vec<&History> = hist + .iter() + .copied() + .filter(|h| h.closed_at > now - 56 * DAY && !h.check_log.is_empty()) + .collect(); + let (red, green) = hist + .iter() + .filter(|h| h.closed_at > now - 56 * DAY) + .flat_map(|h| h.check_log.iter()) + .chain( + open.iter() + .flat_map(|o| o.rec.check_log.iter()) + .filter(|c| c.at > now - 56 * DAY), + ) + .fold((0usize, 0usize), |(r, g), c| match c.rollup.as_str() { + "red" => (r + 1, g), + "green" => (r, g + 1), + _ => (r, g), + }); + let mut flaky: BTreeMap<(String, String), (usize, i64)> = BTreeMap::new(); + for h in hist.iter().filter(|h| h.closed_at > now - 30 * DAY) { + for c in &h.flaky_checks { + let e = flaky + .entry((c.clone(), h.repo.clone())) + .or_insert((0, h.closed_at)); + e.0 += 1; + e.1 = e.1.min(h.closed_at); + } + } + for o in &open { + for c in crate::pr_record::flaky_checks(&o.rec.check_attempts) { + let e = flaky.entry((c, o.rec.repo.clone())).or_insert((0, now)); + e.0 += 1; + } + } + let flaky_runs = ci_hist.len() + open.len(); + let flaky_value = (flaky_runs >= MIN_EVENTS).then(|| { + let mut top: Vec<_> = flaky.iter().filter(|(_, (n, _))| *n >= 2).collect(); + top.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n)); + json!({ + "count": top.len(), + "new": top.iter().filter(|(_, (_, first))| *first > since).count(), + "top": top.iter().take(3).map(|((c, r), (n, _))| json!({"check": c, "repo": r, "retries": n})).collect::>(), + }) + }); + if flaky_value.is_none() { + miss( + "failures.flaky", + "history", + "Not enough history yet: a flaky check needs 10 or more runs.", + ); + } + let reverted_14: Vec<&History> = hist + .iter() + .copied() + .filter(|h| { + h.reverted_by + .as_ref() + .is_some_and(|(_, _, t)| *t > now - 14 * DAY) + }) + .collect(); + let merged_30: Vec<&History> = hist + .iter() + .copied() + .filter(|h| merged_in(h, now - 30 * DAY, now)) + .collect(); + let ch_merged = merged_w + .iter() + .filter(|h| h.author_type == "coderhelm") + .count(); + let failures = json!({ + "ci_first_try": share(ci_hist.iter().filter(|h| first_try_green(h)).count(), ci_hist.len()).map(|s| json!({"share": round3(s), "lo": Value::Null, "hi": Value::Null, "n": ci_hist.len()})), + "ci_fail_rate": share(red, red + green).map(|s| json!({"share": round3(s), "n": red + green})), + "flaky": flaky_value, + "main_red": Value::Null, + "reverts": { + "count": reverted_14.len(), + "coderhelm": reverted_14.iter().filter(|h| h.author_type == "coderhelm").count(), + "coderhelm_merged": ch_merged, + "people": reverted_14.iter().filter(|h| h.author_type != "coderhelm").count(), + "people_merged": merged_w.len() - ch_merged, + }, + "proxy": share(merged_30.iter().filter(|h| h.reworked()).count(), merged_30.len()).map(round3), + "suspects": hist.iter().filter(|h| h.merged_at > now - 30 * DAY).flat_map(|h| h.follow_ups.iter().map(move |f| json!({"kind": "hotfix", "target": format!("{}#{}", h.repo, h.number), "by": format!("{}#{}", f.repo, f.number), "reason": f.reason}))).take(3).collect::>(), + "queue_p95_secs": Value::Null, + }); + miss( + "failures.main_red", + "not_recorded", + "Not recorded yet: CoderHelm doesn't keep the default branch's check history yet.", + ); + miss( + "failures.queue_p95_secs", + "not_recorded", + "Not recorded yet: runner queue times aren't kept.", + ); + if ci_hist.len() < MIN_EVENTS { + miss( + "failures.ci_first_try", + "history", + "Not enough history yet: fewer than 10 closed PRs with checks in 8 weeks.", + ); + } + + // ── Security and policy ── + let sec_open: Vec<&&Open> = open + .iter() + .filter(|o| o.rec.category == "security") + .collect(); + let mut sev = BTreeMap::from([("critical", 0usize), ("high", 0), ("medium", 0), ("low", 0)]); + for o in &sec_open { + let k = match o.rec.severity.as_str() { + "critical" | "kev" => "critical", + "high" => "high", + "medium" | "moderate" => "medium", + _ => "low", + }; + *sev.entry(k).or_default() += 1; + } + let mut past_sla: Vec<(&&Open, i64)> = sec_open + .iter() + .map(|o| (*o, age(o, now))) + .filter(|(o, a)| *a > i.sla.days(&o.rec.severity) * DAY) + .collect(); + past_sla.sort_by_key(|(o, a)| (sev_rank(&o.rec.severity), std::cmp::Reverse(*a))); + let bypass_w: Vec<&History> = merged_w + .iter() + .copied() + .filter(|h| h.bypass.is_some()) + .collect(); + let no_human: Vec<&History> = merged_w + .iter() + .copied() + .filter(|h| { + !h.review_log + .iter() + .any(|r| r.human && r.state == "APPROVED") + }) + .collect(); + let dep_group = |g: &str| -> Value { + let resolved: Vec<&History> = hist + .iter() + .copied() + .filter(|h| { + h.closed_at > now - 30 * DAY + && (h.category == "dependency" || h.category == "security") + }) + .filter(|h| match g { + "Dependabot" => h.author.to_ascii_lowercase().starts_with("dependabot"), + "Renovate" => h.author.to_ascii_lowercase().starts_with("renovate"), + _ => is_coderhelm(&h.author), + }) + .collect(); + let merged = resolved.iter().filter(|h| h.merged).count(); + let superseded = resolved + .iter() + .filter(|h| !h.merged && is_bot(&h.merged_by.clone())) + .count(); + json!({"group": g, "merge_rate": share(merged, resolved.len()).map(round3), "superseded": share(superseded, resolved.len()).map(round3)}) + }; + let security = json!({ + "sla_days": {"critical": i.sla.critical, "high": i.sla.high, "medium": i.sla.medium, "low": i.sla.low}, + "open": sev, + "past_sla": past_sla.iter().take(10).map(|(o, a)| json!({"key": o.row.key, "severity": o.rec.severity, "age_secs": a})).collect::>(), + "bypasses": {"count": bypass_w.len(), "reviewed_after": bypass_w.iter().filter(|h| reviewed_after(h)).count()}, + "exempt_by_coderhelm": merged_w.iter().filter(|h| h.merged_by_type == "coderhelm" && h.bypass.is_some()).count(), + "no_human_approval": { + "total": no_human.len(), + "person": no_human.iter().filter(|h| h.author_type == "person").count(), + "coderhelm": no_human.iter().filter(|h| h.author_type == "coderhelm").count(), + "bot": no_human.iter().filter(|h| h.author_type == "bot").count(), + }, + "sensitive_without_owner": Value::Null, + "dependency": [dep_group("Dependabot"), dep_group("Renovate"), dep_group("CoderHelm")], + }); + miss( + "security.sensitive_without_owner", + "not_recorded", + "Not recorded yet: the org's sensitive-path list isn't set.", + ); + miss("security.alerts", "not_recorded", "Not recorded yet: open security alerts with no pull request aren't read; the counts are security-fix pull requests."); + + // ── Events ── + let mut events: Vec<(u8, i64, Value)> = Vec::new(); + for h in &reverted_14 { + if let Some((by_repo, by_n, at)) = &h.reverted_by { + if *at > since { + events.push((2, *at, json!({"at": rfc3339(*at), "repo": h.repo, "kind": "revert", "text": format!("Revert merged: {by_repo}#{by_n} reverted #{} ({}'s PR), {} after it merged", h.number, match h.author_type.as_str() { "coderhelm" => "CoderHelm", "bot" => "a bot", _ => "a person" }, dur_words((at - h.merged_at).max(0))), "link": list(&format!("pr={}#{}", h.repo, h.number)), "severity": 2}))); + } + } + } + for h in &bypass_w { + events.push((3, h.merged_at, json!({"at": rfc3339(h.merged_at), "repo": h.repo, "kind": "bypass", "text": format!("Bypass merge #{} ({}){}", h.number, h.bypass.clone().unwrap_or_default(), if reviewed_after(h) { ", reviewed after" } else { ", no review after" }), "link": list(&format!("pr={}#{}", h.repo, h.number)), "severity": 3}))); + } + for (o, a) in &past_sla { + let crossed = now - a + i.sla.days(&o.rec.severity) * DAY; + if crossed > since { + events.push((3, crossed, json!({"at": rfc3339(crossed), "repo": o.rec.repo, "kind": "sla", "text": format!("{} security fix #{} passed its {}-day SLA", o.rec.severity, o.rec.number, i.sla.days(&o.rec.severity)), "link": list(&format!("pr={}", o.row.key)), "severity": 3}))); + } + } + for ((c, r), (n, first)) in &flaky { + if *first > since && *n >= 2 { + events.push((1, *first, json!({"at": rfc3339(*first), "repo": r, "kind": "flaky", "text": format!("New flaky check {c}: failed then passed on the same commit {n} times"), "link": list(&format!("repo={r}&state=checks_failing")), "severity": 1}))); + } + } + for h in hist + .iter() + .filter(|h| h.closed_at > since && matches!(h.run_outcome.as_str(), "gave_up" | "stopped")) + { + events.push((2, h.closed_at, json!({"at": rfc3339(h.closed_at), "repo": h.repo, "kind": "agent_stopped", "text": format!("CoderHelm {} on #{}{}", if h.run_outcome == "stopped" { "was stopped" } else { "gave up" }, h.number, if h.stop_reason.is_empty() { String::new() } else { format!(": {}", h.stop_reason) }), "link": list(&format!("pr={}#{}", h.repo, h.number)), "severity": 2}))); + } + events.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1))); + let events: Vec = events.into_iter().take(20).map(|e| e.2).collect(); + + // ── CoderHelm's slice ── + let ch_open: Vec<&&Open> = open + .iter() + .filter(|o| o.rec.author_is_coderhelm()) + .collect(); + let ch_hist_w: Vec<&History> = hist + .iter() + .copied() + .filter(|h| h.author_type == "coderhelm" && h.closed_at > since) + .collect(); + let ch_opened = ch_open.iter().filter(|o| o.rec.created_at > since).count() + + hist + .iter() + .filter(|h| h.author_type == "coderhelm" && h.created_at > since) + .count(); + let ch_merged_n = ch_hist_w.iter().filter(|h| h.merged).count(); + let ch_closed = ch_hist_w.len() - ch_merged_n; + let ch_cycles: Vec = ch_hist_w.iter().filter_map(|h| h.cycle_secs()).collect(); + let (wait, open_time) = ch_open.iter().fold((0i64, 0i64), |(w, t), o| { + let start = o.rec.ready_or_created(); + ( + w + pr_history::waiting_on_person(&o.rec.spans, start, now), + t + (now - start).max(0), + ) + }); + let fixer: Vec<&History> = hist + .iter() + .copied() + .filter(|h| h.coderhelm_role == "fixer" && h.closed_at > since) + .collect(); + let fixer_open = open + .iter() + .filter(|o| { + !o.rec.author_is_coderhelm() + && (!o.rec.coderhelm.run_id.is_empty() || !o.rec.coderhelm.run_ids.is_empty()) + }) + .count(); + let reviewed: Vec<&History> = hist + .iter() + .copied() + .filter(|h| h.first_coderhelm_review_at > since) + .collect(); + let looks: Vec = reviewed + .iter() + .map(|h| (h.first_coderhelm_review_at - h.ready_at).max(0)) + .collect(); + let outcomes: Vec<&History> = hist + .iter() + .copied() + .filter(|h| h.closed_at > since && !h.run_outcome.is_empty()) + .collect(); + let runs = (!outcomes.is_empty()).then(|| { + let c = |k: &str| outcomes.iter().filter(|h| h.run_outcome == k).count(); + let mut reasons: BTreeMap<&str, usize> = BTreeMap::new(); + for h in outcomes.iter().filter(|h| !h.stop_reason.is_empty()) { + *reasons.entry(h.stop_reason.as_str()).or_default() += 1; + } + json!({ + "first_try": c("first_try"), "after_fixes": c("after_fixes"), "rerun_only": c("rerun_only"), + "gave_up": c("gave_up"), "blocked": c("blocked"), "stopped": c("stopped"), + "reasons": reasons.iter().map(|(r, n)| json!({"reason": r, "count": n})).collect::>(), + }) + }); + if runs.is_none() { + miss( + "coderhelm.runs", + "not_recorded", + "Not recorded yet: run end states aren't joined to pull requests yet.", + ); + } + miss( + "coderhelm.reviewer.findings", + "not_recorded", + "Not recorded yet: CoderHelm's findings aren't joined to pull requests yet.", + ); + miss( + "coderhelm.reviewer.verified_rate", + "not_recorded", + "Not recorded yet: CoderHelm's findings aren't joined to pull requests yet.", + ); + miss( + "coderhelm.exceptions.cost_per_merged", + "not_recorded", + "Not recorded yet: run cost isn't joined to pull requests yet.", + ); + let ch_merged_w: Vec<&History> = merged_w + .iter() + .copied() + .filter(|h| h.author_type == "coderhelm") + .collect(); + let people_merged_w: Vec<&History> = merged_w + .iter() + .copied() + .filter(|h| h.author_type != "coderhelm") + .collect(); + let ch_decisions: Vec<&&Open> = ch_open + .iter() + .copied() + .filter(|o| o.row.state == "needs_decision") + .collect(); + let coderhelm = json!({ + "author": { + "opened": ch_opened, + "merged": ch_merged_n, + "closed_unmerged": ch_closed, + "open": ch_open.len(), + "merge_rate": share(ch_merged_n, ch_hist_w.len()).map(round3), + "p50_merge_secs": median(&ch_cycles), + "waiting_on_people": (open_time > 0).then(|| round3(wait as f64 / open_time as f64)), + "rule": "Merged / (merged + closed unmerged) for PRs resolved in the window; open PRs excluded; shown on 10 or more.", + }, + "fixer": {"fixed": fixer.len() + fixer_open, "merged": fixer.iter().filter(|h| h.merged).count(), "closed_unmerged": fixer.iter().filter(|h| !h.merged).count(), "open": fixer_open}, + "reviewer": {"reviewed": reviewed.len(), "findings": Value::Null, "verified_rate": Value::Null, "p50_first_look_secs": median(&looks)}, + "runs": runs, + "exceptions": { + "needs_decision": ch_decisions.len(), + "oldest_secs": ch_decisions.iter().map(|o| age(o, now)).max(), + "reworked": { + "coderhelm": ch_merged_w.iter().filter(|h| h.reworked()).count(), + "people": people_merged_w.iter().filter(|h| h.reworked()).count(), + "coderhelm_merged": ch_merged_w.len(), + "people_merged": people_merged_w.len(), + }, + "merges": { + "on_approval": ch_merged_w.iter().filter(|h| h.review_log.iter().any(|r| r.human && r.state == "APPROVED")).count(), + "own_authority": ch_merged_w.iter().filter(|h| h.merged_by_type == "coderhelm" && !h.review_log.iter().any(|r| r.human && r.state == "APPROVED")).count(), + "exempt": ch_merged_w.iter().filter(|h| h.merged_by_type == "coderhelm" && h.bypass.is_some()).count(), + }, + "cost_per_merged": Value::Null, + } + }); + + // ── Summary ── + let ctx = SummaryCtx { + org: &org_name, + scope: &scope_name, + repos_n: repos.len(), + open: &open, + open_n, + stale: &stale, + past_usual, + lines: &lines, + merged_w: &merged_w, + merged_prev: &merged_prev, + merges_range: range8(i.snaps, now, |s| s.merges), + merges_median: { + let v: Vec = (1..=8) + .filter_map(|w| snap_at(i.snaps, now, w * 7).map(|s| s.merges as i64)) + .collect(); + (v.len() == 8).then(|| median(&v)).flatten() + }, + past_range: range8(i.snaps, now, |s| s.past_p85), + past_sla: &past_sla, + bypass_w: &bypass_w, + reverted_14: &reverted_14, + merged_30: &merged_30, + strip: &strip, + decisions: &ch_decisions, + ch_opened, + ch_merged: ch_merged_n, + ch_reverted: ch_merged_w + .iter() + .filter(|h| h.reverted_by.is_some()) + .count(), + ch_outcomes: &outcomes, + ch_reviewed: reviewed.len(), + human_now: human_share(&merged_w), + human_prev: human_share(&merged_prev), + org_health: org_health.0, + sla: i.sla, + since, + now, + window_days: i.window_days, + }; + let mut b = Builder::default(); + let summary = summary(&ctx, &mut b); + let facts: Vec = b + .facts + .iter() + .map(|f| json!({"id": f.id, "kind": "count", "scope": f.scope, "value": f.value, "prev": f.prev, "delta": f.prev.map(|p| f.value - p), "unusual": false, "weight": f.weight, "link": f.link})) + .collect(); + + json!({ + "scope": {"org": if org_name.is_empty() { Value::Null } else { json!(org_name) }, "repo": i.repo, "window": format!("{}d", i.window_days), "vs": "8w", "repos": repos.len(), "repos_read": repos.len()}, + "generated_at": rfc3339(now), + "history": { + "days": history_secs / DAY, + "weeks": history_secs / (7 * DAY), + "young": young, + "merged_90d": hist.iter().filter(|h| h.merged && h.merged_at > now - 90 * DAY).count(), + "since": rfc3339(first_seen), + "backfill": backfill, + }, + "thresholds": thresholds, + "open": open_n, + "drafts": drafts, + "strip": strip, + "turns": turns, + "conditions": conditions, + "needs_decision": needs_decision, + "aging": {"dots": dots, "total": open.len(), "shown": open.len().min(MAX_DOTS)}, + "repos": repos, + "rollup": {"health": org_health.0, "repo": Value::Null, "rule": ROLLUP_RULE}, + "review": review, + "stale": stale_panel, + "failures": failures, + "security": security, + "events": events, + "coderhelm": coderhelm, + "facts": facts, + "summary": summary, + "missing": missing, + }) +} + +/// The verdict's printed roll-up rule. +pub const ROLLUP_RULE: &str = "Slipping: any obligation breached (a critical security fix past its SLA, an unreviewed bypass) or main red now. At risk: a headline number outside its 8-week range in the bad direction. Quiet: merges under a quarter of the 8-week median and nothing past usual. Healthy otherwise. The org takes the worst state of any repo holding 10% or more of open PRs, plus any obligation breach anywhere."; + +const METHOD: &str = "Facts are computed from CoderHelm's records of every pull request in the installed repos, people's, CoderHelm's and other bots'. Each is ranked by its effect on the org total; a change is mentioned only when it is at least 2 and 10% of the week before, a wait only past 24 hours, and no rate on fewer than 10 events. Each line is a fixed template over one fact; no number is written that isn't in the facts."; + +fn sev_rank(s: &str) -> u8 { + match s { + "critical" | "kev" => 0, + "high" => 1, + "medium" | "moderate" => 2, + _ => 3, + } +} + +/// The first required-check rollup on the pull request turned green, not red. +fn first_try_green(h: &History) -> bool { + h.check_log + .iter() + .find(|c| c.rollup == "red" || c.rollup == "green") + .is_some_and(|c| c.rollup == "green") +} + +/// A person reviewed it after it merged (a bypass's after-review). +fn reviewed_after(h: &History) -> bool { + h.review_log + .iter() + .any(|r| r.human && r.at > h.merged_at && h.merged_at > 0) +} + +struct SummaryCtx<'a> { + org: &'a str, + scope: &'a str, + repos_n: usize, + open: &'a [&'a Open], + open_n: usize, + stale: &'a [(&'a &'a Open, &'a str)], + past_usual: usize, + lines: &'a Lines, + merged_w: &'a [&'a History], + merged_prev: &'a [&'a History], + merges_range: Option<(u32, u32)>, + merges_median: Option, + past_range: Option<(u32, u32)>, + past_sla: &'a [(&'a &'a Open, i64)], + bypass_w: &'a [&'a History], + reverted_14: &'a [&'a History], + merged_30: &'a [&'a History], + strip: &'a [Value], + decisions: &'a [&'a &'a Open], + ch_opened: usize, + ch_merged: usize, + ch_reverted: usize, + ch_outcomes: &'a [&'a History], + ch_reviewed: usize, + human_now: Option, + human_prev: Option, + org_health: &'a str, + sla: Sla, + since: i64, + now: i64, + window_days: i64, +} + +/// A change worth mentioning: at least 2 and at least 10% of before. +pub fn passes_floor(now: f64, prev: f64) -> bool { + let d = (now - prev).abs(); + d >= 2.0 && d >= 0.1 * prev.abs() +} + +fn summary(c: &SummaryCtx, b: &mut Builder) -> Value { + let scope = c.scope; + let merged_link = gh_search(c.org, &format!("is:merged merged:>={}", day_of(c.since))); + let merges = c.merged_w.len() as f64; + let unreviewed_bypass: Vec<&&History> = + c.bypass_w.iter().filter(|h| !reviewed_after(h)).collect(); + let critical: Vec<&(&&Open, i64)> = c + .past_sla + .iter() + .filter(|(o, _)| sev_rank(&o.rec.severity) == 0) + .collect(); + let quiet_week = c.merges_median.is_some_and(|m| (merges as i64) * 4 < m) && c.past_usual == 0; + let past_out = c.past_range.is_some_and(|(_, hi)| c.past_usual as u32 > hi); + let merges_out = c.merges_range.is_some_and(|(lo, _)| (merges as u32) < lo); + let state = + if !critical.is_empty() || !unreviewed_bypass.is_empty() || c.org_health == "slipping" { + "slipping" + } else if past_out || merges_out || c.org_health == "at_risk" { + "at_risk" + } else if quiet_week { + "quiet" + } else { + "healthy" + }; + b.fact( + "merges", + scope, + merges, + Some(c.merged_prev.len() as f64), + 0.2, + merged_link.clone(), + ); + let usual = |b: &mut Builder| -> Vec { + let mut v = vec![b.num("merges", scope, merges, "count", merged_link.clone())]; + match c.merges_range { + Some((lo, hi)) => { + v.push(t(" merged (usual ")); + v.push(b.num( + "merges_8w_low", + scope, + lo as f64, + "count", + merged_link.clone(), + )); + v.push(t(" to ")); + v.push(b.num( + "merges_8w_high", + scope, + hi as f64, + "count", + merged_link.clone(), + )); + v.push(t(").")); + } + None => v.push(t(" merged.")), + } + v + }; + let mut parts: Vec = Vec::new(); + match state { + "slipping" => { + if !critical.is_empty() { + parts.push(b.num( + "security_past_sla", + scope, + critical.len() as f64, + "count", + list("past=sla"), + )); + parts.push(t(format!( + " critical security {} past the ", + if critical.len() == 1 { + "fix is" + } else { + "fixes are" + } + ))); + parts.push(b.num( + "sla_critical_days", + scope, + c.sla.critical as f64, + "count", + list("past=sla"), + )); + parts.push(t("-day SLA")); + parts.push(t(if unreviewed_bypass.is_empty() { + ". " + } else { + ", and " + })); + } + if !unreviewed_bypass.is_empty() { + parts.push(b.num( + "bypass_unreviewed", + scope, + unreviewed_bypass.len() as f64, + "count", + list("view=needs_decision"), + )); + parts.push(t(format!( + " {} through a bypass with no review after. ", + if unreviewed_bypass.len() == 1 { + "merge went" + } else { + "merges went" + } + ))); + } + if critical.is_empty() && unreviewed_bypass.is_empty() { + parts.push(t("A repo holding 10% or more of open PRs is slipping. ")); + } + parts.extend(usual(b)); + } + "at_risk" => { + if past_out { + let (lo, hi) = c.past_range.unwrap_or((0, 0)); + parts.push(b.num( + "past_p85", + scope, + c.past_usual as f64, + "count", + list("past=p85"), + )); + parts.push(t(" open PRs are past usual (8-week range ")); + parts.push(b.num( + "past_p85_8w_low", + scope, + lo as f64, + "count", + list("past=p85"), + )); + parts.push(t(" to ")); + parts.push(b.num( + "past_p85_8w_high", + scope, + hi as f64, + "count", + list("past=p85"), + )); + parts.push(t("). ")); + } else if merges_out { + parts.push(t("Merges fell below their 8-week range: ")); + } else { + parts.push(t( + "A repo holding 10% or more of open PRs is outside its 8-week range. ", + )); + } + parts.extend(usual(b)); + } + "quiet" => { + parts.extend(usual(b)); + parts.push(t(" Nothing is past usual.")); + } + _ => { + parts.extend(usual(b)); + if let Some([p50, _, _]) = c.lines.cycle { + parts.push(t(" Half of merged PRs take under ")); + parts.push(b.num("cycle_p50", scope, p50 as f64, "secs", merged_link.clone())); + parts.push(t("; nothing is past a deadline.")); + } else { + parts.push(t(" Nothing is past a deadline.")); + } + } + } + let word = match state { + "slipping" => "Slipping", + "at_risk" => "At risk", + "quiet" => "Quiet", + _ => "Healthy", + }; + + // Three fixed tiles. + let human_link = gh_search( + c.org, + &format!("is:merged review:approved merged:>={}", day_of(c.since)), + ); + let stale_n = c.stale.len() as f64; + b.fact("stale", scope, stale_n, None, 0.3, list("view=stale")); + if let Some(h) = c.human_now { + b.fact( + "reviewed", + scope, + round3(h), + c.human_prev.map(round3), + 0.2, + human_link.clone(), + ); + } + let reverts = c + .reverted_14 + .iter() + .filter(|h| h.reverted_by.as_ref().is_some_and(|(_, _, t)| *t > c.since)) + .count(); + b.fact( + "reverts", + scope, + reverts as f64, + None, + 0.1, + gh_search(c.org, "is:merged revert in:title"), + ); + let tiles = json!([ + {"fact": "stale", "label": "Stale: idle past the stage p85", "value": c.stale.len(), "unit": "count", "delta": Value::Null, "link": list("view=stale")}, + {"fact": "failures", "label": "Failures: main red this week", "value": Value::Null, "unit": "secs", "delta": Value::Null, + "second": {"value": reverts, "unit": "count", "label": if reverts == 1 { "revert" } else { "reverts" }, "link": gh_search(c.org, "is:merged revert in:title")}, + "link": list("state=checks_failing")}, + {"fact": "reviewed", "label": "Reviewed: human-approved merges", "value": c.human_now.map(round3), "unit": "share", + "delta": c.human_now.zip(c.human_prev).map(|(a, p)| round3(a - p)), "link": human_link}, + ]); + + // Needs attention: obligations, then stale by age, then decisions. + let mut items: Vec<(u8, i64, Value)> = Vec::new(); + for (o, a) in c.past_sla.iter().take(3) { + let (owner, kind) = owner_of(&o.row); + items.push((0, *a, json!({ + "fact": "security_past_sla", "owner": owner, "owner_kind": kind, + "owner_note": if owner.is_none() { json!("no owner on the fix yet") } else { Value::Null }, + "age_secs": a, "link": list(&format!("pr={}", o.row.key)), + "parts": [t(format!("{} is a {} security fix past its SLA", short_key(&o.row.key), o.rec.severity))], + }))); + } + for h in unreviewed_bypass.iter().take(2) { + items.push((1, c.now - h.merged_at, json!({ + "fact": "bypass", "owner": Value::Null, "owner_kind": Value::Null, "owner_note": "no reviewer after the merge", + "age_secs": c.now - h.merged_at, "link": list(&format!("pr={}#{}", h.repo, h.number)), + "parts": [t(format!("{}#{} merged through a bypass ({}), no review after", h.repo.split('/').nth(1).unwrap_or(&h.repo), h.number, h.bypass.clone().unwrap_or_default()))], + }))); + } + let mut stale_sorted: Vec<&(&&Open, &str)> = c.stale.iter().collect(); + stale_sorted + .sort_by_key(|(o, _)| std::cmp::Reverse(idle_of(o, c.now).map(|x| x.1).unwrap_or(0))); + for (o, who) in stale_sorted.iter().take(5) { + let idle = idle_of(o, c.now).map(|x| x.1).unwrap_or(0); + if idle < WAIT_FLOOR_SECS { + continue; + } + let (owner, kind) = owner_of(&o.row); + items.push((3, idle, json!({ + "fact": "stale", "owner": owner, "owner_kind": kind, + "owner_note": if owner.is_none() { json!(if *who == "reviewer" { "no reviewer assigned" } else { "nobody holds it" }) } else { Value::Null }, + "age_secs": idle, "link": list(&format!("pr={}", o.row.key)), + // The state's words, never the needs sentence: that one can + // name people, and a name appears only as the owner. + "parts": [t(format!("{}: {}, nobody acting on it", short_key(&o.row.key), o.row.state_label.to_lowercase()))], + }))); + } + for o in c.decisions.iter().take(1) { + let (owner, kind) = owner_of(&o.row); + items.push(( + 2, + age(o, c.now), + json!({ + "fact": "needs_decision", "owner": owner, "owner_kind": kind, + "owner_note": if owner.is_none() { json!("nobody asked yet") } else { Value::Null }, + "age_secs": age(o, c.now), "link": list(&format!("pr={}", o.row.key)), + "parts": [t(format!("CoderHelm needs a decision on {}", short_key(&o.row.key)))], + }), + )); + } + items.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1))); + let total_items = items.len(); + let attention: Vec = items + .into_iter() + .take(5) + .enumerate() + .map(|(k, (_, _, mut v))| { + v["rank"] = json!(k + 1); + v + }) + .collect(); + let more = + (total_items > 5).then(|| json!({"count": total_items - 5, "link": list("view=stale")})); + let quiet = attention.is_empty().then(|| { + let mut p = vec![t("Nothing needs you. Checked ")]; + p.push(b.num( + "repos", + scope, + c.repos_n as f64, + "count", + json!({"overview": ""}), + )); + p.push(t(" repos and ")); + p.push(b.num("open", scope, c.open_n as f64, "count", list(""))); + p.push(t( + " open PRs: none stale past a day, no security fix past SLA, no bypasses, no reverts.", + )); + json!({"repos": c.repos_n, "open": c.open_n, "parts": p}) + }); + + // What changed: the largest stage change past the floor. + let mut changed: Option = None; + let mut best = 0.0; + for s in c.strip { + if let (Some(n), Some(d)) = (s["count"].as_f64(), s["delta"].as_f64()) { + let prev = n - d; + if passes_floor(n, prev) && d.abs() > best { + best = d.abs(); + let label = s["label"].as_str().unwrap_or("").to_string(); + let code = s["stage"].as_str().unwrap_or("").to_string(); + let id = format!("stage_{code}"); + b.fact( + &id, + scope, + n, + Some(prev), + d.abs() / (c.open_n.max(1) as f64), + list(&format!("stage={code}")), + ); + let before = format!("{id}_before"); + b.fact( + &before, + scope, + prev, + None, + 0.0, + list(&format!("stage={code}")), + ); + let pp = b.num( + &before, + scope, + prev, + "count", + list(&format!("stage={code}")), + ); + let pn = b.num(&id, scope, n, "count", list(&format!("stage={code}"))); + changed = Some( + json!({"fact": id, "parts": [t(format!("{label} {} from ", if d > 0.0 { "rose" } else { "fell" })), pp, t(" to "), pn, t(".")]}), + ); + } + } + } + + // Stability: always. + let mut st = vec![b.num( + "reverts", + scope, + reverts as f64, + "count", + gh_search(c.org, "is:merged revert in:title"), + )]; + st.push(t(format!( + " revert{} this window", + if reverts == 1 { "" } else { "s" } + ))); + let reworked = c.merged_30.iter().filter(|h| h.reworked()).count(); + match share(reworked, c.merged_30.len()) { + Some(sh) => { + st.push(t( + "; merged PRs later reverted or hotfixed over the last month: ", + )); + st.push(b.num("proxy", scope, round3(sh), "share", merged_link.clone())); + st.push(t(".")); + } + None => st.push(t("; too few merges in the last month to give a rate.")), + } + + // CoderHelm: always, its failures first. + let ch_link = list("turn=coderhelm"); + let mut ch: Vec = Vec::new(); + let short_runs = c + .ch_outcomes + .iter() + .filter(|h| matches!(h.run_outcome.as_str(), "gave_up" | "blocked" | "stopped")) + .count(); + if c.ch_reverted > 0 { + ch.push(b.num( + "coderhelm_reverted", + scope, + c.ch_reverted as f64, + "count", + ch_link.clone(), + )); + ch.push(t(" of its merged PRs were reverted. ")); + } + if short_runs > 0 { + ch.push(b.num( + "coderhelm_stopped", + scope, + short_runs as f64, + "count", + ch_link.clone(), + )); + ch.push(t(" of its runs stopped short. ")); + } + if c.ch_opened == 0 && c.ch_merged == 0 && c.ch_reviewed == 0 { + ch.push(t("No PRs from CoderHelm in this window: opened ")); + ch.push(b.num("coderhelm_opened", scope, 0.0, "count", ch_link.clone())); + ch.push(t(", reviewed ")); + ch.push(b.num("coderhelm_reviewed", scope, 0.0, "count", ch_link.clone())); + ch.push(t(". Every number above is people's and other bots' work.")); + } else { + ch.push(t("Opened ")); + ch.push(b.num( + "coderhelm_opened", + scope, + c.ch_opened as f64, + "count", + ch_link.clone(), + )); + ch.push(t(", merged ")); + ch.push(b.num( + "coderhelm_merged", + scope, + c.ch_merged as f64, + "count", + gh_search( + c.org, + &format!( + "is:merged author:app/coderhelm merged:>={}", + day_of(c.since) + ), + ), + )); + ch.push(t(", reviewed ")); + ch.push(b.num( + "coderhelm_reviewed", + scope, + c.ch_reviewed as f64, + "count", + ch_link.clone(), + )); + ch.push(t(".")); + } + let _ = (c.open, c.window_days); + + json!({ + "window": {"from": rfc3339(c.since), "to": rfc3339(c.now)}, + "computed_at": rfc3339(c.now), + "verdict": {"state": state, "word": word, "parts": parts, "rule": ROLLUP_RULE}, + "tiles": tiles, + "attention": attention, + "more": more, + "quiet": quiet, + "changed": changed, + "stability": {"fact": "reverts", "parts": st}, + "coderhelm": {"fact": "coderhelm_opened", "parts": ch, "link": ch_link}, + "method": METHOD, + }) +} + +fn short_key(key: &str) -> String { + key.split('/').nth(1).unwrap_or(key).to_string() +} + +/// Every number in the summary, with the fact it names: for the tests and +/// the incident case. +pub fn summary_numbers(v: &Value) -> Vec<(String, f64)> { + fn walk(v: &Value, out: &mut Vec<(String, f64)>) { + match v { + Value::Object(m) => { + if let (Some(n), Some(f)) = ( + m.get("n").and_then(Value::as_f64), + m.get("fact").and_then(Value::as_str), + ) { + out.push((f.to_string(), n)); + } + for x in m.values() { + walk(x, out); + } + } + Value::Array(a) => a.iter().for_each(|x| walk(x, out)), + _ => {} + } + } + let mut out = Vec::new(); + walk(&v["summary"], &mut out); + out +} diff --git a/services/common/src/run_wake.rs b/services/common/src/run_wake.rs index a1f9e948..881c0de2 100644 --- a/services/common/src/run_wake.rs +++ b/services/common/src/run_wake.rs @@ -250,6 +250,125 @@ pub async fn put_back( } } +/// The ticket id of an alert's runs for its fingerprint (stable across +/// repeats), as the gateway gives it when the alert starts a run. +pub fn alert_ticket_id(fingerprint: &str) -> String { + format!( + "ALERT-{}", + crate::content_hash(fingerprint)[..8].to_uppercase() + ) +} + +fn text<'a>(item: &'a HashMap, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or("") +} + +/// The newest run of `ticket_id` for the team. +pub async fn newest_of_ticket( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team_id: &str, + ticket_id: &str, +) -> Option> { + let out = dynamo + .query() + .table_name(runs_table) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .ok()?; + out.items() + .iter() + .max_by(|a, b| text(a, "run_id").cmp(text(b, "run_id"))) + .cloned() +} + +/// Why a waiting alert run closes when its alert cleared. +pub const ALERT_CLEARED_WHY: &str = "the alert cleared by itself, so nothing is left to fix"; + +/// Closes the waiting alert run `item` whose alert cleared by itself (only +/// while it still waits). Returns whether it closed. +pub async fn close_cleared( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team_id: &str, + item: &HashMap, +) -> bool { + use crate::run_ending::EndWrite; + let run_id = text(item, "run_id").to_string(); + let why = ALERT_CLEARED_WHY; + let now = chrono::Utc::now().to_rfc3339(); + let closed = dynamo + .update_item() + .table_name(runs_table) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.clone())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t, \ + progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", + ) + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &crate::run_ending::gate( + &run_id, + &crate::run_ending::RunEnd::Stopped(crate::run_ending::Stopped { + reason: crate::run_ending::Stop::ClosedBy { + who: "CoderHelm".into(), + why: why.into(), + }, + tried: Default::default(), + }), + ), + ) + .expression_attribute_values(":waiting", AttributeValue::S(WAITING.into())) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values( + ":n", + AttributeValue::L(vec![AttributeValue::M(HashMap::from([ + ( + "message".to_string(), + AttributeValue::S(format!("Closed: {why}.")), + ), + ("timestamp".to_string(), AttributeValue::S(now.clone())), + ]))]), + ) + .expression_attribute_values(":t", AttributeValue::S(now)) + .send() + .await; + if closed.is_ok() { + tracing::info!(run_id, "Alert cleared: its waiting run closed"); + } + closed.is_ok() +} + +/// The alert whose runs' ticket is `ticket_id` cleared: its newest run, when +/// it waits on a person, closes ([`alert_wake`] with `cleared`, then +/// [`close_cleared`]). The one path every recovery takes, whether it posts +/// at once or after a route's quiet window. Returns whether a run closed. +pub async fn alert_cleared( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team_id: &str, + ticket_id: &str, +) -> bool { + let Some(item) = newest_of_ticket(dynamo, runs_table, team_id, ticket_id).await else { + return false; + }; + let wait = crate::run_wait::WaitingOn::of_item(&item).unwrap_or_default(); + match alert_wake(text(&item, "status"), &wait.handback, true) { + Some(AlertWake::Close) => close_cleared(dynamo, runs_table, team_id, &item).await, + _ => false, + } +} + #[cfg(test)] mod tests { use super::*; @@ -282,6 +401,30 @@ mod tests { ); } + /// A recovery closes its waiting run whatever the run waits on, and + /// whichever way it posts (at once, or after the route's quiet window): + /// both find the run by the same ticket. + #[test] + fn a_cleared_alert_closes_its_waiting_run_however_the_recovery_posts() { + for why in crate::handback::HUMAN_ONLY { + assert_eq!( + alert_wake(WAITING, why.code(), true), + Some(AlertWake::Close), + "{why:?}" + ); + } + assert_eq!(alert_wake(WAITING, "", true), Some(AlertWake::Close)); + // Only a run that waits: a finished or running one is left alone. + assert_eq!(alert_wake("completed", "", true), None); + assert_eq!(alert_wake("running", "", true), None); + let fp = "cloudwatch:example-alarm:eu-west-1"; + let t = alert_ticket_id(fp); + assert!(t.starts_with("ALERT-") && t.len() == 14, "{t}"); + assert_eq!(t, alert_ticket_id(fp)); + assert_ne!(t, alert_ticket_id("cloudwatch:other-alarm:eu-west-1")); + assert_eq!(crate::rendered::person_text(ALERT_CLEARED_WHY), None); + } + #[test] fn a_wake_whose_run_was_not_queued_goes_back_to_waiting() { let s = |v: &str| AttributeValue::S(v.into()); diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index b02b645a..a1d2da68 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -693,6 +693,7 @@ fn build_app(state: Arc) -> Router { .route("/reviewer/live", get(routes::reviewer::live_prs)) .route("/prs", get(routes::prs::list_prs)) .route("/prs/detail", get(routes::prs::get_pr)) + .route("/prs/overview", get(routes::prs_overview::get_overview)) .route("/reviewer/open-prs", get(routes::reviewer::open_prs)) .route( "/reviewer/gate", diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 6f488995..d5e26982 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -127,6 +127,7 @@ pub const CAPABILITIES: &[Capability] = &[ "reviewer::open_prs", "prs::list_prs", "prs::get_pr", + "prs_overview::get_overview", "review_lessons::list_lessons", "learning::get_learning", "learning::get_health", diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 08fceabf..49fa18fd 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -387,10 +387,7 @@ pub fn ticket_body(topic_arn: &str, alert: &Alert, instructions: &str) -> String /// Pure: the run's ticket id for an alert fingerprint (stable across repeats). pub fn ticket_id(fingerprint: &str) -> String { - format!( - "ALERT-{}", - common::content_hash(fingerprint)[..8].to_uppercase() - ) + common::run_wake::alert_ticket_id(fingerprint) } /// Pure: `arn:aws:sns:::` → account, when well-formed. diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index acb99c2a..4b03cb80 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -2015,6 +2015,25 @@ pub(crate) fn rerequest_key(delivery_id: &str, payload: &Value) -> String { } /// Track PR merges for CoderHelm branches — updates run status to "merged". +/// The worker message that has a team's runs waiting on another change read +/// the pull request of `payload` again, for an event that moves it (a +/// close, merged or not, or a reopen). `None` for any other action. +pub fn change_wait_check(action: &str, payload: &Value, team_id: &str) -> Option { + if !common::change_wait::event_moves_change(action) { + return None; + } + Some(WorkerMessage::ChangeWaitCheck( + common::messages::ChangeWaitCheckMessage { + team_id: team_id.to_string(), + repo: payload["repository"]["full_name"] + .as_str() + .unwrap_or("") + .to_string(), + pr: payload["pull_request"]["number"].as_u64().unwrap_or(0), + }, + )) +} + async fn handle_pull_request( state: &AppState, payload: &Value, @@ -2096,6 +2115,17 @@ async fn handle_pull_request( return send_review_job(state, message, head, 0).await; } + // Runs waiting on this change read it again at once + // (`common::change_wait`): a merge resumes them, a close stops them for + // a person, and a reopen takes a run that close stopped back to waiting. + // Before the returns below, since a reopen goes on to the review + // triggers. The worker's 15-minute sweep is the backstop. + if let Some(check) = change_wait_check(action, payload, team_id) { + if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &check).await { + warn!(error = ?e, "Could not ask waiting runs to read their change again"); + } + } + // The scorecard: one of CoderHelm's pull requests opened or reopened. if action == "opened" || action == "reopened" { super::scorecard::on_pull_request(state, team_id, payload, action, None).await; @@ -2140,15 +2170,6 @@ async fn handle_pull_request( if action != "closed" { return Ok(StatusCode::OK); } - // Runs waiting for another change to merge read their dependency again - // (`common::change_wait`): a merge resumes them, a close stops them for - // a person. The worker does nothing for a team with no waiting run. - let check = WorkerMessage::ChangeWaitCheck(common::messages::ChangeWaitCheckMessage { - team_id: team_id.to_string(), - }); - if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &check).await { - warn!(error = ?e, "Could not ask waiting runs to read their dependency again"); - } // A merge: the open pull requests based on its branch move to its base // (the worker reads the pull request and the repository's setting). if let Some(m) = stack_merged_message(payload, installation_id, team_id, merged) { @@ -6940,3 +6961,50 @@ mod ci_wake_tests { assert!(prs_headed_at(&json!({"message": "Not Found"}), "c0ffee1").is_empty()); } } + +#[cfg(test)] +mod change_wait_check_tests { + use super::{change_wait_check, WorkerMessage}; + use serde_json::json; + + fn event(action: &str) -> serde_json::Value { + json!({ + "action": action, + "repository": {"full_name": "acme/bookstore-web", "name": "bookstore-web", + "owner": {"login": "acme"}}, + "pull_request": {"number": 12, "merged": false}, + }) + } + + /// A reopened change reaches the runs waiting on it as GitHub reports + /// it, not at the next sweep; a close (merged or not) does too. + #[test] + fn a_reopen_or_close_asks_the_waiting_runs_at_once() { + for action in ["reopened", "closed"] { + match change_wait_check(action, &event(action), "T1") { + Some(WorkerMessage::ChangeWaitCheck(m)) => { + assert_eq!(m.team_id, "T1"); + assert_eq!(m.repo, "acme/bookstore-web"); + assert_eq!(m.pr, 12); + } + other => panic!("{action}: {other:?}"), + } + } + for action in ["opened", "synchronize", "labeled", "edited"] { + assert!(change_wait_check(action, &event(action), "T1").is_none()); + } + } + + /// The check is sent before the reopen goes on to the review triggers + /// (which return), so no early return skips it. + #[test] + fn the_check_is_sent_before_any_return_a_reopen_reaches() { + let src = include_str!("github_webhook.rs"); + let handler = src.split("async fn handle_pull_request(").nth(1).unwrap(); + let check = handler + .find("change_wait_check(action, payload, team_id)") + .unwrap(); + let review = handler.find("return handle_review_trigger(").unwrap(); + assert!(check < review); + } +} diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 541b684e..7335d1de 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -82,6 +82,7 @@ pub mod plugin_pkgs; pub mod plugins; pub mod preview_access; pub mod prs; +pub mod prs_overview; pub mod repo_setup; pub mod require_sso; #[cfg(test)] diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 1136ddd1..050b5a35 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -249,7 +249,11 @@ fn n(item: &Item, k: &str) -> Option { item.get(k)?.as_n().ok()?.parse().ok() } -async fn items_under(state: &AppState, team_id: &str, prefix: &str) -> Result, String> { +pub(crate) async fn items_under( + state: &AppState, + team_id: &str, + prefix: &str, +) -> Result, String> { let mut out = Vec::new(); let mut start: Option = None; loop { @@ -427,7 +431,10 @@ async fn runs_by_id(state: &AppState, team_id: &str, ids: &[String]) -> HashMap< } /// The team's records and joins, from the short cache or the tables. -async fn read_all(state: &AppState, team_id: &str) -> Result<(Snapshot, Vec), StatusCode> { +pub(crate) async fn read_all( + state: &AppState, + team_id: &str, +) -> Result<(Snapshot, Vec), StatusCode> { let installation_id = super::api::get_team_installation_id(state, team_id) .await .unwrap_or(0); @@ -483,10 +490,41 @@ pub struct ListQuery { person: Option, q: Option, view: Option, + /// The overview's drill-down: one stage, or open past a cycle-time percentile. + stage: Option, + past: Option, limit: Option, cursor: Option, } +/// Pure: the overview's drill-down filters, or 400 for a word outside them. +pub fn drill_of( + stage: Option, + past: Option, +) -> Result<(Option, Option), StatusCode> { + let stage = clean(stage); + if stage.as_deref().is_some_and(|s| { + ![ + "draft", + "first_review", + "in_review", + "blocked", + "coderhelm_working", + "approved", + ] + .contains(&s) + }) { + return Err(StatusCode::BAD_REQUEST); + } + let past = match clean(past).as_deref() { + None => None, + Some("p85") => Some(85), + Some("p95") => Some(95), + Some(_) => return Err(StatusCode::BAD_REQUEST), + }; + Ok((stage, past)) +} + fn clean(v: Option) -> Option { v.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) } @@ -575,15 +613,51 @@ fn synced_at(items: &[Item], team_id: &str, q: &pr_view::Query) -> Option>, Extension(claims): Extension, - Query(q): Query, + Query(mut q): Query, ) -> Result, StatusCode> { + let (stage, past) = drill_of(q.stage.take(), q.past.take())?; let (query, limit, cursor) = query_of(q)?; - let (data, sources) = read_all(&state, &claims.team_id).await?; + let (data, mut sources) = read_all(&state, &claims.team_id).await?; let (items, joins) = (&data.0, &data.1); let viewer = claims.github_login.as_deref(); - let rows = pr_view::rows(&claims.team_id, items, joins, viewer, now()); + let t = now(); + let rows = pr_view::rows(&claims.team_id, items, joins, viewer, t); let synced = synced_at(items, &claims.team_id, &query); - let page = pr_view::page(rows, &query, limit, cursor.as_deref()); + let page = if stage.is_none() && past.is_none() { + pr_view::page(rows, &query, limit, cursor.as_deref()) + } else { + // The counts stay over the whole scope; the rows are the drill-down's. + let limit_secs = match past { + Some(p) => past_secs(&state, &claims.team_id, &query, p, t).await, + None => None, + }; + if past.is_some() && limit_secs.is_none() { + sources.push(json!({"name": "percentiles", "read": "held", "detail": "no percentiles yet, so every open pull request is shown"})); + } + let picked: Vec = rows + .iter() + .filter(|r| { + stage + .as_deref() + .is_none_or(|s| r.stage.as_deref() == Some(s)) + }) + .filter(|r| match limit_secs { + Some(l) => { + !r.draft + && r.ready_at + .as_deref() + .and_then(|a| chrono::DateTime::parse_from_rfc3339(a).ok()) + .is_some_and(|a| t - a.timestamp() > l) + } + None => true, + }) + .cloned() + .collect(); + let counts = pr_view::page(rows, &query, 1, None).counts; + let mut p = pr_view::page(picked, &query, limit, cursor.as_deref()); + p.counts = counts; + p + }; let backfill = backfill_progress(&state, &claims.team_id).await; Ok(Json(json!({ "backfill": backfill, @@ -597,6 +671,32 @@ pub async fn list_prs( }))) } +/// The scope's cycle-time percentile from its newest snapshot (90 days of +/// merges): the line "past usual" is measured against. +async fn past_secs( + state: &AppState, + team_id: &str, + q: &pr_view::Query, + p: u32, + now: i64, +) -> Option { + let scope = q.repo.clone().or_else(|| q.org.clone())?; + let since = chrono::DateTime::from_timestamp(now - 3 * 86_400, 0)? + .format("%Y-%m-%d") + .to_string(); + let snaps = common::pr_history::snapshots_of( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &scope, + &since, + ) + .await + .ok()?; + let c = &snaps.last()?.pct.cycle; + c.get(if p == 95 { 2 } else { 1 }).copied() +} + /// Pure: each organization's history backfill as the page shows it. pub fn backfill_json(items: &[Item]) -> Vec { use common::pr_history::{Backfill, BACKFILL_MONTHS}; diff --git a/services/gateway/src/routes/prs_overview.rs b/services/gateway/src/routes/prs_overview.rs new file mode 100644 index 00000000..8880c9a2 --- /dev/null +++ b/services/gateway/src/routes/prs_overview.rs @@ -0,0 +1,269 @@ +//! `GET /api/prs/overview?org=&repo=&window=` — the org's pull requests in +//! one answer (`common::pr_overview::build`): the written summary, the stage +//! strip, the aging dots, each repository's health, the stale, failure, +//! review and security panels, this week's events and CoderHelm's slice. +//! +//! Every pull request in the team's repositories counts: people's, +//! CoderHelm's and other bots'. The team is the session's, never a +//! parameter; every read is keyed by it (records, history, snapshots, +//! backfill progress). The short cache is keyed by the installation, the +//! team and the scope. + +use std::collections::BTreeMap; +use std::sync::{Arc, LazyLock}; +use std::time::{Duration, Instant}; + +use axum::{ + extract::{Query, State}, + http::StatusCode, + Extension, Json, +}; +use common::pr_history::{self, Backfill, History, Snapshot}; +use common::pr_overview::{self, Input, Open, Sla}; +use common::pr_view; +use serde::Deserialize; +use serde_json::{json, Value}; +use tracing::{error, warn}; + +use super::prs::{items_under, read_all}; +use super::run_checks::{read_key, TtlCache}; +use crate::models::Claims; +use crate::AppState; + +/// How long one scope's overview is reused (the page polls every minute). +const OVERVIEW_TTL: Duration = Duration::from_secs(60); +/// Most repositories whose own snapshots are read for sparklines and ranges. +const MAX_REPO_SNAPS: usize = 30; + +/// The built overview, keyed by +/// `read_key(installation_id, "prs_overview####")`. +static OVERVIEW: LazyLock>> = LazyLock::new(TtlCache::new); + +#[derive(Deserialize, Default)] +pub struct OverviewQuery { + org: Option, + repo: Option, + window: Option, +} + +fn clean(v: Option) -> Option { + v.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) +} + +/// Pure: the scope and window, or 400 for anything outside them. +pub fn scope_of(q: OverviewQuery) -> Result<(Option, Option, i64), StatusCode> { + let org = clean(q.org); + if let Some(o) = &org { + if o.len() > 100 + || !o + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') + { + return Err(StatusCode::BAD_REQUEST); + } + } + let repo = clean(q.repo); + if let Some(r) = &repo { + super::reviewer::validate_repo(r)?; + } + let days = + pr_overview::window_days(clean(q.window).as_deref()).ok_or(StatusCode::BAD_REQUEST)?; + Ok((org, repo, days)) +} + +fn day(t: i64) -> String { + chrono::DateTime::from_timestamp(t, 0) + .map(|d| d.format("%Y-%m-%d").to_string()) + .unwrap_or_default() +} + +/// GET /api/prs/overview — computed facts only; what isn't stored yet is +/// null and named in `missing`. +pub async fn get_overview( + State(state): State>, + Extension(claims): Extension, + Query(q): Query, +) -> Result, StatusCode> { + let (org, repo, days) = scope_of(q)?; + let team_id = claims.team_id.as_str(); + let installation_id = super::api::get_team_installation_id(&state, team_id) + .await + .unwrap_or(0); + let key = read_key( + installation_id, + &format!( + "prs_overview#{team_id}#{}#{}#{days}", + org.as_deref().unwrap_or(""), + repo.as_deref().unwrap_or("") + ), + ); + let at = Instant::now(); + if let Some(hit) = OVERVIEW.get(&key, at) { + return Ok(Json((*hit).clone())); + } + + let now = chrono::Utc::now().timestamp(); + let table = &state.config.settings_table_name; + let (data, mut sources) = read_all(&state, team_id).await?; + let (items, joins) = (&data.0, &data.1); + let recs = pr_view::records_of(team_id, items); + let rows = pr_view::rows(team_id, items, joins, None, now); + let open: Vec = recs + .into_iter() + .filter(|r| r.is_open()) + .filter_map(|rec| { + let k = format!("{}#{}", rec.repo, rec.number); + let row = rows + .iter() + .find(|r| r.key.eq_ignore_ascii_case(&k))? + .clone(); + Some(Open { rec, row }) + }) + .collect(); + + let hist: Vec = match pr_history::all_since( + &state.dynamo, + table, + team_id, + now - pr_history::HISTORY_KEEP_SECS, + ) + .await + { + Ok(h) => h, + Err(e) => { + warn!(team_id, error = %e, "Overview: history not read"); + sources.push(json!({"name": "history", "read": "failed", "detail": "merged and closed pull requests couldn't be read; numbers that need them say so"})); + Vec::new() + } + }; + let org_scope = repo + .as_deref() + .and_then(|r| r.split('/').next()) + .map(str::to_string) + .or(org.clone()) + .or_else(|| open.first().map(|o| o.rec.org().to_string())) + .unwrap_or_default(); + let scope = repo.clone().unwrap_or_else(|| org_scope.clone()); + let since_day = day(now - 63 * 86_400); + let snaps: Vec = if scope.is_empty() { + Vec::new() + } else { + pr_history::snapshots_of(&state.dynamo, table, team_id, &scope, &since_day) + .await + .unwrap_or_else(|e| { + warn!(team_id, error = %e, "Overview: snapshots not read"); + Vec::new() + }) + }; + // Each repository's own snapshots, for its sparkline and 8-week range: + // the busiest first, bounded. + let mut busy: BTreeMap = BTreeMap::new(); + for o in &open { + if repo + .as_deref() + .is_none_or(|r| o.rec.repo.eq_ignore_ascii_case(r)) + && (org_scope.is_empty() || o.rec.org().eq_ignore_ascii_case(&org_scope)) + { + *busy.entry(o.rec.repo.clone()).or_default() += 1; + } + } + let mut names: Vec<(String, usize)> = busy.into_iter().collect(); + names.sort_by_key(|b| std::cmp::Reverse(b.1)); + let reads = names.iter().take(MAX_REPO_SNAPS).map(|(n, _)| { + let n = n.clone(); + let st = state.clone(); + let since = since_day.clone(); + let team = team_id.to_string(); + async move { + let t = st.config.settings_table_name.clone(); + let s = pr_history::snapshots_of(&st.dynamo, &t, &team, &n, &since) + .await + .unwrap_or_default(); + (n, s) + } + }); + let repo_snaps: BTreeMap> = + futures::future::join_all(reads).await.into_iter().collect(); + let backfill: Vec = + match items_under(&state, team_id, pr_history::BACKFILL_PREFIX).await { + Ok(items) => items + .iter() + .filter(|i| { + i.get("pk").and_then(|v| v.as_s().ok()).map(String::as_str) == Some(team_id) + }) + .filter_map(|i| i.get("doc").and_then(|v| v.as_s().ok())) + .filter_map(|d| serde_json::from_str(d).ok()) + .collect(), + Err(e) => { + error!(team_id, error = %e, "Overview: backfill progress not read"); + Vec::new() + } + }; + + let mut out = pr_overview::build(&Input { + open: &open, + hist: &hist, + snaps: &snaps, + repo_snaps: &repo_snaps, + backfill: &backfill, + org: if org_scope.is_empty() { + None + } else { + Some(org_scope.as_str()) + }, + repo: repo.as_deref(), + window_days: days, + sla: Sla::default(), + now, + }); + let mut orgs: Vec = open.iter().map(|o| o.rec.org().to_string()).collect(); + orgs.sort(); + orgs.dedup(); + out["scope"]["orgs"] = json!(orgs); + out["synced_at"] = json!(open + .iter() + .map(|o| o.rec.synced_at.max(o.rec.event_at)) + .filter(|t| *t > 0) + .min() + .and_then(pr_view::rfc3339)); + out["sources"] = json!(sources); + let out = Arc::new(out); + OVERVIEW.put(key, out.clone(), OVERVIEW_TTL, at); + Ok(Json((*out).clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_scope_takes_only_its_own_words() { + let q = |org: Option<&str>, repo: Option<&str>, w: Option<&str>| OverviewQuery { + org: org.map(Into::into), + repo: repo.map(Into::into), + window: w.map(Into::into), + }; + assert_eq!(scope_of(q(Some("acme"), None, None)).unwrap().2, 7); + assert_eq!( + scope_of(q(None, Some("acme/web"), Some("28d"))).unwrap().2, + 28 + ); + assert!(scope_of(q(Some("acme corp"), None, None)).is_err()); + assert!(scope_of(q(None, Some("acme/../web"), None)).is_err()); + assert!(scope_of(q(None, None, Some("1y"))).is_err()); + } + + #[test] + fn the_lists_drill_down_takes_a_stage_or_a_percentile() { + use super::super::prs::drill_of; + let w = |s: &str| Some(s.to_string()); + assert_eq!( + drill_of(w("first_review"), None).unwrap(), + (w("first_review"), None) + ); + assert_eq!(drill_of(None, w("p85")).unwrap(), (None, Some(85))); + assert_eq!(drill_of(None, w("p95")).unwrap().1, Some(95)); + assert!(drill_of(w("everything"), None).is_err()); + assert!(drill_of(None, w("p99")).is_err()); + } +} diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs index 1bc5c96a..1fd3dd41 100644 --- a/services/gateway/src/routes/run_wake.rs +++ b/services/gateway/src/routes/run_wake.rs @@ -296,21 +296,13 @@ async fn run_item(state: &AppState, team_id: &str, run_id: &str) -> Option /// The newest run of `ticket_id`, whatever its status. async fn newest_of_ticket(state: &AppState, team_id: &str, ticket_id: &str) -> Option { - let out = state - .dynamo - .query() - .table_name(&state.config.runs_table_name) - .index_name("ticket-index") - .key_condition_expression("team_id = :tid AND ticket_id = :ticket") - .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) - .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) - .send() - .await - .ok()?; - out.items() - .iter() - .max_by(|a, b| text(a, "run_id").cmp(text(b, "run_id"))) - .cloned() + run_wake::newest_of_ticket( + &state.dynamo, + &state.config.runs_table_name, + team_id, + ticket_id, + ) + .await } /// The answer to approval `approval_id` sends the run that waited for it @@ -400,70 +392,27 @@ pub async fn alert_delivery( ticket_id: &str, cleared: bool, ) -> bool { + // A clear takes the one path every recovery takes, whether it posts at + // once or after the route's quiet window (`run_wake::alert_cleared`). + if cleared { + return run_wake::alert_cleared( + &state.dynamo, + &state.config.runs_table_name, + team_id, + ticket_id, + ) + .await; + } let Some(item) = newest_of_ticket(state, team_id, ticket_id).await else { return false; }; let wait = WaitingOn::of_item(&item).unwrap_or_default(); - match run_wake::alert_wake(text(&item, "status"), &wait.handback, cleared) { + match run_wake::alert_wake(text(&item, "status"), &wait.handback, false) { Some(run_wake::AlertWake::Resume) => { wake_one(state, team_id, &item, "its alert fired again").await } - Some(run_wake::AlertWake::Close) => close_cleared(state, team_id, &item).await, - None => false, - } -} - -/// Closes a waiting alert run whose alert cleared by itself. -async fn close_cleared(state: &AppState, team_id: &str, item: &Item) -> bool { - let run_id = text(item, "run_id").to_string(); - let why = "the alert cleared by itself, so nothing is left to fix"; - let closed = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", AttributeValue::S(team_id.to_string())) - .key("run_id", AttributeValue::S(run_id.clone())) - .update_expression( - "SET #status = :s, status_run_id = :sri, updated_at = :t, \ - progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", - ) - .condition_expression("#status = :waiting") - .expression_attribute_names("#status", "status") - .run_status( - ":s", - &common::run_ending::gate( - &run_id, - &common::run_ending::RunEnd::Stopped(common::run_ending::Stopped { - reason: common::run_ending::Stop::ClosedBy { - who: "CoderHelm".into(), - why: why.into(), - }, - tried: Default::default(), - }), - ), - ) - .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) - .expression_attribute_values(":empty", AttributeValue::L(vec![])) - .expression_attribute_values( - ":n", - AttributeValue::L(vec![AttributeValue::M(HashMap::from([ - ( - "message".to_string(), - AttributeValue::S(format!("Closed: {why}.")), - ), - ( - "timestamp".to_string(), - AttributeValue::S(chrono::Utc::now().to_rfc3339()), - ), - ]))]), - ) - .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) - .send() - .await; - if closed.is_ok() { - info!(run_id, "Alert cleared: its waiting run closed"); + _ => false, } - closed.is_ok() } #[cfg(test)] diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 080a944f..2426690a 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -1164,7 +1164,7 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe passes::webhooks::run_waiting(&state, &msg).await; } models::WorkerMessage::ChangeWaitCheck(msg) => { - passes::change_wait::check_all(&state, Some(&msg.team_id)).await; + passes::change_wait::check_change(&state, &msg).await; } models::WorkerMessage::PrRecordsSync(msg) => { passes::pr_records::sync_message(&state, &msg).await; diff --git a/services/worker/src/passes/alert_episodes.rs b/services/worker/src/passes/alert_episodes.rs index 6c93b33a..5ef5445c 100644 --- a/services/worker/src/passes/alert_episodes.rs +++ b/services/worker/src/passes/alert_episodes.rs @@ -98,6 +98,16 @@ pub async fn run(state: &WorkerState, msg: AlertEpisodeCheckMessage) { match applied.decision { Decision::Cleared(ended) => { episodes::post_cleared(&posting, &msg.team_id, &ended).await; + // The recovery is final: its run waiting on a person closes the + // way a recovery posted at once closes it (the gateway's + // `run_wake::alert_delivery` takes the same path). + common::run_wake::alert_cleared( + &state.dynamo, + &state.config.runs_table_name, + &msg.team_id, + &common::run_wake::alert_ticket_id(&msg.fingerprint), + ) + .await; } Decision::Remind => { let Some(ep) = applied.episode else { return }; diff --git a/services/worker/src/passes/change_wait.rs b/services/worker/src/passes/change_wait.rs index 2ae5637f..d67cc4f6 100644 --- a/services/worker/src/passes/change_wait.rs +++ b/services/worker/src/passes/change_wait.rs @@ -211,6 +211,23 @@ pub struct Checked { /// as "needs you" (closed without merging), or left waiting with its /// page saying why (the dependency's run stopped). pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { + check_scoped(state, team, "", 0).await +} + +/// A pull request of the team moved (a merge, a close, a reopen as GitHub +/// reports it): the team's waiting runs read their change again, and a run +/// stopped because this change closed goes back to waiting at once when it +/// is reopened (or on when it merged). The sweep is the backstop. +pub async fn check_change( + state: &WorkerState, + msg: &common::messages::ChangeWaitCheckMessage, +) -> Checked { + check_scoped(state, Some(&msg.team_id), &msg.repo, msg.pr).await +} + +/// [`check_all`], with the stopped runs read only for the change `repo` +/// `pr` that moved (empty and 0: every change). +async fn check_scoped(state: &WorkerState, team: Option<&str>, repo: &str, pr: u64) -> Checked { let mut out = Checked::default(); // Read to the last page either way: one team's waiting runs by the // status index, or every team's runs by key (a capped scan of the runs @@ -263,10 +280,9 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { } } // Runs that stopped because their change closed: reopened, they wait - // for it again; merged, they go on (the 15-minute sweep reads them). - if team.is_none() { - out.resumed += check_closed(state).await; - } + // for it again; merged, they go on (a pull request event for the team + // reads them at once; the 15-minute sweep reads every team's). + out.resumed += check_closed(state, team, repo, pr).await; info!( waiting = out.waiting, resumed = out.resumed, @@ -279,14 +295,23 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { /// Every run that stopped because the change it waited for closed: when /// that change is reopened the run waits for it again, and when it merged /// the run goes on. Returns how many went back. -async fn check_closed(state: &WorkerState) -> usize { +async fn check_closed(state: &WorkerState, team: Option<&str>, repo: &str, pr: u64) -> usize { let filter = super::team_runs::Filter { expr: "#s = :n AND attribute_exists(#w)", names: vec![("#s", "status"), ("#w", cw::FIELD)], values: vec![(":n", attr_s(common::run_wake::WAITING))], projection: None, }; - let items = super::team_runs::matching(state, "Runs whose change closed", &filter).await; + let items = match team { + Some(t) => match super::team_runs::of_team(state, t, &filter).await { + Ok(items) => items, + Err(e) => { + warn!(error = %e, "Runs whose change closed couldn't be listed"); + Vec::new() + } + }, + None => super::team_runs::matching(state, "Runs whose change closed", &filter).await, + }; let mut back = 0; for item in items { if s(&item, "status") != common::run_status::NEEDS_INPUT { @@ -302,6 +327,10 @@ async fn check_closed(state: &WorkerState) -> usize { let Some(dep) = Dependency::from_json(s(&item, cw::FIELD)) else { continue; }; + // An event reads only the runs of the change it reports. + if !cw::moved_is(&dep, repo, pr) { + continue; + } let Some((o, r)) = dep.repo.split_once('/') else { continue; }; diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs index f4988d90..2d58121a 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -353,6 +353,10 @@ const CACHES: &[(&str, &str)] = &[ ("gateway/src/permissions.rs::ROUTES", "route table; no data"), ("gateway/src/routes/chat_work_prs.rs::CACHE", "URL, reused only on a 304 to the team's own token; repo checked against the team's repos first"), ("gateway/src/routes/github_webhook.rs::SEEN", "installation id; log throttle"), + ( + "gateway/src/routes/prs_overview.rs::OVERVIEW", + "installation id plus the team id, org, repo and window (read_key(installation_id, \"prs_overview##...\")); built only from that team's records, history and snapshots", + ), ("gateway/src/routes/prs.rs::LIST", "installation id plus the team id (read_key(installation_id, \"prs#\")); its rows keep only that team's records"), ("gateway/src/routes/roles.rs::CACHE", "(team, role)"), ("gateway/src/routes/run_checks.rs::TOKENS", "installation id"), diff --git a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs index 0a2c1777..88d71f52 100644 --- a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs +++ b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs @@ -255,7 +255,7 @@ fn a_limit_wait_wakes_when_the_limit_allows_runs_again() { fn a_reopened_change_takes_its_run_back() { assert!(!CHANGE_WAIT.contains("then press Retry")); assert!(CHANGE_WAIT.contains("action: cw::closed_action(&dep),")); - assert!(CHANGE_WAIT.contains("out.resumed += check_closed(state).await;")); + assert!(CHANGE_WAIT.contains("out.resumed += check_closed(state, team, repo, pr).await;")); assert_eq!( common::change_wait::after_close(Some(("open", false))), Some(common::change_wait::AfterClose::Reopened) diff --git a/services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs b/services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs new file mode 100644 index 00000000..42bc3975 --- /dev/null +++ b/services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs @@ -0,0 +1,126 @@ +//! xx. Two waits went on after what they waited for had happened. A run +//! stopped because the change it built on closed was told that reopening +//! the change takes it back to waiting by itself. The change was reopened, +//! but only the 15-minute sweep read stopped runs: the reopen webhook went +//! to the review triggers and returned, and the check a pull request event +//! sent skipped stopped runs. On an alert route that waits out a quiet +//! window before posting the recovery, the run that waited on a person for +//! that alert stayed waiting after the recovery posted: only a recovery +//! posted at once closed it, and the later post (the worker's episode +//! check) never reached the run. +//! +//! Guarantees: a pull request closed or reopened sends the team's change +//! check before any return a reopen reaches, naming the change, and that +//! check reads the runs stopped by that change's close (the sweep stays the +//! backstop for every team). A recovery closes its waiting run through one +//! path, `common::run_wake::alert_cleared`, whether it posts at once (the +//! gateway's `alert_delivery`) or after the quiet window (the worker's +//! episode check). + +use common::change_wait::{self as cw, Dependency}; +use common::run_wake::{self, AlertWake}; + +const GITHUB_WEBHOOK: &str = include_str!("../../../../gateway/src/routes/github_webhook.rs"); +const GATEWAY_WAKE: &str = include_str!("../../../../gateway/src/routes/run_wake.rs"); +const COMMON_WAKE: &str = include_str!("../../../../common/src/run_wake.rs"); +const CHANGE_WAIT: &str = include_str!("../change_wait.rs"); +const EPISODES: &str = include_str!("../alert_episodes.rs"); +const MAIN: &str = include_str!("../../main.rs"); + +fn fn_src<'a>(src: &'a str, head: &str) -> &'a str { + let start = src.find(head).unwrap_or_else(|| panic!("{head} is gone")); + let rest = &src[start..]; + let end = [ + "\nfn ", + "\npub fn ", + "\nasync fn ", + "\npub async fn ", + "\n#[cfg(test)]", + ] + .iter() + .filter_map(|h| rest[1..].find(h).map(|i| i + 1)) + .min() + .unwrap_or(rest.len()); + &rest[..end] +} + +/// The reopen GitHub reports reaches the run stopped by that change's close +/// at once; the sweep is only the backstop. +#[test] +fn a_reopened_change_takes_its_run_back_when_github_reports_it() { + assert!(cw::event_moves_change("reopened")); + assert!(cw::event_moves_change("closed")); + let dep = Dependency { + ticket: "WEB-7".into(), + repo: "acme/bookstore-web".into(), + pr: 12, + ..Default::default() + }; + assert!(cw::moved_is(&dep, "acme/bookstore-web", 12)); + assert!(!cw::moved_is(&dep, "acme/bookstore-web", 99)); + assert!(cw::moved_is(&dep, "", 0), "the sweep reads every change"); + assert_eq!( + cw::after_close(Some(("open", false))), + Some(cw::AfterClose::Reopened) + ); + + // The webhook sends the check before the reopen returns to the review + // triggers. + let handler = GITHUB_WEBHOOK + .split("async fn handle_pull_request(") + .nth(1) + .unwrap(); + let check = handler + .find("change_wait_check(action, payload, team_id)") + .expect("the pull request handler sends the change check"); + assert!(check < handler.find("return handle_review_trigger(").unwrap()); + assert!(check < handler.find("if action != \"closed\"").unwrap()); + + // The worker's check reads the stopped runs of that team for that + // change, not only the sweep. + assert!(MAIN.contains("passes::change_wait::check_change(&state, &msg).await;")); + let scoped = fn_src(CHANGE_WAIT, "async fn check_scoped("); + assert!(scoped.contains("check_closed(state, team, repo, pr)")); + assert!(!scoped.contains("if team.is_none()")); + let closed = fn_src(CHANGE_WAIT, "async fn check_closed("); + assert!(closed.contains("super::team_runs::of_team(state, t, &filter)")); + assert!(closed.contains("cw::moved_is(&dep, repo, pr)")); + assert!(CHANGE_WAIT.contains("check_scoped(state, team, \"\", 0)")); +} + +/// A recovery posted after the quiet window closes the waiting run the +/// way a recovery posted at once does: one path. +#[test] +fn a_later_recovery_closes_its_waiting_run_through_the_same_path() { + for why in common::handback::HUMAN_ONLY { + assert_eq!( + run_wake::alert_wake(run_wake::WAITING, why.code(), true), + Some(AlertWake::Close), + "{why:?}" + ); + } + // Both posts end in the one close. + let gateway = fn_src(GATEWAY_WAKE, "pub async fn alert_delivery("); + assert!(gateway.contains("run_wake::alert_cleared(")); + assert!(!GATEWAY_WAKE.contains("async fn close_cleared(")); + let cleared = EPISODES + .split("Decision::Cleared(ended) =>") + .nth(1) + .unwrap(); + let cleared = &cleared[..cleared.find("Decision::Remind =>").unwrap()]; + assert!(cleared.contains("episodes::post_cleared(")); + assert!(cleared.contains("common::run_wake::alert_cleared(")); + assert!(cleared.contains("common::run_wake::alert_ticket_id(&msg.fingerprint)")); + // The close is written once, in common. + let shared = fn_src(COMMON_WAKE, "pub async fn alert_cleared("); + assert!(shared.contains("alert_wake(text(&item, \"status\"), &wait.handback, true)")); + assert!(shared.contains("close_cleared(dynamo, runs_table, team_id, &item)")); + assert_eq!( + COMMON_WAKE.matches("pub async fn close_cleared(").count(), + 1 + ); + // The gateway's ticket for an alert is the one the worker looks up. + let alerts = include_str!("../../../../gateway/src/routes/alerts.rs"); + let ticket = fn_src(alerts, "pub fn ticket_id("); + assert!(ticket.contains("common::run_wake::alert_ticket_id(fingerprint)")); +} diff --git a/services/worker/src/passes/incidents/xz_org_overview_facts_only.rs b/services/worker/src/passes/incidents/xz_org_overview_facts_only.rs new file mode 100644 index 00000000..277bd7bf --- /dev/null +++ b/services/worker/src/passes/incidents/xz_org_overview_facts_only.rs @@ -0,0 +1,459 @@ +//! xz. A leader opened the pull requests page to understand the state of +//! the org's pull requests and found only a list: no summary of what was +//! stuck, on whom, or whether that was usual. The overview above the list +//! answers that, and it is the one place a page could rank people, write a +//! number nothing computed, or mix two teams' pull requests. +//! +//! Guarantees: +//! - no per-person ranking, count or duration is ever returned; a GitHub +//! login appears only as the owner of one item in "Needs attention"; +//! - every number in the summary is a computed fact's value; +//! - one team never sees another's data: every read is keyed by the +//! session's team and the cache by the installation and the team; +//! - an org with no CoderHelm pull requests still gets the whole overview; +//! - the Stale tile and the Stale panel's headline are one number, and no +//! rate is shown on fewer than 10 events. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::pr_history::{Backfill, History}; +use common::pr_overview::{self, Input, Open, Sla}; +use common::pr_record::{self, Item, PrRecord, RequestEvent, ReviewEvent}; +use common::pr_view::{self, Joins}; +use serde_json::Value; +use std::collections::BTreeMap; + +const NOW: i64 = 1_800_000_000; +const H: i64 = 3_600; +const D: i64 = 86_400; +const PEOPLE: [&str; 4] = ["octocat", "mara", "theo", "jun"]; + +fn item(team: &str, rec: &PrRecord) -> Item { + let mut i = Item::new(); + i.insert("pk".into(), AttributeValue::S(team.into())); + i.insert( + "sk".into(), + AttributeValue::S(pr_record::record_sk(&rec.repo, rec.number)), + ); + i.insert( + "doc".into(), + AttributeValue::S(serde_json::to_string(rec).expect("record")), + ); + i +} + +fn src(path: &str) -> String { + let root = concat!(env!("CARGO_MANIFEST_DIR"), "/.."); + std::fs::read_to_string(format!("{root}/{path}")).unwrap_or_else(|e| panic!("{path}: {e}")) +} + +/// An open pull request by a person, waiting on a review by another. +fn open_pr(repo: &str, n: u64, author: &str, reviewer: &str, ready_ago: i64) -> PrRecord { + let mut r = PrRecord::new(repo, n); + r.known = true; + r.title = format!("Show stock per warehouse, part {n}"); + r.author = author.into(); + r.created_at = NOW - ready_ago - H; + r.ready_at = NOW - ready_ago; + r.additions = 120; + r.deletions = 30; + r.requested = vec![reviewer.into()]; + r.request_log.push(RequestEvent { + who: reviewer.into(), + at: NOW - ready_ago, + removed_at: 0, + }); + r.last_author_action_at = NOW - ready_ago; + r.people.insert(author.into(), vec!["author".into()]); + r.people.insert(reviewer.into(), vec!["requested".into()]); + r +} + +/// A merged pull request by a person, reviewed by another. +fn merged(repo: &str, n: u64, author: &str, reviewer: &str, ready_ago: i64, took: i64) -> History { + History { + repo: repo.into(), + number: n, + title: format!("Cache the bestseller list, part {n}"), + author: author.into(), + author_type: if pr_record::is_coderhelm(author) { + "coderhelm".to_string() + } else { + "person".into() + }, + created_at: NOW - ready_ago - H, + ready_at: NOW - ready_ago, + first_human_review_at: NOW - ready_ago + took / 2, + final_approval_at: NOW - ready_ago + took - H, + merged: true, + merged_at: NOW - ready_ago + took, + closed_at: NOW - ready_ago + took, + merged_by: author.into(), + additions: 80, + deletions: 20, + coverage: "human_approved".into(), + review_log: vec![ReviewEvent { + who: reviewer.into(), + state: "APPROVED".into(), + at: NOW - ready_ago + took - H, + human: true, + ..Default::default() + }], + request_log: vec![RequestEvent { + who: reviewer.into(), + at: NOW - ready_ago, + removed_at: 0, + }], + ..Default::default() + } +} + +struct World { + open: Vec, + hist: Vec, + backfill: Vec, +} + +/// The bookstore's org: people's pull requests only, unless `coderhelm`. +fn world(team: &str, coderhelm: bool) -> World { + let mut recs = Vec::new(); + for n in 0..24u64 { + let author = PEOPLE[(n % 4) as usize]; + let reviewer = PEOPLE[((n + 1) % 4) as usize]; + let repo = ["acme/web", "acme/checkout", "acme/api"][(n % 3) as usize]; + recs.push(open_pr( + repo, + 100 + n, + author, + reviewer, + (n as i64 + 1) * 9 * H, + )); + } + if coderhelm { + recs.push(open_pr("acme/web", 300, "coderhelm[bot]", "mara", 2 * D)); + } + let items: Vec = recs.iter().map(|r| item(team, r)).collect(); + let rows = pr_view::rows(team, &items, &Joins::default(), None, NOW); + let open = pr_view::records_of(team, &items) + .into_iter() + .filter_map(|rec| { + let k = format!("{}#{}", rec.repo, rec.number); + let row = rows.iter().find(|r| r.key == k)?.clone(); + Some(Open { rec, row }) + }) + .collect(); + let mut hist = Vec::new(); + for n in 0..60u64 { + let author = PEOPLE[(n % 4) as usize]; + let reviewer = PEOPLE[((n + 2) % 4) as usize]; + let repo = ["acme/web", "acme/checkout", "acme/api"][(n % 3) as usize]; + hist.push(merged( + repo, + 1 + n, + author, + reviewer, + (n as i64 + 2) * D, + (n as i64 % 7 + 1) * 6 * H, + )); + } + let backfill = vec![Backfill { + owner: "acme".into(), + done: true, + months_read: 14, + repos: BTreeMap::from([ + ("acme/web".into(), 20), + ("acme/checkout".into(), 20), + ("acme/api".into(), 20), + ]), + ..Default::default() + }]; + World { + open, + hist, + backfill, + } +} + +fn overview(w: &World) -> Value { + let repo_snaps = BTreeMap::new(); + pr_overview::build(&Input { + open: &w.open, + hist: &w.hist, + snaps: &[], + repo_snaps: &repo_snaps, + backfill: &w.backfill, + org: Some("acme"), + repo: None, + window_days: 7, + sla: Sla::default(), + now: NOW, + }) +} + +/// Every string and key in the answer, with its path. +fn strings(v: &Value, path: &str, out: &mut Vec<(String, String)>) { + match v { + Value::String(s) => out.push((path.to_string(), s.clone())), + Value::Array(a) => a + .iter() + .enumerate() + .for_each(|(i, x)| strings(x, &format!("{path}[{i}]"), out)), + Value::Object(m) => { + for (k, x) in m { + out.push((format!("{path}.{k}#key"), k.clone())); + strings(x, &format!("{path}.{k}"), out); + } + } + _ => {} + } +} + +#[test] +fn no_person_is_ranked_counted_or_timed() { + let o = overview(&world("TEAM#bookstore", true)); + let mut all = Vec::new(); + strings(&o, "", &mut all); + for (path, s) in &all { + for p in PEOPLE { + let named = s + .to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric() && c != '-') + .any(|w| w == p); + if named { + // The only place: the owner of one item that needs attention. + assert!( + path.starts_with(".summary.attention[") && path.ends_with(".owner"), + "{p} appears at {path}: {s}" + ); + } + } + } + // Concentration is a share and a count of reviewers, never a list. + let c = &o["review"]["concentration"]; + assert!(c["top_share"].is_number() || c["top_share"].is_null()); + assert!(c.get("reviewers").is_some_and(Value::is_number)); + assert!( + c["where"].is_null() + || c["where"] + .as_array() + .is_some_and(|a| a.iter().all(|x| x.get("repo").is_some())) + ); +} + +#[test] +fn every_number_in_the_summary_is_a_fact() { + for coderhelm in [true, false] { + let o = overview(&world("TEAM#bookstore", coderhelm)); + let nums = pr_overview::summary_numbers(&o); + assert!(!nums.is_empty(), "the summary carries numbers"); + let facts = o["facts"].as_array().expect("facts"); + for (fact, n) in nums { + assert!( + facts + .iter() + .any(|f| f["id"] == fact && f["value"].as_f64() == Some(n)), + "summary number {n} ({fact}) is not a fact" + ); + } + // No digit is written outside a number part: words carry only + // pull request references (#318), never a count or a duration. + let s = &o["summary"]; + let mut lines: Vec<&Value> = vec![ + &s["verdict"]["parts"], + &s["stability"]["parts"], + &s["coderhelm"]["parts"], + &s["changed"]["parts"], + &s["quiet"]["parts"], + ]; + for a in s["attention"].as_array().unwrap() { + lines.push(&a["parts"]); + } + for line in lines.into_iter().filter_map(Value::as_array) { + for p in line { + if let Some(t) = p.get("t").and_then(Value::as_str) { + let mut words = String::new(); + let mut ref_digits = false; + for c in t.chars() { + if c == '#' { + ref_digits = true; + } else if !c.is_ascii_digit() { + ref_digits = false; + } + if !(ref_digits && c.is_ascii_digit()) { + words.push(c); + } + } + assert!( + !words + .replace("p85", "") + .replace("8-week", "") + .chars() + .any(|c| c.is_ascii_digit()), + "a number outside a fact: {t}" + ); + } + } + } + // Always one stability line and one CoderHelm line. + assert!(!s["stability"]["parts"].as_array().unwrap().is_empty()); + assert!(!s["coderhelm"]["parts"].as_array().unwrap().is_empty()); + } +} + +#[test] +fn one_team_never_sees_another() { + let mine = open_pr("acme/web", 1, "mara", "theo", D); + let mut theirs = open_pr("acme/web", 2, "jun", "theo", D); + theirs.title = "Another team's pull request".into(); + let items = vec![item("TEAM#a", &mine), item("TEAM#b", &theirs)]; + let recs = pr_view::records_of("TEAM#a", &items); + assert_eq!(recs.len(), 1); + let rows = pr_view::rows("TEAM#a", &items, &Joins::default(), None, NOW); + let open: Vec = recs + .into_iter() + .map(|rec| { + let row = rows + .iter() + .find(|r| r.number == rec.number) + .unwrap() + .clone(); + Open { rec, row } + }) + .collect(); + let repo_snaps = BTreeMap::new(); + let o = pr_overview::build(&Input { + open: &open, + hist: &[], + snaps: &[], + repo_snaps: &repo_snaps, + backfill: &[], + org: Some("acme"), + repo: None, + window_days: 7, + sla: Sla::default(), + now: NOW, + }); + assert!(!o.to_string().contains("Another team's")); + assert_eq!(o["aging"]["total"], 1); + + // The route reads only the session's team, and the cache names the + // installation and the team. + // Compared without whitespace, so formatting never hides a read. + let flat = |t: &str| t.chars().filter(|c| !c.is_whitespace()).collect::(); + let r = flat(&src("gateway/src/routes/prs_overview.rs")); + assert!(r.contains(&flat("let team_id = claims.team_id.as_str();"))); + assert!(r.contains(&flat("read_all(&state, team_id)"))); + assert!(r.contains(&flat("pr_view::records_of(team_id, items)"))); + assert!(r.contains(&flat( + "pr_history::all_since(&state.dynamo, table, team_id," + ))); + assert!(r.contains(&flat( + "pr_history::snapshots_of(&state.dynamo, table, team_id," + ))); + assert!(r.contains(&flat( + "items_under(&state, team_id, pr_history::BACKFILL_PREFIX)" + ))); + assert!( + r.contains(&flat("read_key(installation_id,")) + && r.contains(&flat("prs_overview#{team_id}#")) + ); + assert!(!r.contains(&flat("q.team")) && !r.contains(&flat("team: Option"))); + let perms = src("gateway/src/permissions.rs"); + let view = &perms[perms.find("\"prs::list_prs\"").expect("view list")..]; + assert!( + view[..400].contains("\"prs_overview::get_overview\""), + "the overview is under \"view\"" + ); + let teams = src("worker/src/passes/incidents/bm_teams_never_cross.rs"); + assert!(teams.contains("gateway/src/routes/prs_overview.rs::OVERVIEW")); +} + +#[test] +fn an_org_with_no_coderhelm_pull_requests_gets_the_whole_overview() { + let o = overview(&world("TEAM#bookstore", false)); + assert_eq!(o["aging"]["total"], 24); + assert!( + o["thresholds"]["cycle"].is_object(), + "percentiles from people's merges" + ); + assert_eq!(o["repos"].as_array().unwrap().len(), 3); + assert!(o["review"]["coverage"]["merged"].as_u64().unwrap() > 0); + assert!(o["review"]["first_review_human"].is_object()); + assert_eq!(o["coderhelm"]["author"]["opened"], 0); + let ch: String = o["summary"]["coderhelm"]["parts"] + .as_array() + .unwrap() + .iter() + .filter_map(|p| p.get("t").and_then(Value::as_str)) + .collect(); + assert!(ch.contains("No PRs from CoderHelm"), "{ch}"); + assert!(o["summary"]["verdict"]["parts"] + .as_array() + .is_some_and(|a| !a.is_empty())); +} + +#[test] +fn the_stale_tile_is_the_stale_panels_headline_and_rates_need_ten() { + let w = world("TEAM#bookstore", true); + let o = overview(&w); + let tile = o["summary"]["tiles"] + .as_array() + .unwrap() + .iter() + .find(|t| t["fact"] == "stale") + .unwrap() + .clone(); + assert_eq!(tile["value"], o["stale"]["stale"]); + assert_eq!(tile["value"], o["conditions"]["stale"]["count"]); + + // Under 10 merges, no rate. + let few = World { + open: Vec::new(), + hist: w + .hist + .into_iter() + .take(3) + .map(|mut h| { + h.merged_at = NOW - H; + h.closed_at = NOW - H; + h + }) + .collect(), + backfill: w.backfill, + }; + let o = overview(&few); + assert!(o["review"]["depth"]["merged_without_review"].is_null()); + assert!(o["summary"]["tiles"][2]["value"].is_null()); + assert!(o["coderhelm"]["author"]["merge_rate"].is_null()); +} + +#[test] +fn what_isnt_stored_is_named_never_estimated() { + let o = overview(&world("TEAM#bookstore", true)); + let missing: Vec<&str> = o["missing"] + .as_array() + .unwrap() + .iter() + .filter_map(|m| m["path"].as_str()) + .collect(); + for path in [ + "failures.main_red", + "conditions.blocked_by_main", + "review.funnel", + "coderhelm.exceptions.cost_per_merged", + ] { + assert!(missing.contains(&path), "{path} is named in missing"); + } + assert!(o["failures"]["main_red"].is_null()); + assert!(o["conditions"]["blocked_by_main"].is_null()); + // Before the backfill finishes, the history is young and says so. + let mut w = world("TEAM#bookstore", true); + w.backfill[0].done = false; + let o = overview(&w); + assert_eq!(o["history"]["young"], true); + assert_eq!(o["history"]["backfill"]["done"], false); + assert!(o["missing"] + .as_array() + .unwrap() + .iter() + .any(|m| m["path"] == "history")); +}