From 3dd804598f913af842955f6dcc34708ff0df69d4 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 11:52:38 -0500 Subject: [PATCH 1/7] Every open pull request has a record and one state, read by the merge gates and the new pull requests view A durable record per open pull request in the team's connected repositories, written from the webhooks already received for every author and kept honest by a bounded GraphQL sync under the shared GitHub budget (sweep:dashboard_prs). One function (pr_needs::decide) decides each pull request's state, its turn and what it needs next from whom; the run's watch stores its standing and the reviewer's auto-merge gate merges only what it calls ready. GET /api/prs and GET /api/prs/detail serve the dashboard's pull requests page under the "view" capability. Incident case xw holds it. --- .../xw_every_open_pr_has_one_state.md | 5 + docs/pull-requests.md | 33 + services/common/contract/worker_messages.json | 1 + services/common/src/dlq.rs | 2 + services/common/src/github_budget.rs | 7 +- services/common/src/lib.rs | 3 + services/common/src/messages.rs | 13 + services/common/src/pr_needs.rs | 1470 ++++++++++++++++ services/common/src/pr_record.rs | 1545 +++++++++++++++++ services/common/src/pr_view.rs | 1045 +++++++++++ services/gateway/src/main.rs | 2 + services/gateway/src/permissions.rs | 2 + services/gateway/src/routes/github_webhook.rs | 37 +- services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/prs.rs | 600 +++++++ services/worker/src/main.rs | 13 + services/worker/src/passes/await_merge.rs | 72 + .../passes/incidents/bm_teams_never_cross.rs | 1 + .../xw_every_open_pr_has_one_state.rs | 331 ++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/pr_records.rs | 227 +++ services/worker/src/passes/pr_watch.rs | 4 +- 22 files changed, 5411 insertions(+), 4 deletions(-) create mode 100644 docs/incidents/xw_every_open_pr_has_one_state.md create mode 100644 docs/pull-requests.md create mode 100644 services/common/src/pr_needs.rs create mode 100644 services/common/src/pr_record.rs create mode 100644 services/common/src/pr_view.rs create mode 100644 services/gateway/src/routes/prs.rs create mode 100644 services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs create mode 100644 services/worker/src/passes/pr_records.rs diff --git a/docs/incidents/xw_every_open_pr_has_one_state.md b/docs/incidents/xw_every_open_pr_has_one_state.md new file mode 100644 index 000000000..d2c4d511c --- /dev/null +++ b/docs/incidents/xw_every_open_pr_has_one_state.md @@ -0,0 +1,5 @@ +# xw. `xw_every_open_pr_has_one_state` + +**What happened:** A team asked which pull requests were open in its repositories and what each one needed. Nothing could say. The gateway dropped every event of a pull request CoderHelm hadn't opened, the reviewer's records covered only the pull requests it reviewed and expired after 30 days, and the run page, the reviewer's auto-merge gate and the reviewer page each read what a pull request needed in their own way, so they could disagree. + +**The guarantee:** Every open pull request in the team's connected repositories has one record (`pr_record`), written from its events whoever opened it (pull request, review, comment, check run, check suite, status and push) and from a bounded sync at install and once an hour, with no expiry while it is open. Each one has exactly one state from one function (`pr_needs::decide`); one whose facts aren't known yet is `unknown`, shown and counted, never dropped. The run's watch stores the standing that function decides and the reviewer's auto-merge gate merges only what it says is ready, so the gates and the pull requests list can't disagree. The list is read under the session's team only, and a record of another team never reaches a row. diff --git a/docs/pull-requests.md b/docs/pull-requests.md new file mode 100644 index 000000000..0a78256e4 --- /dev/null +++ b/docs/pull-requests.md @@ -0,0 +1,33 @@ +# The pull requests view + +Every open pull request in a team's connected repositories, people's as much as CoderHelm's: where it is, who worked on it, the one state it is in, and what it needs next from whom. The dashboard's **Pull requests** page reads it from `GET /api/prs`. + +## The record + +One settings-table item per pull request (`pk` = team id, `sk = PRREC##`), its body a JSON document written with a version check (`services/common/src/pr_record.rs`). + +- **Written from the events CoderHelm already receives**, for every pull request: `pull_request`, `pull_request_review`, review and issue comments, `check_run`, `check_suite`, `status` and `push`. A `status` or `push` event finds its pull request through a pointer item by head commit (`PRRECHEAD#`) or branch (`PRRECREF#`). +- **Kept honest by a sync** (`services/worker/src/passes/pr_records.rs`): one GraphQL search per organization of the team's connected repositories. It fills what events don't carry (the review decision, the branch's rules, conflicts, open conversations), adds pull requests opened before the install, and removes records of pull requests no longer open (only when the search was read to its end, and never one an event touched in the last hour). +- **No expiry while open.** A closed or merged pull request is kept for three days. +- **What it holds:** the author; who worked on it (committers, reviewers, commenters, and who asked CoderHelm); requested reviewers and teams; each person's latest review; the review decision; the checks on the head against the branch's required checks; conflicts; draft; open conversations; labels; links to stacked pull requests, to the same run's other pull requests (`plan_repos`, `repo_ci`) and to the ones named under the description's Compatibility heading; CoderHelm's run; a timeline of the newest events; and the wait ledger (who held the turn, and since when). + +## One state per pull request + +`services/common/src/pr_needs.rs` decides the state from the facts, first match wins: merged, closed, in the merge queue, left the queue, CoderHelm working, needs a decision, draft, waiting on another pull request, conflicts, checks failing, changes requested, re-review, needs a reviewer, needs review, needs a code owner, open conversations, checks running, ready with auto-merge on, ready to merge. A pull request whose facts aren't known yet is **not synced yet** (`unknown`): shown and counted, never dropped. + +Each state has a turn (a person, CoderHelm, the machines, or done) and one sentence that names the block, who acts, and the rule's source when a rule is the reason (the repository's rule, CODEOWNERS, a required check, the team's own rule). "Ready" is said only when every requirement is met. + +The same function is the merge gates' decision: the run's pull request watch stores the standing it decides (`run_standing`), and the reviewer's auto-merge gate merges only what it says is ready. The list, the run page and the gate can't disagree. + +## The API + +- `GET /api/prs`: filters `org`, `repo`, `turn` (`you`, `person`, `coderhelm`, `machines`, `done`), `state`, `person`, `q`, `view` (`my_turn`, `coderhelm_working`, `needs_decision`, `ready`, `stale`); `limit` (up to 200) and `cursor`, with `next` on the response. Counts by turn, state, repository, organization and view come over the scope before the other filters. +- `GET /api/prs/detail?repo=&number=`: the row, the path to merge, the wait ledger and the timeline with CoderHelm's runs. + +Both need the "view" capability. The team is always the session's; a record of another team never reaches a row (`docs/incidents/xw_every_open_pr_has_one_state.md`). + +## Cost + +- Reading the list costs no GitHub requests: it reads the team's records, its runs on them (one batched read) and the reviewer's records, and reuses them for 10 seconds per installation and team. +- The sync spends from the installation's shared GitHub budget as `sweep:dashboard_prs`: at most 30 requests an hour, at most 10 pages of 30 pull requests per organization each time, once an hour per team and once at install. It runs only while the budget leaves the runs their share. +- Each webhook costs one read and one write of its record. diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index cf2dceb2e..4c6047dba 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -12,6 +12,7 @@ "infra_analyze": {"type":"infra_analyze","team_id":"TEAM#team-a","triggered_by":"someone","repo":"acme/widgets"}, "resume": {"type":"resume","team_id":"TEAM#team-a","run_id":"r1","installation_id":1}, "change_wait_check": {"type":"change_wait_check","team_id":"TEAM#team-a"}, + "pr_records_sync": {"type":"pr_records_sync","team_id":"TEAM#team-a","installation_id":1}, "review": {"type":"review","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"head_sha":"abc","label":"coderhelm-review","question":"why?","trigger":"labeled","dedup_key":"d","reply_to_comment_id":6,"requested_by":"someone"}, "webhook_emit": {"type":"webhook_emit","team_id":"TEAM#team-a","event":{"id":"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W","type":"run.failed","created_at":"2026-10-26T14:31:47.512Z","team_id":"TEAM#team-a","api_version":"2026-10-26","data":{"run_id":"r1"}}}, "webhook_send": {"type":"webhook_send","team_id":"TEAM#team-a","endpoint_id":"ep_01jbendpt4a7b0c3d6e9f2g5h8","event_id":"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W","delivery_id":"01hzzdelivery","due_at":1792416387}, diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index d8fd9907d..1177ff7ad 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -84,6 +84,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "role_reads_wait", // A team's runs waiting for another change read it again. "change_wait_check", + // A team's open pull requests read into their records, at install. + "pr_records_sync", // A model call's usage, held because its counters couldn't be written. "usage_record", // Knowledge sources: the scheduled sweep, and one source's sync. diff --git a/services/common/src/github_budget.rs b/services/common/src/github_budget.rs index 60797cc3c..526c44312 100644 --- a/services/common/src/github_budget.rs +++ b/services/common/src/github_budget.rs @@ -130,6 +130,10 @@ pub mod caller { pub const SWEEP_QUARANTINE: &str = "sweep:quarantine"; /// Duplicate follow-ups closing themselves. pub const SWEEP_FOLLOWUP_DEDUPE: &str = "sweep:followup_dedupe"; + /// The dashboard's pull requests view: the sync of every open pull + /// request's record (`common::pr_record`), one GraphQL search per + /// organization, at install and once an hour. + pub const SWEEP_DASHBOARD_PRS: &str = "sweep:dashboard_prs"; /// The security release's reads (a finding's pull request or run) /// while `sweep:security` is held: a few each sweep, so the release @@ -151,7 +155,7 @@ pub mod caller { (SWEEP_REVIEW, 120), (SWEEP_DRAFTS, 120), (SWEEP_PR_WATCH, 240), - (SWEEP_DEPLOYS, 270), + (SWEEP_DEPLOYS, 240), (SWEEP_REVIEW_REMINDER, 120), (SWEEP_PR_OUTCOMES, 120), (SWEEP_SKILLS, 60), @@ -166,6 +170,7 @@ pub mod caller { (SWEEP_WEEKLY, 100), (SWEEP_QUARANTINE, 90), (SWEEP_FOLLOWUP_DEDUPE, 30), + (SWEEP_DASHBOARD_PRS, 30), ]; } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 458b6493f..9c7a9526b 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -275,10 +275,12 @@ pub mod pr_dependency; pub mod pr_facts; /// Where each part of a description goes, and how a reader would judge it. pub mod pr_layout; +pub mod pr_needs; /// What happened to a PR CoderHelm opened, read from GitHub. pub mod pr_outcome; /// The last read of a description before it is saved, verified. pub mod pr_reader; +pub mod pr_record; /// The final read of a description before it is posted. pub mod pr_review; /// The work around a pull request that is not in its diff, each step with @@ -286,6 +288,7 @@ pub mod pr_review; pub mod pr_steps; /// A repository's pull request template as the description's structure. pub mod pr_template; +pub mod pr_view; pub mod preview; pub mod preview_access; pub mod preview_find; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index a3915979f..cc0cb05f7 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -243,6 +243,10 @@ pub enum WorkerMessage { /// dependency 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 + /// (`pr_record`): at install, and when repositories are added. + #[serde(rename = "pr_records_sync")] + PrRecordsSync(PrRecordsSyncMessage), /// One plugin run: a brief, a schedule or a release (see /// `plugins::run`). #[serde(rename = "plugin_run")] @@ -518,6 +522,7 @@ impl WorkerMessage { | WorkerMessage::RunWaiting(_) | WorkerMessage::RoleReadsWait(_) | WorkerMessage::ChangeWaitCheck(_) + | WorkerMessage::PrRecordsSync(_) | WorkerMessage::StackMerged(_) | WorkerMessage::LogAutofix | WorkerMessage::AwsPermissionsSweep @@ -601,6 +606,7 @@ impl WorkerMessage { | WorkerMessage::RunWaiting(_) | WorkerMessage::RoleReadsWait(_) | WorkerMessage::ChangeWaitCheck(_) + | WorkerMessage::PrRecordsSync(_) | WorkerMessage::StackMerged(_) | WorkerMessage::PluginRun(_) | WorkerMessage::PluginPublish(_) @@ -948,6 +954,13 @@ pub struct RunWaitingMessage { pub why: String, } +/// Read a team's open pull requests into their records. +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct PrRecordsSyncMessage { + pub team_id: String, + pub installation_id: u64, +} + /// Read again the dependency of a team's runs waiting for another change. #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] pub struct ChangeWaitCheckMessage { diff --git a/services/common/src/pr_needs.rs b/services/common/src/pr_needs.rs new file mode 100644 index 000000000..4823cd85f --- /dev/null +++ b/services/common/src/pr_needs.rs @@ -0,0 +1,1470 @@ +//! What an open pull request needs next, and from whom: one state, one +//! turn, one sentence. Any pull request in the team's repositories, people's +//! as much as CoderHelm's. +//! +//! The run page once had a standing for CoderHelm's own pull requests +//! ([`merge_standing`]) and the reviewer's auto-merge gate had its own +//! decision (`await_merge::decide_gate`), while a person's pull request +//! CoderHelm never touched had no answer at all. A list of every open pull +//! request built a third reading would have said "ready" where the gate +//! held, or "needs review" where the run page said CoderHelm merges it. +//! +//! [`decide`] is the one reading. It takes the facts in the order they hold +//! the merge, first match wins, and returns exactly one [`State`] with its +//! [`Turn`] and a [`Next`] that names the block, who acts, and the source of +//! the rule when a rule is the reason (the repository's rule, CODEOWNERS, a +//! required check, the team's own rule). No fact set falls through: what +//! isn't known yet is [`State::Unknown`], shown, never dropped. +//! +//! - For CoderHelm's own pull request with a run, the standing is +//! [`merge_standing::decide`]'s (the worker's pull request watch stores +//! [`Needs::standing`] from here), so the run page, the gate and the list +//! read one decision. +//! - The reviewer's auto-merge gate merges only when [`decide`] says the +//! pull request is ready (`await_merge::decide_gate`). +//! - A typed hand-off ([`crate::person_only::PersonOnly`]) is shown as the +//! line it is; CoderHelm's own limit ([`crate::person_only::OwnProblem`]) +//! stays CoderHelm's turn, never a person's to-do. + +use serde::{Deserialize, Serialize}; + +use crate::merge_standing::{self, Standing}; + +/// The one state a pull request is in, in the order [`decide`] tries them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum State { + #[serde(rename = "merged")] + Merged, + #[serde(rename = "closed")] + Closed, + #[serde(rename = "in_queue")] + InQueue, + #[serde(rename = "left_queue")] + LeftQueue, + #[serde(rename = "coderhelm_working")] + CoderHelmWorking, + #[serde(rename = "needs_decision")] + NeedsDecision, + #[serde(rename = "draft")] + Draft, + #[serde(rename = "waiting_on_pr")] + WaitingOnPr, + #[serde(rename = "conflicts")] + Conflicts, + #[serde(rename = "checks_failing")] + ChecksFailing, + #[serde(rename = "changes_requested")] + ChangesRequested, + #[serde(rename = "re_review")] + ReReview, + #[serde(rename = "needs_reviewer")] + NeedsReviewer, + #[serde(rename = "needs_review")] + NeedsReview, + #[serde(rename = "needs_code_owner")] + NeedsCodeOwner, + #[serde(rename = "open_threads")] + OpenThreads, + #[serde(rename = "checks_running")] + ChecksRunning, + #[serde(rename = "ready_auto_merge")] + ReadyAutoMerge, + #[serde(rename = "ready_to_merge")] + ReadyToMerge, + #[serde(rename = "unknown")] + Unknown, +} + +/// Every state, in precedence order. +pub const ALL: &[State] = &[ + State::Merged, + State::Closed, + State::InQueue, + State::LeftQueue, + State::CoderHelmWorking, + State::NeedsDecision, + State::Draft, + State::WaitingOnPr, + State::Conflicts, + State::ChecksFailing, + State::ChangesRequested, + State::ReReview, + State::NeedsReviewer, + State::NeedsReview, + State::NeedsCodeOwner, + State::OpenThreads, + State::ChecksRunning, + State::ReadyAutoMerge, + State::ReadyToMerge, + State::Unknown, +]; + +impl State { + /// The stable code (the API's `state`). + pub fn code(self) -> &'static str { + match self { + State::Merged => "merged", + State::Closed => "closed", + State::InQueue => "in_queue", + State::LeftQueue => "left_queue", + State::CoderHelmWorking => "coderhelm_working", + State::NeedsDecision => "needs_decision", + State::Draft => "draft", + State::WaitingOnPr => "waiting_on_pr", + State::Conflicts => "conflicts", + State::ChecksFailing => "checks_failing", + State::ChangesRequested => "changes_requested", + State::ReReview => "re_review", + State::NeedsReviewer => "needs_reviewer", + State::NeedsReview => "needs_review", + State::NeedsCodeOwner => "needs_code_owner", + State::OpenThreads => "open_threads", + State::ChecksRunning => "checks_running", + State::ReadyAutoMerge => "ready_auto_merge", + State::ReadyToMerge => "ready_to_merge", + State::Unknown => "unknown", + } + } + + /// The short label shown on the state chip. + pub fn label(self) -> &'static str { + match self { + State::Merged => "Merged", + State::Closed => "Closed", + State::InQueue => "In merge queue", + State::LeftQueue => "Left the queue", + State::CoderHelmWorking => "CoderHelm working", + State::NeedsDecision => "Needs a decision", + State::Draft => "Draft", + State::WaitingOnPr => "Waiting on a pull request", + State::Conflicts => "Conflicts", + State::ChecksFailing => "Checks failing", + State::ChangesRequested => "Changes requested", + State::ReReview => "Re-review", + State::NeedsReviewer => "Needs a reviewer", + State::NeedsReview => "Needs review", + State::NeedsCodeOwner => "Needs a code owner", + State::OpenThreads => "Open conversations", + State::ChecksRunning => "Checks running", + State::ReadyAutoMerge => "Ready, auto-merge on", + State::ReadyToMerge => "Ready to merge", + State::Unknown => "Not synced yet", + } + } + + pub fn from_code(code: &str) -> Option { + ALL.iter().copied().find(|s| s.code() == code) + } + + /// Ready means every requirement is met; nothing else is called ready. + pub fn is_ready(self) -> bool { + matches!(self, State::ReadyAutoMerge | State::ReadyToMerge) + } +} + +/// Who holds the next move. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Turn { + #[serde(rename = "person")] + Person, + #[serde(rename = "coderhelm")] + CoderHelm, + #[serde(rename = "machines")] + Machines, + #[serde(rename = "done")] + Done, +} + +impl Turn { + pub fn code(self) -> &'static str { + match self { + Turn::Person => "person", + Turn::CoderHelm => "coderhelm", + Turn::Machines => "machines", + Turn::Done => "done", + } + } +} + +/// Where a rule that holds the merge is set. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Rule { + /// The repository's review rule (branch protection or a ruleset). + #[serde(rename = "repo_rule")] + RepoRule, + /// The repository's CODEOWNERS file. + #[serde(rename = "codeowners")] + Codeowners, + /// A check the branch's rules require. + #[serde(rename = "required_check")] + RequiredCheck, + /// The team's own rule in CoderHelm (auto-merge off, a person's + /// approval before CoderHelm merges). + #[serde(rename = "team_rule")] + TeamRule, + /// A branch rule GitHub enforces without naming it. + #[serde(rename = "branch_rule")] + BranchRule, +} + +impl Rule { + /// The words in brackets after the block. + pub fn words(self) -> &'static str { + match self { + Rule::RepoRule => "repo rule", + Rule::Codeowners => "CODEOWNERS", + Rule::RequiredCheck => "required check", + Rule::TeamRule => "team rule", + Rule::BranchRule => "branch rule", + } + } +} + +/// Who an actor in [`Next::from`] is: `coderhelm`, `ci`, `queue`, +/// `nobody`, `person:` or `team:/`. +pub fn person(login: &str) -> String { + format!("person:{}", login.trim_start_matches('@')) +} +pub const CODERHELM: &str = "coderhelm"; +pub const CI: &str = "ci"; +pub const QUEUE: &str = "queue"; +pub const NOBODY: &str = "nobody"; + +/// The next step: what, from whom, since when, and the rule's source. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Next { + /// Stable code: the state's code, or for CoderHelm's own pull request + /// the standing's ([`merge_standing::Standing::code`]). + pub code: String, + /// One sentence: the block first, then who. + pub text: String, + /// Who acts ([`person`], [`CODERHELM`], [`CI`], [`QUEUE`], [`NOBODY`]). + pub from: Vec, + /// When the situation began (epoch seconds; 0 when not known). + pub since: i64, + /// Where the rule is set, when a rule is the reason. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rule: Option, +} + +/// One line of the path to merge. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Step { + /// `checks`, `approvals`, `conflicts`, `threads`, `coderhelm_review`, + /// `draft`, `queue`. + pub key: String, + /// `done`, `waiting`, `blocked` or `none` (doesn't apply). + pub mark: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +/// The decision. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Needs { + pub state: State, + pub turn: Turn, + pub next: Next, + /// For CoderHelm's own pull request with its run's facts: the standing + /// the run page shows (the same decision, in its words). + pub standing: Option, +} + +/// The checks on the head. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Checks { + /// Any check was read for the head (a check event, or the sync). + pub known: bool, + pub total: u32, + pub passed: u32, + pub failed: Vec, + pub running: Vec, + /// The checks the base branch's rules require, when read. + pub required: Vec, +} + +impl Checks { + /// Failing checks that hold the merge: the required ones when the + /// branch's list is known, every failing one when it isn't. + pub fn blocking(&self) -> (Vec, Option) { + if self.required.is_empty() { + return (self.failed.clone(), None); + } + let req: Vec = self + .failed + .iter() + .filter(|f| self.required.iter().any(|r| r.eq_ignore_ascii_case(f))) + .cloned() + .collect(); + (req, Some(Rule::RequiredCheck)) + } +} + +/// CoderHelm stopped and waits on a person through a typed hand-off. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Stop { + /// The hand-off's code (`person_only::PersonOnly::code`, or the run's + /// `handback` reason). + pub code: String, + /// The hand-off's own line, as the run shows it. + pub text: String, + /// The person it names, when it names one. + pub person: String, +} + +/// CoderHelm's own pull request's standing: decided here from its facts +/// (the worker's watch), or as the watch stored it (the list reads it). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OwnStanding { + Facts(merge_standing::Facts), + Decided(Standing), +} + +/// CoderHelm's run on this pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Own { + pub run_id: String, + /// The person who asked CoderHelm (the pull request is "for" them). + pub requester: String, + /// A run or round works on it now. + pub active: bool, + /// What it does now ("fixing CI", "addressing 3 review comments"). + pub what: String, + /// The fix round, from 1; 0 when not counted. + pub round: u32, + /// The run waits on a person, through a typed hand-off. + pub stopped: Option, + /// CoderHelm met a limit of its own: its line, CoderHelm's turn. + pub own_problem: Option, + pub standing: Option, +} + +/// Everything known about one pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Facts { + /// The pull request itself was read (a webhook or the sync). + pub known: bool, + pub merged: bool, + pub closed: bool, + pub draft: bool, + pub head: String, + pub base: String, + pub author: String, + pub author_is_coderhelm: bool, + pub merged_by: String, + /// In a merge queue, with its position when known. + pub in_queue: bool, + pub queue_position: Option<(u32, u32)>, + /// Removed from the merge queue since the last push: the reason. + pub left_queue: Option, + pub own: Option, + /// CoderHelm's reviewer is reviewing the head now. + pub reviewing: bool, + /// CoderHelm's latest review verdict and the commit it is on. + pub coderhelm_verdict: Option<(String, String)>, + /// Pull requests that merge first and are still open (`owner/repo#n`). + pub waits_on: Vec, + /// `Some(true)` conflicts, `Some(false)` merges cleanly, `None` GitHub + /// hasn't said. + pub conflict: Option, + pub checks: Checks, + /// GitHub's `reviewDecision`, when read. + pub review_decision: Option, + /// People whose latest review asks for changes. + pub changes_requested_by: Vec, + /// The author pushed after the latest request for changes. + pub pushed_since_changes: bool, + /// People whose approval counts on the head. + pub approved_by: Vec, + pub requested: Vec, + pub requested_teams: Vec, + /// Approvals the repository's rule requires (0 none or not known). + pub approvals_required: u32, + /// The team's rule: a person approves before CoderHelm merges. + pub team_requires_approval: bool, + pub codeowners_required: bool, + pub threads_required: bool, + pub open_threads: u32, + pub thread_authors: Vec, + /// GitHub's auto-merge is on. + pub auto_merge: bool, + /// CoderHelm's auto-merge gate is armed on it: CoderHelm merges. + pub coderhelm_merges: bool, + /// GitHub reports the merge blocked with nothing above explaining it. + pub blocked_by_rules: bool, + /// When the current situation began (epoch seconds). + pub since: i64, +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +fn at(list: &[String]) -> String { + let names: Vec = list + .iter() + .map(|l| format!("@{}", l.trim_start_matches('@'))) + .collect(); + match names.len() { + 0 => String::new(), + 1 => names[0].clone(), + 2 => format!("{} and {}", names[0], names[1]), + _ => format!( + "{} and {}", + names[..names.len() - 1].join(", "), + names[names.len() - 1] + ), + } +} + +fn names(list: &[String], max: usize) -> String { + let mut out: Vec = list.iter().take(max).cloned().collect(); + if list.len() > max { + out.push(format!("{} more", list.len() - max)); + } + out.join(", ") +} + +fn rule_tag(rule: Option) -> String { + rule.map(|r| format!(" ({})", r.words())) + .unwrap_or_default() +} + +/// Turn for a list of actors: CoderHelm's when it's CoderHelm, the +/// machines' when it's CI, the queue or nobody, a person's otherwise. +pub fn turn_of(from: &[String]) -> Turn { + if from.iter().any(|f| f == CODERHELM) { + Turn::CoderHelm + } else if from + .iter() + .any(|f| f.starts_with("person:") || f.starts_with("team:")) + { + Turn::Person + } else { + Turn::Machines + } +} + +fn need(state: State, text: String, from: Vec, since: i64, rule: Option) -> Needs { + let turn = match state { + State::Merged | State::Closed => Turn::Done, + State::InQueue | State::ChecksRunning | State::ReadyAutoMerge | State::Unknown => { + Turn::Machines + } + State::CoderHelmWorking => Turn::CoderHelm, + _ => turn_of(&from), + }; + Needs { + state, + turn, + next: Next { + code: state.code().to_string(), + text, + from, + since, + rule, + }, + standing: None, + } +} + +/// The people a step is the author's: CoderHelm's when it wrote the pull +/// request for someone, the author otherwise. +fn author_from(f: &Facts) -> Vec { + if f.author_is_coderhelm { + return vec![CODERHELM.to_string()]; + } + if f.author.is_empty() { + vec![NOBODY.to_string()] + } else { + vec![person(&f.author)] + } +} + +fn author_words(f: &Facts) -> String { + if f.author_is_coderhelm { + "CoderHelm".to_string() + } else if f.author.is_empty() { + "the author".to_string() + } else { + format!("@{}", f.author) + } +} + +/// The state of `repo`'s pull request from its facts, first match wins. +pub fn decide(repo: &str, f: &Facts) -> Needs { + let mut n = decide_state(repo, f); + if n.standing.is_none() { + n.standing = f.own.as_ref().and_then(|o| own_standing(repo, o)); + } + n +} + +/// The standing of CoderHelm's own run's pull request, through [`decide`]: +/// what the worker's pull request watch stores on the run, so the run page +/// shows the decision this module makes. +pub fn run_standing(repo: &str, facts: &merge_standing::Facts) -> Standing { + let f = Facts { + known: true, + merged: facts.merged, + closed: facts.closed, + draft: facts.draft, + head: facts.head.clone(), + author_is_coderhelm: true, + own: Some(Own { + standing: Some(OwnStanding::Facts(facts.clone())), + ..Default::default() + }), + ..Default::default() + }; + decide(repo, &f) + .standing + .unwrap_or_else(|| merge_standing::decide(repo, facts)) +} + +fn decide_state(repo: &str, f: &Facts) -> Needs { + let since = f.since; + if !f.known { + return need( + State::Unknown, + "Not synced yet: CoderHelm has events for this pull request but not the pull \ + request itself; the next sync reads it." + .into(), + vec![NOBODY.into()], + since, + None, + ); + } + if f.merged { + let by = if f.merged_by.is_empty() { + String::new() + } else if f.merged_by.contains("coderhelm") { + " by CoderHelm".to_string() + } else { + format!(" by @{}", f.merged_by) + }; + return need(State::Merged, format!("Merged{by}."), vec![], since, None); + } + if f.closed { + return need( + State::Closed, + "Closed without merging.".into(), + vec![], + since, + None, + ); + } + if f.in_queue { + let pos = f + .queue_position + .map(|(p, n)| format!(": {p} of {n}")) + .unwrap_or_default(); + return need( + State::InQueue, + format!("In the merge queue{pos}; GitHub merges it when its turn comes."), + vec![QUEUE.into()], + since, + None, + ); + } + let own_active = f.own.as_ref().is_some_and(|o| o.active); + if let Some(reason) = &f.left_queue { + let (who, words) = if own_active { + ( + vec![CODERHELM.to_string()], + "CoderHelm is fixing it".to_string(), + ) + } else { + (author_from(f), format!("{} to push a fix", author_words(f))) + }; + return need( + State::LeftQueue, + format!( + "Left the merge queue: {}; {words}.", + reason.trim_end_matches('.') + ), + who, + since, + None, + ); + } + if let Some(own) = &f.own { + if own.active || own.own_problem.is_some() { + let round = if own.round > 1 { + format!(", round {}", own.round) + } else { + String::new() + }; + let what = if own.what.is_empty() { + "working on it".to_string() + } else { + own.what.clone() + }; + let text = match &own.own_problem { + Some(line) if !own.active => line.clone(), + _ => format!("CoderHelm is {what}{round}."), + }; + let mut n = need( + State::CoderHelmWorking, + text, + vec![CODERHELM.into()], + since, + None, + ); + n.standing = own_standing(repo, own); + return n; + } + if let Some(stop) = &own.stopped { + let who = [&stop.person, &own.requester, &f.author] + .into_iter() + .find(|p| !p.is_empty() && !p.contains("coderhelm")) + .map(|p| person(p)) + .unwrap_or_else(|| NOBODY.to_string()); + let rule = (stop.code == "approval").then_some(Rule::TeamRule); + let named = if who == NOBODY { + String::new() + } else { + format!( + " for {}", + at(&[who.trim_start_matches("person:").to_string()]) + ) + }; + let mut n = need( + State::NeedsDecision, + format!( + "CoderHelm stopped{named}: {}", + stop.text.trim().trim_end_matches('.').to_string() + "." + ), + vec![who], + since, + rule, + ); + n.standing = own_standing(repo, own); + return n; + } + if let Some(standing) = own_standing(repo, own) { + return from_standing(f, own, standing); + } + } + if f.reviewing { + return need( + State::CoderHelmWorking, + format!("CoderHelm is reviewing the head `{}`.", short(&f.head)), + vec![CODERHELM.into()], + since, + None, + ); + } + if f.draft { + return need( + State::Draft, + format!( + "Still a draft: {} marks it ready for review when it is.", + author_words(f) + ), + author_from(f), + since, + None, + ); + } + if !f.waits_on.is_empty() { + return need( + State::WaitingOnPr, + format!( + "Merges after {}, still open; {} follows it.", + names(&f.waits_on, 3), + author_words(f) + ), + author_from(f), + since, + None, + ); + } + if f.conflict == Some(true) { + let base = if f.base.is_empty() { + "its base" + } else { + &f.base + }; + let tail = if f.author_is_coderhelm { + "CoderHelm merges the base in and resolves them".to_string() + } else { + format!( + "{} resolves them, or asks CoderHelm with `@coderhelm fix conflicts`", + author_words(f) + ) + }; + return need( + State::Conflicts, + format!("Conflicts with `{base}`: {tail}."), + author_from(f), + since, + None, + ); + } + let (blocking, check_rule) = f.checks.blocking(); + if !blocking.is_empty() { + let tail = if f.author_is_coderhelm { + "CoderHelm fixes them".to_string() + } else { + format!( + "{} fixes them, or asks CoderHelm with `@coderhelm fix ci`", + author_words(f) + ) + }; + return need( + State::ChecksFailing, + format!( + "Checks fail on `{}`{}: {}; {tail}.", + short(&f.head), + rule_tag(check_rule), + names(&blocking, 4) + ), + author_from(f), + since, + check_rule, + ); + } + if !f.changes_requested_by.is_empty() { + if f.pushed_since_changes { + return need( + State::ReReview, + format!( + "{} pushed since the request for changes: {} reviews again.", + author_words(f), + at(&f.changes_requested_by) + ), + f.changes_requested_by.iter().map(|p| person(p)).collect(), + since, + None, + ); + } + return need( + State::ChangesRequested, + format!( + "Changes requested by {}: {} takes them.", + at(&f.changes_requested_by), + author_words(f) + ), + author_from(f), + since, + None, + ); + } + // CoderHelm's auto-merge merges only on its own approval of the head. + if f.coderhelm_merges { + match &f.coderhelm_verdict { + Some((v, sha)) if sha == &f.head && v == "APPROVE" => {} + Some((v, sha)) if sha == &f.head && v == "REQUEST_CHANGES" => { + return need( + State::ChangesRequested, + format!( + "CoderHelm's review asks for changes on `{}`: {} takes them, or asks \ + CoderHelm with `@coderhelm fix`.", + short(&f.head), + author_words(f) + ), + author_from(f), + since, + None, + ); + } + _ => { + return need( + State::CoderHelmWorking, + format!( + "CoderHelm reviews the head `{}` before its auto-merge merges it.", + short(&f.head) + ), + vec![CODERHELM.into()], + since, + None, + ); + } + } + } + // Approvals: the repository's rule, and the team's own rule when + // CoderHelm merges. + let (required, approval_rule) = if f.approvals_required > 0 { + (f.approvals_required, Some(Rule::RepoRule)) + } else if f.team_requires_approval { + (1, Some(Rule::TeamRule)) + } else if f.review_decision.as_deref() == Some("REVIEW_REQUIRED") { + (1, Some(Rule::RepoRule)) + } else { + (0, None) + }; + // GitHub's own decision is the authority on the repository's count. + let mut have = f.approved_by.len() as u32; + if f.review_decision.as_deref() == Some("APPROVED") && have > 0 { + have = have.max(required); + } + let codeowner_gap = f.codeowners_required + && f.review_decision.as_deref() == Some("REVIEW_REQUIRED") + && have >= required.max(1); + if have < required && !codeowner_gap { + let missing = required - have; + let words = merge_standing::approvals_words(missing); + let asked: Vec = f + .requested + .iter() + .map(|p| person(p)) + .chain(f.requested_teams.iter().map(|t| format!("team:{t}"))) + .collect(); + if asked.is_empty() { + return need( + State::NeedsReviewer, + format!( + "Needs {words}{} and nobody is asked to review: {} asks a reviewer.", + rule_tag(approval_rule), + author_words(f) + ), + author_from(f), + since, + approval_rule, + ); + } + let mut who: Vec = f.requested.clone(); + who.extend(f.requested_teams.iter().cloned()); + return need( + State::NeedsReview, + format!( + "Needs {words}{}: {} {} asked to review.", + rule_tag(approval_rule), + at(&who), + if who.len() == 1 { "is" } else { "are" } + ), + asked, + since, + approval_rule, + ); + } + if codeowner_gap { + let owners: Vec = f.requested_teams.clone(); + let who = if owners.is_empty() { + "a code owner of the changed files".to_string() + } else { + at(&owners) + }; + let from = if owners.is_empty() { + author_from(f) + } else { + owners.iter().map(|t| format!("team:{t}")).collect() + }; + return need( + State::NeedsCodeOwner, + format!("Needs a code owner's approval (CODEOWNERS): {who}."), + from, + since, + Some(Rule::Codeowners), + ); + } + if required == 0 && have == 0 && !f.requested.is_empty() { + let verb = if f.requested.len() == 1 { "is" } else { "are" }; + return need( + State::NeedsReview, + format!("{} {verb} asked to review.", at(&f.requested)), + f.requested.iter().map(|p| person(p)).collect(), + since, + None, + ); + } + if f.threads_required && f.open_threads > 0 { + let who = if f.thread_authors.is_empty() { + author_words(f) + } else { + at(&f.thread_authors) + }; + let from = if f.thread_authors.is_empty() { + author_from(f) + } else { + f.thread_authors.iter().map(|p| person(p)).collect() + }; + return need( + State::OpenThreads, + format!( + "{} open conversation{} hold the merge (repo rule): {who} to resolve.", + f.open_threads, + if f.open_threads == 1 { "" } else { "s" } + ), + from, + since, + Some(Rule::RepoRule), + ); + } + if !f.checks.running.is_empty() { + let done = f.checks.total.saturating_sub(f.checks.running.len() as u32); + return need( + State::ChecksRunning, + format!( + "Checks running on `{}`: {done} of {} done.", + short(&f.head), + f.checks.total.max(f.checks.running.len() as u32) + ), + vec![CI.into()], + since, + None, + ); + } + if !f.checks.known { + return need( + State::Unknown, + format!( + "Not synced yet: no check result for `{}` has reached CoderHelm; the next sync \ + reads them.", + short(&f.head) + ), + vec![NOBODY.into()], + since, + None, + ); + } + if f.conflict.is_none() { + return need( + State::Unknown, + "Not synced yet: GitHub hasn't said whether it merges cleanly; the next sync reads \ + it." + .into(), + vec![NOBODY.into()], + since, + None, + ); + } + if f.blocked_by_rules { + return need( + State::NeedsReview, + format!( + "The branch's rules still hold the merge (branch rule) and GitHub doesn't say \ + which: {} reads them on the pull request.", + author_words(f) + ), + author_from(f), + since, + Some(Rule::BranchRule), + ); + } + if f.coderhelm_merges { + return need( + State::ReadyToMerge, + "Ready to merge: every rule is met, and CoderHelm's auto-merge merges it.".into(), + vec![CODERHELM.into()], + since, + None, + ); + } + if f.auto_merge { + return need( + State::ReadyAutoMerge, + "Ready: every rule is met, and GitHub's auto-merge merges it.".into(), + vec![QUEUE.into()], + since, + None, + ); + } + need( + State::ReadyToMerge, + format!( + "Ready to merge: every rule is met; {} merges it.", + author_words(f) + ), + author_from(f), + since, + None, + ) +} + +fn own_standing(repo: &str, own: &Own) -> Option { + match own.standing.as_ref()? { + OwnStanding::Facts(facts) => Some(merge_standing::decide(repo, facts)), + OwnStanding::Decided(s) => Some(s.clone()), + } +} + +/// CoderHelm's own pull request: the standing's one reason, as a state. +fn from_standing(f: &Facts, own: &Own, s: Standing) -> Needs { + let requester = [&own.requester, &f.author] + .into_iter() + .find(|p| !p.is_empty() && !p.contains("coderhelm")) + .map(|p| person(p)); + let people = || { + let asked: Vec = f.requested.iter().map(|p| person(p)).collect(); + if !asked.is_empty() { + asked + } else { + requester + .clone() + .map(|p| vec![p]) + .unwrap_or_else(|| vec![NOBODY.to_string()]) + } + }; + let ch = || vec![CODERHELM.to_string()]; + let (state, from, rule) = match s.code.as_str() { + "merged" => (State::Merged, vec![], None), + "closed" => (State::Closed, vec![], None), + "building_plan" | "reviewing" | "fixing_review" => (State::CoderHelmWorking, ch(), None), + "conflict" => (State::Conflicts, ch(), None), + "checks_failing" => (State::ChecksFailing, ch(), None), + "review_changes_requested" => (State::ChangesRequested, ch(), None), + "checks_running" => (State::ChecksRunning, vec![CI.to_string()], None), + "draft" => (State::Draft, ch(), None), + "plan_needs_access" => (State::NeedsDecision, people(), None), + "auto_merge_off" => (State::ReadyToMerge, people(), Some(Rule::TeamRule)), + "needs_person_approval" => (State::NeedsReview, people(), Some(Rule::TeamRule)), + "repo_requires_person_review" => (State::NeedsReview, people(), Some(Rule::RepoRule)), + "merging" => (State::ReadyToMerge, ch(), None), + _ => (State::Unknown, vec![NOBODY.to_string()], None), + }; + let text = match rule { + Some(r) if !s.text.contains(r.words()) && r != Rule::RepoRule => { + format!( + "{} ({}) {}", + s.text.trim_end_matches('.'), + r.words(), + s.next + ) + } + _ => format!("{} {}", s.text, s.next), + }; + let mut n = need(state, text, from, f.since, rule); + n.next.code = s.code.clone(); + n.standing = Some(s); + n +} + +/// The path to merge: one line per requirement, from the same facts. +pub fn checklist(f: &Facts) -> Vec { + let step = |key: &str, mark: &str, text: String, source: Option| Step { + key: key.into(), + mark: mark.into(), + text, + source, + }; + let mut out = Vec::new(); + let c = &f.checks; + let (blocking, rule) = c.blocking(); + out.push(if !c.known { + step( + "checks", + "waiting", + "Checks: no result read yet".into(), + None, + ) + } else if !blocking.is_empty() { + step( + "checks", + "blocked", + format!( + "Checks {} of {} pass; failing: {}", + c.passed, + c.total, + names(&blocking, 4) + ), + rule, + ) + } else if !c.running.is_empty() { + step( + "checks", + "waiting", + format!( + "Checks {} of {} done; running: {}", + c.total.saturating_sub(c.running.len() as u32), + c.total, + names(&c.running, 4) + ), + rule, + ) + } else { + step( + "checks", + "done", + format!("Checks {} of {} pass", c.passed, c.total), + rule, + ) + }); + let (required, src) = if f.approvals_required > 0 { + (f.approvals_required, Some(Rule::RepoRule)) + } else if f.team_requires_approval { + (1, Some(Rule::TeamRule)) + } else { + (0, None) + }; + let have = f.approved_by.len() as u32; + out.push(if !f.changes_requested_by.is_empty() { + step( + "approvals", + "blocked", + format!("Changes requested by {}", at(&f.changes_requested_by)), + None, + ) + } else if required == 0 { + step( + "approvals", + if have > 0 { "done" } else { "none" }, + if have > 0 { + format!("Approved by {}", at(&f.approved_by)) + } else { + "No approval required".into() + }, + None, + ) + } else if have >= required { + step( + "approvals", + "done", + format!("Approvals {have} of {required}: {}", at(&f.approved_by)), + src, + ) + } else { + let waiting = if f.requested.is_empty() { + "nobody asked yet".to_string() + } else { + format!("waiting on {}", at(&f.requested)) + }; + step( + "approvals", + "waiting", + format!("Approvals {have} of {required}; {waiting}"), + src, + ) + }); + if f.codeowners_required { + let pending = f.review_decision.as_deref() == Some("REVIEW_REQUIRED"); + out.push(step( + "code_owners", + if pending { "waiting" } else { "done" }, + if pending { + "A code owner's approval is still needed".into() + } else { + "Code owners approved".into() + }, + Some(Rule::Codeowners), + )); + } + out.push(match f.conflict { + Some(true) => step( + "conflicts", + "blocked", + format!( + "Conflicts with `{}`", + if f.base.is_empty() { + "its base" + } else { + &f.base + } + ), + None, + ), + Some(false) => step("conflicts", "done", "No conflicts".into(), None), + None => step( + "conflicts", + "waiting", + "Conflicts: GitHub hasn't said yet".into(), + None, + ), + }); + if f.threads_required || f.open_threads > 0 { + out.push(if f.open_threads == 0 { + step( + "threads", + "done", + "Conversations resolved".into(), + f.threads_required.then_some(Rule::RepoRule), + ) + } else { + step( + "threads", + if f.threads_required { + "blocked" + } else { + "waiting" + }, + format!("{} open conversation(s)", f.open_threads), + f.threads_required.then_some(Rule::RepoRule), + ) + }); + } + if let Some((verdict, sha)) = &f.coderhelm_verdict { + let on_head = sha == &f.head; + out.push(step( + "coderhelm_review", + match (verdict.as_str(), on_head) { + ("APPROVE", true) => "done", + ("REQUEST_CHANGES", true) => "blocked", + _ => "waiting", + }, + match (verdict.as_str(), on_head) { + ("APPROVE", true) => "CoderHelm's review: approved this commit".into(), + ("REQUEST_CHANGES", true) => "CoderHelm's review: asks for changes".into(), + (_, false) => format!("CoderHelm's review is of `{}`, not the head", short(sha)), + _ => "CoderHelm's review: commented".into(), + }, + None, + )); + } + if f.draft { + out.push(step("draft", "waiting", "Still a draft".into(), None)); + } + out.push(if f.in_queue { + step("queue", "waiting", "In the merge queue".into(), None) + } else if f.coderhelm_merges { + step( + "queue", + "none", + "CoderHelm's auto-merge merges it once everything above is done".into(), + None, + ) + } else if f.auto_merge { + step("queue", "none", "GitHub's auto-merge is on".into(), None) + } else { + step("queue", "none", "Not queued; merged by hand".into(), None) + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEAD: &str = "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432"; + + /// A person's pull request with every requirement met. + fn ready() -> Facts { + Facts { + known: true, + head: HEAD.into(), + base: "main".into(), + author: "octocat".into(), + conflict: Some(false), + checks: Checks { + known: true, + total: 3, + passed: 3, + ..Default::default() + }, + approvals_required: 1, + approved_by: vec!["mara".into()], + since: 1_700_000_000, + ..Default::default() + } + } + + #[test] + fn a_pull_request_with_every_rule_met_is_ready_and_names_who_merges() { + let n = decide("acme/web", &ready()); + assert_eq!(n.state, State::ReadyToMerge); + assert_eq!(n.turn, Turn::Person); + assert_eq!(n.next.from, vec!["person:octocat"]); + assert!( + n.next.text.contains("@octocat merges it"), + "{}", + n.next.text + ); + } + + #[test] + fn every_state_is_reached_and_each_has_one_turn() { + let mut seen = std::collections::BTreeSet::new(); + let mut cases: Vec = vec![Facts::default(), ready()]; + let mut push = |m: &dyn Fn(&mut Facts)| { + let mut f = ready(); + m(&mut f); + cases.push(f); + }; + push(&|f| f.merged = true); + push(&|f| f.closed = true); + push(&|f| f.in_queue = true); + push(&|f| f.left_queue = Some("tests failed on the merge commit".into())); + push(&|f| f.reviewing = true); + push(&|f| { + f.own = Some(Own { + stopped: Some(Stop { + code: "product_decision".into(), + text: "Your call: keep the old stock counts?".into(), + person: "jun".into(), + }), + ..Default::default() + }) + }); + push(&|f| f.draft = true); + push(&|f| f.waits_on = vec!["acme/api#12".into()]); + push(&|f| f.conflict = Some(true)); + push(&|f| f.checks.failed = vec!["lint".into()]); + push(&|f| f.changes_requested_by = vec!["mara".into()]); + push(&|f| { + f.changes_requested_by = vec!["mara".into()]; + f.pushed_since_changes = true + }); + push(&|f| f.approved_by.clear()); + push(&|f| { + f.approved_by.clear(); + f.requested = vec!["mara".into()] + }); + push(&|f| { + f.codeowners_required = true; + f.review_decision = Some("REVIEW_REQUIRED".into()); + f.requested_teams = vec!["acme/payments".into()] + }); + push(&|f| { + f.threads_required = true; + f.open_threads = 2 + }); + push(&|f| f.checks.running = vec!["unit".into()]); + push(&|f| f.auto_merge = true); + for f in &cases { + let n = decide("acme/web", f); + assert!(!n.next.text.is_empty(), "{n:?}"); + assert_eq!(n.next.code, n.state.code()); + seen.insert(n.state); + } + for s in ALL { + assert!(seen.contains(s), "{s:?} is never reached"); + assert_eq!(State::from_code(s.code()), Some(*s)); + } + } + + #[test] + fn what_is_not_known_yet_is_unknown_never_ready() { + let mut f = ready(); + f.conflict = None; + assert_eq!(decide("acme/web", &f).state, State::Unknown); + let mut f = ready(); + f.checks.known = false; + assert_eq!(decide("acme/web", &f).state, State::Unknown); + assert_eq!(decide("acme/web", &Facts::default()).turn, Turn::Machines); + } + + #[test] + fn a_rule_that_is_the_reason_is_named_with_its_source() { + let mut f = ready(); + f.approved_by.clear(); + f.requested = vec!["mara".into()]; + let n = decide("acme/web", &f); + assert_eq!(n.state, State::NeedsReview); + assert_eq!(n.next.rule, Some(Rule::RepoRule)); + assert!(n.next.text.contains("(repo rule)"), "{}", n.next.text); + let mut f = ready(); + f.checks.failed = vec!["lint".into()]; + f.checks.required = vec!["lint".into()]; + let n = decide("acme/web", &f); + assert!(n.next.text.contains("(required check)"), "{}", n.next.text); + // A failing check the branch doesn't require holds nothing. + f.checks.required = vec!["unit".into()]; + assert_eq!(decide("acme/web", &f).state, State::ReadyToMerge); + } + + #[test] + fn coderhelms_own_pull_request_reads_its_runs_standing() { + let mut f = ready(); + f.author = "coderhelm[bot]".into(); + f.author_is_coderhelm = true; + let standing = merge_standing::Facts { + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), HEAD.into())), + auto_merge: true, + require_human_approval: true, + ..Default::default() + }; + f.own = Some(Own { + requester: "octocat".into(), + standing: Some(OwnStanding::Facts(standing.clone())), + ..Default::default() + }); + let n = decide("acme/web", &f); + let s = merge_standing::decide("acme/web", &standing); + assert_eq!(n.standing.as_ref(), Some(&s)); + assert_eq!(n.next.code, "needs_person_approval"); + assert_eq!(n.state, State::NeedsReview); + assert_eq!(n.next.from, vec!["person:octocat"]); + assert_eq!(n.next.rule, Some(Rule::TeamRule)); + // The stored standing gives the same decision. + if let Some(o) = f.own.as_mut() { + o.standing = Some(OwnStanding::Decided(s)); + } + assert_eq!(decide("acme/web", &f), n); + } + + #[test] + fn coderhelms_own_limit_stays_its_turn() { + let mut f = ready(); + f.own = Some(Own { + own_problem: Some( + "CoderHelm met a limit in its tools and is taking another route".into(), + ), + ..Default::default() + }); + let n = decide("acme/web", &f); + assert_eq!(n.state, State::CoderHelmWorking); + assert_eq!(n.turn, Turn::CoderHelm); + } + + #[test] + fn a_hand_off_names_the_person_and_shows_its_own_line() { + let mut f = ready(); + f.own = Some(Own { + requester: "theo".into(), + stopped: Some(Stop { + code: "product_decision".into(), + text: "Your call: keep the old stock counts?".into(), + person: String::new(), + }), + ..Default::default() + }); + let n = decide("acme/web", &f); + assert_eq!(n.state, State::NeedsDecision); + assert_eq!(n.next.from, vec!["person:theo"]); + assert!(n + .next + .text + .contains("Your call: keep the old stock counts?")); + } + + #[test] + fn no_sentence_uses_words_the_copy_rules_ban() { + let banned = [ + "please review", + "complete manually", + "re-trigger", + "a person should", + "handed off for human review", + "mergeable", + ]; + for s in ALL { + assert!(!s.label().to_lowercase().contains("mergeable")); + } + let mut f = ready(); + for m in 0..6 { + match m { + 0 => f.draft = true, + 1 => f.conflict = Some(true), + 2 => f.checks.failed = vec!["lint".into()], + 3 => f.changes_requested_by = vec!["mara".into()], + 4 => f.blocked_by_rules = true, + _ => f.approved_by.clear(), + } + let t = decide("acme/web", &f).next.text.to_lowercase(); + for b in banned { + assert!(!t.contains(b), "{t}"); + } + } + } + + #[test] + fn the_checklist_covers_each_requirement() { + let mut f = ready(); + f.codeowners_required = true; + f.threads_required = true; + let keys: Vec = checklist(&f).into_iter().map(|s| s.key).collect(); + for k in [ + "checks", + "approvals", + "code_owners", + "conflicts", + "threads", + "queue", + ] { + assert!(keys.iter().any(|x| x == k), "{k}"); + } + } +} diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs new file mode 100644 index 000000000..aa1e85f4d --- /dev/null +++ b/services/common/src/pr_record.rs @@ -0,0 +1,1545 @@ +//! One durable record per open pull request in the team's repositories, +//! people's as much as CoderHelm's, written from the GitHub events +//! CoderHelm already receives and kept honest by a bounded sync. +//! +//! The gateway once dropped every event of a pull request CoderHelm hadn't +//! opened ("Only track our PRs"), so nothing could say which pull requests +//! were open in a team's repositories, who worked on them, or what each one +//! needed next. The reviewer's and the merge gate's records cover only the +//! pull requests they handle, and they expire after 30 days. +//! +//! - One settings-table item per pull request (`pk` = team id, `sk` = +//! [`record_sk`]), its body a JSON document ([`PrRecord`]) written with a +//! version check, so two events at once never lose each other's facts. +//! - Every webhook of a pull request updates it: `pull_request`, +//! `pull_request_review`, review and issue comments, `check_run`, +//! `check_suite`, `status` and `push` (the last two find their pull +//! request through a pointer item by head commit or branch). +//! - The sync (one GraphQL search per organization, under the shared GitHub +//! budget) fills what events don't carry: the review decision, the +//! branch's rules, conflicts, open conversations; it also adds pull +//! requests opened before the install, and removes the ones no longer +//! open. +//! - No expiry while the pull request is open: a closed or merged one is +//! kept for [`CLOSED_KEEP_SECS`], so "recently merged" can be shown. +//! +//! The pure parts ([`PrRecord::apply_event`], [`PrRecord::apply_node`], +//! [`PrRecord::facts`], [`PrRecord::note_needs`]) are what the tests and the +//! incident cases drive. + +use std::collections::BTreeMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::pr_needs::{self, Facts, Needs}; + +/// Sort-key prefix of every record. +pub const SK_PREFIX: &str = "PRREC#"; +/// Pointer from a head commit to its pull request (`status` events). +pub const HEAD_PREFIX: &str = "PRRECHEAD#"; +/// Pointer from a branch to its pull request (`push` events). +pub const REF_PREFIX: &str = "PRRECREF#"; +/// How long a closed or merged pull request's record is kept. +pub const CLOSED_KEEP_SECS: i64 = 3 * 86_400; +/// How long a pointer item is kept after its last write. +pub const POINTER_KEEP_SECS: i64 = 30 * 86_400; +/// Most timeline events kept on a record (the newest). +pub const MAX_EVENTS: usize = 120; +/// Most wait-ledger spans kept on a record (the newest). +pub const MAX_SPANS: usize = 80; +/// Most check names kept for one head. +pub const MAX_CHECKS: usize = 100; + +/// Settings-table sort key of a pull request's record. +pub fn record_sk(repo: &str, number: u64) -> String { + format!("{SK_PREFIX}{repo}#{number:06}") +} + +/// `owner/repo` and the number from a record's sort key. +pub fn parse_sk(sk: &str) -> Option<(String, u64)> { + let (repo, n) = sk.strip_prefix(SK_PREFIX)?.rsplit_once('#')?; + Some((repo.to_string(), n.parse().ok()?)) +} + +pub fn head_sk(repo: &str, sha: &str) -> String { + format!("{HEAD_PREFIX}{repo}#{sha}") +} + +pub fn ref_sk(repo: &str, branch: &str) -> String { + format!("{REF_PREFIX}{repo}#{branch}") +} + +/// A GitHub login is CoderHelm's own (its app, under any install's name). +pub fn is_coderhelm(login: &str) -> bool { + login.to_ascii_lowercase().contains("coderhelm") +} + +/// One person's latest review. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Review { + /// `APPROVED`, `CHANGES_REQUESTED`, `COMMENTED`, `DISMISSED`. + pub state: String, + pub sha: String, + pub at: i64, +} + +/// One check on the head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Check { + /// `queued`, `in_progress`, `completed`. + pub status: String, + /// GitHub's conclusion once completed (`success`, `failure`, ...). + #[serde(default)] + pub conclusion: String, + pub at: i64, +} + +impl Check { + fn failed(&self) -> bool { + self.status == "completed" + && matches!( + self.conclusion.as_str(), + "failure" | "timed_out" | "startup_failure" | "action_required" | "error" + ) + } + fn running(&self) -> bool { + self.status != "completed" + } +} + +/// A link to another pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Link { + /// `stack_base` (this one is based on it), `plan` (the same run's plan, + /// in merge order), `depends` (merges after it), `contract` (named + /// under the description's Compatibility heading). + pub kind: String, + pub repo: String, + pub number: u64, +} + +/// CoderHelm's work on the pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CoderHelmLink { + /// The run that opened it or worked on it last. + #[serde(default)] + pub run_id: String, + /// The reviewer's latest session on it. + #[serde(default)] + pub session_id: String, +} + +/// One timeline event. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Event { + pub at: i64, + /// A GitHub login, `coderhelm`, or `ci`. + pub actor: String, + /// opened, pushed, review, comment, check, queue, run, label, ready, + /// draft, merged, closed, reviewers, state. + pub kind: String, + pub text: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub run_id: String, +} + +/// One span of the wait ledger: who held the turn from `from` until the +/// next span began. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Span { + /// `person:`, `team:`, `coderhelm`, `ci`, `queue`, + /// `nobody` (the first actor of the step). + pub who: String, + pub state: String, + pub from: i64, +} + +/// The record's body. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PrRecord { + pub repo: String, + pub number: u64, + /// The pull request itself was read (an event that carries it, or the + /// sync). + pub known: bool, + pub title: String, + pub url: String, + pub author: String, + /// `open`, `closed` or `merged`. + pub status: String, + pub draft: bool, + pub head_sha: String, + pub head_ref: String, + pub base_ref: String, + pub created_at: i64, + pub updated_at: i64, + pub closed_at: i64, + pub merged_by: String, + pub additions: u32, + pub deletions: u32, + pub labels: Vec, + pub requested: Vec, + pub requested_teams: Vec, + /// Each person's latest review that took a side (approved or changes), + /// or their latest comment review when they took none. + pub reviews: BTreeMap, + /// CoderHelm's latest verdict (`APPROVE`, `REQUEST_CHANGES`, `COMMENT`) + /// and the commit it is on. + pub coderhelm_verdict: Option<(String, String)>, + pub review_decision: Option, + pub approvals_required: u32, + pub codeowners_required: bool, + pub threads_required: bool, + pub required_checks: Vec, + /// The commit `checks` are for. + pub checks_sha: String, + pub checks: BTreeMap, + pub conflict: Option, + /// GitHub's `mergeStateStatus` / `mergeable_state`, lower case. + pub merge_state: String, + pub open_threads: u32, + pub thread_authors: Vec, + pub auto_merge: bool, + pub in_queue: bool, + pub left_queue: Option, + /// Who worked on it: login to roles (author, committer, reviewer, + /// commenter, requester, requested). + pub people: BTreeMap>, + /// The person who asked CoderHelm for it. + pub requester: String, + pub links: Vec, + pub coderhelm: CoderHelmLink, + pub events: Vec, + pub spans: Vec, + /// When the sync last read it (epoch seconds; 0 never). + pub synced_at: i64, + /// When an event last changed it. + pub event_at: i64, +} + +fn ts(v: &Value) -> i64 { + v.as_str() + .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) + .map(|d| d.timestamp()) + .unwrap_or(0) +} + +fn s(v: &Value) -> String { + v.as_str().unwrap_or("").to_string() +} + +fn login(v: &Value) -> String { + v["login"].as_str().unwrap_or("").to_string() +} + +fn push_unique(list: &mut Vec, v: &str) { + if !v.is_empty() && !list.iter().any(|x| x.eq_ignore_ascii_case(v)) { + list.push(v.to_string()); + } +} + +/// `owner/repo#n` references under the description's `## Compatibility` +/// heading (the contracts index's link between pull requests). +pub fn compatibility_links(body: &str) -> Vec<(String, u64)> { + let mut out = Vec::new(); + let mut inside = false; + for line in body.lines() { + let t = line.trim(); + if t.starts_with('#') { + inside = t + .trim_start_matches('#') + .trim() + .eq_ignore_ascii_case("compatibility"); + continue; + } + if !inside { + continue; + } + for word in t.split(|c: char| c.is_whitespace() || "()[],;`".contains(c)) { + let word = word + .trim_start_matches("https://github.com/") + .replace("/pull/", "#"); + let Some((repo, n)) = word.rsplit_once('#') else { + continue; + }; + let ok = repo.split('/').count() == 2 + && repo + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)); + if let (true, Ok(n)) = (ok, n.parse::()) { + if !out.contains(&(repo.to_string(), n)) { + out.push((repo.to_string(), n)); + } + } + } + } + out.truncate(10); + out +} + +impl PrRecord { + pub fn new(repo: &str, number: u64) -> PrRecord { + PrRecord { + repo: repo.to_string(), + number, + status: "open".into(), + ..Default::default() + } + } + + pub fn org(&self) -> &str { + self.repo.split('/').next().unwrap_or("") + } + + pub fn is_open(&self) -> bool { + self.status == "open" + } + + pub fn author_is_coderhelm(&self) -> bool { + is_coderhelm(&self.author) + } + + fn role(&mut self, who: &str, role: &str) { + if who.is_empty() { + return; + } + let who = if is_coderhelm(who) { "coderhelm" } else { who }; + let roles = self.people.entry(who.to_string()).or_default(); + if !roles.iter().any(|r| r == role) { + roles.push(role.to_string()); + } + if self.people.len() > 40 { + // Keep the author and the first people seen. + let keep: Vec = self.people.keys().take(40).cloned().collect(); + self.people.retain(|k, _| keep.contains(k)); + } + } + + fn event(&mut self, at: i64, actor: &str, kind: &str, text: String) { + let actor = if is_coderhelm(actor) { + "coderhelm".to_string() + } else { + actor.to_string() + }; + // A redelivered event is the same event. + if self + .events + .iter() + .rev() + .take(5) + .any(|e| e.at == at && e.kind == kind && e.text == text && e.actor == actor) + { + return; + } + self.events.push(Event { + at, + actor, + kind: kind.into(), + text, + run_id: String::new(), + }); + self.events.sort_by_key(|e| e.at); + if self.events.len() > MAX_EVENTS { + let cut = self.events.len() - MAX_EVENTS; + self.events.drain(..cut); + } + } + + fn new_head(&mut self, sha: &str) { + if !sha.is_empty() && sha != self.head_sha { + self.head_sha = sha.to_string(); + self.left_queue = None; + } + } + + /// The pull request object (webhook or REST shape). + fn take_pr(&mut self, pr: &Value) { + if pr["number"].as_u64().is_none() { + return; + } + self.known = true; + self.title = s(&pr["title"]); + self.url = s(&pr["html_url"]); + let author = login(&pr["user"]); + if !author.is_empty() { + self.author = author.clone(); + self.role(&author, "author"); + } + self.draft = pr["draft"].as_bool().unwrap_or(false); + let merged = pr["merged"].as_bool().unwrap_or(false) || !pr["merged_at"].is_null(); + self.status = match (pr["state"].as_str(), merged) { + (_, true) => "merged", + (Some("closed"), _) => "closed", + _ => "open", + } + .into(); + self.new_head(pr["head"]["sha"].as_str().unwrap_or("")); + self.head_ref = s(&pr["head"]["ref"]); + self.base_ref = s(&pr["base"]["ref"]); + self.created_at = ts(&pr["created_at"]); + self.updated_at = ts(&pr["updated_at"]).max(self.updated_at); + if let Some(t) = [ts(&pr["merged_at"]), ts(&pr["closed_at"])] + .into_iter() + .find(|t| *t > 0) + { + self.closed_at = t; + } + if let Some(by) = pr["merged_by"]["login"].as_str() { + self.merged_by = by.to_string(); + } + if let Some(a) = pr["additions"].as_u64() { + self.additions = a as u32; + self.deletions = pr["deletions"].as_u64().unwrap_or(0) as u32; + } + if let Some(labels) = pr["labels"].as_array() { + self.labels = labels.iter().map(|l| s(&l["name"])).collect(); + } + if let Some(r) = pr["requested_reviewers"].as_array() { + self.requested = r.iter().map(login).filter(|l| !l.is_empty()).collect(); + } + if let Some(t) = pr["requested_teams"].as_array() { + let org = self.org().to_string(); + self.requested_teams = t + .iter() + .map(|t| format!("{org}/{}", s(&t["slug"]))) + .collect(); + } + for r in self.requested.clone() { + self.role(&r, "requested"); + } + if let Some(m) = pr["mergeable"].as_bool() { + self.conflict = Some(!m); + } + if let Some(st) = pr["mergeable_state"].as_str() { + self.merge_state = st.to_ascii_lowercase(); + if st == "dirty" { + self.conflict = Some(true); + } + } + if pr.get("auto_merge").is_some() { + self.auto_merge = !pr["auto_merge"].is_null(); + } + if let Some(body) = pr["body"].as_str() { + self.links.retain(|l| l.kind != "contract"); + for (repo, n) in compatibility_links(body) { + self.links.push(Link { + kind: "contract".into(), + repo, + number: n, + }); + } + } + } + + /// Apply one GitHub webhook. Returns false when it says nothing about + /// this pull request. + pub fn apply_event(&mut self, event_type: &str, payload: &Value, now: i64) -> bool { + let action = payload["action"].as_str().unwrap_or(""); + let sender = login(&payload["sender"]); + let at = |v: &Value| { + let t = ts(v); + if t > 0 { + t + } else { + now + } + }; + match event_type { + "pull_request" => { + let pr = &payload["pull_request"]; + let before = self.head_sha.clone(); + self.take_pr(pr); + let when = at(&pr["updated_at"]); + match action { + "opened" => self.event( + at(&pr["created_at"]), + &self.author.clone(), + "opened", + "opened it".into(), + ), + "reopened" => self.event(when, &sender, "opened", "reopened it".into()), + "closed" if self.status == "merged" => { + let by = if self.merged_by.is_empty() { + sender.clone() + } else { + self.merged_by.clone() + }; + self.event(when, &by, "merged", "merged it".into()) + } + "closed" => { + self.event(when, &sender, "closed", "closed it without merging".into()) + } + "synchronize" => { + let short = self.head_sha.get(..7).unwrap_or("").to_string(); + self.role(&sender, "committer"); + self.event( + when, + &sender, + "pushed", + format!("pushed; the head is now {short}"), + ); + if before != self.head_sha { + self.checks.clear(); + self.checks_sha = self.head_sha.clone(); + } + } + "ready_for_review" => { + self.event(when, &sender, "ready", "marked it ready for review".into()) + } + "converted_to_draft" => { + self.event(when, &sender, "draft", "turned it back into a draft".into()) + } + "review_requested" => { + let who = payload["requested_reviewer"]["login"] + .as_str() + .map(|l| format!("@{l}")) + .or_else(|| { + payload["requested_team"]["slug"] + .as_str() + .map(|t| format!("@{}/{t}", self.org())) + }) + .unwrap_or_default(); + self.event(when, &sender, "reviewers", format!("asked {who} to review")) + } + "review_request_removed" => self.event( + when, + &sender, + "reviewers", + "removed a review request".into(), + ), + "labeled" => self.event( + when, + &sender, + "label", + format!("added the label `{}`", s(&payload["label"]["name"])), + ), + "unlabeled" => self.event( + when, + &sender, + "label", + format!("took the label `{}` off", s(&payload["label"]["name"])), + ), + "enqueued" => { + self.in_queue = true; + self.left_queue = None; + self.event(when, &sender, "queue", "added it to the merge queue".into()) + } + "dequeued" => { + self.in_queue = false; + let reason = payload["reason"] + .as_str() + .unwrap_or("") + .to_ascii_lowercase() + .replace('_', " "); + if self.status == "open" && reason != "merged" { + self.left_queue = Some(if reason.is_empty() { + "removed from the queue".into() + } else { + reason.clone() + }); + } + self.event( + when, + "ci", + "queue", + format!( + "left the merge queue{}", + if reason.is_empty() { + String::new() + } else { + format!(": {reason}") + } + ), + ) + } + "auto_merge_enabled" => { + self.auto_merge = true; + self.event( + when, + &sender, + "state", + "turned GitHub's auto-merge on".into(), + ) + } + "auto_merge_disabled" => { + self.auto_merge = false; + self.event( + when, + &sender, + "state", + "turned GitHub's auto-merge off".into(), + ) + } + _ => {} + } + if !self.head_sha.is_empty() && self.checks_sha.is_empty() { + self.checks_sha = self.head_sha.clone(); + } + self.event_at = now; + true + } + "pull_request_review" => { + let r = &payload["review"]; + let who = login(&r["user"]); + if who.is_empty() { + return false; + } + if !self.known { + self.take_pr(&payload["pull_request"]); + } + let state = r["state"].as_str().unwrap_or("").to_ascii_uppercase(); + let sha = s(&r["commit_id"]); + let when = at(&r["submitted_at"]); + if is_coderhelm(&who) { + let verdict = match state.as_str() { + "APPROVED" => "APPROVE", + "CHANGES_REQUESTED" => "REQUEST_CHANGES", + _ => "COMMENT", + }; + if action != "dismissed" { + self.coderhelm_verdict = Some((verdict.into(), sha.clone())); + } else { + self.coderhelm_verdict = None; + } + } else { + let keep = match self.reviews.get(&who) { + // A comment never replaces a side taken. + Some(prev) if state == "COMMENTED" => prev.state == "COMMENTED", + _ => true, + }; + if keep || action == "dismissed" { + self.reviews.insert( + who.clone(), + Review { + state: if action == "dismissed" { + "DISMISSED".into() + } else { + state.clone() + }, + sha, + at: when, + }, + ); + } + self.requested.retain(|p| !p.eq_ignore_ascii_case(&who)); + } + self.role(&who, "reviewer"); + let words = match (action, state.as_str()) { + ("dismissed", _) => "had a review dismissed".to_string(), + (_, "APPROVED") => "approved".to_string(), + (_, "CHANGES_REQUESTED") => "asked for changes".to_string(), + _ => "commented in a review".to_string(), + }; + self.event(when, &who, "review", words); + self.event_at = now; + true + } + "pull_request_review_comment" | "issue_comment" => { + if action != "created" { + return false; + } + let c = &payload["comment"]; + let who = login(&c["user"]); + if who.is_empty() { + return false; + } + if event_type == "pull_request_review_comment" && !self.known { + self.take_pr(&payload["pull_request"]); + } + let body = c["body"].as_str().unwrap_or(""); + if !is_coderhelm(&who) && body.to_ascii_lowercase().contains("@coderhelm") { + self.role(&who, "requester"); + if self.requester.is_empty() { + self.requester = who.clone(); + } + self.event( + at(&c["created_at"]), + &who, + "comment", + "asked CoderHelm".into(), + ); + } else { + self.role(&who, "commenter"); + self.event(at(&c["created_at"]), &who, "comment", "commented".into()); + } + self.event_at = now; + true + } + "check_run" => { + let run = &payload["check_run"]; + let sha = s(&run["head_sha"]); + if !self.take_check_sha(&sha) { + return false; + } + let name = s(&run["name"]); + self.checks.retain(|k, _| !k.starts_with("suite:")); + let c = Check { + status: s(&run["status"]), + conclusion: s(&run["conclusion"]), + at: at(&run["completed_at"]).max(at(&run["started_at"])), + }; + if c.failed() && self.checks.get(&name).is_none_or(|p| !p.failed()) { + self.event(c.at, "ci", "check", format!("`{name}` failed")); + } + self.put_check(name, c); + self.event_at = now; + true + } + "check_suite" => { + let suite = &payload["check_suite"]; + let sha = s(&suite["head_sha"]); + if !self.take_check_sha(&sha) { + return false; + } + // Named checks come from check runs; a suite stands in only + // while no run is known for the head. + if self.checks.keys().all(|k| k.starts_with("suite:")) { + let app = suite["app"]["name"].as_str().unwrap_or("checks"); + self.put_check( + format!("suite:{app}"), + Check { + status: s(&suite["status"]), + conclusion: s(&suite["conclusion"]), + at: at(&suite["updated_at"]), + }, + ); + } + if action == "completed" { + let concl = s(&suite["conclusion"]); + self.event( + at(&suite["updated_at"]), + "ci", + "check", + format!("a check suite finished: {concl}"), + ); + } + self.event_at = now; + true + } + "status" => { + let sha = s(&payload["sha"]); + if !self.take_check_sha(&sha) { + return false; + } + let state = payload["state"].as_str().unwrap_or(""); + let (status, conclusion) = match state { + "pending" => ("in_progress", ""), + "success" => ("completed", "success"), + "failure" => ("completed", "failure"), + _ => ("completed", "error"), + }; + self.put_check( + s(&payload["context"]), + Check { + status: status.into(), + conclusion: conclusion.into(), + at: at(&payload["updated_at"]), + }, + ); + self.event_at = now; + true + } + "push" => { + let after = s(&payload["after"]); + let pusher = payload["pusher"]["name"].as_str().unwrap_or("").to_string(); + let mut authors: Vec = Vec::new(); + for c in payload["commits"].as_array().into_iter().flatten().take(50) { + let a = c["author"]["username"].as_str().unwrap_or(""); + push_unique(&mut authors, a); + } + for a in &authors { + self.role(a, "committer"); + } + if !pusher.is_empty() { + self.role(&pusher, "committer"); + } + if !after.is_empty() && !after.starts_with("0000000") { + if after != self.head_sha { + self.checks.clear(); + self.checks_sha = after.clone(); + } + self.new_head(&after); + } + self.event_at = now; + true + } + _ => false, + } + } + + fn take_check_sha(&mut self, sha: &str) -> bool { + if sha.is_empty() { + return false; + } + if self.head_sha.is_empty() { + self.head_sha = sha.to_string(); + } + if sha != self.head_sha { + return false; + } + if self.checks_sha != sha { + self.checks.clear(); + self.checks_sha = sha.to_string(); + } + true + } + + fn put_check(&mut self, name: String, c: Check) { + if name.is_empty() { + return; + } + if self.checks.len() >= MAX_CHECKS && !self.checks.contains_key(&name) { + return; + } + // An older report never replaces a newer one. + if self + .checks + .get(&name) + .is_some_and(|p| p.at > c.at && c.at > 0) + { + return; + } + self.checks.insert(name, c); + } + + /// Apply one pull request node from the sync's GraphQL search + /// ([`SEARCH_QUERY`]); it is the authority for everything it names. + pub fn apply_node(&mut self, n: &Value, now: i64) { + self.known = true; + self.title = s(&n["title"]); + self.url = s(&n["url"]); + let author = login(&n["author"]); + if !author.is_empty() { + self.author = author.clone(); + self.role(&author, "author"); + } + self.draft = n["isDraft"].as_bool().unwrap_or(false); + self.status = match n["state"].as_str() { + Some("MERGED") => "merged", + Some("CLOSED") => "closed", + _ => "open", + } + .into(); + let head = s(&n["headRefOid"]); + if head != self.head_sha { + self.checks.clear(); + } + self.new_head(&head); + self.checks_sha = self.head_sha.clone(); + self.head_ref = s(&n["headRefName"]); + self.base_ref = s(&n["baseRefName"]); + self.created_at = ts(&n["createdAt"]); + self.updated_at = ts(&n["updatedAt"]); + self.additions = n["additions"].as_u64().unwrap_or(0) as u32; + self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; + self.labels = n["labels"]["nodes"] + .as_array() + .into_iter() + .flatten() + .map(|l| s(&l["name"])) + .collect(); + self.requested.clear(); + self.requested_teams.clear(); + for r in n["reviewRequests"]["nodes"] + .as_array() + .into_iter() + .flatten() + { + let rv = &r["requestedReviewer"]; + if let Some(l) = rv["login"].as_str() { + push_unique(&mut self.requested, l); + } else if let Some(slug) = rv["slug"].as_str() { + let t = format!("{}/{slug}", self.org()); + push_unique(&mut self.requested_teams, &t); + } + } + for r in self.requested.clone() { + self.role(&r, "requested"); + } + for r in n["latestOpinionatedReviews"]["nodes"] + .as_array() + .into_iter() + .flatten() + { + let who = login(&r["author"]); + if who.is_empty() { + continue; + } + let state = s(&r["state"]); + let sha = s(&r["commit"]["oid"]); + if is_coderhelm(&who) { + let v = match state.as_str() { + "APPROVED" => "APPROVE", + "CHANGES_REQUESTED" => "REQUEST_CHANGES", + _ => "COMMENT", + }; + self.coderhelm_verdict = Some((v.into(), sha)); + } else { + self.reviews.insert( + who.clone(), + Review { + state, + sha, + at: ts(&r["submittedAt"]), + }, + ); + } + self.role(&who, "reviewer"); + } + for p in n["participants"]["nodes"].as_array().into_iter().flatten() { + let l = login(p); + if !self.people.contains_key(&l) && !l.is_empty() { + self.role(&l, "commenter"); + } + } + self.review_decision = n["reviewDecision"].as_str().map(str::to_string); + self.conflict = match n["mergeable"].as_str() { + Some("CONFLICTING") => Some(true), + Some("MERGEABLE") => Some(false), + _ => None, + }; + self.merge_state = n["mergeStateStatus"] + .as_str() + .unwrap_or("") + .to_ascii_lowercase(); + self.auto_merge = !n["autoMergeRequest"].is_null(); + self.in_queue = n["isInMergeQueue"].as_bool().unwrap_or(false); + let rule = &n["baseRef"]["branchProtectionRule"]; + if rule.is_object() { + self.approvals_required = + rule["requiredApprovingReviewCount"].as_u64().unwrap_or(0) as u32; + self.codeowners_required = rule["requiresCodeOwnerReviews"].as_bool().unwrap_or(false); + self.threads_required = rule["requiresConversationResolution"] + .as_bool() + .unwrap_or(false); + self.required_checks = rule["requiredStatusCheckContexts"] + .as_array() + .into_iter() + .flatten() + .map(s) + .collect(); + } + let mut open = 0; + let mut authors = Vec::new(); + for t in n["reviewThreads"]["nodes"].as_array().into_iter().flatten() { + if t["isResolved"].as_bool() == Some(false) { + open += 1; + let a = login(&t["comments"]["nodes"][0]["author"]); + push_unique(&mut authors, &a); + } + } + self.open_threads = open; + self.thread_authors = authors; + let contexts = + &n["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]["nodes"]; + if let Some(list) = contexts.as_array() { + self.checks.clear(); + for c in list.iter().take(MAX_CHECKS) { + let (name, check) = if c["__typename"] == "StatusContext" { + let (status, concl) = match c["state"].as_str() { + Some("PENDING") | Some("EXPECTED") => ("in_progress", ""), + Some("SUCCESS") => ("completed", "success"), + Some("FAILURE") => ("completed", "failure"), + _ => ("completed", "error"), + }; + ( + s(&c["context"]), + Check { + status: status.into(), + conclusion: concl.into(), + at: now, + }, + ) + } else { + ( + s(&c["name"]), + Check { + status: s(&c["status"]).to_ascii_lowercase(), + conclusion: s(&c["conclusion"]).to_ascii_lowercase(), + at: now, + }, + ) + }; + if !name.is_empty() { + self.checks.insert(name, check); + } + } + } + self.synced_at = now; + } + + /// The facts the needs function reads, from this record alone; the + /// reader adds CoderHelm's run, its reviewer and stacked pull requests. + pub fn facts(&self) -> Facts { + let head = &self.head_sha; + let mut changes = Vec::new(); + let mut approved = Vec::new(); + for (who, r) in &self.reviews { + match r.state.as_str() { + "CHANGES_REQUESTED" => changes.push(who.clone()), + // An approval of an older commit counts when GitHub's own + // decision keeps it, or it is on the head. + "APPROVED" + if &r.sha == head || self.review_decision.as_deref() == Some("APPROVED") => + { + approved.push(who.clone()) + } + _ => {} + } + } + let pushed_since = !changes.is_empty() + && self.reviews.iter().any(|(_, r)| { + r.state == "CHANGES_REQUESTED" && !r.sha.is_empty() && &r.sha != head + }); + let mut checks = pr_needs::Checks { + known: !self.checks.is_empty() && self.checks_sha == *head, + required: self.required_checks.clone(), + ..Default::default() + }; + if checks.known { + for (name, c) in &self.checks { + let name = name.trim_start_matches("suite:").to_string(); + checks.total += 1; + if c.running() { + checks.running.push(name); + } else if c.failed() { + checks.failed.push(name); + } else { + checks.passed += 1; + } + } + } + // A required check not reported yet is still to run. + if checks.known { + for r in &self.required_checks { + if !self.checks.keys().any(|k| k.eq_ignore_ascii_case(r)) { + checks.total += 1; + checks.running.push(r.clone()); + } + } + } + let blocked = self.merge_state == "blocked"; + Facts { + known: self.known, + merged: self.status == "merged", + closed: self.status == "closed", + draft: self.draft, + head: head.clone(), + base: self.base_ref.clone(), + author: self.author.clone(), + author_is_coderhelm: self.author_is_coderhelm(), + merged_by: self.merged_by.clone(), + in_queue: self.in_queue, + left_queue: self.left_queue.clone(), + coderhelm_verdict: self.coderhelm_verdict.clone(), + conflict: self.conflict, + checks, + review_decision: self.review_decision.clone(), + changes_requested_by: changes, + pushed_since_changes: pushed_since, + approved_by: approved, + requested: self + .requested + .iter() + .filter(|p| !is_coderhelm(p)) + .cloned() + .collect(), + requested_teams: self.requested_teams.clone(), + approvals_required: self.approvals_required, + codeowners_required: self.codeowners_required, + threads_required: self.threads_required, + open_threads: self.open_threads, + thread_authors: self.thread_authors.clone(), + auto_merge: self.auto_merge, + blocked_by_rules: blocked, + since: self.spans.last().map(|s| s.from).unwrap_or(self.created_at), + ..Default::default() + } + } + + /// Record the decision on the wait ledger: a new span when the step or + /// who holds it changed. Returns whether it changed. + pub fn note_needs(&mut self, n: &Needs, now: i64) -> bool { + let who = n + .next + .from + .first() + .cloned() + .unwrap_or_else(|| pr_needs::NOBODY.to_string()); + let state = n.state.code().to_string(); + if self + .spans + .last() + .is_some_and(|s| s.who == who && s.state == state) + { + return false; + } + let from = if self.spans.is_empty() && self.created_at > 0 { + self.created_at.min(now) + } else { + now + }; + self.spans.push(Span { who, state, from }); + if self.spans.len() > MAX_SPANS { + let cut = self.spans.len() - MAX_SPANS; + self.spans.drain(..cut); + } + true + } + + /// When the record expires: never while open. + pub fn ttl(&self) -> Option { + (!self.is_open()).then(|| self.closed_at.max(self.event_at) + CLOSED_KEEP_SECS) + } +} + +/// Totals of the wait ledger: seconds each holder held the turn, up to +/// `now` (or when it closed), largest first. +pub fn ledger_totals(spans: &[Span], end: i64) -> Vec<(String, i64)> { + let mut by: BTreeMap = BTreeMap::new(); + for (i, s) in spans.iter().enumerate() { + let to = spans.get(i + 1).map(|n| n.from).unwrap_or(end); + *by.entry(s.who.clone()).or_default() += (to - s.from).max(0); + } + let mut out: Vec<(String, i64)> = by.into_iter().collect(); + out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + out +} + +/// The sync's search: open pull requests of one owner, newest first, with +/// everything the needs function reads. `$q` is the search, `$after` the +/// page cursor. +pub const SEARCH_QUERY: &str = "query($q: String!, $after: String) { + search(type: ISSUE, query: $q, first: 30, after: $after) { + issueCount + pageInfo { hasNextPage endCursor } + nodes { + ... on PullRequest { + number title url state isDraft createdAt updatedAt additions deletions + headRefName headRefOid baseRefName reviewDecision mergeable mergeStateStatus + isInMergeQueue + repository { nameWithOwner } + author { login } + autoMergeRequest { enabledAt } + labels(first: 20) { nodes { name } } + reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } ... on Team { slug } } } } + latestOpinionatedReviews(first: 20) { nodes { state submittedAt author { login } commit { oid } } } + participants(first: 20) { nodes { login } } + reviewThreads(first: 50) { nodes { isResolved comments(first: 1) { nodes { author { login } } } } } + baseRef { branchProtectionRule { requiredApprovingReviewCount requiresCodeOwnerReviews requiresConversationResolution requiredStatusCheckContexts } } + commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 60) { nodes { __typename ... on CheckRun { name status conclusion } ... on StatusContext { context state } } } } } } } + } + } + } +}"; + +/// Pages of [`SEARCH_QUERY`] one sync reads per owner at most (30 pull +/// requests a page): the bound of one owner's sync. +pub const MAX_PAGES: u32 = 10; + +/// The search for an owner's open pull requests. +pub fn search_text(owner: &str, org: bool) -> String { + let q = if org { "org" } else { "user" }; + format!("is:pr is:open archived:false {q}:{owner} sort:updated-desc") +} + +// ─── Storage ──────────────────────────────────────────────────────────────── + +type Err = Box; +pub type Item = std::collections::HashMap; + +/// The record in `item`, with its version. +pub fn from_item(item: &Item) -> Option<(PrRecord, i64)> { + let doc = item.get("doc")?.as_s().ok()?; + let rec: PrRecord = serde_json::from_str(doc).ok()?; + let ver = item + .get("ver") + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + Some((rec, ver)) +} + +/// Read one record. +pub async fn load( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + number: u64, +) -> Result, Err> { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(record_sk(repo, number))) + .consistent_read(true) + .send() + .await?; + Ok(out.item().and_then(from_item)) +} + +/// Write a record when its version is still `ver` (0: not there yet). +/// False when another writer got there first. +async fn put( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + rec: &PrRecord, + needs: &Needs, + ver: i64, +) -> Result { + let mut req = dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(record_sk(&rec.repo, rec.number))) + .item("doc", AttributeValue::S(serde_json::to_string(rec)?)) + .item("ver", AttributeValue::N((ver + 1).to_string())) + .item("repo", AttributeValue::S(rec.repo.clone())) + .item("status", AttributeValue::S(rec.status.clone())) + .item("state", AttributeValue::S(needs.state.code().into())) + .item("turn", AttributeValue::S(needs.turn.code().into())); + if let Some(t) = rec.ttl() { + req = req.item("ttl", AttributeValue::N(t.to_string())); + } + req = if ver == 0 { + req.condition_expression("attribute_not_exists(sk)") + } else { + req.condition_expression("ver = :v") + .expression_attribute_values(":v", AttributeValue::N(ver.to_string())) + }; + match req.send().await { + Ok(_) => Ok(true), + Err(e) => { + let lost = e + .as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()); + if lost { + Ok(false) + } else { + Err(e.into()) + } + } + } +} + +/// Read, change and write one record, again from a fresh read when +/// another writer got there first (a few times). `change` returns false to +/// write nothing. +pub async fn update( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + number: u64, + now: i64, + mut change: F, +) -> Result, Err> +where + F: FnMut(&mut PrRecord) -> bool, +{ + for _ in 0..4 { + let (mut rec, ver) = load(dynamo, table, team_id, repo, number) + .await? + .unwrap_or_else(|| (PrRecord::new(repo, number), 0)); + if !change(&mut rec) { + return Ok(None); + } + let needs = pr_needs::decide(repo, &rec.facts()); + rec.note_needs(&needs, now); + if put(dynamo, table, team_id, &rec, &needs, ver).await? { + return Ok(Some(rec)); + } + } + Err("the pull request's record kept changing under this write".into()) +} + +/// Remove a record (the sync found it no longer open). +pub async fn delete( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + number: u64, +) -> Result<(), Err> { + dynamo + .delete_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(record_sk(repo, number))) + .send() + .await?; + Ok(()) +} + +/// Point a head commit and a branch at their pull request. +pub async fn point( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + rec: &PrRecord, + now: i64, +) -> Result<(), Err> { + for sk in [ + (!rec.head_sha.is_empty()).then(|| head_sk(&rec.repo, &rec.head_sha)), + (!rec.head_ref.is_empty()).then(|| ref_sk(&rec.repo, &rec.head_ref)), + ] + .into_iter() + .flatten() + { + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(sk)) + .item("pr_number", AttributeValue::N(rec.number.to_string())) + .item( + "ttl", + AttributeValue::N((now + POINTER_KEEP_SECS).to_string()), + ) + .send() + .await?; + } + Ok(()) +} + +/// The pull request a pointer names. +pub async fn pointed( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + sk: &str, +) -> Result, Err> { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(sk.into())) + .send() + .await?; + Ok(out + .item() + .and_then(|i| i.get("pr_number")) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok())) +} + +/// Every record of a team (one query, paged). +pub async fn all(dynamo: &DynamoClient, table: &str, team_id: &str) -> Result, Err> { + let mut out = Vec::new(); + let mut start: Option = None; + loop { + let page = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":p", AttributeValue::S(SK_PREFIX.into())) + .set_exclusive_start_key(start) + .send() + .await?; + let now = chrono::Utc::now().timestamp(); + for item in page.items() { + // DynamoDB deletes expired items late. + let expired = item + .get("ttl") + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .is_some_and(|t| t < now); + if expired { + continue; + } + if let Some((rec, _)) = from_item(item) { + out.push(rec); + } + } + start = page.last_evaluated_key().cloned(); + if start.is_none() { + return Ok(out); + } + } +} + +/// The pull requests one webhook is about, in `repo`: `None` when the +/// event names none directly (a `status` or `push`: found by pointer). +pub fn event_prs(event_type: &str, payload: &Value) -> Option> { + let one = |v: &Value| v.as_u64().map(|n| vec![n]); + match event_type { + "pull_request" | "pull_request_review" | "pull_request_review_comment" => { + one(&payload["pull_request"]["number"]) + } + "issue_comment" => payload["issue"]["pull_request"] + .is_object() + .then(|| one(&payload["issue"]["number"])) + .flatten(), + "check_run" => Some( + payload["check_run"]["pull_requests"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p["number"].as_u64()) + .take(5) + .collect(), + ), + "check_suite" => Some( + payload["check_suite"]["pull_requests"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p["number"].as_u64()) + .take(5) + .collect(), + ), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const NOW: i64 = 1_800_000_000; + + fn opened() -> Value { + json!({ + "action": "opened", + "sender": {"login": "octocat"}, + "pull_request": { + "number": 318, "title": "Round cart totals per currency", + "html_url": "https://github.com/acme/web/pull/318", + "user": {"login": "octocat"}, "draft": false, "state": "open", "merged": false, + "head": {"sha": "aaaaaaa1111111", "ref": "fix/cart-rounding"}, + "base": {"ref": "main"}, + "created_at": "2026-01-10T10:00:00Z", "updated_at": "2026-01-10T10:00:00Z", + "requested_reviewers": [{"login": "mara"}], "requested_teams": [], + "labels": [{"name": "bookstore"}], + "body": "Fixes rounding.\n\n## Compatibility\n- acme/api#12 adds the field\n" + } + }) + } + + #[test] + fn a_persons_pull_request_is_recorded_from_its_events() { + let mut r = PrRecord::new("acme/web", 318); + assert!(r.apply_event("pull_request", &opened(), NOW)); + assert!(r.known); + assert_eq!(r.author, "octocat"); + assert_eq!(r.requested, vec!["mara"]); + assert_eq!( + r.links, + vec![Link { + kind: "contract".into(), + repo: "acme/api".into(), + number: 12 + }] + ); + // A check run on the head, then a review asking for changes. + let run = json!({"action": "completed", "check_run": {"name": "lint", "head_sha": "aaaaaaa1111111", + "status": "completed", "conclusion": "failure", "completed_at": "2026-01-10T10:05:00Z", + "pull_requests": [{"number": 318}]}}); + assert!(r.apply_event("check_run", &run, NOW)); + let f = r.facts(); + assert_eq!(f.checks.failed, vec!["lint"]); + let review = json!({"action": "submitted", "review": {"user": {"login": "mara"}, "state": "changes_requested", + "commit_id": "aaaaaaa1111111", "submitted_at": "2026-01-10T11:00:00Z"}, "pull_request": {"number": 318}}); + assert!(r.apply_event("pull_request_review", &review, NOW)); + assert_eq!(r.facts().changes_requested_by, vec!["mara"]); + assert!(r.requested.is_empty()); + assert!(r.people["mara"].contains(&"reviewer".to_string())); + // A check on another commit says nothing about the head. + let other = + json!({"check_run": {"name": "unit", "head_sha": "bbbbbbb", "status": "queued"}}); + assert!(!r.apply_event("check_run", &other, NOW)); + } + + #[test] + fn a_push_after_changes_requested_asks_for_a_re_review() { + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW); + r.reviews.insert( + "mara".into(), + Review { + state: "CHANGES_REQUESTED".into(), + sha: "aaaaaaa1111111".into(), + at: NOW, + }, + ); + let mut sync = opened(); + sync["action"] = json!("synchronize"); + sync["pull_request"]["head"]["sha"] = json!("ccccccc2222222"); + r.apply_event("pull_request", &sync, NOW); + assert!(r.facts().pushed_since_changes); + assert!(r.checks.is_empty(), "checks belong to the old head"); + assert!(r.people["octocat"].contains(&"committer".to_string())); + } + + #[test] + fn asking_coderhelm_in_a_comment_names_the_requester() { + let mut r = PrRecord::new("acme/web", 318); + let c = json!({"action": "created", "issue": {"number": 318, "pull_request": {}}, + "comment": {"user": {"login": "theo"}, "body": "@coderhelm fix ci", "created_at": "2026-01-10T12:00:00Z"}}); + assert!(r.apply_event("issue_comment", &c, NOW)); + assert_eq!(r.requester, "theo"); + assert_eq!(event_prs("issue_comment", &c), Some(vec![318])); + } + + #[test] + fn the_sync_node_fills_what_events_dont_carry() { + let node = json!({ + "number": 318, "title": "Round cart totals", "url": "https://github.com/acme/web/pull/318", + "state": "OPEN", "isDraft": false, "createdAt": "2026-01-10T10:00:00Z", + "updatedAt": "2026-01-10T12:00:00Z", "additions": 40, "deletions": 3, + "headRefName": "fix/cart-rounding", "headRefOid": "aaaaaaa1111111", "baseRefName": "main", + "reviewDecision": "REVIEW_REQUIRED", "mergeable": "MERGEABLE", "mergeStateStatus": "BLOCKED", + "isInMergeQueue": false, "author": {"login": "octocat"}, "autoMergeRequest": null, + "labels": {"nodes": []}, + "reviewRequests": {"nodes": [{"requestedReviewer": {"slug": "payments"}}]}, + "latestOpinionatedReviews": {"nodes": []}, + "participants": {"nodes": [{"login": "jun"}]}, + "reviewThreads": {"nodes": [{"isResolved": false, "comments": {"nodes": [{"author": {"login": "jun"}}]}}]}, + "baseRef": {"branchProtectionRule": {"requiredApprovingReviewCount": 1, "requiresCodeOwnerReviews": true, + "requiresConversationResolution": true, "requiredStatusCheckContexts": ["unit"]}}, + "commits": {"nodes": [{"commit": {"statusCheckRollup": {"contexts": {"nodes": [ + {"__typename": "CheckRun", "name": "unit", "status": "COMPLETED", "conclusion": "SUCCESS"}]}}}}]} + }); + let mut r = PrRecord::new("acme/web", 318); + r.apply_node(&node, NOW); + assert_eq!(r.requested_teams, vec!["acme/payments"]); + assert_eq!(r.open_threads, 1); + assert_eq!(r.thread_authors, vec!["jun"]); + assert_eq!(r.conflict, Some(false)); + let n = pr_needs::decide("acme/web", &r.facts()); + assert_eq!(n.state, pr_needs::State::NeedsReview, "{n:?}"); + assert!(n.next.text.contains("@acme/payments"), "{}", n.next.text); + assert_eq!(r.synced_at, NOW); + } + + #[test] + fn the_ledger_counts_who_held_the_turn() { + let mut r = PrRecord::new("acme/web", 318); + r.created_at = NOW - 100; + let mut n = pr_needs::decide("acme/web", &Facts::default()); + assert!(r.note_needs(&n, NOW)); + assert!(!r.note_needs(&n, NOW + 5), "the same step is one span"); + n.next.from = vec!["person:mara".into()]; + assert!(r.note_needs(&n, NOW + 50)); + let t = ledger_totals(&r.spans, NOW + 80); + assert_eq!(t[0], ("nobody".to_string(), 150)); + assert_eq!(t[1], ("person:mara".to_string(), 30)); + } + + #[test] + fn an_open_record_never_expires_and_a_closed_one_does() { + let mut r = PrRecord::new("acme/web", 318); + assert_eq!(r.ttl(), None); + r.status = "merged".into(); + r.closed_at = NOW; + assert_eq!(r.ttl(), Some(NOW + CLOSED_KEEP_SECS)); + } +} diff --git a/services/common/src/pr_view.rs b/services/common/src/pr_view.rs new file mode 100644 index 000000000..d055b96e4 --- /dev/null +++ b/services/common/src/pr_view.rs @@ -0,0 +1,1045 @@ +//! The pull requests view: every open pull request of one team, each with +//! its one state from [`crate::pr_needs::decide`], filtered, counted and +//! paged for `GET /api/prs`. +//! +//! Everything here is pure: the gateway reads the team's records +//! ([`crate::pr_record`]), its runs on them and its reviewer's records, and +//! hands them in. [`rows`] keeps only the records whose key names the team +//! asking, so a record of another team never reaches a row, whatever the +//! read returned. + +use std::collections::{BTreeMap, HashMap}; + +use serde::Serialize; + +use crate::merge_standing::Standing; +use crate::pr_needs::{self, Facts, Needs, Own, OwnStanding, State, Stop, Turn}; +use crate::pr_record::{self, Item, Link, PrRecord}; + +/// CoderHelm's run on a pull request, as the runs table has it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RunJoin { + pub run_id: String, + pub status: String, + pub title: String, + pub sender: String, + pub current_pass: String, + pub created_at: String, + pub updated_at: String, + pub round: u32, + /// The standing the watch stored (`merge_standing::FIELD`). + pub standing: Option, + /// `needs_input`: the hand-off's code and line. + pub stop: Option, + /// A limit of CoderHelm's own, its line. + pub own_problem: Option, + /// The run's other pull requests, in merge order (`owner/repo#n`). + pub plan: Vec, + /// Pull requests this one merges after (from `repo_ci`). + pub after: Vec, +} + +/// The reviewer's records on a pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ReviewJoin { + /// A review of the head is queued or running. + pub reviewing: bool, + pub session_id: String, + /// CoderHelm's auto-merge gate is armed (waiting, not stopped). + pub gate_armed: bool, +} + +/// Everything joined to the records. +#[derive(Debug, Clone, Default)] +pub struct Joins { + pub runs: HashMap, + /// By `owner/repo#n`. + pub reviews: HashMap, +} + +/// One person on the pull request. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Person { + pub login: String, + pub roles: Vec, + pub coderhelm: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Author { + pub login: String, + pub coderhelm: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct NextOut { + pub code: String, + pub text: String, + pub from: Vec, + pub since: Option, + pub rule: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct ChecksOut { + pub total: u32, + pub passed: u32, + pub failed: u32, + pub running: u32, + pub required_failed: Vec, + pub known: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct ReviewsOut { + pub approvals: u32, + pub required: u32, + pub changes_requested_by: Vec, + pub requested: Vec, + pub coderhelm_verdict: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct SizeOut { + pub additions: u32, + pub deletions: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct LastAction { + pub actor: String, + pub text: String, + pub at: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CoderHelmOut { + pub run_id: Option, + pub session_id: Option, + pub round: u32, + pub working: bool, + pub what: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct LinkOut { + pub kind: String, + pub repo: String, + pub number: u64, + pub url: String, + pub state: Option, +} + +/// One row of the list. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Row { + pub key: String, + pub org: String, + pub repo: String, + pub number: u64, + pub title: String, + pub url: String, + pub author: Author, + /// For CoderHelm's pull request: the person it works for. + #[serde(rename = "for")] + pub for_person: Option, + pub draft: bool, + pub base: String, + pub head: String, + pub created_at: Option, + pub updated_at: Option, + pub state: String, + pub state_label: String, + pub turn: String, + pub next: NextOut, + pub modifiers: Vec, + pub people: Vec, + pub checks: ChecksOut, + pub reviews: ReviewsOut, + pub conflict: Option, + pub open_threads: u32, + pub labels: Vec, + pub size: Option, + pub last_action: Option, + pub coderhelm: Option, + pub links: Vec, + pub waiting_since: Option, + /// Sort and filter keys, not sent. + #[serde(skip)] + pub rank: (u8, u8, i64), + #[serde(skip)] + pub involves: Vec, + #[serde(skip)] + pub stale: bool, +} + +pub fn rfc3339(secs: i64) -> Option { + (secs > 0) + .then(|| chrono::DateTime::from_timestamp(secs, 0)) + .flatten() + .map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) +} + +fn parse_time(s: &str) -> i64 { + chrono::DateTime::parse_from_rfc3339(s) + .map(|d| d.timestamp()) + .unwrap_or(0) +} + +/// What CoderHelm does now, from the run's step. +pub fn what_of(current_pass: &str) -> &'static str { + match current_pass { + "triage" => "reading the ticket", + "plan" => "planning the change", + "implement" => "writing the change", + "review" | "self_review" => "reviewing its own change", + "pr" => "opening the pull request", + "ci" | "ci_fix" | "fix_ci" => "fixing CI", + "feedback" | "fix_round" => "addressing review comments", + "conflict" | "conflicts" | "resolve_conflicts" => "resolving conflicts", + _ => "working on it", + } +} + +/// Run statuses in which CoderHelm works on the pull request now. +pub const RUN_ACTIVE: &[&str] = &[ + crate::run_status::PENDING, + crate::run_status::QUEUED, + crate::run_status::RUNNING, +]; + +fn run_active(status: &str) -> bool { + RUN_ACTIVE.contains(&status) +} + +/// The team's records out of the read: only items whose key is the team's. +pub fn records_of(team_id: &str, items: &[Item]) -> Vec { + items + .iter() + .filter(|i| i.get("pk").and_then(|v| v.as_s().ok()).map(String::as_str) == Some(team_id)) + .filter(|i| { + i.get("sk") + .and_then(|v| v.as_s().ok()) + .is_some_and(|s| s.starts_with(pr_record::SK_PREFIX)) + }) + .filter_map(|i| pr_record::from_item(i).map(|(r, _)| r)) + .collect() +} + +/// The facts of one record with its joins. +pub fn facts_of( + rec: &PrRecord, + run: Option<&RunJoin>, + review: Option<&ReviewJoin>, + open_keys: &BTreeMap, +) -> Facts { + let mut f = rec.facts(); + if let Some(r) = review { + f.reviewing = r.reviewing; + f.coderhelm_merges = r.gate_armed; + } + if let Some(run) = run { + f.own = Some(Own { + run_id: run.run_id.clone(), + requester: if run.sender.is_empty() { + rec.requester.clone() + } else { + run.sender.clone() + }, + active: run_active(&run.status), + what: what_of(&run.current_pass).to_string(), + round: run.round, + stopped: run.stop.clone(), + own_problem: run.own_problem.clone(), + standing: rec + .author_is_coderhelm() + .then(|| run.standing.clone().map(OwnStanding::Decided)) + .flatten(), + }); + } + // Pull requests it merges after that are still open. + for l in &rec.links { + let key = format!("{}#{}", l.repo, l.number); + if matches!(l.kind.as_str(), "stack_base" | "depends") && open_keys.contains_key(&key) { + f.waits_on.push(key); + } + } + if let Some(run) = run { + for k in &run.after { + if open_keys.contains_key(k) && !f.waits_on.contains(k) { + f.waits_on.push(k.clone()); + } + } + } + f +} + +/// Links between the team's own records: a pull request based on another's +/// branch is stacked on it; the run's plan links its pull requests. +pub fn link_records(recs: &mut [PrRecord], joins: &Joins) { + let heads: HashMap<(String, String), u64> = recs + .iter() + .filter(|r| r.is_open() && !r.head_ref.is_empty()) + .map(|r| ((r.repo.clone(), r.head_ref.clone()), r.number)) + .collect(); + let mut children: HashMap<(String, u64), Vec> = HashMap::new(); + for r in recs.iter_mut() { + r.links.retain(|l| { + !matches!( + l.kind.as_str(), + "stack_base" | "stack_child" | "plan" | "depends" + ) + }); + if let Some(n) = heads.get(&(r.repo.clone(), r.base_ref.clone())) { + if *n != r.number { + r.links.push(Link { + kind: "stack_base".into(), + repo: r.repo.clone(), + number: *n, + }); + children + .entry((r.repo.clone(), *n)) + .or_default() + .push(r.number); + } + } + if let Some(run) = joins.runs.get(&r.coderhelm.run_id) { + let me = format!("{}#{}", r.repo, r.number); + for k in run.plan.iter().filter(|k| **k != me) { + if let Some((repo, n)) = k.rsplit_once('#') { + if let Ok(n) = n.parse() { + let kind = if run.after.contains(k) { + "depends" + } else { + "plan" + }; + r.links.push(Link { + kind: kind.into(), + repo: repo.into(), + number: n, + }); + } + } + } + } + } + for r in recs.iter_mut() { + if let Some(kids) = children.get(&(r.repo.clone(), r.number)) { + for k in kids { + r.links.push(Link { + kind: "stack_child".into(), + repo: r.repo.clone(), + number: *k, + }); + } + } + } +} + +fn turn_rank(turn: &str) -> u8 { + match turn { + "you" => 0, + "coderhelm" => 1, + "person" => 2, + "machines" => 3, + _ => 4, + } +} + +/// The turn as the viewer sees it: theirs when they are among who acts. +pub fn viewer_turn(n: &Needs, viewer: Option<&str>) -> String { + if n.turn == Turn::Person { + if let Some(v) = viewer.filter(|v| !v.is_empty()) { + let me = pr_needs::person(v); + if n.next.from.iter().any(|f| f.eq_ignore_ascii_case(&me)) { + return "you".into(); + } + } + } + n.turn.code().to_string() +} + +/// One row per record of the team, each with its one state. +pub fn rows( + team_id: &str, + items: &[Item], + joins: &Joins, + viewer: Option<&str>, + now: i64, +) -> Vec { + let mut recs = records_of(team_id, items); + link_records(&mut recs, joins); + let mut decided: Vec<(PrRecord, Needs, Facts)> = Vec::new(); + let open_keys: BTreeMap = recs + .iter() + .filter(|r| r.is_open()) + .map(|r| (format!("{}#{}", r.repo, r.number), String::new())) + .collect(); + for r in recs { + let key = format!("{}#{}", r.repo, r.number); + let run = joins.runs.get(&r.coderhelm.run_id); + let review = joins.reviews.get(&key); + let f = facts_of(&r, run, review, &open_keys); + let n = pr_needs::decide(&r.repo, &f); + decided.push((r, n, f)); + } + let states: HashMap = decided + .iter() + .map(|(r, n, _)| { + ( + format!("{}#{}", r.repo, r.number), + n.state.code().to_string(), + ) + }) + .collect(); + // The repository's usual wait in each state: a row waiting longer than + // three in four of its peers is stale (none below four peers). + let mut waits: HashMap<(String, State), Vec> = HashMap::new(); + for (r, n, _) in &decided { + if r.is_open() { + let since = waiting_since(r); + waits + .entry((r.repo.clone(), n.state)) + .or_default() + .push(now - since); + } + } + let p75: HashMap<(String, State), i64> = waits + .into_iter() + .filter(|(_, v)| v.len() >= 4) + .map(|(k, mut v)| { + v.sort(); + let i = (v.len() * 3).div_ceil(4).saturating_sub(1); + (k, v[i]) + }) + .collect(); + decided + .into_iter() + .map(|(r, n, f)| { + let since = waiting_since(&r); + let stale = r.is_open() + && p75 + .get(&(r.repo.clone(), n.state)) + .is_some_and(|p| now - since > *p && *p > 0); + row(&r, &n, &f, joins, &states, viewer, since, stale) + }) + .collect() +} + +fn waiting_since(r: &PrRecord) -> i64 { + r.spans + .last() + .map(|s| s.from) + .filter(|t| *t > 0) + .unwrap_or(r.created_at) +} + +#[allow(clippy::too_many_arguments)] +fn row( + r: &PrRecord, + n: &Needs, + f: &Facts, + joins: &Joins, + states: &HashMap, + viewer: Option<&str>, + since: i64, + stale: bool, +) -> Row { + let key = format!("{}#{}", r.repo, r.number); + let run = joins.runs.get(&r.coderhelm.run_id); + let review = joins.reviews.get(&key); + let turn = viewer_turn(n, viewer); + let for_person = r + .author_is_coderhelm() + .then(|| { + run.map(|x| x.sender.clone()) + .filter(|s| !s.is_empty()) + .or_else(|| (!r.requester.is_empty()).then(|| r.requester.clone())) + }) + .flatten(); + let mut people: Vec = r + .people + .iter() + .map(|(login, roles)| Person { + login: login.clone(), + roles: roles.clone(), + coderhelm: login == "coderhelm", + }) + .collect(); + if let Some(p) = &for_person { + match people.iter_mut().find(|x| &x.login == p) { + Some(x) if !x.roles.iter().any(|r| r == "requester") => { + x.roles.push("requester".into()) + } + Some(_) => {} + None => people.push(Person { + login: p.clone(), + roles: vec!["requester".into()], + coderhelm: false, + }), + } + } + if (run.is_some() || review.is_some()) && !people.iter().any(|p| p.coderhelm) { + people.push(Person { + login: "coderhelm".into(), + roles: vec![if run.is_some() { "worker" } else { "reviewer" }.into()], + coderhelm: true, + }); + } + // Author first. + people.sort_by_key(|p| (!p.roles.iter().any(|r| r == "author"), p.login.clone())); + let (blocking, _) = f.checks.blocking(); + let mut modifiers = Vec::new(); + if stale { + modifiers.push("stale".to_string()); + } + if r.links + .iter() + .any(|l| matches!(l.kind.as_str(), "stack_base" | "stack_child")) + { + modifiers.push("stacked".into()); + } + if r.author_is_coderhelm() { + modifiers.push("agent_authored".into()); + } + if r.additions + r.deletions >= 1000 { + modifiers.push("large".into()); + } + let last = r.events.last().map(|e| LastAction { + actor: e.actor.clone(), + text: e.text.clone(), + at: rfc3339(e.at).unwrap_or_default(), + }); + let coderhelm = (run.is_some() + || review.is_some_and(|v| !v.session_id.is_empty() || v.reviewing)) + .then(|| CoderHelmOut { + run_id: run.map(|x| x.run_id.clone()), + session_id: review + .map(|v| v.session_id.clone()) + .filter(|s| !s.is_empty()), + round: run.map(|x| x.round).unwrap_or(0), + working: n.state == State::CoderHelmWorking, + what: if review.is_some_and(|v| v.reviewing) && !run.is_some_and(|x| run_active(&x.status)) + { + "reviewing".into() + } else { + run.map(|x| what_of(&x.current_pass).to_string()) + .unwrap_or_default() + }, + }); + let links = r + .links + .iter() + .map(|l| { + let k = format!("{}#{}", l.repo, l.number); + LinkOut { + kind: l.kind.clone(), + repo: l.repo.clone(), + number: l.number, + url: format!("https://github.com/{}/pull/{}", l.repo, l.number), + state: states.get(&k).cloned(), + } + }) + .collect(); + let mut involves: Vec = r.people.keys().map(|k| k.to_ascii_lowercase()).collect(); + if let Some(p) = &for_person { + involves.push(p.to_ascii_lowercase()); + } + let blocks_others = r.links.iter().any(|l| l.kind == "stack_child") + || r.labels.iter().any(|l| l.eq_ignore_ascii_case("hotfix")); + Row { + key, + org: r.org().to_string(), + repo: r.repo.clone(), + number: r.number, + title: r.title.clone(), + url: if r.url.is_empty() { + format!("https://github.com/{}/pull/{}", r.repo, r.number) + } else { + r.url.clone() + }, + author: Author { + login: r.author.clone(), + coderhelm: r.author_is_coderhelm(), + }, + for_person, + draft: r.draft, + base: r.base_ref.clone(), + head: r.head_ref.clone(), + created_at: rfc3339(r.created_at), + updated_at: rfc3339(r.updated_at.max(r.event_at)), + state: n.state.code().into(), + state_label: n.state.label().into(), + turn: turn.clone(), + next: NextOut { + code: n.next.code.clone(), + text: n.next.text.clone(), + from: n.next.from.clone(), + since: rfc3339(since), + rule: n.next.rule.map(|r| { + serde_json::to_value(r) + .ok() + .and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_default() + }), + }, + modifiers, + people, + checks: ChecksOut { + total: f.checks.total, + passed: f.checks.passed, + failed: f.checks.failed.len() as u32, + running: f.checks.running.len() as u32, + required_failed: if f.checks.required.is_empty() { + vec![] + } else { + blocking + }, + known: f.checks.known, + }, + reviews: ReviewsOut { + approvals: f.approved_by.len() as u32, + required: f.approvals_required, + changes_requested_by: f.changes_requested_by.clone(), + requested: f + .requested + .iter() + .cloned() + .chain(f.requested_teams.iter().cloned()) + .collect(), + coderhelm_verdict: f.coderhelm_verdict.as_ref().map(|(v, _)| v.clone()), + }, + conflict: f.conflict, + open_threads: f.open_threads, + labels: r.labels.clone(), + size: (r.additions + r.deletions > 0).then_some(SizeOut { + additions: r.additions, + deletions: r.deletions, + }), + last_action: last, + coderhelm, + links, + waiting_since: rfc3339(since), + rank: ( + turn_rank(&turn), + if n.state == State::NeedsDecision { + 0 + } else if blocks_others { + 1 + } else { + 2 + }, + since, + ), + involves, + stale, + } +} + +/// The list's filters. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Query { + pub org: Option, + pub repo: Option, + pub turn: Option, + pub states: Vec, + pub person: Option, + pub q: Option, + pub view: Option, +} + +/// The saved views, by code. +pub const VIEWS: &[&str] = &[ + "my_turn", + "coderhelm_working", + "needs_decision", + "ready", + "stale", +]; + +fn in_view(row: &Row, view: &str) -> bool { + match view { + "my_turn" => row.turn == "you", + "coderhelm_working" => row.state == "coderhelm_working", + "needs_decision" => row.state == "needs_decision", + "ready" => matches!(row.state.as_str(), "ready_to_merge" | "ready_auto_merge"), + "stale" => row.stale, + _ => true, + } +} + +fn in_scope(row: &Row, q: &Query) -> bool { + q.org + .as_deref() + .is_none_or(|o| row.org.eq_ignore_ascii_case(o)) + && q.repo + .as_deref() + .is_none_or(|r| row.repo.eq_ignore_ascii_case(r)) +} + +fn matches(row: &Row, q: &Query) -> bool { + if let Some(t) = q.turn.as_deref() { + if row.turn != t { + return false; + } + } + if !q.states.is_empty() && !q.states.iter().any(|s| s == &row.state) { + return false; + } + if let Some(p) = q.person.as_deref() { + let p = p.trim_start_matches('@').to_ascii_lowercase(); + if !row.involves.contains(&p) { + return false; + } + } + if let Some(v) = q.view.as_deref() { + if !in_view(row, v) { + return false; + } + } + if let Some(text) = q.q.as_deref().map(str::trim).filter(|t| !t.is_empty()) { + let t = text.to_ascii_lowercase(); + let hay = format!( + "{} {}#{} #{} {} {} {}", + row.title, row.repo, row.number, row.number, row.author.login, row.head, row.next.text + ) + .to_ascii_lowercase(); + if !t.split_whitespace().all(|w| hay.contains(w)) { + return false; + } + } + true +} + +/// Counts over the scope, before the other filters: the strip and the +/// saved views always show their totals. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Counts { + pub turn: BTreeMap, + pub state: BTreeMap, + pub repo: BTreeMap, + pub org: BTreeMap, + pub views: BTreeMap, +} + +/// One page. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Page { + pub rows: Vec, + pub total: usize, + pub next: Option, + pub counts: Counts, +} + +/// Filter, count, order and page the rows. The cursor is the offset into +/// the ordered, filtered list (`o:`). +pub fn page(mut all: Vec, q: &Query, limit: usize, cursor: Option<&str>) -> Page { + let mut counts = Counts::default(); + for r in all.iter() { + *counts.org.entry(r.org.clone()).or_default() += 1; + if q.org + .as_deref() + .is_none_or(|o| r.org.eq_ignore_ascii_case(o)) + { + *counts.repo.entry(r.repo.clone()).or_default() += 1; + } + } + all.retain(|r| in_scope(r, q)); + for r in &all { + *counts.turn.entry(r.turn.clone()).or_default() += 1; + *counts.state.entry(r.state.clone()).or_default() += 1; + for v in VIEWS { + if in_view(r, v) { + *counts.views.entry(v.to_string()).or_default() += 1; + } + } + } + for v in VIEWS { + counts.views.entry(v.to_string()).or_default(); + } + all.retain(|r| matches(r, q)); + all.sort_by(|a, b| a.rank.cmp(&b.rank).then_with(|| a.key.cmp(&b.key))); + let total = all.len(); + let start = cursor + .and_then(|c| c.strip_prefix("o:")) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0) + .min(total); + let limit = limit.clamp(1, 200); + let end = (start + limit).min(total); + let next = (end < total).then(|| format!("o:{end}")); + let rows = all.drain(start..end).collect(); + Page { + rows, + total, + next, + counts, + } +} + +/// The wait ledger of one record, up to `now` (or when it closed). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct LedgerSpan { + pub who: String, + pub state: String, + pub from: Option, + pub to: Option, + pub secs: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct LedgerTotal { + pub who: String, + pub secs: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Ledger { + pub open_secs: i64, + pub spans: Vec, + pub totals: Vec, +} + +/// The ledger, with the current decision as its live last span when it +/// differs from the stored one (the run or the reviewer moved since the +/// last event). +pub fn ledger(r: &PrRecord, n: &Needs, now: i64) -> Ledger { + let mut rec = r.clone(); + rec.note_needs(n, now); + let end = if r.is_open() { now } else { r.closed_at.max(1) }; + let spans: Vec = rec + .spans + .iter() + .enumerate() + .map(|(i, s)| { + let to = rec.spans.get(i + 1).map(|x| x.from); + LedgerSpan { + who: s.who.clone(), + state: s.state.clone(), + from: rfc3339(s.from), + to: to.and_then(rfc3339), + secs: (to.unwrap_or(end) - s.from).max(0), + } + }) + .collect(); + let totals = pr_record::ledger_totals(&rec.spans, end) + .into_iter() + .map(|(who, secs)| LedgerTotal { who, secs }) + .collect(); + Ledger { + open_secs: (end + - rec + .created_at + .max(rec.spans.first().map(|s| s.from).unwrap_or(end))) + .max(0), + spans, + totals, + } +} + +/// One timeline event out. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct TimelineEvent { + pub at: String, + pub actor: String, + pub coderhelm: bool, + pub kind: String, + pub text: String, + pub run_id: Option, +} + +/// The timeline, oldest first: the record's events, and CoderHelm's runs +/// as one event each (the dashboard folds a run's events under it). +pub fn timeline(r: &PrRecord, runs: &[RunJoin]) -> Vec { + let mut out: Vec<(i64, TimelineEvent)> = r + .events + .iter() + .map(|e| { + ( + e.at, + TimelineEvent { + at: rfc3339(e.at).unwrap_or_default(), + actor: e.actor.clone(), + coderhelm: e.actor == "coderhelm", + kind: e.kind.clone(), + text: e.text.clone(), + run_id: None, + }, + ) + }) + .collect(); + for run in runs { + let start = parse_time(&run.created_at); + let end = parse_time(&run.updated_at).max(start); + // CoderHelm's own events inside the run's time are the run's. + for (t, e) in out.iter_mut() { + if e.coderhelm && *t >= start && *t <= end && e.run_id.is_none() { + e.run_id = Some(run.run_id.clone()); + } + } + out.push(( + start, + TimelineEvent { + at: rfc3339(start).unwrap_or_default(), + actor: "coderhelm".into(), + coderhelm: true, + kind: "run".into(), + text: if run.title.is_empty() { + format!("run: {}", run.status) + } else { + format!("{} ({})", run.title, run.status) + }, + run_id: Some(run.run_id.clone()), + }, + )); + } + out.sort_by_key(|(t, _)| *t); + out.into_iter().map(|(_, e)| e).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use aws_sdk_dynamodb::types::AttributeValue; + + const NOW: i64 = 1_800_000_000; + + 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).unwrap()), + ); + i + } + + fn rec(repo: &str, n: u64, author: &str) -> PrRecord { + let mut r = PrRecord::new(repo, n); + r.known = true; + r.title = format!("Bookstore change {n}"); + r.author = author.into(); + r.people.insert(author.into(), vec!["author".into()]); + r.head_sha = "aaaaaaa1111111".into(); + r.checks_sha = r.head_sha.clone(); + r.checks.insert( + "unit".into(), + pr_record::Check { + status: "completed".into(), + conclusion: "success".into(), + at: NOW, + }, + ); + r.conflict = Some(false); + r.created_at = NOW - 3600; + r + } + + #[test] + fn another_teams_record_never_becomes_a_row() { + let mine = rec("acme/web", 1, "octocat"); + let theirs = rec("acme/web", 2, "octocat"); + let items = vec![item("TEAM#a", &mine), item("TEAM#b", &theirs)]; + let rows = rows("TEAM#a", &items, &Joins::default(), None, NOW); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].number, 1); + } + + #[test] + fn the_viewers_turn_is_theirs_and_views_count_before_filters() { + let mut a = rec("acme/web", 1, "octocat"); + a.requested = vec!["mara".into()]; + a.approvals_required = 1; + let b = rec("acme/api", 2, "theo"); + let items = vec![item("TEAM#a", &a), item("TEAM#a", &b)]; + let all = rows("TEAM#a", &items, &Joins::default(), Some("mara"), NOW); + let q = Query { + view: Some("my_turn".into()), + ..Default::default() + }; + let p = page(all.clone(), &q, 50, None); + assert_eq!(p.total, 1); + assert_eq!(p.rows[0].turn, "you"); + assert_eq!(p.counts.views["my_turn"], 1); + assert_eq!(p.counts.org["acme"], 2); + let q = Query { + repo: Some("acme/api".into()), + ..Default::default() + }; + let p = page(all, &q, 50, None); + assert_eq!(p.total, 1); + assert_eq!(p.counts.repo.len(), 2, "repos count across the org"); + } + + #[test] + fn a_stacked_pull_request_waits_on_its_base() { + let mut base = rec("acme/web", 1, "octocat"); + base.head_ref = "feature/a".into(); + base.base_ref = "main".into(); + let mut top = rec("acme/web", 2, "octocat"); + top.head_ref = "feature/b".into(); + top.base_ref = "feature/a".into(); + let items = vec![item("TEAM#a", &base), item("TEAM#a", &top)]; + let all = rows("TEAM#a", &items, &Joins::default(), None, NOW); + let top = all.iter().find(|r| r.number == 2).unwrap(); + assert_eq!(top.state, "waiting_on_pr"); + assert!(top.modifiers.contains(&"stacked".to_string())); + let base = all.iter().find(|r| r.number == 1).unwrap(); + assert!(base.links.iter().any(|l| l.kind == "stack_child")); + } + + #[test] + fn paging_is_by_cursor_and_ends() { + let items: Vec = (1..=5) + .map(|n| item("TEAM#a", &rec("acme/web", n, "octocat"))) + .collect(); + let all = rows("TEAM#a", &items, &Joins::default(), None, NOW); + let p = page(all.clone(), &Query::default(), 2, None); + assert_eq!(p.rows.len(), 2); + assert_eq!(p.next.as_deref(), Some("o:2")); + let p = page(all, &Query::default(), 2, Some("o:4")); + assert_eq!(p.rows.len(), 1); + assert_eq!(p.next, None); + } + + #[test] + fn a_coderhelm_pull_request_is_for_its_requester_and_folds_its_runs() { + let mut r = rec("acme/web", 7, "coderhelm[bot]"); + r.coderhelm.run_id = "run-1".into(); + r.events.push(pr_record::Event { + at: NOW - 100, + actor: "coderhelm".into(), + kind: "pushed".into(), + text: "pushed".into(), + run_id: String::new(), + }); + let run = RunJoin { + run_id: "run-1".into(), + status: "running".into(), + sender: "octocat".into(), + current_pass: "ci_fix".into(), + round: 2, + created_at: rfc3339(NOW - 200).unwrap(), + updated_at: rfc3339(NOW).unwrap(), + ..Default::default() + }; + let mut joins = Joins::default(); + joins.runs.insert("run-1".into(), run.clone()); + let all = rows("TEAM#a", &[item("TEAM#a", &r)], &joins, None, NOW); + assert_eq!(all[0].for_person.as_deref(), Some("octocat")); + assert_eq!(all[0].state, "coderhelm_working"); + assert!( + all[0].next.text.contains("fixing CI, round 2"), + "{}", + all[0].next.text + ); + let t = timeline(&r, &[run]); + assert!(t + .iter() + .all(|e| !e.coderhelm || e.run_id.as_deref() == Some("run-1"))); + } +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index a374b1e04..b02b645a1 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -691,6 +691,8 @@ fn build_app(state: Arc) -> Router { .route("/reviewer/review", get(routes::reviewer::get_review)) .route("/reviewer/session", get(routes::reviewer::get_session)) .route("/reviewer/live", get(routes::reviewer::live_prs)) + .route("/prs", get(routes::prs::list_prs)) + .route("/prs/detail", get(routes::prs::get_pr)) .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 ee9b660f3..6f488995f 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -125,6 +125,8 @@ pub const CAPABILITIES: &[Capability] = &[ "reviewer::get_review", "reviewer::get_session", "reviewer::open_prs", + "prs::list_prs", + "prs::get_pr", "review_lessons::list_lessons", "learning::get_learning", "learning::get_health", diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index c5d1e5bcd..acb99c2ac 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -443,6 +443,23 @@ async fn route( .await; } } + // Installed, or repositories added: the team's open pull requests + // are read once, in the background (`pr_records` in the worker). + if !team.is_empty() + && r.is_ok() + && matches!( + payload["action"].as_str(), + Some("created" | "added" | "new_permissions_accepted" | "unsuspend") + ) + { + let sync = WorkerMessage::PrRecordsSync(common::messages::PrRecordsSyncMessage { + team_id: team.clone(), + installation_id, + }); + if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &sync).await { + warn!(error = ?e, "Could not ask for the team's open pull requests to be read"); + } + } d.target = team.clone(); return (r, team); } @@ -497,6 +514,21 @@ async fn dispatch( .await; // Activity on a pull request takes CoderHelm's stale label off now. super::stale_prs::on_webhook(state, event_type, payload, team_id).await; + // Every pull request's record follows its events, people's pull + // requests as much as CoderHelm's (the pull requests view). + if matches!( + event_type, + "pull_request" + | "pull_request_review" + | "pull_request_review_comment" + | "issue_comment" + | "check_run" + | "check_suite" + | "status" + | "push" + ) { + super::prs::on_webhook(state, team_id, event_type, payload).await; + } // A plan task's pull request moved: its plan's state follows. if matches!( event_type, @@ -2172,7 +2204,8 @@ async fn handle_pull_request( record_revert(state, payload, team_id, installation_id).await; } - // Only track our PRs + // The rest is for CoderHelm's own runs; every pull request's record + // (people's too) was written in `dispatch` (`prs::on_webhook`). let pr_user = payload["pull_request"]["user"]["login"] .as_str() .unwrap_or(""); @@ -5529,7 +5562,7 @@ async fn trigger_plan_dependents( } /// Look up run_id from the runs table by PR number using the repo-index GSI. -async fn lookup_run_by_pr( +pub(super) async fn lookup_run_by_pr( state: &AppState, team_id: &str, owner: &str, diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 21817c6d9..541b684ed 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -81,6 +81,7 @@ pub mod plans; pub mod plugin_pkgs; pub mod plugins; pub mod preview_access; +pub mod prs; 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 new file mode 100644 index 000000000..9c7057222 --- /dev/null +++ b/services/gateway/src/routes/prs.rs @@ -0,0 +1,600 @@ +//! The pull requests view: every open pull request in the team's +//! repositories, where it is, who worked on it, its one state, and what it +//! needs next from whom. +//! +//! - [`on_webhook`] writes each pull request's record +//! (`common::pr_record`) from the GitHub events the gateway already +//! receives, for every pull request, not only CoderHelm's. +//! - `GET /api/prs` ([`list_prs`]) and `GET /api/prs/detail` +//! ([`get_pr`]) read the team's records, join CoderHelm's runs and its +//! reviewer's records, and decide each one's state with +//! `common::pr_needs::decide`, the same function the merge gates use. +//! +//! The team is the session's, never a parameter; every read is keyed by it, +//! and the rows keep only records whose key is the team's +//! (`common::pr_view::records_of`). The short cache is keyed by the +//! installation and the team. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock}; +use std::time::{Duration, Instant}; + +use aws_sdk_dynamodb::types::{AttributeValue, KeysAndAttributes}; +use axum::{ + extract::{Query, State}, + http::StatusCode, + Extension, Json, +}; +use common::pr_record::{self, Item, PrRecord}; +use common::pr_view::{self, Joins, ReviewJoin, RunJoin}; +use serde::Deserialize; +use serde_json::{json, Value}; +use tracing::{error, warn}; + +use super::run_checks::{read_key, TtlCache}; +use crate::models::Claims; +use crate::AppState; + +/// How long one team's read is reused (the page polls while visible). +const LIST_TTL: Duration = Duration::from_secs(10); + +/// One team's records and what is joined to them. +type Snapshot = Arc<(Vec, Joins)>; + +/// The team's records and joins as last read, keyed by +/// `read_key(installation_id, "prs#")`. +static LIST: LazyLock> = LazyLock::new(TtlCache::new); + +fn now() -> i64 { + chrono::Utc::now().timestamp() +} + +// ─── The writer ───────────────────────────────────────────────────────────── + +/// Every pull request event updates its pull request's record: people's +/// pull requests as much as CoderHelm's. Never fails the webhook; a write +/// that can't land is logged, and the sync reads the pull request again. +pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, payload: &Value) { + let repo = payload["repository"]["full_name"].as_str().unwrap_or(""); + if repo.is_empty() || team_id.is_empty() { + return; + } + let table = &state.config.settings_table_name; + let numbers = match pr_record::event_prs(event_type, payload) { + Some(n) => n, + None => { + let sk = match event_type { + "status" => payload["sha"] + .as_str() + .map(|sha| pr_record::head_sk(repo, sha)), + "push" => payload["ref"] + .as_str() + .and_then(|r| r.strip_prefix("refs/heads/")) + .map(|b| pr_record::ref_sk(repo, b)), + _ => None, + }; + let Some(sk) = sk else { return }; + match pr_record::pointed(&state.dynamo, table, team_id, &sk).await { + Ok(Some(n)) => vec![n], + Ok(None) => return, + Err(e) => { + warn!(repo, event_type, error = %e, "Pull request record: pointer read failed"); + return; + } + } + } + }; + let t = now(); + for number in numbers { + let written = pr_record::update(&state.dynamo, table, team_id, repo, number, t, |r| { + r.apply_event(event_type, payload, t) + }) + .await; + let rec = match written { + Ok(Some(rec)) => rec, + Ok(None) => continue, + Err(e) => { + warn!(repo, number, event_type, error = %e, "Pull request record not written"); + continue; + } + }; + if event_type == "pull_request" { + if let Err(e) = pr_record::point(&state.dynamo, table, team_id, &rec, t).await { + warn!(repo, number, error = %e, "Pull request record: pointer not written"); + } + } + // CoderHelm's run on it, found once. + let asks = rec.author_is_coderhelm() || !rec.requester.is_empty(); + if rec.coderhelm.run_id.is_empty() && asks { + let (owner, name) = repo.split_once('/').unwrap_or((repo, "")); + let run_id = + super::github_webhook::lookup_run_by_pr(state, team_id, owner, name, number).await; + if !run_id.is_empty() { + let _ = pr_record::update(&state.dynamo, table, team_id, repo, number, t, |r| { + if r.coderhelm.run_id == run_id { + return false; + } + r.coderhelm.run_id = run_id.clone(); + true + }) + .await; + } + } + } +} + +// ─── The reads ────────────────────────────────────────────────────────────── + +fn s(item: &Item, k: &str) -> String { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +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> { + let mut out = Vec::new(); + let mut start: Option = None; + loop { + let page = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":p", AttributeValue::S(prefix.into())) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(&e)))?; + out.extend(page.items().iter().cloned()); + start = page.last_evaluated_key().cloned(); + if start.is_none() { + return Ok(out); + } + } +} + +/// Pure: a run record's facts for the view. +pub fn run_join(item: &Item) -> RunJoin { + use common::run_status::NEEDS_INPUT; + let status = s(item, "status"); + let stop = (status == NEEDS_INPUT) + .then(|| { + let w: common::run_wait::WaitingOn = + serde_json::from_str(&s(item, "waiting_on")).ok()?; + if w.pause.is_some() { + return None; + } + let text = if w.detail.is_empty() { + w.action.clone() + } else { + format!("{}: {}", w.action.trim_end_matches('.'), w.detail) + }; + Some(pr_needs_stop(&w.handback, &text)) + }) + .flatten(); + let prs = common::run_prs::from_item(item); + let plan: Vec = prs + .iter() + .filter(|p| p.pr_number > 0 && p.repo.contains('/')) + .map(|p| format!("{}#{}", p.repo, p.pr_number)) + .collect(); + let mut after = Vec::new(); + if let Ok(ci) = serde_json::from_str::(&s(item, "repo_ci")) { + // Each pull request's `after` names the repositories it merges + // after: their pull requests in the same plan. + for p in ci["prs"].as_array().into_iter().flatten() { + for repo in p["after"].as_array().into_iter().flatten() { + if let Some(k) = plan + .iter() + .find(|k| k.starts_with(&format!("{}#", repo.as_str().unwrap_or("")))) + { + if !after.contains(k) { + after.push(k.clone()); + } + } + } + } + } + RunJoin { + run_id: common::paged::run_id_of(item).unwrap_or_default(), + title: s(item, "title"), + sender: s(item, "sender"), + current_pass: s(item, "current_pass"), + created_at: s(item, "created_at"), + updated_at: s(item, "updated_at"), + round: n(item, "review_cycle").unwrap_or(0).max(0) as u32, + standing: common::merge_standing::Standing::from_json(&s( + item, + common::merge_standing::FIELD, + )), + stop, + own_problem: None, + plan, + after, + status, + } +} + +fn pr_needs_stop(code: &str, text: &str) -> common::pr_needs::Stop { + common::pr_needs::Stop { + code: code.to_string(), + text: text.to_string(), + person: String::new(), + } +} + +/// Pure: the reviewer's records by pull request. +pub fn review_joins(live: &[Item], gates: &[Item], now: i64) -> HashMap { + use common::review_live as rl; + let mut out: HashMap = HashMap::new(); + let key = |sk: &str, prefix: &str| -> Option { + let (repo, pr) = sk.strip_prefix(prefix)?.rsplit_once('#')?; + Some(format!("{repo}#{}", pr.parse::().ok()?)) + }; + for it in live { + if let Some(k) = key(&s(it, "sk"), rl::SK_PREFIX) { + let raw = s(it, "phase"); + let step = rl::effective_phase(&raw, n(it, "expires_at"), now); + let e = out.entry(k).or_default(); + e.reviewing = rl::in_flight(step); + e.session_id = s(it, "job"); + } + } + for it in gates { + if let Some(k) = key(&s(it, "sk"), common::merge_gate::SK_PREFIX) { + let st = s(it, "state"); + let armed = matches!( + st.as_str(), + common::merge_gate::STATE_WAITING_APPROVAL | common::merge_gate::STATE_WAITING_CI + ); + out.entry(k).or_default().gate_armed = armed; + } + } + out +} + +async fn runs_by_id(state: &AppState, team_id: &str, ids: &[String]) -> HashMap { + let mut out = HashMap::new(); + let table = &state.config.runs_table_name; + for chunk in ids.chunks(100) { + let mut ka = KeysAndAttributes::builder(); + for id in chunk { + ka = ka.keys(HashMap::from([ + ( + "team_id".to_string(), + AttributeValue::S(team_id.to_string()), + ), + ("run_id".to_string(), AttributeValue::S(id.clone())), + ])); + } + let Ok(ka) = ka.build() else { continue }; + let mut request = HashMap::from([(table.clone(), ka)]); + for _ in 0..2 { + match state + .dynamo + .batch_get_item() + .set_request_items(Some(request.clone())) + .send() + .await + { + Ok(res) => { + for item in res + .responses() + .and_then(|r| r.get(table)) + .into_iter() + .flatten() + { + // The key names the team; a row of another team is + // never joined. + if s(item, "team_id") != team_id { + continue; + } + let j = run_join(item); + out.insert(j.run_id.clone(), j); + } + match res.unprocessed_keys().filter(|u| !u.is_empty()) { + Some(left) => request = left.clone(), + None => break, + } + } + Err(e) => { + warn!(team_id, error = %e, "Pull requests: runs not read"); + break; + } + } + } + } + out +} + +/// 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> { + let installation_id = super::api::get_team_installation_id(state, team_id) + .await + .unwrap_or(0); + let key = read_key(installation_id, &format!("prs#{team_id}")); + let at = Instant::now(); + if let Some(hit) = LIST.get(&key, at) { + return Ok(( + hit, + vec![json!({"name": "records", "read": "ok", "detail": "cached"})], + )); + } + let items = items_under(state, team_id, pr_record::SK_PREFIX) + .await + .map_err(|e| { + error!(team_id, error = %e, "Pull requests: records not read"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let mut sources = vec![json!({"name": "records", "read": "ok", "detail": ""})]; + let t = now(); + let (live, gates) = match ( + items_under(state, team_id, common::review_live::SK_PREFIX).await, + items_under(state, team_id, common::merge_gate::SK_PREFIX).await, + ) { + (Ok(l), Ok(g)) => (l, g), + (l, g) => { + sources.push(json!({"name": "reviewer", "read": "failed", "detail": "the reviewer's records couldn't be read; its work isn't shown"})); + (l.unwrap_or_default(), g.unwrap_or_default()) + } + }; + let recs = pr_view::records_of(team_id, &items); + let mut ids: Vec = recs + .iter() + .map(|r| r.coderhelm.run_id.clone()) + .filter(|r| !r.is_empty()) + .collect(); + ids.sort(); + ids.dedup(); + let joins = Joins { + runs: runs_by_id(state, team_id, &ids).await, + reviews: review_joins(&live, &gates, t), + }; + let v = Arc::new((items, joins)); + LIST.put(key, v.clone(), LIST_TTL, at); + Ok((v, sources)) +} + +#[derive(Deserialize, Default)] +pub struct ListQuery { + org: Option, + repo: Option, + turn: Option, + state: Option, + person: Option, + q: Option, + view: Option, + limit: Option, + cursor: Option, +} + +fn clean(v: Option) -> Option { + v.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) +} + +fn valid_word(v: &str) -> bool { + v.len() <= 100 + && v.chars() + .all(|c| c.is_ascii_alphanumeric() || "-_.,/@".contains(c)) +} + +/// Pure: the query's filters, or 400 for a word outside the vocabulary. +pub fn query_of(q: ListQuery) -> Result<(pr_view::Query, usize, Option), StatusCode> { + let org = clean(q.org); + let repo = clean(q.repo); + if let Some(r) = &repo { + super::reviewer::validate_repo(r)?; + } + for v in [&org, &q.person, &q.turn, &q.state, &q.view] + .into_iter() + .flatten() + { + if !valid_word(v) { + return Err(StatusCode::BAD_REQUEST); + } + } + let turn = clean(q.turn); + if turn + .as_deref() + .is_some_and(|t| !["you", "person", "coderhelm", "machines", "done"].contains(&t)) + { + return Err(StatusCode::BAD_REQUEST); + } + let states: Vec = clean(q.state) + .map(|s| s.split(',').map(|x| x.trim().to_string()).collect()) + .unwrap_or_default(); + if states + .iter() + .any(|s| common::pr_needs::State::from_code(s).is_none()) + { + return Err(StatusCode::BAD_REQUEST); + } + let view = clean(q.view); + if view + .as_deref() + .is_some_and(|v| !pr_view::VIEWS.contains(&v)) + { + return Err(StatusCode::BAD_REQUEST); + } + let text = clean(q.q).map(|t| common::truncate_str(&t, 200).to_string()); + Ok(( + pr_view::Query { + org, + repo, + turn, + states, + person: clean(q.person), + q: text, + view, + }, + q.limit.unwrap_or(100).clamp(1, 200), + clean(q.cursor), + )) +} + +fn synced_at(items: &[Item], team_id: &str, q: &pr_view::Query) -> Option { + let recs = pr_view::records_of(team_id, items); + recs.iter() + .filter(|r| { + q.org + .as_deref() + .is_none_or(|o| r.org().eq_ignore_ascii_case(o)) + }) + .filter(|r| { + q.repo + .as_deref() + .is_none_or(|x| r.repo.eq_ignore_ascii_case(x)) + }) + .map(|r| r.synced_at.max(r.event_at)) + .filter(|t| *t > 0) + .min() + .and_then(pr_view::rfc3339) +} + +/// GET /api/prs — every open pull request of the team, its one state and +/// what it needs next from whom; filters, counts over the scope, paging. +pub async fn list_prs( + State(state): State>, + Extension(claims): Extension, + Query(q): Query, +) -> Result, StatusCode> { + let (query, limit, cursor) = query_of(q)?; + let (data, 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 synced = synced_at(items, &claims.team_id, &query); + let page = pr_view::page(rows, &query, limit, cursor.as_deref()); + Ok(Json(json!({ + "prs": page.rows, + "total": page.total, + "next": page.next, + "counts": page.counts, + "viewer": viewer, + "synced_at": synced, + "sources": sources, + }))) +} + +#[derive(Deserialize)] +pub struct DetailQuery { + repo: String, + number: u64, +} + +/// GET /api/prs/detail?repo=&number= — one pull request: its row, the path +/// to merge, the wait ledger and the timeline with CoderHelm's runs. +pub async fn get_pr( + State(state): State>, + Extension(claims): Extension, + Query(q): Query, +) -> Result, StatusCode> { + super::reviewer::validate_repo(&q.repo)?; + let (data, _) = read_all(&state, &claims.team_id).await?; + let (items, joins) = (&data.0, &data.1); + let t = now(); + let viewer = claims.github_login.as_deref(); + let key = format!("{}#{}", q.repo, q.number); + let rows = pr_view::rows(&claims.team_id, items, joins, viewer, t); + let row = rows + .into_iter() + .find(|r| r.key.eq_ignore_ascii_case(&key)) + .ok_or(StatusCode::NOT_FOUND)?; + let recs = pr_view::records_of(&claims.team_id, items); + let rec: PrRecord = recs + .into_iter() + .find(|r| r.repo.eq_ignore_ascii_case(&q.repo) && r.number == q.number) + .ok_or(StatusCode::NOT_FOUND)?; + let open_keys = Default::default(); + let run = joins.runs.get(&rec.coderhelm.run_id); + let facts = pr_view::facts_of(&rec, run, joins.reviews.get(&row.key), &open_keys); + let needs = common::pr_needs::decide(&rec.repo, &facts); + let runs: Vec = run.cloned().into_iter().collect(); + let runs_out: Vec = runs + .iter() + .map(|r| { + json!({ + "run_id": r.run_id, + "title": r.title, + "status": r.status, + "started_at": (!r.created_at.is_empty()).then_some(&r.created_at), + "ended_at": (!common::pr_view::RUN_ACTIVE.contains(&r.status.as_str()) && !r.updated_at.is_empty()).then_some(&r.updated_at), + "url": format!("/runs/detail?id={}", r.run_id), + }) + }) + .collect(); + Ok(Json(json!({ + "pr": row, + "checklist": common::pr_needs::checklist(&facts), + "ledger": pr_view::ledger(&rec, &needs, t), + "timeline": pr_view::timeline(&rec, &runs), + "runs": runs_out, + "synced_at": pr_view::rfc3339(rec.synced_at.max(rec.event_at)), + }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn q(f: impl FnOnce(&mut ListQuery)) -> ListQuery { + let mut l = ListQuery::default(); + f(&mut l); + l + } + + #[test] + fn the_query_takes_only_its_own_words() { + assert!(query_of(q(|l| l.turn = Some("you".into()))).is_ok()); + assert!(query_of(q(|l| l.turn = Some("everyone".into()))).is_err()); + assert!(query_of(q(|l| l.state = Some("needs_review,draft".into()))).is_ok()); + assert!(query_of(q(|l| l.state = Some("mergeable".into()))).is_err()); + assert!(query_of(q(|l| l.view = Some("my_turn".into()))).is_ok()); + assert!(query_of(q(|l| l.repo = Some("acme/../web".into()))).is_err()); + let (_, limit, _) = query_of(q(|l| l.limit = Some(9_999))).unwrap(); + assert_eq!(limit, 200); + } + + #[test] + fn a_waiting_run_is_its_hand_off_and_a_paused_one_is_not() { + let mut item = Item::new(); + item.insert("run_id".into(), AttributeValue::S("01AAAA".into())); + item.insert("status".into(), AttributeValue::S("needs_input".into())); + item.insert( + "waiting_on".into(), + AttributeValue::S( + r#"{"action":"Choose how stock counts migrate","handback":"product_decision"}"# + .into(), + ), + ); + let j = run_join(&item); + assert_eq!( + j.stop.as_ref().map(|s| s.code.as_str()), + Some("product_decision") + ); + assert!(j.stop.unwrap().text.contains("stock counts")); + } + + #[test] + fn the_reviewers_records_join_by_pull_request() { + let mut live = Item::new(); + live.insert( + "sk".into(), + AttributeValue::S(common::review_live::record_sk("acme", "web", 318)), + ); + live.insert("phase".into(), AttributeValue::S("reviewing".into())); + live.insert("job".into(), AttributeValue::S("job-1".into())); + let j = review_joins(&[live], &[], 0); + assert!(j["acme/web#318"].reviewing); + assert_eq!(j["acme/web#318"].session_id, "job-1"); + } +} diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index accbe1601..53056b38e 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -808,6 +808,16 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe if let Err(e) = as_sweep(who::SWEEP_SKILLS, passes::skills::sweep(&state)).await { error!("Skill repository sweep failed: {e:?}"); } + // Every open pull request's record (the pull requests view): + // each team at most once an hour, one search per organization. + let prs = as_sweep(who::SWEEP_DASHBOARD_PRS, passes::pr_records::sweep(&state)).await; + info!( + teams = prs.teams, + written = prs.written, + removed = prs.removed, + pages = prs.pages, + "Pull request records sync done" + ); // Stale pull requests: each repository at most once an hour. let stale = as_sweep(who::SWEEP_STALE_PRS, passes::stale_prs::sweep(&state)).await; info!( @@ -1152,6 +1162,9 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe models::WorkerMessage::ChangeWaitCheck(msg) => { passes::change_wait::check_all(&state, Some(&msg.team_id)).await; } + models::WorkerMessage::PrRecordsSync(msg) => { + passes::pr_records::sync_message(&state, &msg).await; + } models::WorkerMessage::RoleReadsWait(msg) => { passes::role_wait::check(&state, &msg).await; } diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 19c31b892..fe6fd264b 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -652,6 +652,18 @@ pub(crate) fn decide_gate(v: &GateView) -> GateDecision { } Ci::Green => { lines.push((Mark::Done, "CI green".to_string())); + // The shared needs function has the last word: the gate merges + // only what the pull requests view shows as ready. + let needs = common::pr_needs::decide("", &gate_facts(v, Some(&Ci::Green))); + if !needs.state.is_ready() { + lines.push((Mark::Waiting, needs.next.text)); + return GateDecision { + state: STATE_WAITING_APPROVAL, + lines, + note: None, + action: Action::WaitForPeople, + }; + } GateDecision { state: STATE_WAITING_CI, lines, @@ -662,6 +674,66 @@ pub(crate) fn decide_gate(v: &GateView) -> GateDecision { } } +/// Pure: what the gate knows, as the shared needs function +/// (`common::pr_needs::decide`) reads it. `ci` is the gate's reading of the +/// head's checks, `None` before it reads them. Conflicts are read by the +/// merge itself (`MergeOutcome::BaseMoved`), so the gate's facts say none. +pub(crate) fn gate_facts(v: &GateView, ci: Option<&Ci>) -> common::pr_needs::Facts { + use common::pr_needs::{Checks, Facts}; + let human = person_key(v); + let mut checks = Checks::default(); + match ci { + Some(Ci::Green) => { + checks.known = true; + checks.total = 1; + checks.passed = 1; + } + Some(Ci::Pending(names)) => { + checks.known = true; + checks.total = names.len().max(1) as u32; + checks.running = names.clone(); + } + Some(Ci::Failing(names)) => { + checks.known = true; + checks.total = names.len().max(1) as u32; + checks.failed = names.clone(); + } + None => {} + } + let approved_by = if !human { + Vec::new() + } else if v.approvals.approved_at_head.is_empty() { + v.approvals.approved_by.clone() + } else { + v.approvals.approved_at_head.clone() + }; + Facts { + known: true, + draft: v.draft, + head: v.head.clone(), + base: v.base.clone(), + coderhelm_verdict: v + .bot_verdict + .clone() + .filter(|_| !v.approvals.bot_dismissed_at_head) + .map(|verdict| (verdict, v.head.clone())), + changes_requested_by: v.approvals.blocking_by.clone(), + approved_by, + requested: v.requested.clone(), + review_decision: v.review_decision.clone(), + approvals_required: v + .rules + .required_approvals + .unwrap_or(0) + .min(u64::from(u32::MAX)) as u32, + team_requires_approval: v.require_human, + conflict: Some(false), + checks, + coderhelm_merges: true, + ..Default::default() + } +} + /// Pure: the panel's lines for CoderHelm's block: what holds it, as the review /// named it. A review older than named items points at the review. fn holding_lines(holding: &[String]) -> Vec<(Mark, String)> { 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 b2b40f107..f4988d90c 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,7 @@ 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.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"), ("gateway/src/routes/run_checks.rs::PR_HEADS", "installation id (read_key)"), diff --git a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs new file mode 100644 index 000000000..348e869bd --- /dev/null +++ b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs @@ -0,0 +1,331 @@ +//! xw. A team asked which pull requests were open in its repositories and +//! what each one needed. Nothing could say: the gateway dropped every event +//! of a pull request CoderHelm hadn't opened ("Only track our PRs"), the +//! reviewer's records covered only the pull requests it reviewed and +//! expired after 30 days, and the run page, the reviewer's auto-merge gate +//! and the reviewer page each read what a pull request needed in their own +//! way. +//! +//! Guarantees: +//! - every open pull request of the team's repositories has a record, +//! written from its events (any author) and the sync, and appears in the +//! list; +//! - each pull request has exactly one state from one function +//! (`common::pr_needs::decide`), and a pull request whose facts aren't +//! known yet is `unknown`, shown and counted, never dropped; +//! - the merge gates and the list read that same function, so they can't +//! disagree; +//! - a record of another team never reaches a row. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::merge_standing; +use common::pr_needs::{self, Checks, Facts, Own, OwnStanding, State}; +use common::pr_record::{self, Item, PrRecord}; +use common::pr_view::{self, Joins, Query}; + +use crate::passes::await_merge::{ + decide_gate, gate_facts, Action, CheckSummary, Ci, GateView, ReviewRules, +}; +use crate::passes::review_actions::Approvals; + +const NOW: i64 = 1_800_000_000; +const HEAD: &str = "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432"; + +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 opened(n: u64, author: &str) -> serde_json::Value { + serde_json::json!({ + "action": "opened", + "sender": {"login": author}, + "pull_request": { + "number": n, "title": format!("Bookstore change {n}"), + "html_url": format!("https://github.com/acme/web/pull/{n}"), + "user": {"login": author}, "draft": false, "state": "open", "merged": false, + "head": {"sha": HEAD, "ref": format!("change-{n}")}, "base": {"ref": "main"}, + "created_at": "2026-01-10T10:00:00Z", "updated_at": "2026-01-10T10:00:00Z", + "requested_reviewers": [], "requested_teams": [], "labels": [] + } + }) +} + +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}")) +} + +#[test] +fn every_open_pull_request_appears_whoever_opened_it() { + let team = "TEAM#bookstore"; + let mut items = Vec::new(); + // A person's pull request, CoderHelm's, a draft, and one only a check + // event has named so far. + for (n, author) in [(1, "octocat"), (2, "coderhelm[bot]"), (3, "mara")] { + let mut r = PrRecord::new("acme/web", n); + assert!(r.apply_event("pull_request", &opened(n, author), NOW)); + if n == 3 { + r.draft = true; + } + items.push(item(team, &r)); + } + let mut only_checks = PrRecord::new("acme/web", 4); + let run = + serde_json::json!({"check_run": {"name": "unit", "head_sha": HEAD, "status": "queued"}}); + assert!(only_checks.apply_event("check_run", &run, NOW)); + items.push(item(team, &only_checks)); + let rows = pr_view::rows(team, &items, &Joins::default(), None, NOW); + let page = pr_view::page(rows, &Query::default(), 200, None); + assert_eq!(page.total, 4); + let mut numbers: Vec = page.rows.iter().map(|r| r.number).collect(); + numbers.sort(); + assert_eq!(numbers, vec![1, 2, 3, 4]); + + // Every pull request event reaches the writer, before any handler's + // early return, and the writer names the pull request of each. + let hook = src("gateway/src/routes/github_webhook.rs"); + let dispatch = &hook[hook.find("async fn dispatch(").expect("dispatch")..]; + let dispatch = &dispatch[..dispatch + .find("\nasync fn route_event(") + .expect("route_event")]; + assert!(dispatch.contains("super::prs::on_webhook(state, team_id, event_type, payload)")); + for ev in [ + "\"pull_request\"", + "\"pull_request_review\"", + "\"pull_request_review_comment\"", + "\"issue_comment\"", + "\"check_run\"", + "\"check_suite\"", + "\"status\"", + "\"push\"", + ] { + assert!(dispatch.contains(ev), "{ev} isn't written"); + } + assert!(!hook.contains("// Only track our PRs")); + // The install and the sweep read the pull requests opened before. + assert!(hook.contains("WorkerMessage::PrRecordsSync(")); + let main = src("worker/src/main.rs"); + assert!(main.contains("passes::pr_records::sweep(&state)")); + assert!(main.contains("passes::pr_records::sync_message(&state, &msg)")); + // No expiry while open. + let mut r = PrRecord::new("acme/web", 1); + assert_eq!(r.ttl(), None); + r.status = "closed".into(); + assert!(r.ttl().is_some()); +} + +#[test] +fn one_state_per_pull_request_and_unknown_is_shown() { + let mut seen = std::collections::BTreeSet::new(); + let base = Facts { + known: true, + head: HEAD.into(), + author: "octocat".into(), + conflict: Some(false), + checks: Checks { + known: true, + total: 1, + passed: 1, + ..Default::default() + }, + ..Default::default() + }; + // Every combination of the facts that hold the merge gets exactly one + // state, and the same facts always the same one. + for bits in 0u32..(1 << 9) { + let mut f = base.clone(); + let on = |i: u32| bits & (1 << i) != 0; + f.draft = on(0); + f.conflict = if on(1) { Some(true) } else { f.conflict }; + if on(2) { + f.checks.failed = vec!["lint".into()]; + } + if on(3) { + f.checks.running = vec!["unit".into()]; + } + if on(4) { + f.changes_requested_by = vec!["mara".into()]; + } + f.approvals_required = if on(5) { 1 } else { 0 }; + f.known = !on(6); + f.checks.known = !on(7); + f.coderhelm_merges = on(8); + let a = pr_needs::decide("acme/web", &f); + let b = pr_needs::decide("acme/web", &f); + assert_eq!(a, b); + assert!(!a.next.text.is_empty()); + assert!(pr_needs::ALL.contains(&a.state)); + seen.insert(a.state); + } + assert!(seen.contains(&State::Unknown)); + + // An unknown pull request is a row, counted under its state. + let team = "TEAM#bookstore"; + let mut r = PrRecord::new("acme/web", 9); + r.apply_event( + "check_run", + &serde_json::json!({"check_run": {"name": "unit", "head_sha": HEAD, "status": "queued"}}), + NOW, + ); + let rows = pr_view::rows(team, &[item(team, &r)], &Joins::default(), None, NOW); + let page = pr_view::page(rows, &Query::default(), 50, None); + assert_eq!(page.rows.len(), 1); + assert_eq!(page.rows[0].state, "unknown"); + assert_eq!(page.counts.state.get("unknown"), Some(&1)); + assert_eq!(page.rows[0].turn, "machines"); +} + +fn gate_view() -> GateView { + GateView { + draft: false, + require_human: true, + bot_verdict: Some("APPROVE".into()), + bot_holding: vec![], + approvals: Approvals::default(), + want_labels: vec![], + present_labels: vec![], + labels_added_at: None, + taken_off: vec![], + preview_ran: vec![], + ci: None, + now: NOW, + head: HEAD.into(), + base: "main".into(), + review_decision: None, + earlier_approval_holds: false, + rules: ReviewRules::default(), + requested: vec![], + base_merge_at_head: false, + } +} + +#[test] +fn the_merge_gates_and_the_list_read_one_decision() { + // The reviewer's auto-merge gate merges exactly when the list says + // ready, over every combination of what it weighs. + for bits in 0u32..(1 << 8) { + let on = |i: u32| bits & (1 << i) != 0; + let mut v = gate_view(); + v.draft = on(0); + v.require_human = on(1); + v.bot_verdict = match (on(2), on(3)) { + (true, _) => Some("APPROVE".into()), + (false, true) => Some("REQUEST_CHANGES".into()), + _ => None, + }; + if on(4) { + v.approvals.approved_by = vec!["mara".into()]; + v.approvals.approved_at_head = vec!["mara".into()]; + } + if on(5) { + v.approvals.blocking_by = vec!["jun".into()]; + } + let summary = match (on(6), on(7)) { + (false, false) => CheckSummary::default(), + (true, false) => CheckSummary { + failing: vec!["lint".into()], + ..Default::default() + }, + _ => CheckSummary { + pending: vec!["unit".into()], + ..Default::default() + }, + }; + let ci = summary.ci(); + v.ci = Some(summary); + let gate = decide_gate(&v); + let list = pr_needs::decide("acme/web", &gate_facts(&v, Some(&ci))); + assert_eq!( + gate.action == Action::Merge, + list.state.is_ready(), + "bits {bits:08b}: the gate says {:?}, the list says {:?}", + gate.action, + list.state + ); + if matches!(ci, Ci::Failing(_)) { + assert_ne!(gate.action, Action::Merge); + } + } + + // The run's watch stores the standing this function decides, and the + // list reads the stored standing to the same state. + let watch = src("worker/src/passes/pr_watch.rs"); + assert!(watch.contains("common::pr_needs::run_standing(")); + assert!(!watch.contains("merge_standing::decide(")); + let gate = src("worker/src/passes/await_merge.rs"); + assert!(gate.contains("common::pr_needs::decide(\"\", &gate_facts(v, Some(&Ci::Green)))")); + for bits in 0u32..(1 << 6) { + let on = |i: u32| bits & (1 << i) != 0; + let facts = merge_standing::Facts { + head: HEAD.into(), + reviewer_on: on(0), + own_verdict: on(1).then(|| ("APPROVE".to_string(), HEAD.to_string())), + auto_merge: on(2), + require_human_approval: on(3), + conflict: on(4), + checks_running: on(5), + ..Default::default() + }; + let standing = pr_needs::run_standing("acme/web", &facts); + assert_eq!(standing, merge_standing::decide("acme/web", &facts)); + let stored = Facts { + known: true, + head: HEAD.into(), + author: "coderhelm[bot]".into(), + author_is_coderhelm: true, + own: Some(Own { + standing: Some(OwnStanding::Decided(standing.clone())), + ..Default::default() + }), + ..Default::default() + }; + let fresh = Facts { + own: Some(Own { + standing: Some(OwnStanding::Facts(facts)), + ..Default::default() + }), + ..stored.clone() + }; + let a = pr_needs::decide("acme/web", &stored); + let b = pr_needs::decide("acme/web", &fresh); + assert_eq!(a.state, b.state); + assert_eq!(a.next.code, standing.code); + } +} + +#[test] +fn no_pull_request_of_another_team_reaches_a_row() { + let mine = PrRecord { + known: true, + ..PrRecord::new("acme/web", 1) + }; + let theirs = PrRecord { + known: true, + ..PrRecord::new("acme/web", 2) + }; + let items = vec![item("TEAM#a", &mine), item("TEAM#b", &theirs)]; + let rows = pr_view::rows("TEAM#a", &items, &Joins::default(), None, NOW); + assert_eq!(rows.iter().map(|r| r.number).collect::>(), vec![1]); + assert!(pr_view::records_of("TEAM#c", &items).is_empty()); + + // The reads are keyed by the session's team, the runs it joins are + // the team's, and the cache names the installation and the team. + let prs = src("gateway/src/routes/prs.rs"); + assert!(prs.contains("read_all(&state, &claims.team_id)")); + assert!(prs.contains("pr_view::rows(&claims.team_id, items, joins, viewer")); + assert!(prs.contains("read_key(installation_id, &format!(\"prs#{team_id}\"))")); + assert!(prs.contains("if s(item, \"team_id\") != team_id {")); + assert!(!prs.contains("q.team")); + let perms = src("gateway/src/permissions.rs"); + assert!(perms.contains("\"prs::list_prs\"") && perms.contains("\"prs::get_pr\"")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index efb87db81..468c76ce8 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1403,6 +1403,7 @@ pub mod plugins; mod pr; mod pr_holder; pub mod pr_outcomes; +pub mod pr_records; mod pr_risk; pub mod pr_watch; pub mod preview; diff --git a/services/worker/src/passes/pr_records.rs b/services/worker/src/passes/pr_records.rs new file mode 100644 index 000000000..bda8dce40 --- /dev/null +++ b/services/worker/src/passes/pr_records.rs @@ -0,0 +1,227 @@ +//! The sync of every open pull request's record (`common::pr_record`): +//! one GraphQL search per organization of the team's repositories, under +//! the shared GitHub budget (`sweep:dashboard_prs`). +//! +//! The webhooks keep each record current; the sync reads what they don't +//! carry (the review decision, the branch's rules, conflicts, open +//! conversations), adds the pull requests opened before the install, and +//! removes the records of pull requests no longer open. It runs when the +//! app is installed or repositories are added (`PrRecordsSync`), and on the +//! sweep tick at most once an hour per team. +//! +//! Bounds: [`pr_record::MAX_PAGES`] pages of 30 per organization, each one +//! counted request, each asked of the budget first ([`SweepGate`]); a +//! record is removed only when the search was read to its end. + +use std::collections::HashSet; + +use common::github_budget::caller as who; +use common::pr_record; +use serde_json::json; +use tracing::{info, warn}; + +use crate::clients::github::GitHubClient; +use crate::clients::github_budget::SweepGate; +use crate::WorkerState; + +/// What one sweep did. +#[derive(Debug, Default)] +pub struct SweepReport { + pub teams: usize, + pub written: usize, + pub removed: usize, + pub pages: u32, +} + +/// The sweep tick: each team at most once an hour. +pub async fn sweep(state: &WorkerState) -> SweepReport { + let mut report = SweepReport::default(); + let mut gate = SweepGate::new(who::SWEEP_DASHBOARD_PRS); + let hour = chrono::Utc::now().format("%Y%m%d%H").to_string(); + for team in super::learning_wait::teams(state).await { + let Some(iid) = super::review_reminder::team_installation_id(state, &team).await else { + continue; + }; + let claim = format!("PRREC_SYNC#{hour}"); + if !super::review_pr::claim_once_ttl(state, &team, &claim, 2 * 3600).await { + continue; + } + report.teams += 1; + sync_team(state, &team, iid, &mut gate, &mut report).await; + } + report +} + +/// One team, now (the install's first read). +pub async fn sync_message(state: &WorkerState, msg: &common::messages::PrRecordsSyncMessage) { + let mut gate = SweepGate::new(who::SWEEP_DASHBOARD_PRS); + let mut report = SweepReport::default(); + crate::clients::github_budget::scoped( + who::SWEEP_DASHBOARD_PRS, + sync_team( + state, + &msg.team_id, + msg.installation_id, + &mut gate, + &mut report, + ), + ) + .await; + info!( + team_id = %msg.team_id, + written = report.written, + removed = report.removed, + pages = report.pages, + "Pull request records read at install" + ); +} + +/// Pure: the organizations to search, from the team's connected +/// repositories, and the repositories kept. +pub fn owners_of(repos: &[String]) -> (Vec, HashSet) { + let keep: HashSet = repos.iter().map(|r| r.to_ascii_lowercase()).collect(); + let mut owners: Vec = repos + .iter() + .filter_map(|r| r.split_once('/').map(|(o, _)| o.to_string())) + .collect(); + owners.sort(); + owners.dedup(); + (owners, keep) +} + +async fn sync_team( + state: &WorkerState, + team_id: &str, + installation_id: u64, + gate: &mut SweepGate, + report: &mut SweepReport, +) { + let repos: Vec = super::infra_repo::team_repos(state, team_id) + .await + .into_iter() + .filter(|r| r.enabled) + .map(|r| r.full_name) + .collect(); + let (owners, keep) = owners_of(&repos); + if owners.is_empty() { + return; + } + let github = match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + installation_id, + &state.http, + ) { + Ok(g) => g, + Err(e) => { + warn!(team_id, error = %e, "Pull request sync: no GitHub client"); + return; + } + }; + let table = &state.config.settings_table_name; + for owner in owners { + let mut seen: HashSet = HashSet::new(); + let mut complete = false; + let mut after: Option = None; + let mut as_org = true; + let mut page = 0; + while page < pr_record::MAX_PAGES { + if !gate.allows(state, installation_id, 1).await { + break; + } + let vars = json!({"q": pr_record::search_text(&owner, as_org), "after": after}); + let data = match github.graphql_read(pr_record::SEARCH_QUERY, vars).await { + Ok(d) => d, + // A personal account's repositories are searched by user. + Err(_) if as_org && page == 0 => { + as_org = false; + continue; + } + Err(e) => { + warn!(team_id, owner = %owner, error = %e, "Pull request sync: search failed"); + break; + } + }; + page += 1; + report.pages += 1; + let now = chrono::Utc::now().timestamp(); + for node in data["search"]["nodes"].as_array().into_iter().flatten() { + let repo = node["repository"]["nameWithOwner"].as_str().unwrap_or(""); + let Some(number) = node["number"].as_u64() else { + continue; + }; + if !keep.contains(&repo.to_ascii_lowercase()) { + continue; + } + seen.insert(format!("{}#{number}", repo.to_ascii_lowercase())); + let written = + pr_record::update(&state.dynamo, table, team_id, repo, number, now, |r| { + r.apply_node(node, now); + true + }) + .await; + match written { + Ok(Some(rec)) => { + report.written += 1; + let _ = pr_record::point(&state.dynamo, table, team_id, &rec, now).await; + } + Ok(None) => {} + Err(e) => { + warn!(team_id, repo, number, error = %e, "Pull request record not synced") + } + } + } + let info = &data["search"]["pageInfo"]; + if info["hasNextPage"].as_bool() != Some(true) { + complete = true; + break; + } + after = info["endCursor"].as_str().map(str::to_string); + } + if !complete { + continue; + } + // Read to its end: a record of this owner's still marked open that + // the search no longer lists is no longer open. + let items = match pr_record::all(&state.dynamo, table, team_id).await { + Ok(i) => i, + Err(e) => { + warn!(team_id, error = %e, "Pull request sync: records not read"); + continue; + } + }; + // The search index trails GitHub by a little: a pull request an + // event touched in the last hour is never taken off. + let recent = chrono::Utc::now().timestamp() - 3600; + for rec in items { + if rec.event_at > recent { + continue; + } + let key = format!("{}#{}", rec.repo.to_ascii_lowercase(), rec.number); + if rec.org().eq_ignore_ascii_case(&owner) && rec.is_open() && !seen.contains(&key) { + match pr_record::delete(&state.dynamo, table, team_id, &rec.repo, rec.number).await + { + Ok(()) => report.removed += 1, + Err(e) => warn!(team_id, error = %e, "Pull request record not removed"), + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_organization_is_searched_once_and_only_connected_repos_are_kept() { + let (owners, keep) = owners_of(&[ + "acme/web".to_string(), + "acme/api".to_string(), + "octocat/bookstore".to_string(), + ]); + assert_eq!(owners, vec!["acme", "octocat"]); + assert!(keep.contains("acme/web")); + assert!(!keep.contains("acme/infra")); + } +} diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 570d8ad9c..518046b52 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -1142,7 +1142,9 @@ async fn standing( ), None => (Vec::new(), None), }; - let standing = merge_standing::decide( + // The one decision the run page, the merge gate and the pull requests + // view share (`common::pr_needs`). + let standing = common::pr_needs::run_standing( &format!("{}/{}", c.owner, c.repo), &merge_standing::Facts { approvals_required, From da7e4e7c6b53bd506639c3873047a9186e92b48e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 11:57:38 -0500 Subject: [PATCH 2/7] Format the pull requests route --- services/gateway/src/routes/prs.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 9c7057222..238b9db29 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -314,10 +314,7 @@ 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> { +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); From 9ef4f5d2fda8ba0d960ba254d84ecd1c66acd834 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 12:29:52 -0500 Subject: [PATCH 3/7] Keep each pull request's history, change log and nightly percentiles for the org overview Every duration starts at ready for review, and human review leaves out the author and every bot. Records keep their state and turn change log, people's reviews and review requests, and check transitions. A merged or closed pull request leaves a history row kept 400 days with its run and session links and revert and follow-up links. A nightly job writes each org's and repository's snapshot and percentiles, team-scoped and bounded. --- docs/pull-requests.md | 10 + docs/pull-requests/api_contract.md | 114 +++ services/common/src/lib.rs | 1 + services/common/src/pr_history.rs | 771 ++++++++++++++++++ services/common/src/pr_needs.rs | 85 ++ services/common/src/pr_record.rs | 285 ++++++- services/common/src/pr_view.rs | 7 + services/gateway/src/routes/prs.rs | 52 ++ services/worker/src/main.rs | 4 + .../xw_every_open_pr_has_one_state.rs | 5 + services/worker/src/passes/pr_records.rs | 43 + 11 files changed, 1369 insertions(+), 8 deletions(-) create mode 100644 docs/pull-requests/api_contract.md create mode 100644 services/common/src/pr_history.rs diff --git a/docs/pull-requests.md b/docs/pull-requests.md index 0a78256e4..a79896e45 100644 --- a/docs/pull-requests.md +++ b/docs/pull-requests.md @@ -11,6 +11,16 @@ One settings-table item per pull request (`pk` = team id, `sk = PRREC##`) is written and kept 400 days: ready, first human review, CoderHelm's first review, final approval, merge or close and who merged, rounds of changes requested, size, author type, CoderHelm's part (author, fixer, reviewer or none) with its runs and review sessions, the change log, and links. +- **Reverts and follow-ups.** A merged revert ("Reverts owner/repo#n") marks the pull request it reverts; a merged pull request that names an earlier merged one within 14 days of its merge marks it as followed up. Both are labeled a proxy for a failed change. +- **The nightly snapshot** (`sk = PRSNAP##`, kept 400 days), once a day per team and per org and repository (the first 300): open pull requests by stage and turn, how many are past the scope's p85, arrivals, merges (by author type), closed without merging, reviews asked and done, reverts, and the percentiles: cycle time p50, p85 and p95 over 90 days, first human review p50 and p85 over 8 weeks, and each stage's p85. A repository with fewer than 30 merges in 90 days uses its org's percentiles and says so; an org with less than 8 weeks of history is marked young, so the page shows external bands instead. The job reads only the team's own records and history (at most 25,000 history rows) and makes no GitHub requests. + ## One state per pull request `services/common/src/pr_needs.rs` decides the state from the facts, first match wins: merged, closed, in the merge queue, left the queue, CoderHelm working, needs a decision, draft, waiting on another pull request, conflicts, checks failing, changes requested, re-review, needs a reviewer, needs review, needs a code owner, open conversations, checks running, ready with auto-merge on, ready to merge. A pull request whose facts aren't known yet is **not synced yet** (`unknown`): shown and counted, never dropped. diff --git a/docs/pull-requests/api_contract.md b/docs/pull-requests/api_contract.md new file mode 100644 index 000000000..bfa99cc47 --- /dev/null +++ b/docs/pull-requests/api_contract.md @@ -0,0 +1,114 @@ +# /api/prs contract (platform PR and dashboard PR share this) + +All times are RFC 3339 UTC strings. All example data invented (acme/web, octocat, the bookstore). + +## GET /api/prs + +Query (all optional): `org`, `repo` (owner/name), `turn` (you|person|coderhelm|machines|done), +`state` (one State code, or several joined by ","), `person` (a GitHub login: involves), +`q` (free text: title, repo, number, author, branch), `view` (my_turn|coderhelm_working|needs_decision|ready|stale), +`limit` (1..200, default 100), `cursor` (opaque string from `next`). + +Team comes from the session only. 404 from an older backend means "not served yet". + +```json +{ + "prs": [PrRow], + "total": 37, + "next": "o:100" , + "counts": { + "turn": {"you": 2, "person": 9, "coderhelm": 4, "machines": 6, "done": 1}, + "state": {"needs_review": 5, "checks_failing": 2, "unknown": 1}, + "repo": {"acme/web": 20, "acme/api": 17}, + "org": {"acme": 37}, + "views": {"my_turn": 2, "coderhelm_working": 4, "needs_decision": 1, "ready": 3, "stale": 2} + }, + "viewer": "octocat", + "synced_at": "2026-01-10T12:00:00Z", + "sources": [{"name": "webhooks", "read": "ok", "detail": ""}, {"name": "reconcile", "read": "ok", "detail": "acme: 37 open pull requests read"}] +} +``` +`counts` are over the scope (org/repo) BEFORE the turn/state/person/q/view filters, so the strip and the saved views always show their totals. `total` is after filters. + +### PrRow +```json +{ + "key": "acme/web#318", + "org": "acme", "repo": "acme/web", "number": 318, + "title": "Round cart totals per currency", + "url": "https://github.com/acme/web/pull/318", + "author": {"login": "coderhelm[bot]", "coderhelm": true}, + "for": "octocat", + "draft": false, "base": "main", "head": "fix/cart-rounding", + "created_at": "...", "updated_at": "...", + "state": "checks_failing", + "state_label": "Checks failing", + "stage": "blocked", + "ready_at": "...", + "turn": "coderhelm", + "next": {"code": "checks_failing", "text": "Checks fail on lint: CoderHelm is fixing them, round 2.", "from": ["coderhelm"], "since": "...", "rule": "required_check"}, + "modifiers": ["stale", "stacked", "agent_authored", "large"], + "people": [{"login": "octocat", "roles": ["requester", "reviewer"], "coderhelm": false}], + "checks": {"total": 12, "passed": 10, "failed": 1, "running": 1, "required_failed": ["lint"], "known": true}, + "reviews": {"approvals": 1, "required": 2, "changes_requested_by": [], "requested": ["mara"], "coderhelm_verdict": "APPROVE"}, + "conflict": false, + "open_threads": 0, + "labels": ["hotfix"], + "size": {"additions": 240, "deletions": 31}, + "last_action": {"actor": "coderhelm", "text": "pushed 2 commits", "at": "..."}, + "coderhelm": {"run_id": "...", "session_id": "...", "round": 2, "working": true, "what": "Fixing CI"}, + "links": [{"kind": "depends", "repo": "acme/api", "number": 12, "url": "https://github.com/acme/api/pull/12", "state": "needs_review"}], + "waiting_since": "..." +} +``` +`from` entries: `coderhelm`, `ci`, `queue`, `nobody`, `person:`, `team:/`, `author`. +`rule`: `repo_rule` | `codeowners` | `required_check` | `team_rule` | `branch_rule` | null. +`turn`: "you" when the viewer's login is in `from` (or is the author on an author turn). + +### States (exactly one per PR, first match wins) +merged, closed, in_queue, left_queue, coderhelm_working, needs_decision, draft, waiting_on_pr, +conflicts, checks_failing, changes_requested, re_review, needs_reviewer, needs_review, +needs_code_owner, open_threads, checks_running, ready_auto_merge, ready_to_merge, unknown. + +Turn per state: merged/closed = done; in_queue/checks_running/ready_auto_merge/unknown = machines; +coderhelm_working = coderhelm; the others = person or coderhelm (per PR, from `next.from`). + +## GET /api/prs/detail?repo=acme/web&number=318 +```json +{ + "pr": PrRow, + "checklist": [{"key": "checks", "mark": "done|waiting|blocked|none", "text": "Required checks 12 of 12 pass", "source": "required_check"}], + "ledger": {"open_secs": 97200, "spans": [{"who": "person:mara", "from": "...", "to": "...", "secs": 3600}], "totals": [{"who": "coderhelm", "secs": 2820}]}, + "timeline": [{"at": "...", "actor": "octocat", "coderhelm": false, "kind": "review", "text": "approved", "run_id": null}], + "runs": [{"run_id": "...", "title": "Fix CI (lint)", "status": "running", "started_at": "...", "ended_at": null, "url": "/runs/detail?id=..."}], + "synced_at": "..." +} +``` +`kind`: opened, pushed, review, comment, check, queue, run, label, ready, draft, merged, closed, reviewers, state. +Timeline events with a `run_id` belong to that run's collapsible block. 404 when the PR isn't the team's. + + +## Stages (the overview's strip), from `common::pr_needs::stage_of` +`draft`, `first_review`, `in_review`, `blocked`, `coderhelm_working`, `approved` (null once merged or closed). +first_review = needs_reviewer/needs_review with no human review yet; in_review = the same after one, plus changes_requested, re_review, needs_code_owner, open_threads; +blocked = conflicts, checks_failing, waiting_on_pr, left_queue, needs_decision, unknown; approved = in_queue, checks_running, ready_auto_merge, ready_to_merge. +Every age and duration starts at `ready_at` (left draft, else created). Human review excludes the author, CoderHelm and every `[bot]`. + +## Stored shapes the overview reads (shared Rust types; do not fork them) +All settings-table rows, `pk` = team id, body JSON in `doc`. Types live in `services/common/src/pr_record.rs` and `services/common/src/pr_history.rs`. + +- Current row `PRREC#owner/repo#000318` (`pr_record::PrRecord`), no expiry while open, 3 days after close. Adds to the fields above: + `ready_at`, `spans[] {who, state, turn, stage, from}` (the state and turn change log, newest 80), + `review_log[] {who, state, sha, at, human, has_body}`, `request_log[] {who, at, removed_at}`, + `check_log[] {rollup: red|pending|green, at}` (newest 150 each), + `coderhelm {run_id, session_id, run_ids[], session_ids[]}`, `links[] {kind: stack_base|stack_child|plan|depends|contract|references|reverts, repo, number}`. +- History `PRHIST#owner/repo#000318` (`pr_history::History`), written on merge or close, kept 400 days: + `repo, number, title, author, author_type (person|coderhelm|bot), created_at, ready_at, first_human_review_at, first_coderhelm_review_at, final_approval_at, + merged, merged_at, closed_at, merged_by, changes_rounds, additions, deletions, coderhelm_role (author|fixer|reviewer|none), run_ids[], session_ids[], requester, + spans[], review_log[], request_log[], check_log[], links[], reverted_by: [repo, number, at] | null, follow_ups: [[repo, number, at]]`. + Helpers: `cycle_secs()`, `first_review_secs()`, `waiting_on_person_secs()`, `reworked()` (revert or follow-up within 14 days; a proxy). + Attribute `closed_at` (number) for range filters; `pr_history::all_since(team, since)`. +- Daily snapshot `PRSNAP##YYYY-MM-DD` (`pr_history::Snapshot`), scope = `acme` (org) or `acme/web`, kept 400 days, written nightly per team (first 300 repos): + `scope, day, stages {stage: n}, turns {turn: n}, open, past_p85, arrivals, merges, closed_unmerged, review_requests, reviews_done, reverts, merges_by {author_type: n}, + pct {cycle: [p50,p85,p95] secs over 90 days, first_review: [p50,p85] over 8 weeks, stage_p85 {stage: secs}, merged}, inherited (repo under 30 merges uses the org's), young (org under 8 weeks: show external bands)`. + Weekly counts are the 7 days to the snapshot. `pr_history::snapshots_of(team, scope, since_day)` reads them oldest first. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 9c7a9526b..32f2da030 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -273,6 +273,7 @@ pub mod pr_conventions; /// A dependency pull request's facts, from what the pipeline records. pub mod pr_dependency; pub mod pr_facts; +pub mod pr_history; /// Where each part of a description goes, and how a reader would judge it. pub mod pr_layout; pub mod pr_needs; diff --git a/services/common/src/pr_history.rs b/services/common/src/pr_history.rs new file mode 100644 index 000000000..ba1069462 --- /dev/null +++ b/services/common/src/pr_history.rs @@ -0,0 +1,771 @@ +//! What happened to every pull request after it closed, kept long enough to +//! answer "how long do our pull requests usually take" from the org's own +//! history, and the nightly snapshot of each org and repository that the +//! overview reads instead of scanning pull requests on page load. +//! +//! - One history row per merged or closed pull request (`pk` = team id, +//! `sk` = [`hist_sk`]), written when it closes, kept [`HISTORY_KEEP_SECS`] +//! (over a year: a quarter-on-quarter comparison and a year of reverts +//! fit). It carries every duration from **ready for review**, human +//! review times that leave out the author and every bot, the wait +//! ledger's turn changes, the review, request and check logs, CoderHelm's +//! runs and review sessions on it, and its revert and follow-up links. +//! - One snapshot per scope and day (`sk` = [`snap_sk`]): counts by stage +//! and turn, arrivals, merges, reviews asked and done, and the cycle-time +//! percentiles the thresholds come from ([`Percentiles`]). A repository +//! uses its own percentiles once it has [`MIN_MERGED_FOR_OWN`] merges in +//! 90 days, else the org's, and says so ([`Snapshot::inherited`]). +//! +//! Everything here is pure except the storage functions at the end, and +//! every read and write is keyed by the team. + +use std::collections::{BTreeMap, BTreeSet}; + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde::{Deserialize, Serialize}; + +use crate::pr_needs::{self, Stage}; +use crate::pr_record::{ + is_bot, is_coderhelm, CheckTransition, Item, Link, PrRecord, RequestEvent, ReviewEvent, Span, +}; + +/// Sort-key prefix of the history rows. +pub const HIST_PREFIX: &str = "PRHIST#"; +/// Sort-key prefix of the daily snapshots. +pub const SNAP_PREFIX: &str = "PRSNAP#"; +/// How long a history row and a snapshot are kept. +pub const HISTORY_KEEP_SECS: i64 = 400 * 86_400; +/// A repository uses its own percentiles from this many merges in 90 days. +pub const MIN_MERGED_FOR_OWN: usize = 30; +/// Weeks of history before the org's own percentiles stand on their own. +pub const MIN_WEEKS_OWN: i64 = 8; +/// A revert or a follow-up within this long of the merge counts as rework. +pub const REWORK_WINDOW_SECS: i64 = 14 * 86_400; +/// Most repositories one snapshot run covers per team. +pub const MAX_SNAPSHOT_REPOS: usize = 300; +/// Most history rows one snapshot run reads per team. +pub const MAX_HISTORY_READ: usize = 25_000; + +const DAY: i64 = 86_400; + +pub fn hist_sk(repo: &str, number: u64) -> String { + format!("{HIST_PREFIX}{repo}#{number:06}") +} + +/// `org` for the org scope, `org/repo` for a repository. +pub fn snap_sk(scope: &str, day: &str) -> String { + format!("{SNAP_PREFIX}{scope}#{day}") +} + +/// Who wrote it. +pub fn author_type(login: &str) -> &'static str { + if is_coderhelm(login) { + "coderhelm" + } else if is_bot(login) { + "bot" + } else { + "person" + } +} + +/// A merged or closed pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct History { + pub repo: String, + pub number: u64, + pub title: String, + pub author: String, + /// `person`, `coderhelm` or `bot`. + pub author_type: String, + pub created_at: i64, + pub ready_at: i64, + pub first_human_review_at: i64, + pub first_coderhelm_review_at: i64, + pub final_approval_at: i64, + pub merged: bool, + pub merged_at: i64, + pub closed_at: i64, + pub merged_by: String, + /// People's rounds of changes requested. + pub changes_rounds: u32, + pub additions: u32, + pub deletions: u32, + /// CoderHelm's part: `author`, `fixer`, `reviewer` or `none`. + pub coderhelm_role: String, + pub run_ids: Vec, + pub session_ids: Vec, + /// The person who asked CoderHelm for it. + pub requester: String, + pub spans: Vec, + pub review_log: Vec, + pub request_log: Vec, + pub check_log: Vec, + pub links: Vec, + /// The pull request that reverted it, and when. + pub reverted_by: Option<(String, u64, i64)>, + /// Pull requests that named it after it merged (fix-ups), and when. + pub follow_ups: Vec<(String, u64, i64)>, +} + +impl History { + pub fn from_record(r: &PrRecord) -> History { + let role = if r.author_is_coderhelm() { + "author" + } else if !r.coderhelm.run_ids.is_empty() || !r.coderhelm.run_id.is_empty() { + "fixer" + } else if r.first_coderhelm_review_at().is_some() || !r.coderhelm.session_id.is_empty() { + "reviewer" + } else { + "none" + }; + let mut run_ids = r.coderhelm.run_ids.clone(); + if !r.coderhelm.run_id.is_empty() && !run_ids.contains(&r.coderhelm.run_id) { + run_ids.push(r.coderhelm.run_id.clone()); + } + let mut session_ids = r.coderhelm.session_ids.clone(); + if !r.coderhelm.session_id.is_empty() && !session_ids.contains(&r.coderhelm.session_id) { + session_ids.push(r.coderhelm.session_id.clone()); + } + let merged = r.status == "merged"; + History { + repo: r.repo.clone(), + number: r.number, + title: r.title.clone(), + author: r.author.clone(), + author_type: author_type(&r.author).into(), + created_at: r.created_at, + ready_at: r.ready_or_created(), + first_human_review_at: r.first_human_review_at().unwrap_or(0), + first_coderhelm_review_at: r.first_coderhelm_review_at().unwrap_or(0), + final_approval_at: r.final_approval_at().unwrap_or(0), + merged, + merged_at: if merged { r.closed_at } else { 0 }, + closed_at: r.closed_at, + merged_by: r.merged_by.clone(), + changes_rounds: r.changes_rounds(), + additions: r.additions, + deletions: r.deletions, + coderhelm_role: role.into(), + run_ids, + session_ids, + requester: r.requester.clone(), + spans: r.spans.clone(), + review_log: r.review_log.clone(), + request_log: r.request_log.clone(), + check_log: r.check_log.clone(), + links: r.links.clone(), + reverted_by: None, + follow_ups: Vec::new(), + } + } + + /// Ready to merged, in seconds. + pub fn cycle_secs(&self) -> Option { + (self.merged && self.merged_at > 0 && self.ready_at > 0) + .then(|| (self.merged_at - self.ready_at).max(0)) + } + + /// Ready to the first human review, in seconds. + pub fn first_review_secs(&self) -> Option { + (self.first_human_review_at > 0 && self.ready_at > 0) + .then(|| (self.first_human_review_at - self.ready_at).max(0)) + } + + /// Seconds a person held the turn, from ready to the end. + pub fn waiting_on_person_secs(&self) -> i64 { + waiting_on_person( + &self.spans, + self.ready_at, + self.closed_at.max(self.merged_at), + ) + } + + /// Reverted, or fixed by a later pull request, within 14 days of its + /// merge (a proxy for a failed change, labeled as one). + pub fn reworked(&self) -> bool { + let within = |t: i64| { + self.merged_at > 0 && t >= self.merged_at && t - self.merged_at <= REWORK_WINDOW_SECS + }; + self.reverted_by + .as_ref() + .is_some_and(|(_, _, t)| within(*t)) + || self.follow_ups.iter().any(|(_, _, t)| within(*t)) + } +} + +/// Seconds the turn was a person's between `start` and `end`. +pub fn waiting_on_person(spans: &[Span], start: i64, end: i64) -> i64 { + let mut total = 0; + for (i, s) in spans.iter().enumerate() { + let to = spans.get(i + 1).map(|n| n.from).unwrap_or(end); + let from = s.from.max(start); + if s.turn == "person" && to > from { + total += to - from; + } + } + total +} + +/// The value at percentile `p` (0 to 100) of `v`, nearest rank; `None` +/// when empty. +pub fn percentile(v: &[i64], p: u32) -> Option { + if v.is_empty() { + return None; + } + let mut s = v.to_vec(); + s.sort_unstable(); + let rank = ((p as usize * s.len()).div_ceil(100)).max(1); + Some(s[rank.min(s.len()) - 1]) +} + +/// The percentiles a scope's thresholds come from. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Percentiles { + /// Ready to merged over the last 90 days: p50, p85, p95 (seconds). + pub cycle: Vec, + /// Ready to first human review over the last 8 weeks: p50, p85. + pub first_review: Vec, + /// Time in each stage before leaving it, p85, over 90 days. + pub stage_p85: BTreeMap, + /// Merges they come from. + pub merged: usize, +} + +/// One scope's day. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Snapshot { + /// `acme` (the org) or `acme/web`. + pub scope: String, + pub day: String, + /// Open pull requests by stage and by turn. + pub stages: BTreeMap, + pub turns: BTreeMap, + pub open: u32, + /// Open pull requests past the scope's p85 cycle time. + pub past_p85: u32, + /// In the 7 days to the snapshot. + pub arrivals: u32, + pub merges: u32, + pub closed_unmerged: u32, + pub review_requests: u32, + pub reviews_done: u32, + pub reverts: u32, + /// Merges by author type. + pub merges_by: BTreeMap, + pub pct: Percentiles, + /// The scope had too few merges and uses the org's percentiles. + pub inherited: bool, + /// The org has less than 8 weeks of history: external bands stand in. + pub young: bool, +} + +fn stage_durations(spans: &[Span], end: i64) -> BTreeMap> { + let mut out: BTreeMap> = BTreeMap::new(); + for (i, s) in spans.iter().enumerate() { + if s.stage.is_empty() { + continue; + } + let to = spans.get(i + 1).map(|n| n.from).unwrap_or(end); + out.entry(s.stage.clone()) + .or_default() + .push((to - s.from).max(0)); + } + out +} + +fn pct_of(hist: &[&History], now: i64) -> Percentiles { + 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 (k, v) in stage_durations(&h.spans, h.closed_at) { + stages.entry(k).or_default().extend(v); + } + } + Percentiles { + cycle: [50, 85, 95] + .iter() + .filter_map(|p| percentile(&cycles, *p)) + .collect(), + first_review: [50, 85] + .iter() + .filter_map(|p| percentile(&first, *p)) + .collect(), + stage_p85: stages + .into_iter() + .filter_map(|(k, v)| percentile(&v, 85).map(|p| (k, p))) + .collect(), + merged: cycles.len(), + } +} + +/// Every scope's snapshot for the day of `now`: the org of each owner and +/// each repository (the first [`MAX_SNAPSHOT_REPOS`]). +pub fn snapshots(open: &[(PrRecord, Stage, String)], hist: &[History], now: i64) -> Vec { + let day = chrono::DateTime::from_timestamp(now, 0) + .map(|d| d.format("%Y-%m-%d").to_string()) + .unwrap_or_default(); + let week = now - 7 * DAY; + let mut scopes: BTreeSet = BTreeSet::new(); + for (r, _, _) in open { + scopes.insert(r.org().to_string()); + scopes.insert(r.repo.clone()); + } + for h in hist { + scopes.insert(h.repo.split('/').next().unwrap_or("").to_string()); + scopes.insert(h.repo.clone()); + } + let first_seen = hist + .iter() + .map(|h| h.created_at) + .chain(open.iter().map(|(r, _, _)| r.created_at)) + .filter(|t| *t > 0) + .min() + .unwrap_or(now); + let young = now - first_seen < MIN_WEEKS_OWN * 7 * DAY; + let in_scope = |scope: &str, repo: &str| { + if scope.contains('/') { + repo.eq_ignore_ascii_case(scope) + } else { + repo.split('/') + .next() + .is_some_and(|o| o.eq_ignore_ascii_case(scope)) + } + }; + let mut orgs: BTreeMap = BTreeMap::new(); + let mut out = Vec::new(); + let mut repos = 0; + // Orgs first, so a repository can inherit its org's percentiles. + let ordered: Vec = scopes + .iter() + .filter(|s| !s.contains('/')) + .chain(scopes.iter().filter(|s| s.contains('/'))) + .cloned() + .collect(); + for scope in ordered { + if scope.is_empty() { + continue; + } + if scope.contains('/') { + repos += 1; + if repos > MAX_SNAPSHOT_REPOS { + break; + } + } + let h: Vec<&History> = hist.iter().filter(|h| in_scope(&scope, &h.repo)).collect(); + let own = pct_of(&h, now); + let org = scope.split('/').next().unwrap_or("").to_string(); + let (pct, inherited) = if scope.contains('/') && own.merged < MIN_MERGED_FOR_OWN { + (orgs.get(&org).cloned().unwrap_or(own), true) + } else { + (own, false) + }; + if !scope.contains('/') { + orgs.insert(scope.clone(), pct.clone()); + } + let mut s = Snapshot { + scope: scope.clone(), + day: day.clone(), + pct: pct.clone(), + inherited, + young, + ..Default::default() + }; + for st in pr_needs::STAGES { + s.stages.insert(st.code().into(), 0); + } + let p85 = pct.cycle.get(1).copied(); + for (r, stage, turn) in open.iter().filter(|(r, _, _)| in_scope(&scope, &r.repo)) { + *s.stages.entry(stage.code().into()).or_default() += 1; + *s.turns.entry(turn.clone()).or_default() += 1; + s.open += 1; + let age = now - r.ready_or_created(); + if *stage != Stage::Draft && p85.is_some_and(|p| age > p) { + s.past_p85 += 1; + } + if r.ready_or_created() > week { + s.arrivals += 1; + } + s.review_requests += r.request_log.iter().filter(|q| q.at > week).count() as u32; + s.reviews_done += r + .review_log + .iter() + .filter(|q| q.human && q.at > week) + .count() as u32; + } + for h in &h { + if h.ready_at > week { + s.arrivals += 1; + } + if h.merged && h.merged_at > week { + s.merges += 1; + *s.merges_by.entry(h.author_type.clone()).or_default() += 1; + } else if !h.merged && h.closed_at > week { + s.closed_unmerged += 1; + } + if h.reverted_by.as_ref().is_some_and(|(_, _, t)| *t > week) { + s.reverts += 1; + } + s.review_requests += h.request_log.iter().filter(|q| q.at > week).count() as u32; + s.reviews_done += h + .review_log + .iter() + .filter(|q| q.human && q.at > week) + .count() as u32; + } + out.push(s); + } + out +} + +// ─── Storage ──────────────────────────────────────────────────────────────── + +type Err = Box; + +/// Write a closed pull request's history (again, when it closes again). +/// A revert or follow-up already recorded on the row is kept. +pub async fn put( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + h: &History, + now: i64, +) -> Result<(), Err> { + let mut h = h.clone(); + if let Some(old) = load(dynamo, table, team_id, &h.repo, h.number).await? { + h.reverted_by = h.reverted_by.or(old.reverted_by); + for f in old.follow_ups { + if !h.follow_ups.contains(&f) { + h.follow_ups.push(f); + } + } + } + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(hist_sk(&h.repo, h.number))) + .item("doc", AttributeValue::S(serde_json::to_string(&h)?)) + .item("closed_at", AttributeValue::N(h.closed_at.to_string())) + .item( + "ttl", + AttributeValue::N((h.closed_at.max(now) + HISTORY_KEEP_SECS).to_string()), + ) + .send() + .await?; + Ok(()) +} + +pub async fn load( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + number: u64, +) -> Result, Err> { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(hist_sk(repo, number))) + .send() + .await?; + Ok(out + .item() + .and_then(|i| i.get("doc")) + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str(d).ok())) +} + +/// A merged pull request reverting or following up an earlier one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rework<'a> { + /// The earlier pull request. + pub target: (&'a str, u64), + /// The later one, and when it merged. + pub by: (&'a str, u64), + pub at: i64, + pub revert: bool, +} + +/// Mark the earlier pull request reverted or followed up: only a merged +/// pull request of the same team, and a follow-up within the rework window. +pub async fn mark( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + w: &Rework<'_>, + now: i64, +) -> Result { + let (target, by, at, revert) = (w.target, w.by, w.at, w.revert); + let Some(mut h) = load(dynamo, table, team_id, target.0, target.1).await? else { + return Ok(false); + }; + if !h.merged || at < h.merged_at || (!revert && at - h.merged_at > REWORK_WINDOW_SECS) { + return Ok(false); + } + let link = (by.0.to_string(), by.1, at); + if revert { + h.reverted_by = Some(link); + } else if !h.follow_ups.contains(&link) { + h.follow_ups.push(link); + } else { + return Ok(false); + } + put(dynamo, table, team_id, &h, now).await?; + Ok(true) +} + +/// Every history row of a team closed after `since` (bounded). +pub async fn all_since( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + since: i64, +) -> Result, Err> { + let mut out = Vec::new(); + let mut start: Option = None; + loop { + let page = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .filter_expression("closed_at >= :s") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":p", AttributeValue::S(HIST_PREFIX.into())) + .expression_attribute_values(":s", AttributeValue::N(since.to_string())) + .set_exclusive_start_key(start) + .send() + .await?; + for item in page.items() { + if let Some(h) = item + .get("doc") + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str::(d).ok()) + { + out.push(h); + } + } + start = page.last_evaluated_key().cloned(); + if start.is_none() || out.len() >= MAX_HISTORY_READ { + return Ok(out); + } + } +} + +/// Write the day's snapshots. +pub async fn put_snapshots( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + snaps: &[Snapshot], + now: i64, +) -> Result { + let mut n = 0; + for s in snaps { + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(snap_sk(&s.scope, &s.day))) + .item("doc", AttributeValue::S(serde_json::to_string(s)?)) + .item( + "ttl", + AttributeValue::N((now + HISTORY_KEEP_SECS).to_string()), + ) + .send() + .await?; + n += 1; + } + Ok(n) +} + +/// A scope's snapshots from `since_day` (`YYYY-MM-DD`) on, oldest first. +pub async fn snapshots_of( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + scope: &str, + since_day: &str, +) -> Result, Err> { + let out = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND sk BETWEEN :a AND :b") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":a", AttributeValue::S(snap_sk(scope, since_day))) + .expression_attribute_values(":b", AttributeValue::S(snap_sk(scope, "9999"))) + .send() + .await?; + Ok(out + .items() + .iter() + .filter_map(|i| i.get("doc").and_then(|v| v.as_s().ok())) + .filter_map(|d| serde_json::from_str(d).ok()) + .collect()) +} + +/// The open records of a team with their stage and turn, for a snapshot. +pub fn open_with_stage(recs: Vec) -> Vec<(PrRecord, Stage, String)> { + recs.into_iter() + .filter(PrRecord::is_open) + .filter_map(|r| { + let n = pr_needs::decide(&r.repo, &r.facts()); + let stage = pr_needs::stage_of(n.state, r.first_human_review_at().is_some())?; + Some((r, stage, n.turn.code().to_string())) + }) + .collect() +} + +/// `pr_record` is the source of every history row. +pub fn from_records(recs: &[PrRecord]) -> Vec { + recs.iter() + .filter(|r| !r.is_open()) + .map(History::from_record) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW: i64 = 1_800_000_000; + + fn merged(repo: &str, n: u64, ready_ago: i64, merged_ago: i64) -> History { + History { + repo: repo.into(), + number: n, + author: "octocat".into(), + author_type: "person".into(), + created_at: NOW - ready_ago, + ready_at: NOW - ready_ago, + merged: true, + merged_at: NOW - merged_ago, + closed_at: NOW - merged_ago, + ..Default::default() + } + } + + #[test] + fn durations_start_at_ready_and_human_review_leaves_out_bots_and_the_author() { + let mut r = PrRecord::new("acme/web", 1); + r.author = "octocat".into(); + r.created_at = NOW - 10 * DAY; + r.ready_at = NOW - 4 * DAY; + r.status = "merged".into(); + r.closed_at = NOW; + for (who, at, human) in [ + ("coderhelm[bot]", NOW - 3 * DAY, false), + ("octocat", NOW - 3 * DAY + 1, false), + ("mara", NOW - 2 * DAY, true), + ] { + r.review_log.push(ReviewEvent { + who: who.into(), + state: "APPROVED".into(), + at, + human, + ..Default::default() + }); + } + let h = History::from_record(&r); + assert_eq!(h.cycle_secs(), Some(4 * DAY)); + assert_eq!(h.first_review_secs(), Some(2 * DAY)); + assert_eq!(h.coderhelm_role, "reviewer"); + assert_eq!(h.first_coderhelm_review_at, NOW - 3 * DAY); + } + + #[test] + fn waiting_on_a_person_sums_the_person_turns_from_ready() { + let spans = vec![ + Span { + who: "nobody".into(), + state: "draft".into(), + from: 0, + turn: "person".into(), + stage: "draft".into(), + }, + Span { + who: "person:mara".into(), + state: "needs_review".into(), + from: 100, + turn: "person".into(), + stage: "first_review".into(), + }, + Span { + who: "ci".into(), + state: "checks_running".into(), + from: 300, + turn: "machines".into(), + stage: "approved".into(), + }, + ]; + assert_eq!(waiting_on_person(&spans, 100, 400), 200); + } + + #[test] + fn percentiles_are_nearest_rank() { + let v: Vec = (1..=100).collect(); + assert_eq!(percentile(&v, 50), Some(50)); + assert_eq!(percentile(&v, 85), Some(85)); + assert_eq!(percentile(&v, 95), Some(95)); + assert_eq!(percentile(&[], 50), None); + } + + #[test] + fn a_small_repository_inherits_its_orgs_percentiles_and_says_so() { + let mut hist: Vec = (0..40) + .map(|i| merged("acme/web", i, (i as i64 + 1) * 3600, 0)) + .collect(); + hist.extend((0..5).map(|i| merged("acme/api", 100 + i, 10 * DAY, 0))); + let snaps = snapshots(&[], &hist, NOW); + let org = snaps.iter().find(|s| s.scope == "acme").unwrap(); + let web = snaps.iter().find(|s| s.scope == "acme/web").unwrap(); + let api = snaps.iter().find(|s| s.scope == "acme/api").unwrap(); + assert!(!web.inherited); + assert!(api.inherited); + assert_eq!(api.pct, org.pct); + assert_eq!(org.merges, 45); + assert!(org.young, "less than 8 weeks of history"); + } + + #[test] + fn rework_counts_only_inside_the_window() { + let mut h = merged("acme/web", 1, DAY, 20 * DAY); + h.follow_ups.push(("acme/web".into(), 2, NOW - 19 * DAY)); + assert!(h.reworked()); + h.follow_ups = vec![("acme/web".into(), 2, NOW)]; + assert!(!h.reworked()); + } + + #[test] + fn a_revert_names_what_it_reverts() { + assert_eq!( + crate::pr_record::reverted( + "Revert \"Round cart totals\"", + "Reverts acme/web#318", + "acme/web" + ), + Some(("acme/web".to_string(), 318)) + ); + assert_eq!( + crate::pr_record::reverted("Round cart totals", "Reverts acme/web#318", "acme/web"), + None + ); + assert_eq!( + crate::pr_record::references("Follow-up to #318 and acme/api#12.", "acme/web"), + vec![("acme/web".to_string(), 318), ("acme/api".to_string(), 12)] + ); + } +} diff --git a/services/common/src/pr_needs.rs b/services/common/src/pr_needs.rs index 4823cd85f..573b37499 100644 --- a/services/common/src/pr_needs.rs +++ b/services/common/src/pr_needs.rs @@ -162,6 +162,91 @@ impl State { } } +/// The six stages of the overview's strip, mutually exclusive, mapped from +/// the state ([`stage_of`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Stage { + #[serde(rename = "draft")] + Draft, + #[serde(rename = "first_review")] + FirstReview, + #[serde(rename = "in_review")] + InReview, + #[serde(rename = "blocked")] + Blocked, + #[serde(rename = "coderhelm_working")] + CoderHelmWorking, + #[serde(rename = "approved")] + Approved, +} + +/// Every stage, in the strip's order. +pub const STAGES: &[Stage] = &[ + Stage::Draft, + Stage::FirstReview, + Stage::InReview, + Stage::Blocked, + Stage::CoderHelmWorking, + Stage::Approved, +]; + +impl Stage { + pub fn code(self) -> &'static str { + match self { + Stage::Draft => "draft", + Stage::FirstReview => "first_review", + Stage::InReview => "in_review", + Stage::Blocked => "blocked", + Stage::CoderHelmWorking => "coderhelm_working", + Stage::Approved => "approved", + } + } + + pub fn label(self) -> &'static str { + match self { + Stage::Draft => "Draft", + Stage::FirstReview => "Waiting for first review", + Stage::InReview => "In review", + Stage::Blocked => "Blocked", + Stage::CoderHelmWorking => "CoderHelm working", + Stage::Approved => "Approved, not merged", + } + } + + pub fn from_code(code: &str) -> Option { + STAGES.iter().copied().find(|s| s.code() == code) + } +} + +/// The stage of an open pull request in `state`; `None` once it is merged +/// or closed. `reviewed`: a person other than the author has reviewed it, +/// which tells a first review from a later one. A pull request whose facts +/// aren't known yet, and one that waits on a person's decision, are +/// blocked. +pub fn stage_of(state: State, reviewed: bool) -> Option { + Some(match state { + State::Merged | State::Closed => return None, + State::Draft => Stage::Draft, + State::NeedsReviewer | State::NeedsReview if !reviewed => Stage::FirstReview, + State::NeedsReviewer + | State::NeedsReview + | State::ChangesRequested + | State::ReReview + | State::NeedsCodeOwner + | State::OpenThreads => Stage::InReview, + State::Conflicts + | State::ChecksFailing + | State::WaitingOnPr + | State::LeftQueue + | State::NeedsDecision + | State::Unknown => Stage::Blocked, + State::CoderHelmWorking => Stage::CoderHelmWorking, + State::InQueue | State::ChecksRunning | State::ReadyAutoMerge | State::ReadyToMerge => { + Stage::Approved + } + }) +} + /// Who holds the next move. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub enum Turn { diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs index aa1e85f4d..f3bf7d548 100644 --- a/services/common/src/pr_record.rs +++ b/services/common/src/pr_record.rs @@ -130,6 +130,62 @@ pub struct CoderHelmLink { /// The reviewer's latest session on it. #[serde(default)] pub session_id: String, + /// Every run on it, oldest first (its findings and cost are the runs' + /// and the review sessions'). + #[serde(default)] + pub run_ids: Vec, + /// Every review session on it, oldest first. + #[serde(default)] + pub session_ids: Vec, +} + +/// One review submitted, as it happened (people's and CoderHelm's). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ReviewEvent { + pub who: String, + /// `APPROVED`, `CHANGES_REQUESTED`, `COMMENTED`, `DISMISSED`. + pub state: String, + pub sha: String, + pub at: i64, + /// A person who isn't the author: CoderHelm, other bots and the author + /// never count as human review. + pub human: bool, + /// The review carried words of its own. + pub has_body: bool, +} + +/// One review request: who, when asked, when taken back (0 never). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RequestEvent { + /// A login, or `org/slug` for a team. + pub who: String, + pub at: i64, + pub removed_at: i64, +} + +/// The head's checks turning `red`, `pending` or `green`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct CheckTransition { + pub rollup: String, + pub at: i64, +} + +/// Most review, request and check transitions kept on a record. +pub const MAX_LOG: usize = 150; + +/// A login is a bot's (GitHub apps end in `[bot]`). +pub fn is_bot(login: &str) -> bool { + login.ends_with("[bot]") || is_coderhelm(login) +} + +fn bounded(v: &mut Vec) { + if v.len() > MAX_LOG { + let cut = v.len() - MAX_LOG; + v.drain(..cut); + } } /// One timeline event. @@ -155,6 +211,12 @@ pub struct Span { pub who: String, pub state: String, pub from: i64, + /// The turn and the stage of the overview strip, for time in stage and + /// time waiting on a person. + #[serde(default)] + pub turn: String, + #[serde(default)] + pub stage: String, } /// The record's body. @@ -176,6 +238,9 @@ pub struct PrRecord { pub head_ref: String, pub base_ref: String, pub created_at: i64, + /// When it was first ready for review: its creation when it never was + /// a draft, else when it left draft. Every duration starts here. + pub ready_at: i64, pub updated_at: i64, pub closed_at: i64, pub merged_by: String, @@ -215,6 +280,11 @@ pub struct PrRecord { pub coderhelm: CoderHelmLink, pub events: Vec, pub spans: Vec, + /// Every review, request and check transition (the newest + /// [`MAX_LOG`]): what the history and the overview's durations read. + pub review_log: Vec, + pub request_log: Vec, + pub check_log: Vec, /// When the sync last read it (epoch seconds; 0 never). pub synced_at: i64, /// When an event last changed it. @@ -281,6 +351,49 @@ pub fn compatibility_links(body: &str) -> Vec<(String, u64)> { out } +/// The pull request a revert reverts: GitHub's own revert writes "Reverts +/// owner/repo#n" in the description. +pub fn reverted(title: &str, body: &str, repo: &str) -> Option<(String, u64)> { + if !title.trim_start().starts_with("Revert") { + return None; + } + references(body, repo) + .into_iter() + .find(|_| body.contains("Reverts ")) +} + +/// Pull requests a description names (`owner/repo#n`, or `#n` in the same +/// repository), the first few. +pub fn references(body: &str, repo: &str) -> Vec<(String, u64)> { + let mut out: Vec<(String, u64)> = Vec::new(); + for word in body.split(|c: char| c.is_whitespace() || "()[],;`:".contains(c)) { + let word = word + .trim_start_matches("https://github.com/") + .replace("/pull/", "#") + .trim_end_matches('.') + .to_string(); + let Some((r, n)) = word.rsplit_once('#') else { + continue; + }; + let Ok(n) = n.parse::() else { continue }; + let r = if r.is_empty() { + repo.to_string() + } else { + r.to_string() + }; + let ok = r.split('/').count() == 2 + && r.chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)); + if ok && !out.contains(&(r.clone(), n)) { + out.push((r, n)); + } + if out.len() >= 5 { + break; + } + } + out +} + impl PrRecord { pub fn new(repo: &str, number: u64) -> PrRecord { PrRecord { @@ -424,6 +537,24 @@ impl PrRecord { self.auto_merge = !pr["auto_merge"].is_null(); } if let Some(body) = pr["body"].as_str() { + self.links.retain(|l| l.kind != "reverts"); + if let Some((repo, n)) = reverted(&self.title, body, &self.repo) { + self.links.push(Link { + kind: "reverts".into(), + repo, + number: n, + }); + } + self.links.retain(|l| l.kind != "references"); + for (repo, n) in references(body, &self.repo) { + if repo != self.repo || n != self.number { + self.links.push(Link { + kind: "references".into(), + repo, + number: n, + }); + } + } self.links.retain(|l| l.kind != "contract"); for (repo, n) in compatibility_links(body) { self.links.push(Link { @@ -454,6 +585,13 @@ impl PrRecord { let before = self.head_sha.clone(); self.take_pr(pr); let when = at(&pr["updated_at"]); + if self.ready_at == 0 { + if action == "ready_for_review" { + self.ready_at = when; + } else if !self.draft && self.created_at > 0 { + self.ready_at = self.created_at; + } + } match action { "opened" => self.event( at(&pr["created_at"]), @@ -503,14 +641,42 @@ impl PrRecord { .map(|t| format!("@{}/{t}", self.org())) }) .unwrap_or_default(); + let key = who.trim_start_matches('@').to_string(); + if !key.is_empty() { + self.request_log.push(RequestEvent { + who: key, + at: when, + removed_at: 0, + }); + bounded(&mut self.request_log); + } self.event(when, &sender, "reviewers", format!("asked {who} to review")) } - "review_request_removed" => self.event( - when, - &sender, - "reviewers", - "removed a review request".into(), - ), + "review_request_removed" => { + let who = payload["requested_reviewer"]["login"] + .as_str() + .map(str::to_string) + .or_else(|| { + payload["requested_team"]["slug"] + .as_str() + .map(|t| format!("{}/{t}", self.org())) + }) + .unwrap_or_default(); + if let Some(r) = self + .request_log + .iter_mut() + .rev() + .find(|r| r.who.eq_ignore_ascii_case(&who) && r.removed_at == 0) + { + r.removed_at = when; + } + self.event( + when, + &sender, + "reviewers", + "removed a review request".into(), + ) + } "labeled" => self.event( when, &sender, @@ -627,6 +793,19 @@ impl PrRecord { } self.requested.retain(|p| !p.eq_ignore_ascii_case(&who)); } + self.review_log.push(ReviewEvent { + who: who.clone(), + state: if action == "dismissed" { + "DISMISSED".into() + } else { + state.clone() + }, + sha: s(&r["commit_id"]), + at: when, + human: !is_bot(&who) && !who.eq_ignore_ascii_case(&self.author), + has_body: r["body"].as_str().is_some_and(|b| !b.trim().is_empty()), + }); + bounded(&mut self.review_log); self.role(&who, "reviewer"); let words = match (action, state.as_str()) { ("dismissed", _) => "had a review dismissed".to_string(), @@ -686,6 +865,7 @@ impl PrRecord { self.event(c.at, "ci", "check", format!("`{name}` failed")); } self.put_check(name, c); + self.note_checks(now); self.event_at = now; true } @@ -717,6 +897,7 @@ impl PrRecord { format!("a check suite finished: {concl}"), ); } + self.note_checks(now); self.event_at = now; true } @@ -740,6 +921,7 @@ impl PrRecord { at: at(&payload["updated_at"]), }, ); + self.note_checks(now); self.event_at = now; true } @@ -771,6 +953,75 @@ impl PrRecord { } } + /// The head's checks as one word: `red`, `pending` or `green`. + pub fn check_rollup(&self) -> &'static str { + if self.checks.is_empty() { + return "pending"; + } + if self.checks.values().any(Check::failed) { + "red" + } else if self.checks.values().any(Check::running) { + "pending" + } else { + "green" + } + } + + fn note_checks(&mut self, at: i64) { + let rollup = self.check_rollup(); + if self.check_log.last().is_none_or(|c| c.rollup != rollup) { + self.check_log.push(CheckTransition { + rollup: rollup.into(), + at, + }); + bounded(&mut self.check_log); + } + } + + /// The first review by a person who isn't the author (bots never count). + pub fn first_human_review_at(&self) -> Option { + self.review_log + .iter() + .filter(|r| r.human && r.state != "DISMISSED") + .map(|r| r.at) + .min() + } + + /// CoderHelm's first review. + pub fn first_coderhelm_review_at(&self) -> Option { + self.review_log + .iter() + .filter(|r| is_coderhelm(&r.who)) + .map(|r| r.at) + .min() + } + + /// The last approval by a person who isn't the author. + pub fn final_approval_at(&self) -> Option { + self.review_log + .iter() + .filter(|r| r.human && r.state == "APPROVED") + .map(|r| r.at) + .max() + } + + /// Rounds of changes requested by people. + pub fn changes_rounds(&self) -> u32 { + self.review_log + .iter() + .filter(|r| r.human && r.state == "CHANGES_REQUESTED") + .count() as u32 + } + + /// When every duration starts: ready for review, else its creation. + pub fn ready_or_created(&self) -> i64 { + if self.ready_at > 0 { + self.ready_at + } else { + self.created_at + } + } + fn take_check_sha(&mut self, sha: &str) -> bool { if sha.is_empty() { return false; @@ -834,6 +1085,11 @@ impl PrRecord { self.base_ref = s(&n["baseRefName"]); self.created_at = ts(&n["createdAt"]); self.updated_at = ts(&n["updatedAt"]); + if self.ready_at == 0 && !self.draft { + // The search carries no ready time: the creation stands in + // until an event says better. + self.ready_at = self.created_at; + } self.additions = n["additions"].as_u64().unwrap_or(0) as u32; self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; self.labels = n["labels"]["nodes"] @@ -1083,7 +1339,16 @@ impl PrRecord { } else { now }; - self.spans.push(Span { who, state, from }); + let stage = pr_needs::stage_of(n.state, self.first_human_review_at().is_some()) + .map(|s| s.code().to_string()) + .unwrap_or_default(); + self.spans.push(Span { + who, + state, + from, + turn: n.turn.code().to_string(), + stage, + }); if self.spans.len() > MAX_SPANS { let cut = self.spans.len() - MAX_SPANS; self.spans.drain(..cut); @@ -1432,7 +1697,11 @@ mod tests { assert_eq!(r.author, "octocat"); assert_eq!(r.requested, vec!["mara"]); assert_eq!( - r.links, + r.links + .iter() + .filter(|l| l.kind == "contract") + .cloned() + .collect::>(), vec![Link { kind: "contract".into(), repo: "acme/api".into(), diff --git a/services/common/src/pr_view.rs b/services/common/src/pr_view.rs index d055b96e4..c969dd63a 100644 --- a/services/common/src/pr_view.rs +++ b/services/common/src/pr_view.rs @@ -150,6 +150,10 @@ pub struct Row { pub updated_at: Option, pub state: String, pub state_label: String, + /// The overview's stage (`common::pr_needs::Stage`), null once closed. + pub stage: Option, + /// Ready for review (every age is measured from here). + pub ready_at: Option, pub turn: String, pub next: NextOut, pub modifiers: Vec, @@ -570,6 +574,9 @@ fn row( updated_at: rfc3339(r.updated_at.max(r.event_at)), state: n.state.code().into(), state_label: n.state.label().into(), + stage: pr_needs::stage_of(n.state, r.first_human_review_at().is_some()) + .map(|s| s.code().to_string()), + ready_at: rfc3339(r.ready_or_created()), turn: turn.clone(), next: NextOut { code: n.next.code.clone(), diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 238b9db29..1e6734c67 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -102,6 +102,9 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo if let Err(e) = pr_record::point(&state.dynamo, table, team_id, &rec, t).await { warn!(repo, number, error = %e, "Pull request record: pointer not written"); } + if !rec.is_open() { + record_history(state, team_id, &rec, t).await; + } } // CoderHelm's run on it, found once. let asks = rec.author_is_coderhelm() || !rec.requester.is_empty(); @@ -115,6 +118,9 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo return false; } r.coderhelm.run_id = run_id.clone(); + if !r.coderhelm.run_ids.contains(&run_id) { + r.coderhelm.run_ids.push(run_id.clone()); + } true }) .await; @@ -123,6 +129,52 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo } } +/// A pull request closed: its history row (kept over a year), and on a +/// merge the revert or follow-up links to the merged pull requests it +/// names. +async fn record_history(state: &AppState, team_id: &str, rec: &PrRecord, now: i64) { + let table = &state.config.settings_table_name; + let h = common::pr_history::History::from_record(rec); + if let Err(e) = common::pr_history::put(&state.dynamo, table, team_id, &h, now).await { + warn!(repo = %rec.repo, number = rec.number, error = %e, "Pull request history not written"); + return; + } + if rec.status != "merged" { + return; + } + let reverts = rec + .links + .iter() + .find(|l| l.kind == "reverts") + .map(|l| (l.repo.clone(), l.number)); + let mut targets: Vec<((String, u64), bool)> = + reverts.clone().map(|t| (t, true)).into_iter().collect(); + for l in rec.links.iter().filter(|l| l.kind == "references") { + let t = (l.repo.clone(), l.number); + if Some(&t) != reverts.as_ref() && (t.0 != rec.repo || t.1 != rec.number) { + targets.push((t, false)); + } + } + for ((repo, n), revert) in targets.into_iter().take(5) { + let marked = common::pr_history::mark( + &state.dynamo, + table, + team_id, + &common::pr_history::Rework { + target: (&repo, n), + by: (&rec.repo, rec.number), + at: rec.closed_at.max(1), + revert, + }, + now, + ) + .await; + if let Err(e) = marked { + warn!(repo, n, error = %e, "Revert or follow-up link not written"); + } + } +} + // ─── The reads ────────────────────────────────────────────────────────────── fn s(item: &Item, k: &str) -> String { diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 53056b38e..080a944fc 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -818,6 +818,10 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe pages = prs.pages, "Pull request records sync done" ); + // The overview's nightly snapshot and percentiles, per org and + // repository: once a day per team, no GitHub requests. + let snaps = passes::pr_records::nightly(&state).await; + info!(snapshots = snaps, "Pull request snapshots done"); // Stale pull requests: each repository at most once an hour. let stale = as_sweep(who::SWEEP_STALE_PRS, passes::stale_prs::sweep(&state)).await; info!( diff --git a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs index 348e869bd..3e9bf79a5 100644 --- a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs +++ b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs @@ -122,6 +122,11 @@ fn every_open_pull_request_appears_whoever_opened_it() { assert_eq!(r.ttl(), None); r.status = "closed".into(); assert!(r.ttl().is_some()); + // A closed pull request's history outlives a year, and the gateway + // writes it when the pull request closes. + const _: () = assert!(common::pr_history::HISTORY_KEEP_SECS >= 400 * 86_400); + let prs = src("gateway/src/routes/prs.rs"); + assert!(prs.contains("record_history(state, team_id, &rec, t).await;")); } #[test] diff --git a/services/worker/src/passes/pr_records.rs b/services/worker/src/passes/pr_records.rs index bda8dce40..ad5ca8e20 100644 --- a/services/worker/src/passes/pr_records.rs +++ b/services/worker/src/passes/pr_records.rs @@ -52,6 +52,49 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { report } +/// The nightly snapshot of every org and repository of each team: counts +/// by stage and turn, arrivals, merges, reviews, and the percentiles the +/// thresholds come from (`common::pr_history::snapshots`). Once a day per +/// team, reading only the team's own records and history (bounded), and no +/// GitHub requests. +pub async fn nightly(state: &WorkerState) -> usize { + use common::pr_history; + let day = chrono::Utc::now().format("%Y%m%d").to_string(); + let table = &state.config.settings_table_name; + let mut written = 0; + for team in super::learning_wait::teams(state).await { + let claim = format!("PRSNAP_JOB#{day}"); + if !super::review_pr::claim_once_ttl(state, &team, &claim, 2 * 86_400).await { + continue; + } + let now = chrono::Utc::now().timestamp(); + let recs = match pr_record::all(&state.dynamo, table, &team).await { + Ok(r) => r, + Err(e) => { + warn!(team_id = %team, error = %e, "Pull request snapshot: records not read"); + continue; + } + }; + let hist = + match pr_history::all_since(&state.dynamo, table, &team, now - 120 * 86_400).await { + Ok(h) => h, + Err(e) => { + warn!(team_id = %team, error = %e, "Pull request snapshot: history not read"); + continue; + } + }; + if recs.is_empty() && hist.is_empty() { + continue; + } + let snaps = pr_history::snapshots(&pr_history::open_with_stage(recs), &hist, now); + match pr_history::put_snapshots(&state.dynamo, table, &team, &snaps, now).await { + Ok(n) => written += n, + Err(e) => warn!(team_id = %team, error = %e, "Pull request snapshot not written"), + } + } + written +} + /// One team, now (the install's first read). pub async fn sync_message(state: &WorkerState, msg: &common::messages::PrRecordsSyncMessage) { let mut gate = SweepGate::new(who::SWEEP_DASHBOARD_PRS); From afe30c70770403c4ee616efd45336dcc189554a0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 14:51:40 -0500 Subject: [PATCH 4/7] Every pull request, whoever wrote it: history backfill and health signals A resumable 14-month backfill reads each organization's closed and merged pull requests into history under the shared budget, pausing on a held budget or rate limit and showing its progress per repository. Records keep separate author, reviewer and bot clocks, drift against the base, every check attempt (flaky reads as flaky), category and severity; history adds review coverage, bypass merges, suspect follow-ups with their reason, and CoderHelm's last run outcome and stop reason. --- docs/pull-requests.md | 4 +- docs/pull-requests/api_contract.md | 20 ++ services/common/src/github_budget.rs | 4 +- services/common/src/pr_history.rs | 279 +++++++++++++++++- services/common/src/pr_record.rs | 262 +++++++++++++++- services/gateway/src/routes/prs.rs | 97 +++++- .../xw_every_open_pr_has_one_state.rs | 74 +++++ services/worker/src/passes/pr_records.rs | 142 ++++++++- 8 files changed, 864 insertions(+), 18 deletions(-) diff --git a/docs/pull-requests.md b/docs/pull-requests.md index a79896e45..ea343c375 100644 --- a/docs/pull-requests.md +++ b/docs/pull-requests.md @@ -19,6 +19,8 @@ What the org overview reads, kept so the page never has to be migrated (`service - **The change log.** Each record keeps its turn changes (who held the turn, the state, the turn and the stage, and since when), every review submitted (people's and CoderHelm's, marked human or not), every review request with when it was taken back, and the head's checks turning red, pending or green. Time in a stage and time waiting on a person are read from it. - **History.** When a pull request merges or closes, its history row (`sk = PRHIST##`) is written and kept 400 days: ready, first human review, CoderHelm's first review, final approval, merge or close and who merged, rounds of changes requested, size, author type, CoderHelm's part (author, fixer, reviewer or none) with its runs and review sessions, the change log, and links. - **Reverts and follow-ups.** A merged revert ("Reverts owner/repo#n") marks the pull request it reverts; a merged pull request that names an earlier merged one within 14 days of its merge marks it as followed up. Both are labeled a proxy for a failed change. +- **Every pull request, whoever wrote it.** Nothing filters to CoderHelm's pull requests: the webhooks write people's, bots' and CoderHelm's alike, and the sync keeps every author in the team's connected repositories. +- **The history backfill.** At install and on every hourly reconcile, each organization's closed and merged pull requests of the last 14 months are read into history, a month at a time from the newest, at most 5 search pages per organization per sweep. A held budget or GitHub's rate limit pauses it with the reason and the time; the next sweep resumes from the stored page cursor. Once all 14 months are read, each sweep reads the pull requests closed since its last day. The list shows the progress per organization, with the history rows read per repository. - **The nightly snapshot** (`sk = PRSNAP##`, kept 400 days), once a day per team and per org and repository (the first 300): open pull requests by stage and turn, how many are past the scope's p85, arrivals, merges (by author type), closed without merging, reviews asked and done, reverts, and the percentiles: cycle time p50, p85 and p95 over 90 days, first human review p50 and p85 over 8 weeks, and each stage's p85. A repository with fewer than 30 merges in 90 days uses its org's percentiles and says so; an org with less than 8 weeks of history is marked young, so the page shows external bands instead. The job reads only the team's own records and history (at most 25,000 history rows) and makes no GitHub requests. ## One state per pull request @@ -39,5 +41,5 @@ Both need the "view" capability. The team is always the session's; a record of a ## Cost - Reading the list costs no GitHub requests: it reads the team's records, its runs on them (one batched read) and the reviewer's records, and reuses them for 10 seconds per installation and team. -- The sync spends from the installation's shared GitHub budget as `sweep:dashboard_prs`: at most 30 requests an hour, at most 10 pages of 30 pull requests per organization each time, once an hour per team and once at install. It runs only while the budget leaves the runs their share. +- The sync spends from the installation's shared GitHub budget as `sweep:dashboard_prs`: at most 60 requests an hour: at most 10 pages of 30 open pull requests and 5 pages of closed ones per organization each time, once an hour per team and once at install. It runs only while the budget leaves the runs their share. - Each webhook costs one read and one write of its record. diff --git a/docs/pull-requests/api_contract.md b/docs/pull-requests/api_contract.md index bfa99cc47..51fc77496 100644 --- a/docs/pull-requests/api_contract.md +++ b/docs/pull-requests/api_contract.md @@ -24,6 +24,7 @@ Team comes from the session only. 404 from an older backend means "not served ye "views": {"my_turn": 2, "coderhelm_working": 4, "needs_decision": 1, "ready": 3, "stale": 2} }, "viewer": "octocat", + "backfill": [{"owner": "acme", "months_read": 9, "months_total": 14, "done": false, "paused_until": null, "paused_why": null, "repos": {"acme/web": 212, "acme/api": 97}, "updated_at": "..."}], "synced_at": "2026-01-10T12:00:00Z", "sources": [{"name": "webhooks", "read": "ok", "detail": ""}, {"name": "reconcile", "read": "ok", "detail": "acme: 37 open pull requests read"}] } @@ -112,3 +113,22 @@ All settings-table rows, `pk` = team id, body JSON in `doc`. Types live in `serv `scope, day, stages {stage: n}, turns {turn: n}, open, past_p85, arrivals, merges, closed_unmerged, review_requests, reviews_done, reverts, merges_by {author_type: n}, pct {cycle: [p50,p85,p95] secs over 90 days, first_review: [p50,p85] over 8 weeks, stage_p85 {stage: secs}, merged}, inherited (repo under 30 merges uses the org's), young (org under 8 weeks: show external bands)`. Weekly counts are the 7 days to the snapshot. `pr_history::snapshots_of(team, scope, since_day)` reads them oldest first. + +## History backfill (every pull request, whoever wrote it) +At install and on every hourly reconcile, the worker reads each organization's closed and merged pull requests, a month at a time from the newest, 14 months back (`PRBACKFILL#` holds the progress, `pr_history::Backfill`), into history rows. People's, bots' and CoderHelm's pull requests alike: the only filter is the team's connected repositories. At most 5 search pages per organization per sweep under `sweep:dashboard_prs` (60 requests an hour); a held budget or GitHub's rate limit pauses it (`paused_until`, `paused_why`) and the next sweep resumes from the stored page cursor. `GET /api/prs` returns the progress as `backfill`, with history rows written per repository. + +## Health signals (from "Org pull request health signals") +On the current row (`PrRecord`): +- `last_author_action_at`, `last_reviewer_action_at`, `last_bot_event_at`: separate clocks. Bots, CI and CoderHelm move only the third, so a pull request only bots touch still reads idle. +- `files[]` (the sync reads up to 100 paths), `drift_behind`, `drift_overlap`: commits pushed to its base since its last push, and those touching its files (from the push's own file lists; reset by a push to the pull request). +- `check_attempts[] {name, sha, conclusion, at}`: every completed attempt; `pr_record::flaky_checks()` = failed then passed on the same commit. +- `category` (`feature` | `dependency` | `security`) and `severity` (`critical` | `high` | `moderate` | `low` | ""), from the author, labels and title. The SLA clock starts at `ready_at`. + +On the history row (`History`): +- `coverage`: `human_approved` | `ai_only` | `non_owner_on_owned` | `bypass_or_exempt` | `no_review` (`pr_history::coverage_of`). +- `bypass`: the rule a merge went past ("merged before the required review", "merged with changes requested", "merged with required checks failing: ...", "merged while the branch's rules blocked it") or null; `merged_by_type` (`person` | `coderhelm` | `bot`), so CoderHelm's own bypasses show. +- `follow_ups[] {repo, number, at, reason}`: suspects, never cause, each with its reason; `reverted_by` is the certain link. +- `category`, `severity`, `flaky_checks[]`, `drift_behind`, `drift_overlap`. +- `run_outcome` (the last run's status) and `stop_reason` (its hand-off code when a person had to act). + +Not stored yet (follow-ups): CODEOWNERS file versions and sensitive-path lists (so `non_owner_on_owned` reads only GitHub's review decision today), policy events from the rule-suites API and audit log, Dependabot and code-scanning alerts with KEV and EPSS, default-branch CI episodes, a nightly flaky-check index, review comment counts and comments followed by a change, run cost and findings per pull request, the event feed, and the SLA and working-agreement settings. diff --git a/services/common/src/github_budget.rs b/services/common/src/github_budget.rs index 526c44312..5438e146b 100644 --- a/services/common/src/github_budget.rs +++ b/services/common/src/github_budget.rs @@ -155,7 +155,7 @@ pub mod caller { (SWEEP_REVIEW, 120), (SWEEP_DRAFTS, 120), (SWEEP_PR_WATCH, 240), - (SWEEP_DEPLOYS, 240), + (SWEEP_DEPLOYS, 210), (SWEEP_REVIEW_REMINDER, 120), (SWEEP_PR_OUTCOMES, 120), (SWEEP_SKILLS, 60), @@ -170,7 +170,7 @@ pub mod caller { (SWEEP_WEEKLY, 100), (SWEEP_QUARANTINE, 90), (SWEEP_FOLLOWUP_DEDUPE, 30), - (SWEEP_DASHBOARD_PRS, 30), + (SWEEP_DASHBOARD_PRS, 60), ]; } diff --git a/services/common/src/pr_history.rs b/services/common/src/pr_history.rs index ba1069462..3e5d6301d 100644 --- a/services/common/src/pr_history.rs +++ b/services/common/src/pr_history.rs @@ -27,7 +27,8 @@ use serde::{Deserialize, Serialize}; use crate::pr_needs::{self, Stage}; use crate::pr_record::{ - is_bot, is_coderhelm, CheckTransition, Item, Link, PrRecord, RequestEvent, ReviewEvent, Span, + self, is_bot, is_coderhelm, CheckTransition, Item, Link, PrRecord, RequestEvent, ReviewEvent, + Span, }; /// Sort-key prefix of the history rows. @@ -103,10 +104,94 @@ pub struct History { pub request_log: Vec, pub check_log: Vec, pub links: Vec, - /// The pull request that reverted it, and when. + /// The pull request that reverted it, and when (certain). pub reverted_by: Option<(String, u64, i64)>, - /// Pull requests that named it after it merged (fix-ups), and when. - pub follow_ups: Vec<(String, u64, i64)>, + /// Later pull requests suspected of fixing it, each with its reason + /// (suspect, never cause). + pub follow_ups: Vec, + /// How it was reviewed: `human_approved`, `ai_only`, + /// `non_owner_on_owned`, `bypass_or_exempt` or `no_review` + /// ([`coverage_of`]). + pub coverage: String, + /// Merged past a rule that still held it, and which: CoderHelm's own + /// merges included (`merged_by_type`). + pub bypass: Option, + pub merged_by_type: String, + /// `feature`, `dependency` or `security`, its severity, and when its + /// clock started (ready for review). + pub category: String, + pub severity: String, + /// Checks that failed and then passed on the same commit. + pub flaky_checks: Vec, + /// How far the base had moved under it at the end. + pub drift_behind: u32, + pub drift_overlap: u32, + /// CoderHelm's last run on it: how it ended, and why it stopped when a + /// person had to act (`handback` code). + pub run_outcome: String, + pub stop_reason: String, +} + +/// A later pull request suspected of fixing an earlier one. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Suspect { + pub repo: String, + pub number: u64, + pub at: i64, + /// Why it is suspected, in words ("names it in its description", + /// "labeled hotfix and names it"). + pub reason: String, +} + +/// How a closed pull request was reviewed, one of five. +pub fn coverage_of(r: &PrRecord) -> &'static str { + let human = r + .review_log + .iter() + .any(|v| v.human && v.state == "APPROVED"); + let bot = r + .review_log + .iter() + .any(|v| !v.human && v.state == "APPROVED" && is_bot(&v.who)); + let held = matches!( + r.review_decision.as_deref(), + Some("REVIEW_REQUIRED") | Some("CHANGES_REQUESTED") + ); + if human && held && r.codeowners_required { + "non_owner_on_owned" + } else if human { + "human_approved" + } else if r.status == "merged" && (held || r.approvals_required > 0) { + "bypass_or_exempt" + } else if bot { + "ai_only" + } else { + "no_review" + } +} + +/// The rule a merge went past, when GitHub still held it at the merge. +pub fn bypass_of(r: &PrRecord) -> Option { + if r.status != "merged" { + return None; + } + let f = r.facts(); + let (failing, _) = f.checks.blocking(); + if matches!(r.review_decision.as_deref(), Some("CHANGES_REQUESTED")) { + Some("merged with changes requested".into()) + } else if matches!(r.review_decision.as_deref(), Some("REVIEW_REQUIRED")) { + Some("merged before the required review".into()) + } else if !failing.is_empty() && !f.checks.required.is_empty() { + Some(format!( + "merged with required checks failing: {}", + failing.join(", ") + )) + } else if r.merge_state == "blocked" { + Some("merged while the branch's rules blocked it".into()) + } else { + None + } } impl History { @@ -158,6 +243,20 @@ impl History { links: r.links.clone(), reverted_by: None, follow_ups: Vec::new(), + coverage: coverage_of(r).into(), + bypass: bypass_of(r), + merged_by_type: if r.merged_by.is_empty() { + String::new() + } else { + author_type(&r.merged_by).into() + }, + category: r.category.clone(), + severity: r.severity.clone(), + flaky_checks: pr_record::flaky_checks(&r.check_attempts), + drift_behind: r.drift_behind, + drift_overlap: r.drift_overlap, + run_outcome: String::new(), + stop_reason: String::new(), } } @@ -191,7 +290,7 @@ impl History { self.reverted_by .as_ref() .is_some_and(|(_, _, t)| within(*t)) - || self.follow_ups.iter().any(|(_, _, t)| within(*t)) + || self.follow_ups.iter().any(|f| within(f.at)) } } @@ -430,6 +529,114 @@ pub fn snapshots(open: &[(PrRecord, Stage, String)], hist: &[History], now: i64) out } +// ─── The history backfill ─────────────────────────────────────────────────── + +/// Sort-key prefix of each organization's backfill progress. +pub const BACKFILL_PREFIX: &str = "PRBACKFILL#"; +/// Months of closed pull requests the backfill reads (over 400 days). +pub const BACKFILL_MONTHS: u32 = 14; + +pub fn backfill_sk(owner: &str) -> String { + format!("{BACKFILL_PREFIX}{owner}") +} + +/// How far one organization's history backfill has read: a month at a time, +/// newest first, resumed from its page cursor after a pause. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Backfill { + pub owner: String, + /// Months fully read (0 is the current month). + pub months_read: u32, + /// The page cursor inside the month being read. + pub cursor: Option, + pub done: bool, + /// The budget held it until then (epoch seconds; 0 not held). + pub paused_until: i64, + /// Why it is held, in words. + pub paused_why: String, + /// History rows written, by repository. + pub repos: BTreeMap, + pub pages: u32, + pub started_at: i64, + pub updated_at: i64, + /// The last day the reconcile read after the backfill was done. + pub reconciled_to: String, +} + +impl Backfill { + /// The window of month `i` back from `now` (`YYYY-MM-DD` inclusive). + pub fn window(now: i64, i: u32) -> (String, String) { + use chrono::{Datelike, Duration, NaiveDate}; + let today = chrono::DateTime::from_timestamp(now, 0) + .map(|d| d.date_naive()) + .unwrap_or_default(); + let mut y = today.year(); + let mut m = today.month() as i32 - i as i32; + while m <= 0 { + m += 12; + y -= 1; + } + let first = NaiveDate::from_ymd_opt(y, m as u32, 1).unwrap_or(today); + let next = if m == 12 { + NaiveDate::from_ymd_opt(y + 1, 1, 1) + } else { + NaiveDate::from_ymd_opt(y, m as u32 + 1, 1) + } + .unwrap_or(today); + let last = (next - Duration::days(1)).min(today); + ( + first.format("%Y-%m-%d").to_string(), + last.format("%Y-%m-%d").to_string(), + ) + } +} + +pub async fn load_backfill( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + owner: &str, +) -> Result, Err> { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(backfill_sk(owner))) + .send() + .await?; + Ok(out + .item() + .and_then(|i| i.get("doc")) + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str(d).ok())) +} + +pub async fn save_backfill( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + b: &Backfill, +) -> Result<(), Err> { + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(backfill_sk(&b.owner))) + .item("doc", AttributeValue::S(serde_json::to_string(b)?)) + .send() + .await?; + Ok(()) +} + +/// A closed pull request from the sync's search, as its history row. +pub fn history_of_node(repo: &str, node: &serde_json::Value, now: i64) -> Option { + let number = node["number"].as_u64()?; + let mut r = PrRecord::new(repo, number); + r.apply_node(node, now); + (!r.is_open()).then(|| History::from_record(&r)) +} + // ─── Storage ──────────────────────────────────────────────────────────────── type Err = Box; @@ -498,6 +705,8 @@ pub struct Rework<'a> { pub by: (&'a str, u64), pub at: i64, pub revert: bool, + /// Why a follow-up is suspected. + pub reason: String, } /// Mark the earlier pull request reverted or followed up: only a merged @@ -516,11 +725,19 @@ pub async fn mark( if !h.merged || at < h.merged_at || (!revert && at - h.merged_at > REWORK_WINDOW_SECS) { return Ok(false); } - let link = (by.0.to_string(), by.1, at); if revert { - h.reverted_by = Some(link); - } else if !h.follow_ups.contains(&link) { - h.follow_ups.push(link); + h.reverted_by = Some((by.0.to_string(), by.1, at)); + } else if !h + .follow_ups + .iter() + .any(|f| f.repo == by.0 && f.number == by.1) + { + h.follow_ups.push(Suspect { + repo: by.0.to_string(), + number: by.1, + at, + reason: w.reason.clone(), + }); } else { return Ok(false); } @@ -743,9 +960,14 @@ mod tests { #[test] fn rework_counts_only_inside_the_window() { let mut h = merged("acme/web", 1, DAY, 20 * DAY); - h.follow_ups.push(("acme/web".into(), 2, NOW - 19 * DAY)); + h.follow_ups.push(Suspect { + repo: "acme/web".into(), + number: 2, + at: NOW - 19 * DAY, + reason: "names it in its description".into(), + }); assert!(h.reworked()); - h.follow_ups = vec![("acme/web".into(), 2, NOW)]; + h.follow_ups[0].at = NOW; assert!(!h.reworked()); } @@ -768,4 +990,39 @@ mod tests { vec![("acme/web".to_string(), 318), ("acme/api".to_string(), 12)] ); } + + #[test] + fn coverage_and_bypass_are_named_for_every_merge() { + let mut r = PrRecord::new("acme/web", 7); + r.author = "octocat".into(); + r.status = "merged".into(); + r.merged_by = "coderhelm[bot]".into(); + r.review_decision = Some("REVIEW_REQUIRED".into()); + r.approvals_required = 1; + let h = History::from_record(&r); + assert_eq!(h.coverage, "bypass_or_exempt"); + assert_eq!( + h.bypass.as_deref(), + Some("merged before the required review") + ); + assert_eq!( + h.merged_by_type, "coderhelm", + "CoderHelm's own merges count too" + ); + r.review_decision = None; + r.approvals_required = 0; + r.review_log.push(ReviewEvent { + who: "coderhelm[bot]".into(), + state: "APPROVED".into(), + ..Default::default() + }); + assert_eq!(coverage_of(&r), "ai_only"); + r.review_log.push(ReviewEvent { + who: "mara".into(), + state: "APPROVED".into(), + human: true, + ..Default::default() + }); + assert_eq!(coverage_of(&r), "human_approved"); + } } diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs index f3bf7d548..e624318d8 100644 --- a/services/common/src/pr_record.rs +++ b/services/common/src/pr_record.rs @@ -173,6 +173,57 @@ pub struct CheckTransition { pub at: i64, } +/// One completed attempt of a check on a commit. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct CheckAttempt { + pub name: String, + pub sha: String, + pub conclusion: String, + pub at: i64, +} + +/// Checks that failed and then passed on the same commit. +pub fn flaky_checks(attempts: &[CheckAttempt]) -> Vec { + let mut out: Vec = Vec::new(); + for (i, a) in attempts.iter().enumerate() { + let failed = matches!(a.conclusion.as_str(), "failure" | "timed_out" | "error"); + if failed + && attempts[i + 1..] + .iter() + .any(|b| b.name == a.name && b.sha == a.sha && b.conclusion == "success") + && !out.contains(&a.name) + { + out.push(a.name.clone()); + } + } + out +} + +/// The pull request's kind from its author, labels and title. +pub fn category_of(author: &str, labels: &[String], title: &str) -> (&'static str, &'static str) { + let t = title.to_ascii_lowercase(); + let has = |w: &str| labels.iter().any(|l| l.to_ascii_lowercase().contains(w)) || t.contains(w); + let severity = ["critical", "high", "moderate", "low"] + .into_iter() + .find(|w| { + labels.iter().any(|l| l.to_ascii_lowercase().contains(w)) + || t.contains(&format!("[{w}]")) + || t.contains(&format!("{w} severity")) + }) + .unwrap_or(""); + let a = author.to_ascii_lowercase(); + let category = + if has("security") || has("vulnerab") || t.contains("cve-") || t.contains("ghsa-") { + "security" + } else if a.starts_with("dependabot") || a.starts_with("renovate") || has("dependenc") { + "dependency" + } else { + "feature" + }; + (category, severity) +} + /// Most review, request and check transitions kept on a record. pub const MAX_LOG: usize = 150; @@ -285,6 +336,25 @@ pub struct PrRecord { pub review_log: Vec, pub request_log: Vec, pub check_log: Vec, + /// Every completed attempt of each check on each head: a check that + /// failed and then passed on the same commit is flaky, not fixed. + pub check_attempts: Vec, + /// The last action of the author (a person), of a person reviewing, + /// and of any bot or CI. Bot and agent activity never moves the first + /// two, so a pull request only bots touch still reads as idle. + pub last_author_action_at: i64, + pub last_reviewer_action_at: i64, + pub last_bot_event_at: i64, + /// The files it changes (the sync reads them), and how far the base + /// moved under it since its last push: commits on the base, and those of + /// them touching its files. + pub files: Vec, + pub drift_behind: u32, + pub drift_overlap: u32, + /// `feature`, `dependency` or `security`, and a severity when the + /// labels or title name one (`critical`, `high`, `moderate`, `low`). + pub category: String, + pub severity: String, /// When the sync last read it (epoch seconds; 0 never). pub synced_at: i64, /// When an event last changed it. @@ -433,6 +503,13 @@ impl PrRecord { } fn event(&mut self, at: i64, actor: &str, kind: &str, text: String) { + if is_bot(actor) || actor == "ci" || actor.is_empty() { + self.last_bot_event_at = self.last_bot_event_at.max(at); + } else if actor.eq_ignore_ascii_case(&self.author) { + self.last_author_action_at = self.last_author_action_at.max(at); + } else { + self.last_reviewer_action_at = self.last_reviewer_action_at.max(at); + } let actor = if is_coderhelm(actor) { "coderhelm".to_string() } else { @@ -511,6 +588,9 @@ impl PrRecord { if let Some(labels) = pr["labels"].as_array() { self.labels = labels.iter().map(|l| s(&l["name"])).collect(); } + let (category, severity) = category_of(&self.author, &self.labels, &self.title); + self.category = category.into(); + self.severity = severity.into(); if let Some(r) = pr["requested_reviewers"].as_array() { self.requested = r.iter().map(login).filter(|l| !l.is_empty()).collect(); } @@ -623,6 +703,10 @@ impl PrRecord { if before != self.head_sha { self.checks.clear(); self.checks_sha = self.head_sha.clone(); + // A push brings the base in or rebases onto it, + // most of the time: the drift counts again. + self.drift_behind = 0; + self.drift_overlap = 0; } } "ready_for_review" => { @@ -861,6 +945,18 @@ impl PrRecord { conclusion: s(&run["conclusion"]), at: at(&run["completed_at"]).max(at(&run["started_at"])), }; + if c.status == "completed" && !c.conclusion.is_empty() { + let attempt = CheckAttempt { + name: name.clone(), + sha: sha.clone(), + conclusion: c.conclusion.clone(), + at: c.at, + }; + if !self.check_attempts.contains(&attempt) { + self.check_attempts.push(attempt); + bounded(&mut self.check_attempts); + } + } if c.failed() && self.checks.get(&name).is_none_or(|p| !p.failed()) { self.event(c.at, "ci", "check", format!("`{name}` failed")); } @@ -953,6 +1049,34 @@ impl PrRecord { } } + /// A push to its base branch: commits it is now behind, and those that + /// touch its files (from the push's own file lists). True when this + /// pull request is based on the pushed branch. + pub fn note_base_push(&mut self, branch: &str, payload: &Value, now: i64) -> bool { + if !self.is_open() || self.base_ref != branch { + return false; + } + for c in payload["commits"] + .as_array() + .into_iter() + .flatten() + .take(100) + { + self.drift_behind += 1; + let touched = ["added", "modified", "removed"].iter().any(|k| { + c[*k].as_array().into_iter().flatten().any(|f| { + f.as_str() + .is_some_and(|f| self.files.iter().any(|mine| mine == f)) + }) + }); + if touched { + self.drift_overlap += 1; + } + } + self.event_at = now; + true + } + /// The head's checks as one word: `red`, `pending` or `green`. pub fn check_rollup(&self) -> &'static str { if self.checks.is_empty() { @@ -1085,11 +1209,89 @@ impl PrRecord { self.base_ref = s(&n["baseRefName"]); self.created_at = ts(&n["createdAt"]); self.updated_at = ts(&n["updatedAt"]); + let files: Vec = n["files"]["nodes"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f["path"].as_str().map(str::to_string)) + .take(300) + .collect(); + if !files.is_empty() { + self.files = files; + } + let (category, severity) = category_of(&self.author, &self.labels, &self.title); + self.category = category.into(); + self.severity = severity.into(); + let closed = [ts(&n["mergedAt"]), ts(&n["closedAt"])] + .into_iter() + .find(|t| *t > 0); + if let Some(t) = closed { + self.closed_at = t; + } + if let Some(by) = n["mergedBy"]["login"].as_str() { + self.merged_by = by.to_string(); + } + // Its timeline: when it left draft, and every review request. + let mut requests: Vec = Vec::new(); + for t in n["timelineItems"]["nodes"].as_array().into_iter().flatten() { + let at = ts(&t["createdAt"]); + let who = t["requestedReviewer"]["login"] + .as_str() + .map(str::to_string) + .or_else(|| { + t["requestedReviewer"]["slug"] + .as_str() + .map(|s| format!("{}/{s}", self.org())) + }) + .unwrap_or_default(); + match t["__typename"].as_str() { + Some("ReadyForReviewEvent") if self.ready_at == 0 || at < self.ready_at => { + self.ready_at = at + } + Some("ReviewRequestedEvent") if !who.is_empty() => requests.push(RequestEvent { + who, + at, + removed_at: 0, + }), + Some("ReviewRequestRemovedEvent") => { + if let Some(r) = requests + .iter_mut() + .rev() + .find(|r| r.who.eq_ignore_ascii_case(&who) && r.removed_at == 0) + { + r.removed_at = at; + } + } + _ => {} + } + } + if self.request_log.is_empty() { + self.request_log = requests; + } if self.ready_at == 0 && !self.draft { - // The search carries no ready time: the creation stands in - // until an event says better. + // Never a draft: ready from its creation. self.ready_at = self.created_at; } + // Every review, from GitHub, when no event recorded them. + if self.review_log.is_empty() { + let author = self.author.clone(); + for r in n["reviews"]["nodes"].as_array().into_iter().flatten() { + let who = login(&r["author"]); + if who.is_empty() { + continue; + } + self.review_log.push(ReviewEvent { + human: !is_bot(&who) && !who.eq_ignore_ascii_case(&author), + state: s(&r["state"]), + sha: s(&r["commit"]["oid"]), + at: ts(&r["submittedAt"]), + has_body: r["body"].as_str().is_some_and(|b| !b.trim().is_empty()), + who, + }); + } + self.review_log.sort_by_key(|r| r.at); + bounded(&mut self.review_log); + } self.additions = n["additions"].as_u64().unwrap_or(0) as u32; self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; self.labels = n["labels"]["nodes"] @@ -1392,7 +1594,11 @@ pub const SEARCH_QUERY: &str = "query($q: String!, $after: String) { autoMergeRequest { enabledAt } labels(first: 20) { nodes { name } } reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } ... on Team { slug } } } } + mergedAt closedAt mergedBy { login } + files(first: 100) { nodes { path } } latestOpinionatedReviews(first: 20) { nodes { state submittedAt author { login } commit { oid } } } + reviews(first: 40) { nodes { state submittedAt body author { login } commit { oid } } } + timelineItems(first: 40, itemTypes: [READY_FOR_REVIEW_EVENT, REVIEW_REQUESTED_EVENT, REVIEW_REQUEST_REMOVED_EVENT]) { nodes { __typename ... on ReadyForReviewEvent { createdAt } ... on ReviewRequestedEvent { createdAt requestedReviewer { ... on User { login } ... on Team { slug } } } ... on ReviewRequestRemovedEvent { createdAt requestedReviewer { ... on User { login } ... on Team { slug } } } } } participants(first: 20) { nodes { login } } reviewThreads(first: 50) { nodes { isResolved comments(first: 1) { nodes { author { login } } } } } baseRef { branchProtectionRule { requiredApprovingReviewCount requiresCodeOwnerReviews requiresConversationResolution requiredStatusCheckContexts } } @@ -1406,6 +1612,14 @@ pub const SEARCH_QUERY: &str = "query($q: String!, $after: String) { /// requests a page): the bound of one owner's sync. pub const MAX_PAGES: u32 = 10; +/// The search for an owner's pull requests closed or merged between two +/// days (`YYYY-MM-DD`, inclusive): the history backfill, a month at a time +/// so no window passes the search's 1,000 results. +pub fn closed_search_text(owner: &str, org: bool, from: &str, to: &str) -> String { + let q = if org { "org" } else { "user" }; + format!("is:pr is:closed {q}:{owner} closed:{from}..{to} sort:updated-desc") +} + /// The search for an owner's open pull requests. pub fn search_text(owner: &str, org: bool) -> String { let q = if org { "org" } else { "user" }; @@ -1811,4 +2025,48 @@ mod tests { r.closed_at = NOW; assert_eq!(r.ttl(), Some(NOW + CLOSED_KEEP_SECS)); } + + #[test] + fn health_signals_are_kept_for_every_author() { + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW); + // A bot's push never moves the people's clocks. + let author_at = r.last_author_action_at; + let mut bot = opened(); + bot["action"] = json!("synchronize"); + bot["sender"] = json!({"login": "coderhelm[bot]"}); + bot["pull_request"]["updated_at"] = json!("2026-01-10T15:00:00Z"); + r.apply_event("pull_request", &bot, NOW); + assert_eq!(r.last_author_action_at, author_at); + assert!(r.last_bot_event_at > author_at); + // A check that fails then passes on one commit is flaky. + for (c, t) in [ + ("failure", "2026-01-10T10:05:00Z"), + ("success", "2026-01-10T10:09:00Z"), + ] { + let run = json!({"check_run": {"name": "unit", "head_sha": r.head_sha, "status": "completed", + "conclusion": c, "completed_at": t}}); + r.apply_event("check_run", &run, NOW); + } + assert_eq!(flaky_checks(&r.check_attempts), vec!["unit"]); + // The base moving under it: behind, and touching its files. + r.files = vec!["cart/rounding.ts".into()]; + let push = json!({"ref": "refs/heads/main", "commits": [ + {"modified": ["cart/rounding.ts"]}, {"modified": ["README.md"]}]}); + assert!(r.note_base_push("main", &push, NOW)); + assert_eq!((r.drift_behind, r.drift_overlap), (2, 1)); + // Kinds and severities from the author, labels and title. + assert_eq!( + category_of("dependabot[bot]", &[], "Bump lodash"), + ("dependency", "") + ); + assert_eq!( + category_of( + "octocat", + &["security".into(), "severity: high".into()], + "Patch login" + ), + ("security", "high") + ); + } } diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 1e6734c67..1136ddd13 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -73,6 +73,9 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo .map(|b| pr_record::ref_sk(repo, b)), _ => None, }; + if event_type == "push" { + base_push(state, team_id, repo, payload).await; + } let Some(sk) = sk else { return }; match pr_record::pointed(&state.dynamo, table, team_id, &sk).await { Ok(Some(n)) => vec![n], @@ -129,12 +132,58 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo } } +/// A push to a branch other pull requests are based on: their drift +/// (commits behind, and those touching their files). The repository's open +/// records only, at most 200. +async fn base_push(state: &AppState, team_id: &str, repo: &str, payload: &Value) { + let Some(branch) = payload["ref"] + .as_str() + .and_then(|r| r.strip_prefix("refs/heads/")) + else { + return; + }; + if payload["commits"].as_array().is_none_or(|c| c.is_empty()) { + return; + } + let table = &state.config.settings_table_name; + let prefix = format!("{}{repo}#", pr_record::SK_PREFIX); + let items = match items_under(state, team_id, &prefix).await { + Ok(i) => i, + Err(e) => { + warn!(repo, error = %e, "Drift: records not read"); + return; + } + }; + let t = now(); + for rec in pr_view::records_of(team_id, &items) + .into_iter() + .filter(|r| r.is_open() && r.base_ref == branch) + .take(200) + { + let _ = pr_record::update(&state.dynamo, table, team_id, repo, rec.number, t, |r| { + r.note_base_push(branch, payload, t) + }) + .await; + } +} + /// A pull request closed: its history row (kept over a year), and on a /// merge the revert or follow-up links to the merged pull requests it /// names. async fn record_history(state: &AppState, team_id: &str, rec: &PrRecord, now: i64) { let table = &state.config.settings_table_name; - let h = common::pr_history::History::from_record(rec); + let mut h = common::pr_history::History::from_record(rec); + if !h.run_ids.is_empty() { + let runs = runs_by_id(state, team_id, &h.run_ids).await; + if let Some(last) = h.run_ids.iter().rev().find_map(|id| runs.get(id)) { + h.run_outcome = last.status.clone(); + h.stop_reason = last + .stop + .as_ref() + .map(|s| s.code.clone()) + .unwrap_or_default(); + } + } if let Err(e) = common::pr_history::put(&state.dynamo, table, team_id, &h, now).await { warn!(repo = %rec.repo, number = rec.number, error = %e, "Pull request history not written"); return; @@ -165,6 +214,18 @@ async fn record_history(state: &AppState, team_id: &str, rec: &PrRecord, now: i6 by: (&rec.repo, rec.number), at: rec.closed_at.max(1), revert, + reason: if revert { + String::new() + } else if rec + .labels + .iter() + .any(|l| l.to_ascii_lowercase().contains("hotfix")) + || rec.title.to_ascii_lowercase().contains("hotfix") + { + "a hotfix that names it, merged within 14 days of it".into() + } else { + "names it in its description, merged within 14 days of it".into() + }, }, now, ) @@ -523,7 +584,9 @@ pub async fn list_prs( let rows = pr_view::rows(&claims.team_id, items, joins, viewer, now()); let synced = synced_at(items, &claims.team_id, &query); let page = pr_view::page(rows, &query, limit, cursor.as_deref()); + let backfill = backfill_progress(&state, &claims.team_id).await; Ok(Json(json!({ + "backfill": backfill, "prs": page.rows, "total": page.total, "next": page.next, @@ -534,6 +597,38 @@ pub async fn list_prs( }))) } +/// 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}; + items + .iter() + .filter_map(|i| i.get("doc").and_then(|v| v.as_s().ok())) + .filter_map(|d| serde_json::from_str::(d).ok()) + .map(|b| { + json!({ + "owner": b.owner, + "months_read": b.months_read.min(BACKFILL_MONTHS), + "months_total": BACKFILL_MONTHS, + "done": b.done, + "paused_until": (b.paused_until > 0).then(|| pr_view::rfc3339(b.paused_until)).flatten(), + "paused_why": (!b.paused_why.is_empty()).then_some(b.paused_why), + "repos": b.repos, + "updated_at": pr_view::rfc3339(b.updated_at), + }) + }) + .collect() +} + +async fn backfill_progress(state: &AppState, team_id: &str) -> Vec { + match items_under(state, team_id, common::pr_history::BACKFILL_PREFIX).await { + Ok(items) => backfill_json(&items), + Err(e) => { + warn!(team_id, error = %e, "Pull requests: backfill progress not read"); + Vec::new() + } + } +} + #[derive(Deserialize)] pub struct DetailQuery { repo: String, diff --git a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs index 3e9bf79a5..c33ca1404 100644 --- a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs +++ b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs @@ -334,3 +334,77 @@ fn no_pull_request_of_another_team_reaches_a_row() { let perms = src("gateway/src/permissions.rs"); assert!(perms.contains("\"prs::list_prs\"") && perms.contains("\"prs::get_pr\"")); } + +#[test] +fn a_repository_with_only_peoples_pull_requests_gets_full_records_and_history() { + let team = "TEAM#bookstore"; + // A person's pull request, end to end from its events: opened, a review + // request, a person's review, a check, and the merge. + let mut r = PrRecord::new("acme/web", 21); + assert!(r.apply_event("pull_request", &opened(21, "octocat"), NOW)); + let mut asked = opened(21, "octocat"); + asked["action"] = serde_json::json!("review_requested"); + asked["requested_reviewer"] = serde_json::json!({"login": "mara"}); + assert!(r.apply_event("pull_request", &asked, NOW)); + let review = serde_json::json!({"action": "submitted", "pull_request": {"number": 21}, + "review": {"user": {"login": "mara"}, "state": "approved", "commit_id": HEAD, + "submitted_at": "2026-01-10T12:00:00Z", "body": "Looks right."}}); + assert!(r.apply_event("pull_request_review", &review, NOW)); + let check = serde_json::json!({"check_run": {"name": "unit", "head_sha": HEAD, + "status": "completed", "conclusion": "success", "completed_at": "2026-01-10T11:00:00Z"}}); + assert!(r.apply_event("check_run", &check, NOW)); + let rows = pr_view::rows(team, &[item(team, &r)], &Joins::default(), None, NOW); + assert_eq!(rows.len(), 1); + assert!(!rows[0].author.coderhelm); + assert_eq!(r.request_log.len(), 1); + assert!(r.review_log[0].human); + assert_eq!(r.check_log.last().map(|c| c.rollup.as_str()), Some("green")); + let mut merged = opened(21, "octocat"); + merged["action"] = serde_json::json!("closed"); + merged["pull_request"]["state"] = serde_json::json!("closed"); + merged["pull_request"]["merged"] = serde_json::json!(true); + merged["pull_request"]["merged_at"] = serde_json::json!("2026-01-11T10:00:00Z"); + assert!(r.apply_event("pull_request", &merged, NOW)); + let h = common::pr_history::History::from_record(&r); + assert!(h.merged && h.author_type == "person" && h.coderhelm_role == "none"); + assert_eq!(h.first_review_secs(), Some(2 * 3600)); + assert_eq!(h.cycle_secs(), Some(24 * 3600)); + + // A person's closed pull request from the backfill's search, with no + // events at all, becomes history too: reviews and ready time included. + let node = serde_json::json!({ + "number": 22, "title": "Bookstore shelf labels", "state": "MERGED", "isDraft": false, + "createdAt": "2026-01-01T09:00:00Z", "updatedAt": "2026-01-03T09:00:00Z", + "mergedAt": "2026-01-03T09:00:00Z", "closedAt": "2026-01-03T09:00:00Z", + "mergedBy": {"login": "mara"}, "author": {"login": "theo"}, + "repository": {"nameWithOwner": "acme/web"}, "headRefOid": HEAD, + "reviews": {"nodes": [{"state": "APPROVED", "submittedAt": "2026-01-02T09:00:00Z", + "body": "", "author": {"login": "mara"}, "commit": {"oid": HEAD}}]}, + "timelineItems": {"nodes": [{"__typename": "ReviewRequestedEvent", + "createdAt": "2026-01-01T10:00:00Z", "requestedReviewer": {"login": "mara"}}]} + }); + let h = common::pr_history::history_of_node("acme/web", &node, NOW).expect("history"); + assert_eq!(h.author_type, "person"); + assert_eq!(h.first_review_secs(), Some(86_400)); + assert_eq!(h.request_log.len(), 1); + + // Nothing on the way filters to CoderHelm's own pull requests: the + // writer, the sync and the backfill keep every author. + for file in [ + "gateway/src/routes/prs.rs", + "worker/src/passes/pr_records.rs", + "common/src/pr_history.rs", + ] { + let s = src(file); + let code = &s[..s.find("#[cfg(test)]").unwrap_or(s.len())]; + for filter in [ + "author_is_coderhelm() {\n continue", + "if !rec.author_is_coderhelm()", + "contains(\"coderhelm\") {\n return", + ] { + assert!(!code.contains(filter), "{file} filters by author"); + } + } + let sync = src("worker/src/passes/pr_records.rs"); + assert!(sync.contains("for owner in owners {\n backfill_owner(")); +} diff --git a/services/worker/src/passes/pr_records.rs b/services/worker/src/passes/pr_records.rs index ad5ca8e20..7adcc34e9 100644 --- a/services/worker/src/passes/pr_records.rs +++ b/services/worker/src/passes/pr_records.rs @@ -31,8 +31,14 @@ pub struct SweepReport { pub written: usize, pub removed: usize, pub pages: u32, + /// Closed and merged pull requests written to history. + pub history: usize, } +/// Pages of closed pull requests one sweep reads per organization: the +/// history backfill's share of the budget each hour. +pub const CLOSED_PAGES_PER_SWEEP: u32 = 5; + /// The sweep tick: each team at most once an hour. pub async fn sweep(state: &WorkerState) -> SweepReport { let mut report = SweepReport::default(); @@ -162,7 +168,7 @@ async fn sync_team( } }; let table = &state.config.settings_table_name; - for owner in owners { + for owner in owners.clone() { let mut seen: HashSet = HashSet::new(); let mut complete = false; let mut after: Option = None; @@ -250,6 +256,140 @@ async fn sync_team( } } } + // Every closed and merged pull request of the last 14 months, people's, + // bots' and CoderHelm's alike, into history: resumed where it stopped. + for owner in owners { + backfill_owner( + state, + team_id, + installation_id, + &github, + &owner, + &keep, + gate, + report, + ) + .await; + } +} + +/// One organization's history backfill, a month at a time from the newest, +/// at most [`CLOSED_PAGES_PER_SWEEP`] pages per sweep, under the shared +/// budget: a held budget pauses it with the reason and the time, and the +/// next sweep resumes from the stored page cursor. Once all 14 months are +/// read, each sweep reads the closed pull requests since its last day. +#[allow(clippy::too_many_arguments)] +async fn backfill_owner( + state: &WorkerState, + team_id: &str, + installation_id: u64, + github: &GitHubClient, + owner: &str, + keep: &HashSet, + gate: &mut SweepGate, + report: &mut SweepReport, +) { + use common::pr_history::{self, Backfill, BACKFILL_MONTHS}; + let table = &state.config.settings_table_name; + let now = chrono::Utc::now().timestamp(); + let mut b = match pr_history::load_backfill(&state.dynamo, table, team_id, owner).await { + Ok(Some(b)) => b, + Ok(None) => Backfill { + owner: owner.to_string(), + started_at: now, + ..Default::default() + }, + Err(e) => { + warn!(team_id, owner, error = %e, "History backfill: progress not read"); + return; + } + }; + if b.paused_until > now { + return; + } + b.paused_until = 0; + b.paused_why.clear(); + let today = chrono::Utc::now().format("%Y-%m-%d").to_string(); + let mut as_org = true; + let mut pages = 0; + while pages < CLOSED_PAGES_PER_SWEEP { + let (from, to) = if b.done { + if b.reconciled_to == today && b.cursor.is_none() { + break; + } + let from = if b.reconciled_to.is_empty() { + Backfill::window(now, 0).0 + } else { + b.reconciled_to.clone() + }; + (from, today.clone()) + } else { + Backfill::window(now, b.months_read) + }; + if !gate.allows(state, installation_id, 1).await { + b.paused_until = now + gate.retry_in().unwrap_or(3600) as i64; + b.paused_why = "GitHub's hourly budget is kept for runs and people now".into(); + break; + } + let q = pr_record::closed_search_text(owner, as_org, &from, &to); + let vars = json!({"q": q, "after": b.cursor}); + let data = match github.graphql_read(pr_record::SEARCH_QUERY, vars).await { + Ok(d) => d, + Err(_) if as_org && pages == 0 && b.cursor.is_none() => { + as_org = false; + continue; + } + Err(e) => { + let why = e.to_string(); + b.paused_until = now + 3600; + b.paused_why = if why.to_ascii_lowercase().contains("rate limit") { + "GitHub's rate limit was reached".into() + } else { + "GitHub's search didn't answer".into() + }; + warn!(team_id, owner, error = %why, "History backfill paused"); + break; + } + }; + pages += 1; + b.pages += 1; + report.pages += 1; + for node in data["search"]["nodes"].as_array().into_iter().flatten() { + let repo = node["repository"]["nameWithOwner"].as_str().unwrap_or(""); + if !keep.contains(&repo.to_ascii_lowercase()) { + continue; + } + let Some(h) = pr_history::history_of_node(repo, node, now) else { + continue; + }; + match pr_history::put(&state.dynamo, table, team_id, &h, now).await { + Ok(()) => { + report.history += 1; + *b.repos.entry(repo.to_string()).or_default() += 1; + } + Err(e) => warn!(team_id, repo, error = %e, "History row not written"), + } + } + let info = &data["search"]["pageInfo"]; + if info["hasNextPage"].as_bool() == Some(true) { + b.cursor = info["endCursor"].as_str().map(str::to_string); + continue; + } + b.cursor = None; + if b.done { + b.reconciled_to = today.clone(); + break; + } + b.months_read += 1; + if b.months_read >= BACKFILL_MONTHS { + b.done = true; + b.reconciled_to = today.clone(); + } + } + b.updated_at = now; + if let Err(e) = pr_history::save_backfill(&state.dynamo, table, team_id, &b).await { + warn!(team_id, owner, error = %e, "History backfill: progress not written"); + } } #[cfg(test)] From 053806e7654f73c70b1b61f7909926ff83d45e6e Mon Sep 17 00:00:00 2001 From: Nam Bok Rodriguez Date: Sat, 5 Dec 2026 17:10:02 -0500 Subject: [PATCH 5/7] The org's pull requests in one answer: GET /api/prs/overview (#988) * The org's pull requests in one answer: GET /api/prs/overview Every pull request in the team's repositories counts, people's, CoderHelm's and other bots'; CoderHelm's are one slice. Computed facts only, with thresholds from the scope's own percentiles, no rate on fewer than 10 events, and what isn't stored yet named in `missing`. No per-person ranking, count or duration; a login appears only as one item's owner. The summary's numbers are all facts. GET /api/prs takes the overview's drill-down (stage, past p85/p95). Incident case xz pins it. * Overview: clippy's shapes, and words without hand-off phrases or loose numbers The stability line says "over the last month" so every number in the summary is a fact; the incident case reads the route's source without whitespace, so formatting can't hide a read. * A reopened change and a later alert recovery reach their waiting runs at once (#986) A run stopped because the change it built on closed now goes back to waiting as soon as GitHub reports the change reopened, not at the 15-minute sweep. The pull request handler sends the team's change check for a close or a reopen before any return a reopen reaches, naming the change, and the worker reads the runs that change's close stopped (the sweep stays the backstop for every team). A recovery posted after an alert route's quiet window now closes the run waiting on a person for that alert, through the same path a recovery posted at once uses (common::run_wake::alert_cleared, which the gateway's alert_delivery now calls too). Incident case xx_waits_never_outlive_their_event. --- .../xx_waits_never_outlive_their_event.md | 5 + docs/incidents/xz_org_overview_facts_only.md | 5 + services/common/src/change_wait.rs | 34 + services/common/src/lib.rs | 1 + services/common/src/messages.rs | 14 +- services/common/src/pr_overview.rs | 2139 +++++++++++++++++ services/common/src/run_wake.rs | 143 ++ services/gateway/src/main.rs | 1 + services/gateway/src/permissions.rs | 1 + services/gateway/src/routes/alerts.rs | 5 +- services/gateway/src/routes/github_webhook.rs | 86 +- services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/prs.rs | 112 +- services/gateway/src/routes/prs_overview.rs | 269 +++ services/gateway/src/routes/run_wake.rs | 91 +- services/worker/src/main.rs | 2 +- services/worker/src/passes/alert_episodes.rs | 10 + services/worker/src/passes/change_wait.rs | 41 +- .../passes/incidents/bm_teams_never_cross.rs | 4 + .../incidents/wz_waits_go_on_by_themselves.rs | 2 +- .../xx_waits_never_outlive_their_event.rs | 126 + .../incidents/xz_org_overview_facts_only.rs | 459 ++++ 22 files changed, 3450 insertions(+), 101 deletions(-) create mode 100644 docs/incidents/xx_waits_never_outlive_their_event.md create mode 100644 docs/incidents/xz_org_overview_facts_only.md create mode 100644 services/common/src/pr_overview.rs create mode 100644 services/gateway/src/routes/prs_overview.rs create mode 100644 services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs create mode 100644 services/worker/src/passes/incidents/xz_org_overview_facts_only.rs 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 000000000..c8bd46866 --- /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 000000000..5f925c561 --- /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 4b18ced3e..c37e6888b 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 32f2da030..4566f7905 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 cc0cb05f7..ad3d78a26 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 000000000..7cf3dd90a --- /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 a1f9e948f..881c0de2c 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 b02b645a1..a1d2da685 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 6f488995f..d5e269824 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 08fceabfe..49fa18fd3 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 acb99c2ac..4b03cb80e 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 541b684ed..7335d1de1 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 1136ddd13..050b5a355 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 000000000..8880c9a2d --- /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 1bc5c96a8..1fd3dd415 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 080a944fc..2426690aa 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 6c93b33ad..5ef5445c8 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 2ae5637fe..d67cc4f61 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 f4988d90c..2d58121a6 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 0a2c1777a..88d71f525 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 000000000..42bc39751 --- /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 000000000..277bd7bf2 --- /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")); +} From 43e3196037c4d23dc3a83147bc33d56bba56d00d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 17:18:00 -0500 Subject: [PATCH 6/7] Answer the review: the gate never waits on what GitHub does not require, the sync never undoes events, history is never thinned The repository's approval rule is GitHub's own review decision and the team's rule is a person's approval; a review no rule requires is named, never a hold. The sync never reopens a closed record, yields to events newer than its read, replaces the reviews and requests it lists, and marks lists cut by their page size. History rows merge by source, so the backfill never thins a row written from events. The review decision is worked out at review events and used for bypass only when fresh. Stacks join within one repository, and the detail decides with the list's own linked records. --- docs/pull-requests.md | 1 + docs/pull-requests/api_contract.md | 8 + services/common/src/pr_history.rs | 168 ++++-- services/common/src/pr_needs.rs | 111 +++- services/common/src/pr_record.rs | 570 ++++++++++++++---- services/common/src/pr_view.rs | 97 ++- services/gateway/src/routes/prs.rs | 55 +- services/worker/src/passes/await_merge.rs | 27 +- .../xw_every_open_pr_has_one_state.rs | 32 +- services/worker/src/passes/pr_records.rs | 6 +- 10 files changed, 824 insertions(+), 251 deletions(-) diff --git a/docs/pull-requests.md b/docs/pull-requests.md index ea343c375..9b241d073 100644 --- a/docs/pull-requests.md +++ b/docs/pull-requests.md @@ -8,6 +8,7 @@ One settings-table item per pull request (`pk` = team id, `sk = PRREC# &'static str { .review_log .iter() .any(|v| !v.human && v.state == "APPROVED" && is_bot(&v.who)); - let held = matches!( - r.review_decision.as_deref(), - Some("REVIEW_REQUIRED") | Some("CHANGES_REQUESTED") - ); + // GitHub's decision counts only when it was read or worked out after + // the last review and request; a stale one never names a bypass. + let held = r.decision_fresh() + && matches!( + r.review_decision.as_deref(), + Some("REVIEW_REQUIRED") | Some("CHANGES_REQUESTED") + ); if human && held && r.codeowners_required { "non_owner_on_owned" } else if human { @@ -178,16 +185,21 @@ pub fn bypass_of(r: &PrRecord) -> Option { } let f = r.facts(); let (failing, _) = f.checks.blocking(); - if matches!(r.review_decision.as_deref(), Some("CHANGES_REQUESTED")) { + // The review decision and GitHub's merge state come from the sync or + // are worked out at each review event: a decision older than the last + // review or request says nothing about the merge, so no bypass is + // named from it. + let fresh = r.decision_fresh(); + if fresh && matches!(r.review_decision.as_deref(), Some("CHANGES_REQUESTED")) { Some("merged with changes requested".into()) - } else if matches!(r.review_decision.as_deref(), Some("REVIEW_REQUIRED")) { + } else if fresh && matches!(r.review_decision.as_deref(), Some("REVIEW_REQUIRED")) { Some("merged before the required review".into()) } else if !failing.is_empty() && !f.checks.required.is_empty() { Some(format!( "merged with required checks failing: {}", failing.join(", ") )) - } else if r.merge_state == "blocked" { + } else if fresh && r.synced_at >= r.decision_at && r.merge_state == "blocked" { Some("merged while the branch's rules blocked it".into()) } else { None @@ -257,6 +269,7 @@ impl History { drift_overlap: r.drift_overlap, run_outcome: String::new(), stop_reason: String::new(), + source: "events".into(), } } @@ -598,18 +611,7 @@ pub async fn load_backfill( team_id: &str, owner: &str, ) -> Result, Err> { - let out = dynamo - .get_item() - .table_name(table) - .key("pk", AttributeValue::S(team_id.into())) - .key("sk", AttributeValue::S(backfill_sk(owner))) - .send() - .await?; - Ok(out - .item() - .and_then(|i| i.get("doc")) - .and_then(|v| v.as_s().ok()) - .and_then(|d| serde_json::from_str(d).ok())) + pr_record::get_doc(dynamo, table, team_id, &backfill_sk(owner)).await } pub async fn save_backfill( @@ -633,16 +635,63 @@ pub async fn save_backfill( pub fn history_of_node(repo: &str, node: &serde_json::Value, now: i64) -> Option { let number = node["number"].as_u64()?; let mut r = PrRecord::new(repo, number); - r.apply_node(node, now); - (!r.is_open()).then(|| History::from_record(&r)) + r.apply_node(node, now, now); + (!r.is_open()).then(|| History { + source: "search".into(), + ..History::from_record(&r) + }) } // ─── Storage ──────────────────────────────────────────────────────────────── type Err = Box; -/// Write a closed pull request's history (again, when it closes again). -/// A revert or follow-up already recorded on the row is kept. +fn empty(v: &serde_json::Value) -> bool { + match v { + serde_json::Value::Null => true, + serde_json::Value::String(s) => s.is_empty(), + serde_json::Value::Number(n) => n.as_f64() == Some(0.0), + serde_json::Value::Array(a) => a.is_empty(), + serde_json::Value::Object(o) => o.is_empty(), + serde_json::Value::Bool(b) => !b, + } +} + +/// One row out of the stored one and a new one, never thinner than +/// either. The row from events wins over the search's (it holds the change +/// log, the runs and the logs the search can't see); between two of the +/// same source the newer wins. Every field the winner left empty is taken +/// from the other, and revert and follow-up links are kept from both. +pub fn merge(new: &History, old: &History) -> History { + let new_wins = !(old.source == "events" && new.source == "search"); + let (win, other) = if new_wins { (new, old) } else { (old, new) }; + let mut w = serde_json::to_value(win).unwrap_or_default(); + let o = serde_json::to_value(other).unwrap_or_default(); + if let (Some(w), Some(o)) = (w.as_object_mut(), o.as_object()) { + for (k, v) in o { + if w.get(k).is_none_or(empty) && !empty(v) { + w.insert(k.clone(), v.clone()); + } + } + } + let mut h: History = serde_json::from_value(w).unwrap_or_else(|_| win.clone()); + h.reverted_by = new.reverted_by.clone().or_else(|| old.reverted_by.clone()); + h.follow_ups = old.follow_ups.clone(); + for f in &new.follow_ups { + if !h + .follow_ups + .iter() + .any(|x| x.repo == f.repo && x.number == f.number) + { + h.follow_ups.push(f.clone()); + } + } + h +} + +/// Write a closed pull request's history (again, when it closes again), +/// merged with the stored row ([`merge`]): the backfill and the reconcile +/// never thin a row the gateway wrote from events. pub async fn put( dynamo: &DynamoClient, table: &str, @@ -650,15 +699,10 @@ pub async fn put( h: &History, now: i64, ) -> Result<(), Err> { - let mut h = h.clone(); - if let Some(old) = load(dynamo, table, team_id, &h.repo, h.number).await? { - h.reverted_by = h.reverted_by.or(old.reverted_by); - for f in old.follow_ups { - if !h.follow_ups.contains(&f) { - h.follow_ups.push(f); - } - } - } + let h = match load(dynamo, table, team_id, &h.repo, h.number).await? { + Some(old) => merge(h, &old), + None => h.clone(), + }; dynamo .put_item() .table_name(table) @@ -682,18 +726,7 @@ pub async fn load( repo: &str, number: u64, ) -> Result, Err> { - let out = dynamo - .get_item() - .table_name(table) - .key("pk", AttributeValue::S(team_id.into())) - .key("sk", AttributeValue::S(hist_sk(repo, number))) - .send() - .await?; - Ok(out - .item() - .and_then(|i| i.get("doc")) - .and_then(|v| v.as_s().ok()) - .and_then(|d| serde_json::from_str(d).ok())) + pr_record::get_doc(dynamo, table, team_id, &hist_sk(repo, number)).await } /// A merged pull request reverting or following up an earlier one. @@ -998,6 +1031,7 @@ mod tests { r.status = "merged".into(); r.merged_by = "coderhelm[bot]".into(); r.review_decision = Some("REVIEW_REQUIRED".into()); + r.decision_at = NOW; r.approvals_required = 1; let h = History::from_record(&r); assert_eq!(h.coverage, "bypass_or_exempt"); @@ -1025,4 +1059,50 @@ mod tests { }); assert_eq!(coverage_of(&r), "human_approved"); } + + #[test] + fn a_search_row_never_thins_a_row_written_from_events() { + let mut events = merged("acme/web", 9, DAY, 0); + events.source = "events".into(); + events.run_ids = vec!["run-1".into()]; + events.spans = vec![Span { + who: "person:mara".into(), + state: "needs_review".into(), + from: NOW - DAY, + turn: "person".into(), + stage: "first_review".into(), + }]; + events.coderhelm_role = "fixer".into(); + let mut search = merged("acme/web", 9, DAY, 0); + search.source = "search".into(); + search.title = "Shelf labels".into(); + search.coderhelm_role = "none".into(); + let m = merge(&search, &events); + assert_eq!(m.run_ids, vec!["run-1"]); + assert_eq!(m.spans.len(), 1); + assert_eq!(m.coderhelm_role, "fixer"); + assert_eq!(m.source, "events"); + assert_eq!( + m.title, "Shelf labels", + "an empty field is filled from the other row" + ); + } + + #[test] + fn a_stale_review_decision_never_names_a_bypass() { + let mut r = PrRecord::new("acme/web", 7); + r.author = "octocat".into(); + r.status = "merged".into(); + r.review_decision = Some("REVIEW_REQUIRED".into()); + r.decision_at = NOW - 3600; + r.review_log.push(ReviewEvent { + who: "mara".into(), + state: "APPROVED".into(), + at: NOW - 60, + human: true, + ..Default::default() + }); + assert_eq!(bypass_of(&r), None, "approved after the decision was read"); + assert_eq!(coverage_of(&r), "human_approved"); + } } diff --git a/services/common/src/pr_needs.rs b/services/common/src/pr_needs.rs index 573b37499..bbc69327a 100644 --- a/services/common/src/pr_needs.rs +++ b/services/common/src/pr_needs.rs @@ -472,6 +472,8 @@ pub struct Facts { pub threads_required: bool, pub open_threads: u32, pub thread_authors: Vec, + /// The sync read only the first conversations: more may be open. + pub threads_unread: bool, /// GitHub's auto-merge is on. pub auto_merge: bool, /// CoderHelm's auto-merge gate is armed on it: CoderHelm merges. @@ -511,6 +513,20 @@ fn names(list: &[String], max: usize) -> String { out.join(", ") } +/// Reviews asked for that no rule requires: said, never a hold. +fn optional_asks(f: &Facts) -> String { + let mut who: Vec = f.requested.clone(); + who.extend(f.requested_teams.iter().cloned()); + if who.is_empty() { + return String::new(); + } + format!( + " {} {} also asked to review; no rule waits on it.", + at(&who), + if who.len() == 1 { "is" } else { "are" } + ) +} + fn rule_tag(rule: Option) -> String { rule.map(|r| format!(" ({})", r.words())) .unwrap_or_default() @@ -869,27 +885,35 @@ fn decide_state(repo: &str, f: &Facts) -> Needs { } } } - // Approvals: the repository's rule, and the team's own rule when - // CoderHelm merges. - let (required, approval_rule) = if f.approvals_required > 0 { - (f.approvals_required, Some(Rule::RepoRule)) - } else if f.team_requires_approval { - (1, Some(Rule::TeamRule)) + // Approvals: GitHub's requirement and the team's own rule, apart, and + // never stricter than GitHub. GitHub's review decision is the authority + // on the repository's rule (it counts every approval that counts there, + // an app's included); without one, the rule's count against people's + // approvals stands in. A review someone is asked for but no rule + // requires never holds the merge. + let people = f.approved_by.len() as u32; + let repo_required = if f.approvals_required > 0 { + f.approvals_required } else if f.review_decision.as_deref() == Some("REVIEW_REQUIRED") { - (1, Some(Rule::RepoRule)) + 1 } else { - (0, None) + 0 + }; + let repo_have = match f.review_decision.as_deref() { + Some("APPROVED") => repo_required, + _ => people, }; - // GitHub's own decision is the authority on the repository's count. - let mut have = f.approved_by.len() as u32; - if f.review_decision.as_deref() == Some("APPROVED") && have > 0 { - have = have.max(required); - } let codeowner_gap = f.codeowners_required && f.review_decision.as_deref() == Some("REVIEW_REQUIRED") - && have >= required.max(1); - if have < required && !codeowner_gap { - let missing = required - have; + && repo_have >= repo_required.max(1); + let (missing, approval_rule) = if repo_have < repo_required && !codeowner_gap { + (repo_required - repo_have, Some(Rule::RepoRule)) + } else if f.team_requires_approval && people == 0 && !codeowner_gap { + (1, Some(Rule::TeamRule)) + } else { + (0, None) + }; + if missing > 0 { let words = merge_standing::approvals_words(missing); let asked: Vec = f .requested @@ -945,14 +969,15 @@ fn decide_state(repo: &str, f: &Facts) -> Needs { Some(Rule::Codeowners), ); } - if required == 0 && have == 0 && !f.requested.is_empty() { - let verb = if f.requested.len() == 1 { "is" } else { "are" }; + if f.threads_required && f.open_threads == 0 && f.threads_unread { return need( - State::NeedsReview, - format!("{} {verb} asked to review.", at(&f.requested)), - f.requested.iter().map(|p| person(p)).collect(), + State::Unknown, + "Not synced yet: the pull request has more conversations than the sync reads, \ + and the repo rule needs them resolved; the next event or sync settles it." + .into(), + vec![NOBODY.into()], since, - None, + Some(Rule::RepoRule), ); } if f.threads_required && f.open_threads > 0 { @@ -1050,8 +1075,9 @@ fn decide_state(repo: &str, f: &Facts) -> Needs { need( State::ReadyToMerge, format!( - "Ready to merge: every rule is met; {} merges it.", - author_words(f) + "Ready to merge: every rule is met; {} merges it.{}", + author_words(f), + optional_asks(f) ), author_from(f), since, @@ -1174,7 +1200,12 @@ pub fn checklist(f: &Facts) -> Vec { } else { (0, None) }; - let have = f.approved_by.len() as u32; + // GitHub's decision counts every approval that counts there. + let have = if f.review_decision.as_deref() == Some("APPROVED") { + (f.approved_by.len() as u32).max(f.approvals_required) + } else { + f.approved_by.len() as u32 + }; out.push(if !f.changes_requested_by.is_empty() { step( "approvals", @@ -1552,4 +1583,34 @@ mod tests { assert!(keys.iter().any(|x| x == k), "{k}"); } } + + #[test] + fn a_review_no_rule_requires_never_holds_the_merge() { + let mut f = ready(); + f.approvals_required = 0; + f.approved_by.clear(); + f.requested = vec!["mara".into()]; + let n = decide("acme/web", &f); + assert_eq!(n.state, State::ReadyToMerge, "{n:?}"); + assert!( + n.next.text.contains("no rule waits on it"), + "{}", + n.next.text + ); + } + + #[test] + fn githubs_decision_counts_every_approval_that_counts_there() { + // An app's approval counted toward the rule: GitHub says approved, + // and nothing here is stricter. + let mut f = ready(); + f.approved_by.clear(); + f.approvals_required = 1; + f.review_decision = Some("APPROVED".into()); + assert!(decide("acme/web", &f).state.is_ready()); + // The team's own rule still wants a person. + f.team_requires_approval = true; + let n = decide("acme/web", &f); + assert_eq!(n.next.rule, Some(Rule::TeamRule), "{n:?}"); + } } diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs index e624318d8..4975e1e45 100644 --- a/services/common/src/pr_record.rs +++ b/services/common/src/pr_record.rs @@ -38,10 +38,28 @@ use crate::pr_needs::{self, Facts, Needs}; /// Sort-key prefix of every record. pub const SK_PREFIX: &str = "PRREC#"; -/// Pointer from a head commit to its pull request (`status` events). -pub const HEAD_PREFIX: &str = "PRRECHEAD#"; -/// Pointer from a branch to its pull request (`push` events). -pub const REF_PREFIX: &str = "PRRECREF#"; +/// The pointer items that find a pull request from an event that doesn't +/// name it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Pointer { + /// Head commit to its pull request (`status` events). + Head, + /// Head branch to its pull request (`push` events to the branch). + Ref, + /// Base branch to each pull request based on it (`push` events to the + /// base: drift). One item per pull request. + Base, +} + +impl Pointer { + pub fn prefix(self) -> &'static str { + match self { + Pointer::Head => "PRRECHEAD#", + Pointer::Ref => "PRRECREF#", + Pointer::Base => "PRRECBASE#", + } + } +} /// How long a closed or merged pull request's record is kept. pub const CLOSED_KEEP_SECS: i64 = 3 * 86_400; /// How long a pointer item is kept after its last write. @@ -64,12 +82,9 @@ pub fn parse_sk(sk: &str) -> Option<(String, u64)> { Some((repo.to_string(), n.parse().ok()?)) } -pub fn head_sk(repo: &str, sha: &str) -> String { - format!("{HEAD_PREFIX}{repo}#{sha}") -} - -pub fn ref_sk(repo: &str, branch: &str) -> String { - format!("{REF_PREFIX}{repo}#{branch}") +/// A pointer's sort key: `key` is the commit or the branch. +pub fn pointer_sk(kind: Pointer, repo: &str, key: &str) -> String { + format!("{}{repo}#{key}", kind.prefix()) } /// A GitHub login is CoderHelm's own (its app, under any install's name). @@ -287,6 +302,9 @@ pub struct PrRecord { pub draft: bool, pub head_sha: String, pub head_ref: String, + /// The repository the head branch lives in (a fork's for a pull request + /// from a fork). + pub head_repo: String, pub base_ref: String, pub created_at: i64, /// When it was first ready for review: its creation when it never was @@ -307,6 +325,9 @@ pub struct PrRecord { /// and the commit it is on. pub coderhelm_verdict: Option<(String, String)>, pub review_decision: Option, + /// When the review decision was read (the sync) or worked out (a review + /// or review request event); 0 never. + pub decision_at: i64, pub approvals_required: u32, pub codeowners_required: bool, pub threads_required: bool, @@ -317,6 +338,10 @@ pub struct PrRecord { pub conflict: Option, /// GitHub's `mergeStateStatus` / `mergeable_state`, lower case. pub merge_state: String, + /// The sync's lists were cut short by their page size: the checks it + /// read are not all of them, and neither are the conversations. + pub checks_partial: bool, + pub threads_partial: bool, pub open_threads: u32, pub thread_authors: Vec, pub auto_merge: bool, @@ -569,6 +594,7 @@ impl PrRecord { .into(); self.new_head(pr["head"]["sha"].as_str().unwrap_or("")); self.head_ref = s(&pr["head"]["ref"]); + self.head_repo = s(&pr["head"]["repo"]["full_name"]); self.base_ref = s(&pr["base"]["ref"]); self.created_at = ts(&pr["created_at"]); self.updated_at = ts(&pr["updated_at"]).max(self.updated_at); @@ -734,6 +760,7 @@ impl PrRecord { }); bounded(&mut self.request_log); } + self.derive_decision(when); self.event(when, &sender, "reviewers", format!("asked {who} to review")) } "review_request_removed" => { @@ -754,6 +781,7 @@ impl PrRecord { { r.removed_at = when; } + self.derive_decision(when); self.event( when, &sender, @@ -897,6 +925,7 @@ impl PrRecord { (_, "CHANGES_REQUESTED") => "asked for changes".to_string(), _ => "commented in a review".to_string(), }; + self.derive_decision(when); self.event(when, &who, "review", words); self.event_at = now; true @@ -1077,6 +1106,62 @@ impl PrRecord { true } + /// GitHub's review decision as of a review or review request event, + /// worked out the way GitHub does from the reviews and the branch's + /// rule, so a merge right after an approval never reads a decision the + /// hourly sync read before it. Code owners can't be told from events: + /// with them required the decision keeps its last read and its time, so + /// it reads as stale rather than wrong. + fn derive_decision(&mut self, at: i64) { + if self + .reviews + .values() + .any(|r| r.state == "CHANGES_REQUESTED") + { + self.review_decision = Some("CHANGES_REQUESTED".into()); + self.decision_at = at; + return; + } + if self.codeowners_required { + return; + } + let approved = self + .reviews + .iter() + .filter(|(who, r)| r.state == "APPROVED" && !who.eq_ignore_ascii_case(&self.author)) + .count() as u32; + let decision = match (self.approvals_required, self.review_decision.as_deref()) { + // Nothing requires a review: GitHub reports no decision. + (0, None) => None, + // A rule the sync didn't name (a ruleset) requires one. + (0, Some(_)) => Some(if approved > 0 { + "APPROVED" + } else { + "REVIEW_REQUIRED" + }), + (n, _) => Some(if approved >= n { + "APPROVED" + } else { + "REVIEW_REQUIRED" + }), + }; + self.review_decision = decision.map(str::to_string); + self.decision_at = at; + } + + /// The review decision was read or worked out after the last review, + /// review request and push: bypass and coverage may rely on it. + pub fn decision_fresh(&self) -> bool { + let last = self + .review_log + .iter() + .map(|r| r.at) + .chain(self.request_log.iter().map(|r| r.at.max(r.removed_at))) + .max() + .unwrap_or(0); + self.decision_at > 0 && self.decision_at >= last + } + /// The head's checks as one word: `red`, `pending` or `green`. pub fn check_rollup(&self) -> &'static str { if self.checks.is_empty() { @@ -1182,8 +1267,30 @@ impl PrRecord { } /// Apply one pull request node from the sync's GraphQL search - /// ([`SEARCH_QUERY`]); it is the authority for everything it names. - pub fn apply_node(&mut self, n: &Value, now: i64) { + /// ([`SEARCH_QUERY`]), read at `read_at`. The search trails GitHub, so + /// it never reopens a record an event closed, and when an event reached + /// the record after the search was read it takes only what events never + /// carry (the review decision, the branch's rules, mergeability, + /// conversations, files). Lists it reads in full (reviews, review + /// requests) replace what the record held; a list cut short by its page + /// size is marked partial, never read as complete. False when it changed + /// nothing. + pub fn apply_node(&mut self, n: &Value, read_at: i64, now: i64) -> bool { + let node_open = !matches!(n["state"].as_str(), Some("MERGED") | Some("CLOSED")); + if self.known && !self.is_open() && node_open { + return false; + } + let events_newer = self.known && self.event_at > read_at; + if !events_newer { + self.take_node_events_part(n, now); + } + self.take_node_sync_part(n, read_at, now); + true + } + + /// What events also carry: identity, state, head, labels, requests, + /// each person's latest review and the checks. + fn take_node_events_part(&mut self, n: &Value, now: i64) { self.known = true; self.title = s(&n["title"]); self.url = s(&n["url"]); @@ -1206,9 +1313,123 @@ impl PrRecord { self.new_head(&head); self.checks_sha = self.head_sha.clone(); self.head_ref = s(&n["headRefName"]); + self.head_repo = s(&n["headRepository"]["nameWithOwner"]); self.base_ref = s(&n["baseRefName"]); self.created_at = ts(&n["createdAt"]); self.updated_at = ts(&n["updatedAt"]); + if let Some(t) = [ts(&n["mergedAt"]), ts(&n["closedAt"])] + .into_iter() + .find(|t| *t > 0) + { + self.closed_at = t; + } + if let Some(by) = n["mergedBy"]["login"].as_str() { + self.merged_by = by.to_string(); + } + self.additions = n["additions"].as_u64().unwrap_or(0) as u32; + self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; + self.labels = n["labels"]["nodes"] + .as_array() + .into_iter() + .flatten() + .map(|l| s(&l["name"])) + .collect(); + self.requested.clear(); + self.requested_teams.clear(); + for r in n["reviewRequests"]["nodes"] + .as_array() + .into_iter() + .flatten() + { + let rv = &r["requestedReviewer"]; + if let Some(l) = rv["login"].as_str() { + push_unique(&mut self.requested, l); + } else if let Some(slug) = rv["slug"].as_str() { + let t = format!("{}/{slug}", self.org()); + push_unique(&mut self.requested_teams, &t); + } + } + for r in self.requested.clone() { + self.role(&r, "requested"); + } + // Each person's latest review that took a side, as GitHub has it + // now: a review dismissed or gone leaves the record too. + self.reviews.clear(); + self.coderhelm_verdict = None; + for r in n["latestOpinionatedReviews"]["nodes"] + .as_array() + .into_iter() + .flatten() + { + let who = login(&r["author"]); + if who.is_empty() { + continue; + } + let state = s(&r["state"]); + let sha = s(&r["commit"]["oid"]); + if is_coderhelm(&who) { + let v = match state.as_str() { + "APPROVED" => "APPROVE", + "CHANGES_REQUESTED" => "REQUEST_CHANGES", + _ => "COMMENT", + }; + self.coderhelm_verdict = Some((v.into(), sha)); + } else if state != "DISMISSED" { + self.reviews.insert( + who.clone(), + Review { + state, + sha, + at: ts(&r["submittedAt"]), + }, + ); + } + self.role(&who, "reviewer"); + } + let rollup = &n["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]; + if let Some(list) = rollup["nodes"].as_array() { + let partial = rollup["pageInfo"]["hasNextPage"].as_bool() == Some(true); + // A list cut short keeps the checks events reported beside it. + if !partial { + self.checks.clear(); + } + self.checks_partial = partial; + for c in list.iter().take(MAX_CHECKS) { + let (name, check) = if c["__typename"] == "StatusContext" { + let (status, concl) = match c["state"].as_str() { + Some("PENDING") | Some("EXPECTED") => ("in_progress", ""), + Some("SUCCESS") => ("completed", "success"), + Some("FAILURE") => ("completed", "failure"), + _ => ("completed", "error"), + }; + ( + s(&c["context"]), + Check { + status: status.into(), + conclusion: concl.into(), + at: now, + }, + ) + } else { + ( + s(&c["name"]), + Check { + status: s(&c["status"]).to_ascii_lowercase(), + conclusion: s(&c["conclusion"]).to_ascii_lowercase(), + at: now, + }, + ) + }; + if !name.is_empty() { + self.checks.insert(name, check); + } + } + } + } + + /// What only the search carries. + fn take_node_sync_part(&mut self, n: &Value, read_at: i64, now: i64) { + self.known = true; let files: Vec = n["files"]["nodes"] .as_array() .into_iter() @@ -1222,15 +1443,6 @@ impl PrRecord { let (category, severity) = category_of(&self.author, &self.labels, &self.title); self.category = category.into(); self.severity = severity.into(); - let closed = [ts(&n["mergedAt"]), ts(&n["closedAt"])] - .into_iter() - .find(|t| *t > 0); - if let Some(t) = closed { - self.closed_at = t; - } - if let Some(by) = n["mergedBy"]["login"].as_str() { - self.merged_by = by.to_string(); - } // Its timeline: when it left draft, and every review request. let mut requests: Vec = Vec::new(); for t in n["timelineItems"]["nodes"].as_array().into_iter().flatten() { @@ -1292,62 +1504,6 @@ impl PrRecord { self.review_log.sort_by_key(|r| r.at); bounded(&mut self.review_log); } - self.additions = n["additions"].as_u64().unwrap_or(0) as u32; - self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; - self.labels = n["labels"]["nodes"] - .as_array() - .into_iter() - .flatten() - .map(|l| s(&l["name"])) - .collect(); - self.requested.clear(); - self.requested_teams.clear(); - for r in n["reviewRequests"]["nodes"] - .as_array() - .into_iter() - .flatten() - { - let rv = &r["requestedReviewer"]; - if let Some(l) = rv["login"].as_str() { - push_unique(&mut self.requested, l); - } else if let Some(slug) = rv["slug"].as_str() { - let t = format!("{}/{slug}", self.org()); - push_unique(&mut self.requested_teams, &t); - } - } - for r in self.requested.clone() { - self.role(&r, "requested"); - } - for r in n["latestOpinionatedReviews"]["nodes"] - .as_array() - .into_iter() - .flatten() - { - let who = login(&r["author"]); - if who.is_empty() { - continue; - } - let state = s(&r["state"]); - let sha = s(&r["commit"]["oid"]); - if is_coderhelm(&who) { - let v = match state.as_str() { - "APPROVED" => "APPROVE", - "CHANGES_REQUESTED" => "REQUEST_CHANGES", - _ => "COMMENT", - }; - self.coderhelm_verdict = Some((v.into(), sha)); - } else { - self.reviews.insert( - who.clone(), - Review { - state, - sha, - at: ts(&r["submittedAt"]), - }, - ); - } - self.role(&who, "reviewer"); - } for p in n["participants"]["nodes"].as_array().into_iter().flatten() { let l = login(p); if !self.people.contains_key(&l) && !l.is_empty() { @@ -1355,6 +1511,7 @@ impl PrRecord { } } self.review_decision = n["reviewDecision"].as_str().map(str::to_string); + self.decision_at = read_at; self.conflict = match n["mergeable"].as_str() { Some("CONFLICTING") => Some(true), Some("MERGEABLE") => Some(false), @@ -1381,9 +1538,10 @@ impl PrRecord { .map(s) .collect(); } + let threads = &n["reviewThreads"]; let mut open = 0; let mut authors = Vec::new(); - for t in n["reviewThreads"]["nodes"].as_array().into_iter().flatten() { + for t in threads["nodes"].as_array().into_iter().flatten() { if t["isResolved"].as_bool() == Some(false) { open += 1; let a = login(&t["comments"]["nodes"][0]["author"]); @@ -1392,41 +1550,7 @@ impl PrRecord { } self.open_threads = open; self.thread_authors = authors; - let contexts = - &n["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]["nodes"]; - if let Some(list) = contexts.as_array() { - self.checks.clear(); - for c in list.iter().take(MAX_CHECKS) { - let (name, check) = if c["__typename"] == "StatusContext" { - let (status, concl) = match c["state"].as_str() { - Some("PENDING") | Some("EXPECTED") => ("in_progress", ""), - Some("SUCCESS") => ("completed", "success"), - Some("FAILURE") => ("completed", "failure"), - _ => ("completed", "error"), - }; - ( - s(&c["context"]), - Check { - status: status.into(), - conclusion: concl.into(), - at: now, - }, - ) - } else { - ( - s(&c["name"]), - Check { - status: s(&c["status"]).to_ascii_lowercase(), - conclusion: s(&c["conclusion"]).to_ascii_lowercase(), - at: now, - }, - ) - }; - if !name.is_empty() { - self.checks.insert(name, check); - } - } - } + self.threads_partial = threads["pageInfo"]["hasNextPage"].as_bool() == Some(true); self.synced_at = now; } @@ -1471,10 +1595,16 @@ impl PrRecord { } } } - // A required check not reported yet is still to run. + // A required check not reported yet is still to run, unless the + // sync's list was cut short: then it may be among the checks it + // didn't read, and the checks are not known. if checks.known { for r in &self.required_checks { if !self.checks.keys().any(|k| k.eq_ignore_ascii_case(r)) { + if self.checks_partial { + checks.known = false; + break; + } checks.total += 1; checks.running.push(r.clone()); } @@ -1512,6 +1642,7 @@ impl PrRecord { threads_required: self.threads_required, open_threads: self.open_threads, thread_authors: self.thread_authors.clone(), + threads_unread: self.threads_partial, auto_merge: self.auto_merge, blocked_by_rules: blocked, since: self.spans.last().map(|s| s.from).unwrap_or(self.created_at), @@ -1588,6 +1719,7 @@ pub const SEARCH_QUERY: &str = "query($q: String!, $after: String) { ... on PullRequest { number title url state isDraft createdAt updatedAt additions deletions headRefName headRefOid baseRefName reviewDecision mergeable mergeStateStatus + headRepository { nameWithOwner } isInMergeQueue repository { nameWithOwner } author { login } @@ -1600,9 +1732,9 @@ pub const SEARCH_QUERY: &str = "query($q: String!, $after: String) { reviews(first: 40) { nodes { state submittedAt body author { login } commit { oid } } } timelineItems(first: 40, itemTypes: [READY_FOR_REVIEW_EVENT, REVIEW_REQUESTED_EVENT, REVIEW_REQUEST_REMOVED_EVENT]) { nodes { __typename ... on ReadyForReviewEvent { createdAt } ... on ReviewRequestedEvent { createdAt requestedReviewer { ... on User { login } ... on Team { slug } } } ... on ReviewRequestRemovedEvent { createdAt requestedReviewer { ... on User { login } ... on Team { slug } } } } } participants(first: 20) { nodes { login } } - reviewThreads(first: 50) { nodes { isResolved comments(first: 1) { nodes { author { login } } } } } + reviewThreads(first: 100) { pageInfo { hasNextPage } nodes { isResolved comments(first: 1) { nodes { author { login } } } } } baseRef { branchProtectionRule { requiredApprovingReviewCount requiresCodeOwnerReviews requiresConversationResolution requiredStatusCheckContexts } } - commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 60) { nodes { __typename ... on CheckRun { name status conclusion } ... on StatusContext { context state } } } } } } } + commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { pageInfo { hasNextPage } nodes { __typename ... on CheckRun { name status conclusion } ... on StatusContext { context state } } } } } } } } } } @@ -1644,22 +1776,51 @@ pub fn from_item(item: &Item) -> Option<(PrRecord, i64)> { } /// Read one record. -pub async fn load( +/// One settings item of the team (consistent read), the one read every +/// record, pointer, history row and backfill progress goes through. +pub async fn get_item( dynamo: &DynamoClient, table: &str, team_id: &str, - repo: &str, - number: u64, -) -> Result, Err> { + sk: &str, +) -> Result, Err> { let out = dynamo .get_item() .table_name(table) .key("pk", AttributeValue::S(team_id.into())) - .key("sk", AttributeValue::S(record_sk(repo, number))) + .key("sk", AttributeValue::S(sk.into())) .consistent_read(true) .send() .await?; - Ok(out.item().and_then(from_item)) + Ok(out.item().cloned()) +} + +/// The JSON body (`doc`) of a team's settings item. +pub async fn get_doc( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + sk: &str, +) -> Result, Err> { + Ok(get_item(dynamo, table, team_id, sk) + .await? + .as_ref() + .and_then(|i| i.get("doc")) + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str(d).ok())) +} + +pub async fn load( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + number: u64, +) -> Result, Err> { + Ok(get_item(dynamo, table, team_id, &record_sk(repo, number)) + .await? + .as_ref() + .and_then(from_item)) } /// Write a record when its version is still `ver` (0: not there yet). @@ -1764,9 +1925,12 @@ pub async fn point( rec: &PrRecord, now: i64, ) -> Result<(), Err> { + let base = format!("{}#{:06}", rec.base_ref, rec.number); for sk in [ - (!rec.head_sha.is_empty()).then(|| head_sk(&rec.repo, &rec.head_sha)), - (!rec.head_ref.is_empty()).then(|| ref_sk(&rec.repo, &rec.head_ref)), + (!rec.head_sha.is_empty()).then(|| pointer_sk(Pointer::Head, &rec.repo, &rec.head_sha)), + (!rec.head_ref.is_empty()).then(|| pointer_sk(Pointer::Ref, &rec.repo, &rec.head_ref)), + (!rec.base_ref.is_empty() && rec.is_open()) + .then(|| pointer_sk(Pointer::Base, &rec.repo, &base)), ] .into_iter() .flatten() @@ -1794,18 +1958,42 @@ pub async fn pointed( team_id: &str, sk: &str, ) -> Result, Err> { + Ok(get_item(dynamo, table, team_id, sk) + .await? + .as_ref() + .and_then(|i| i.get("pr_number")) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok())) +} + +/// The open pull requests a base-branch pointer names: those based on +/// `branch` in `repo` (pointers outlive a base change by up to their +/// expiry; the record's own base decides). +pub async fn based_on( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, + branch: &str, +) -> Result, Err> { + let prefix = pointer_sk(Pointer::Base, repo, &format!("{branch}#")); let out = dynamo - .get_item() + .query() .table_name(table) - .key("pk", AttributeValue::S(team_id.into())) - .key("sk", AttributeValue::S(sk.into())) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team_id.into())) + .expression_attribute_values(":p", AttributeValue::S(prefix)) + .projection_expression("pr_number") + .limit(200) .send() .await?; Ok(out - .item() - .and_then(|i| i.get("pr_number")) - .and_then(|v| v.as_n().ok()) - .and_then(|v| v.parse().ok())) + .items() + .iter() + .filter_map(|i| i.get("pr_number")) + .filter_map(|v| v.as_n().ok()) + .filter_map(|v| v.parse().ok()) + .collect()) } /// Every record of a team (one query, paged). @@ -1992,7 +2180,7 @@ mod tests { {"__typename": "CheckRun", "name": "unit", "status": "COMPLETED", "conclusion": "SUCCESS"}]}}}}]} }); let mut r = PrRecord::new("acme/web", 318); - r.apply_node(&node, NOW); + r.apply_node(&node, NOW, NOW); assert_eq!(r.requested_teams, vec!["acme/payments"]); assert_eq!(r.open_threads, 1); assert_eq!(r.thread_authors, vec!["jun"]); @@ -2069,4 +2257,122 @@ mod tests { ("security", "high") ); } + + fn node(state: &str, decision: &str) -> Value { + json!({ + "number": 318, "title": "Round cart totals", "url": "https://github.com/acme/web/pull/318", + "state": state, "isDraft": false, "createdAt": "2026-01-10T10:00:00Z", + "updatedAt": "2026-01-10T12:00:00Z", "headRefName": "fix/cart-rounding", + "headRefOid": "aaaaaaa1111111", "baseRefName": "main", "reviewDecision": decision, + "mergeable": "MERGEABLE", "author": {"login": "octocat"}, + "headRepository": {"nameWithOwner": "acme/web"}, + "latestOpinionatedReviews": {"nodes": []}, + "reviewThreads": {"pageInfo": {"hasNextPage": false}, "nodes": []}, + "commits": {"nodes": [{"commit": {"statusCheckRollup": {"contexts": { + "pageInfo": {"hasNextPage": false}, + "nodes": [{"__typename": "CheckRun", "name": "unit", "status": "COMPLETED", "conclusion": "SUCCESS"}]}}}}]} + }) + } + + #[test] + fn the_sync_never_reopens_a_closed_record_or_overwrites_newer_events() { + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW); + let mut closed = opened(); + closed["action"] = json!("closed"); + closed["pull_request"]["state"] = json!("closed"); + r.apply_event("pull_request", &closed, NOW); + assert!(!r.apply_node(&node("OPEN", "APPROVED"), NOW - 60, NOW)); + assert_eq!(r.status, "closed"); + + // An event after the search was read wins over the page. + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW); + r.title = "Newer title from an event".into(); + assert!(r.apply_node(&node("OPEN", "APPROVED"), NOW - 60, NOW)); + assert_eq!(r.title, "Newer title from an event"); + // ...while what only the search carries still lands. + assert_eq!(r.review_decision.as_deref(), Some("APPROVED")); + } + + #[test] + fn the_sync_is_the_authority_for_the_reviews_it_lists() { + let mut r = PrRecord::new("acme/web", 318); + r.reviews.insert( + "mara".into(), + Review { + state: "CHANGES_REQUESTED".into(), + ..Default::default() + }, + ); + r.coderhelm_verdict = Some(("REQUEST_CHANGES".into(), "aaaaaaa1111111".into())); + r.apply_node(&node("OPEN", "REVIEW_REQUIRED"), NOW, NOW); + assert!( + r.reviews.is_empty(), + "a review gone from GitHub leaves the record" + ); + assert_eq!(r.coderhelm_verdict, None); + } + + #[test] + fn a_list_cut_short_is_never_read_as_complete() { + let mut n = node("OPEN", "APPROVED"); + n["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]["pageInfo"] + ["hasNextPage"] = json!(true); + n["reviewThreads"]["pageInfo"]["hasNextPage"] = json!(true); + let mut r = PrRecord::new("acme/web", 318); + r.checks_sha = "aaaaaaa1111111".into(); + r.head_sha = "aaaaaaa1111111".into(); + r.checks.insert( + "lint".into(), + Check { + status: "completed".into(), + conclusion: "success".into(), + at: NOW, + }, + ); + r.apply_node(&n, NOW, NOW); + assert!(r.checks.contains_key("lint"), "event-fed checks are kept"); + r.required_checks = vec!["e2e".into()]; + let f = r.facts(); + assert!( + !f.checks.known, + "a required check maybe on a later page is unknown, not running" + ); + r.threads_required = true; + r.required_checks.clear(); + let n = pr_needs::decide("acme/web", &r.facts()); + assert_eq!(n.state, pr_needs::State::Unknown, "{n:?}"); + } + + #[test] + fn a_review_event_refreshes_the_review_decision() { + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW); + r.approvals_required = 1; + r.review_decision = Some("REVIEW_REQUIRED".into()); + r.decision_at = NOW - 3600; + let review = json!({"action": "submitted", "pull_request": {"number": 318}, + "review": {"user": {"login": "mara"}, "state": "approved", "commit_id": "aaaaaaa1111111", + "submitted_at": "2026-01-10T11:00:00Z"}}); + r.apply_event("pull_request_review", &review, NOW); + assert_eq!(r.review_decision.as_deref(), Some("APPROVED")); + assert!(r.decision_fresh()); + } + + #[test] + fn one_pointer_helper_names_every_pointer() { + assert_eq!( + pointer_sk(Pointer::Head, "acme/web", "aaa"), + "PRRECHEAD#acme/web#aaa" + ); + assert_eq!( + pointer_sk(Pointer::Ref, "acme/web", "main"), + "PRRECREF#acme/web#main" + ); + assert_eq!( + pointer_sk(Pointer::Base, "acme/web", "main#000318"), + "PRRECBASE#acme/web#main#000318" + ); + } } diff --git a/services/common/src/pr_view.rs b/services/common/src/pr_view.rs index c969dd63a..49980ada1 100644 --- a/services/common/src/pr_view.rs +++ b/services/common/src/pr_view.rs @@ -281,9 +281,14 @@ pub fn facts_of( /// Links between the team's own records: a pull request based on another's /// branch is stacked on it; the run's plan links its pull requests. pub fn link_records(recs: &mut [PrRecord], joins: &Joins) { + // A branch is a base other pull requests stack on only when it lives in + // the same repository: a fork's `main` is not the repository's `main`. + // A head whose repository isn't known stacks nothing. let heads: HashMap<(String, String), u64> = recs .iter() - .filter(|r| r.is_open() && !r.head_ref.is_empty()) + .filter(|r| { + r.is_open() && !r.head_ref.is_empty() && r.head_repo.eq_ignore_ascii_case(&r.repo) + }) .map(|r| ((r.repo.clone(), r.head_ref.clone()), r.number)) .collect(); let mut children: HashMap<(String, u64), Vec> = HashMap::new(); @@ -371,6 +376,31 @@ pub fn rows( viewer: Option<&str>, now: i64, ) -> Vec { + decided(team_id, items, joins, viewer, now) + .into_iter() + .map(|d| d.row) + .collect() +} + +/// One pull request as the list and the detail both read it: its linked +/// record (stack and plan links in), the facts, the decision and the row. +#[derive(Debug, Clone)] +pub struct Decided { + pub record: PrRecord, + pub facts: Facts, + pub needs: Needs, + pub row: Row, +} + +/// The one input builder of the list and the detail: every record of the +/// team linked to the others, decided once. +pub fn decided( + team_id: &str, + items: &[Item], + joins: &Joins, + viewer: Option<&str>, + now: i64, +) -> Vec { let mut recs = records_of(team_id, items); link_records(&mut recs, joins); let mut decided: Vec<(PrRecord, Needs, Facts)> = Vec::new(); @@ -425,11 +455,32 @@ pub fn rows( && p75 .get(&(r.repo.clone(), n.state)) .is_some_and(|p| now - since > *p && *p > 0); - row(&r, &n, &f, joins, &states, viewer, since, stale) + let row = row(&r, &n, &f, joins, &states, viewer, since, stale); + Decided { + record: r, + facts: f, + needs: n, + row, + } }) .collect() } +/// One pull request of the team, decided exactly as the list decides it. +pub fn detail_of( + team_id: &str, + items: &[Item], + joins: &Joins, + viewer: Option<&str>, + now: i64, + repo: &str, + number: u64, +) -> Option { + decided(team_id, items, joins, viewer, now) + .into_iter() + .find(|d| d.record.repo.eq_ignore_ascii_case(repo) && d.record.number == number) +} + fn waiting_since(r: &PrRecord) -> i64 { r.spans .last() @@ -986,6 +1037,7 @@ mod tests { fn a_stacked_pull_request_waits_on_its_base() { let mut base = rec("acme/web", 1, "octocat"); base.head_ref = "feature/a".into(); + base.head_repo = "acme/web".into(); base.base_ref = "main".into(); let mut top = rec("acme/web", 2, "octocat"); top.head_ref = "feature/b".into(); @@ -1049,4 +1101,45 @@ mod tests { .iter() .all(|e| !e.coderhelm || e.run_id.as_deref() == Some("run-1"))); } + + #[test] + fn a_forks_branch_never_stacks_the_repositorys_pull_requests() { + let mut fork = rec("acme/web", 1, "octocat"); + fork.head_ref = "main".into(); + fork.head_repo = "octocat/web".into(); + let mut other = rec("acme/web", 2, "mara"); + other.base_ref = "main".into(); + let items = vec![item("TEAM#a", &fork), item("TEAM#a", &other)]; + let all = rows("TEAM#a", &items, &Joins::default(), None, NOW); + let other = all.iter().find(|r| r.number == 2).unwrap(); + assert_ne!(other.state, "waiting_on_pr"); + assert!(other.links.is_empty()); + } + + #[test] + fn the_detail_decides_a_stacked_pull_request_as_the_list_does() { + let mut base = rec("acme/web", 1, "octocat"); + base.head_ref = "feature/a".into(); + base.head_repo = "acme/web".into(); + let mut top = rec("acme/web", 2, "octocat"); + top.base_ref = "feature/a".into(); + let items = vec![item("TEAM#a", &base), item("TEAM#a", &top)]; + let row = rows("TEAM#a", &items, &Joins::default(), None, NOW) + .into_iter() + .find(|r| r.number == 2) + .unwrap(); + let d = detail_of( + "TEAM#a", + &items, + &Joins::default(), + None, + NOW, + "acme/web", + 2, + ) + .unwrap(); + assert_eq!(row.state, "waiting_on_pr"); + assert_eq!(d.needs.state.code(), row.state); + assert_eq!(d.facts.waits_on, vec!["acme/web#1".to_string()]); + } } diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 1136ddd13..7ba4b28cc 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -25,7 +25,7 @@ use axum::{ http::StatusCode, Extension, Json, }; -use common::pr_record::{self, Item, PrRecord}; +use common::pr_record::{self, Item, Pointer, PrRecord}; use common::pr_view::{self, Joins, ReviewJoin, RunJoin}; use serde::Deserialize; use serde_json::{json, Value}; @@ -38,8 +38,9 @@ use crate::AppState; /// How long one team's read is reused (the page polls while visible). const LIST_TTL: Duration = Duration::from_secs(10); -/// One team's records and what is joined to them. -type Snapshot = Arc<(Vec, Joins)>; +/// One team's records, what is joined to them, and how each source read +/// (a cache hit says the same as the read it keeps). +type Snapshot = Arc<(Vec, Joins, Vec)>; /// The team's records and joins as last read, keyed by /// `read_key(installation_id, "prs#")`. @@ -66,11 +67,11 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo let sk = match event_type { "status" => payload["sha"] .as_str() - .map(|sha| pr_record::head_sk(repo, sha)), + .map(|sha| pr_record::pointer_sk(Pointer::Head, repo, sha)), "push" => payload["ref"] .as_str() .and_then(|r| r.strip_prefix("refs/heads/")) - .map(|b| pr_record::ref_sk(repo, b)), + .map(|b| pr_record::pointer_sk(Pointer::Ref, repo, b)), _ => None, }; if event_type == "push" { @@ -133,8 +134,9 @@ pub async fn on_webhook(state: &AppState, team_id: &str, event_type: &str, paylo } /// A push to a branch other pull requests are based on: their drift -/// (commits behind, and those touching their files). The repository's open -/// records only, at most 200. +/// (commits behind, and those touching their files). Only the pull +/// requests a base pointer names are read (most pushes go to branches +/// nothing is based on, and read nothing), at most 200. async fn base_push(state: &AppState, team_id: &str, repo: &str, payload: &Value) { let Some(branch) = payload["ref"] .as_str() @@ -146,21 +148,16 @@ async fn base_push(state: &AppState, team_id: &str, repo: &str, payload: &Value) return; } let table = &state.config.settings_table_name; - let prefix = format!("{}{repo}#", pr_record::SK_PREFIX); - let items = match items_under(state, team_id, &prefix).await { - Ok(i) => i, + let numbers = match pr_record::based_on(&state.dynamo, table, team_id, repo, branch).await { + Ok(n) => n, Err(e) => { - warn!(repo, error = %e, "Drift: records not read"); + warn!(repo, error = %e, "Drift: base pointers not read"); return; } }; let t = now(); - for rec in pr_view::records_of(team_id, &items) - .into_iter() - .filter(|r| r.is_open() && r.base_ref == branch) - .take(200) - { - let _ = pr_record::update(&state.dynamo, table, team_id, repo, rec.number, t, |r| { + for number in numbers.into_iter().take(200) { + let _ = pr_record::update(&state.dynamo, table, team_id, repo, number, t, |r| { r.note_base_push(branch, payload, t) }) .await; @@ -434,10 +431,8 @@ async fn read_all(state: &AppState, team_id: &str) -> Result<(Snapshot, Vec Result<(Snapshot, Vec = run.cloned().into_iter().collect(); let runs_out: Vec = runs .iter() diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index fe6fd264b..d0d8eff05 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -700,13 +700,28 @@ pub(crate) fn gate_facts(v: &GateView, ci: Option<&Ci>) -> common::pr_needs::Fac } None => {} } - let approved_by = if !human { - Vec::new() - } else if v.approvals.approved_at_head.is_empty() { + // People's approvals. The team's rule takes them only through the + // person key; GitHub's rule is GitHub's own decision. + let people = if v.approvals.approved_at_head.is_empty() { v.approvals.approved_by.clone() } else { v.approvals.approved_at_head.clone() }; + let approved_by = if v.require_human && !human { + Vec::new() + } else { + people + }; + // GitHub reports no review decision when the branch requires no review: + // then no approval count holds the merge, whatever rules were read. + let approvals_required = if v.review_decision.is_none() { + 0 + } else { + v.rules + .required_approvals + .unwrap_or(0) + .min(u64::from(u32::MAX)) as u32 + }; Facts { known: true, draft: v.draft, @@ -721,11 +736,7 @@ pub(crate) fn gate_facts(v: &GateView, ci: Option<&Ci>) -> common::pr_needs::Fac approved_by, requested: v.requested.clone(), review_decision: v.review_decision.clone(), - approvals_required: v - .rules - .required_approvals - .unwrap_or(0) - .min(u64::from(u32::MAX)) as u32, + approvals_required, team_requires_approval: v.require_human, conflict: Some(false), checks, diff --git a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs index c33ca1404..c4d857d60 100644 --- a/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs +++ b/services/worker/src/passes/incidents/xw_every_open_pr_has_one_state.rs @@ -217,8 +217,10 @@ fn gate_view() -> GateView { #[test] fn the_merge_gates_and_the_list_read_one_decision() { // The reviewer's auto-merge gate merges exactly when the list says - // ready, over every combination of what it weighs. - for bits in 0u32..(1 << 8) { + // ready, over every combination of what it weighs: the keys, the + // checks, people asked to review, GitHub's review decision and the + // branch's approval count. + for bits in 0u32..(1 << 12) { let on = |i: u32| bits & (1 << i) != 0; let mut v = gate_view(); v.draft = on(0); @@ -246,6 +248,18 @@ fn the_merge_gates_and_the_list_read_one_decision() { ..Default::default() }, }; + if on(8) { + v.requested = vec!["theo".into()]; + } + v.review_decision = match (on(9), on(10)) { + (false, false) => None, + (true, false) => Some("REVIEW_REQUIRED".into()), + (false, true) => Some("APPROVED".into()), + (true, true) => Some("CHANGES_REQUESTED".into()), + }; + if on(11) { + v.rules.required_approvals = Some(1); + } let ci = summary.ci(); v.ci = Some(summary); let gate = decide_gate(&v); @@ -253,7 +267,7 @@ fn the_merge_gates_and_the_list_read_one_decision() { assert_eq!( gate.action == Action::Merge, list.state.is_ready(), - "bits {bits:08b}: the gate says {:?}, the list says {:?}", + "bits {bits:012b}: the gate says {:?}, the list says {:?}", gate.action, list.state ); @@ -262,6 +276,18 @@ fn the_merge_gates_and_the_list_read_one_decision() { } } + // Never stricter than GitHub: a review someone is asked for that no + // rule requires, with the team's rule off, never holds the merge. + let mut v = gate_view(); + v.require_human = false; + v.requested = vec!["theo".into()]; + v.ci = Some(CheckSummary::default()); + assert_eq!(decide_gate(&v).action, Action::Merge); + // GitHub's approval counts every approval that counts there. + v.review_decision = Some("APPROVED".into()); + v.rules.required_approvals = Some(1); + assert_eq!(decide_gate(&v).action, Action::Merge); + // The run's watch stores the standing this function decides, and the // list reads the stored standing to the same state. let watch = src("worker/src/passes/pr_watch.rs"); diff --git a/services/worker/src/passes/pr_records.rs b/services/worker/src/passes/pr_records.rs index 7adcc34e9..3d6a4026a 100644 --- a/services/worker/src/passes/pr_records.rs +++ b/services/worker/src/passes/pr_records.rs @@ -179,6 +179,9 @@ async fn sync_team( break; } let vars = json!({"q": pr_record::search_text(&owner, as_org), "after": after}); + // Before the read: an event recorded after this moment is newer + // than anything the page says. + let read_at = chrono::Utc::now().timestamp(); let data = match github.graphql_read(pr_record::SEARCH_QUERY, vars).await { Ok(d) => d, // A personal account's repositories are searched by user. @@ -205,8 +208,7 @@ async fn sync_team( seen.insert(format!("{}#{number}", repo.to_ascii_lowercase())); let written = pr_record::update(&state.dynamo, table, team_id, repo, number, now, |r| { - r.apply_node(node, now); - true + r.apply_node(node, read_at, now) }) .await; match written { From 08dde4da3d85565f8ba85af7cdd4469dd8958c56 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 19:58:53 -0500 Subject: [PATCH 7/7] The sync writes each field only when its search was read after the last event that wrote it A page read before an event could undo that event's queue entry, auto-merge or review decision. Every field both events and the sync write (state, title, draft, head, base, labels, review requests, reviews, review decision, checks, mergeability, auto-merge, the merge queue, size) now keeps the time an event last wrote it, and the sync writes that field only when its read is newer. Tests cover a queue, an auto-merge and a review decision event landing after the read and surviving the page. --- docs/pull-requests.md | 2 +- docs/pull-requests/api_contract.md | 2 +- services/common/src/pr_record.rs | 348 +++++++++++++++++++++++------ 3 files changed, 282 insertions(+), 70 deletions(-) diff --git a/docs/pull-requests.md b/docs/pull-requests.md index 9b241d073..7ab21dc72 100644 --- a/docs/pull-requests.md +++ b/docs/pull-requests.md @@ -8,7 +8,7 @@ One settings-table item per pull request (`pk` = team id, `sk = PRREC#, +} + +/// The fields both events and the sync write, each with its own time, so a +/// search read before an event never undoes that event's field. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Field { + /// Status, when it closed and who merged it. + State, + /// Title and link. + Title, + Draft, + /// Head commit, branch and the repository it lives in. + Head, + Base, + Labels, + /// People and teams asked to review. + Requested, + /// Each person's latest review and CoderHelm's verdict. + Reviews, + ReviewDecision, + Checks, + /// Mergeability and GitHub's merge state. + Conflict, + AutoMerge, + Queue, + Size, +} + +impl Field { + fn key(self) -> &'static str { + match self { + Field::State => "state", + Field::Title => "title", + Field::Draft => "draft", + Field::Head => "head", + Field::Base => "base", + Field::Labels => "labels", + Field::Requested => "requested", + Field::Reviews => "reviews", + Field::ReviewDecision => "review_decision", + Field::Checks => "checks", + Field::Conflict => "conflict", + Field::AutoMerge => "auto_merge", + Field::Queue => "queue", + Field::Size => "size", + } + } } fn ts(v: &Value) -> i64 { @@ -564,6 +614,18 @@ impl PrRecord { } } + /// An event wrote `field` at `now`. + fn stamp(&mut self, field: Field, now: i64) { + let t = self.field_at.entry(field.key().into()).or_insert(0); + *t = (*t).max(now); + } + + /// A search read at `read_at` may write `field`: no event wrote it at or + /// after the read. + fn sync_may(&self, field: Field, read_at: i64) -> bool { + self.field_at.get(field.key()).is_none_or(|&t| t < read_at) + } + fn new_head(&mut self, sha: &str) { if !sha.is_empty() && sha != self.head_sha { self.head_sha = sha.to_string(); @@ -572,11 +634,14 @@ impl PrRecord { } /// The pull request object (webhook or REST shape). - fn take_pr(&mut self, pr: &Value) { + fn take_pr(&mut self, pr: &Value, now: i64) { if pr["number"].as_u64().is_none() { return; } self.known = true; + for f in [Field::State, Field::Title, Field::Draft, Field::Base] { + self.stamp(f, now); + } self.title = s(&pr["title"]); self.url = s(&pr["html_url"]); let author = login(&pr["user"]); @@ -593,6 +658,9 @@ impl PrRecord { } .into(); self.new_head(pr["head"]["sha"].as_str().unwrap_or("")); + if pr["head"].is_object() { + self.stamp(Field::Head, now); + } self.head_ref = s(&pr["head"]["ref"]); self.head_repo = s(&pr["head"]["repo"]["full_name"]); self.base_ref = s(&pr["base"]["ref"]); @@ -608,16 +676,19 @@ impl PrRecord { self.merged_by = by.to_string(); } if let Some(a) = pr["additions"].as_u64() { + self.stamp(Field::Size, now); self.additions = a as u32; self.deletions = pr["deletions"].as_u64().unwrap_or(0) as u32; } if let Some(labels) = pr["labels"].as_array() { + self.stamp(Field::Labels, now); self.labels = labels.iter().map(|l| s(&l["name"])).collect(); } let (category, severity) = category_of(&self.author, &self.labels, &self.title); self.category = category.into(); self.severity = severity.into(); if let Some(r) = pr["requested_reviewers"].as_array() { + self.stamp(Field::Requested, now); self.requested = r.iter().map(login).filter(|l| !l.is_empty()).collect(); } if let Some(t) = pr["requested_teams"].as_array() { @@ -631,15 +702,18 @@ impl PrRecord { self.role(&r, "requested"); } if let Some(m) = pr["mergeable"].as_bool() { + self.stamp(Field::Conflict, now); self.conflict = Some(!m); } if let Some(st) = pr["mergeable_state"].as_str() { + self.stamp(Field::Conflict, now); self.merge_state = st.to_ascii_lowercase(); if st == "dirty" { self.conflict = Some(true); } } if pr.get("auto_merge").is_some() { + self.stamp(Field::AutoMerge, now); self.auto_merge = !pr["auto_merge"].is_null(); } if let Some(body) = pr["body"].as_str() { @@ -689,7 +763,7 @@ impl PrRecord { "pull_request" => { let pr = &payload["pull_request"]; let before = self.head_sha.clone(); - self.take_pr(pr); + self.take_pr(pr, now); let when = at(&pr["updated_at"]); if self.ready_at == 0 { if action == "ready_for_review" { @@ -727,6 +801,7 @@ impl PrRecord { format!("pushed; the head is now {short}"), ); if before != self.head_sha { + self.stamp(Field::Checks, now); self.checks.clear(); self.checks_sha = self.head_sha.clone(); // A push brings the base in or rebases onto it, @@ -760,7 +835,7 @@ impl PrRecord { }); bounded(&mut self.request_log); } - self.derive_decision(when); + self.derive_decision(when, now); self.event(when, &sender, "reviewers", format!("asked {who} to review")) } "review_request_removed" => { @@ -781,7 +856,7 @@ impl PrRecord { { r.removed_at = when; } - self.derive_decision(when); + self.derive_decision(when, now); self.event( when, &sender, @@ -802,11 +877,13 @@ impl PrRecord { format!("took the label `{}` off", s(&payload["label"]["name"])), ), "enqueued" => { + self.stamp(Field::Queue, now); self.in_queue = true; self.left_queue = None; self.event(when, &sender, "queue", "added it to the merge queue".into()) } "dequeued" => { + self.stamp(Field::Queue, now); self.in_queue = false; let reason = payload["reason"] .as_str() @@ -835,6 +912,7 @@ impl PrRecord { ) } "auto_merge_enabled" => { + self.stamp(Field::AutoMerge, now); self.auto_merge = true; self.event( when, @@ -844,6 +922,7 @@ impl PrRecord { ) } "auto_merge_disabled" => { + self.stamp(Field::AutoMerge, now); self.auto_merge = false; self.event( when, @@ -867,11 +946,13 @@ impl PrRecord { return false; } if !self.known { - self.take_pr(&payload["pull_request"]); + self.take_pr(&payload["pull_request"], now); } let state = r["state"].as_str().unwrap_or("").to_ascii_uppercase(); let sha = s(&r["commit_id"]); let when = at(&r["submitted_at"]); + self.stamp(Field::Reviews, now); + self.stamp(Field::Requested, now); if is_coderhelm(&who) { let verdict = match state.as_str() { "APPROVED" => "APPROVE", @@ -925,7 +1006,7 @@ impl PrRecord { (_, "CHANGES_REQUESTED") => "asked for changes".to_string(), _ => "commented in a review".to_string(), }; - self.derive_decision(when); + self.derive_decision(when, now); self.event(when, &who, "review", words); self.event_at = now; true @@ -940,7 +1021,7 @@ impl PrRecord { return false; } if event_type == "pull_request_review_comment" && !self.known { - self.take_pr(&payload["pull_request"]); + self.take_pr(&payload["pull_request"], now); } let body = c["body"].as_str().unwrap_or(""); if !is_coderhelm(&who) && body.to_ascii_lowercase().contains("@coderhelm") { @@ -990,6 +1071,7 @@ impl PrRecord { self.event(c.at, "ci", "check", format!("`{name}` failed")); } self.put_check(name, c); + self.stamp(Field::Checks, now); self.note_checks(now); self.event_at = now; true @@ -1013,6 +1095,7 @@ impl PrRecord { }, ); } + self.stamp(Field::Checks, now); if action == "completed" { let concl = s(&suite["conclusion"]); self.event( @@ -1046,6 +1129,7 @@ impl PrRecord { at: at(&payload["updated_at"]), }, ); + self.stamp(Field::Checks, now); self.note_checks(now); self.event_at = now; true @@ -1065,6 +1149,8 @@ impl PrRecord { self.role(&pusher, "committer"); } if !after.is_empty() && !after.starts_with("0000000") { + self.stamp(Field::Head, now); + self.stamp(Field::Checks, now); if after != self.head_sha { self.checks.clear(); self.checks_sha = after.clone(); @@ -1112,7 +1198,7 @@ impl PrRecord { /// hourly sync read before it. Code owners can't be told from events: /// with them required the decision keeps its last read and its time, so /// it reads as stale rather than wrong. - fn derive_decision(&mut self, at: i64) { + fn derive_decision(&mut self, at: i64, now: i64) { if self .reviews .values() @@ -1120,6 +1206,7 @@ impl PrRecord { { self.review_decision = Some("CHANGES_REQUESTED".into()); self.decision_at = at; + self.stamp(Field::ReviewDecision, now); return; } if self.codeowners_required { @@ -1147,6 +1234,7 @@ impl PrRecord { }; self.review_decision = decision.map(str::to_string); self.decision_at = at; + self.stamp(Field::ReviewDecision, now); } /// The review decision was read or worked out after the last review, @@ -1268,72 +1356,112 @@ impl PrRecord { /// Apply one pull request node from the sync's GraphQL search /// ([`SEARCH_QUERY`]), read at `read_at`. The search trails GitHub, so - /// it never reopens a record an event closed, and when an event reached - /// the record after the search was read it takes only what events never - /// carry (the review decision, the branch's rules, mergeability, - /// conversations, files). Lists it reads in full (reviews, review - /// requests) replace what the record held; a list cut short by its page - /// size is marked partial, never read as complete. False when it changed - /// nothing. + /// it never reopens a record an event closed, and it writes each field + /// only when no event wrote that field at or after the read + /// ([`Field`]): a queue, auto-merge, review or label change that landed + /// while the page was in flight survives it. Lists it reads in full + /// (reviews, review requests) replace what the record held; a list cut + /// short by its page size is marked partial, never read as complete. + /// False when it changed nothing. pub fn apply_node(&mut self, n: &Value, read_at: i64, now: i64) -> bool { let node_open = !matches!(n["state"].as_str(), Some("MERGED") | Some("CLOSED")); if self.known && !self.is_open() && node_open { return false; } - let events_newer = self.known && self.event_at > read_at; - if !events_newer { - self.take_node_events_part(n, now); - } + self.take_node_events_part(n, read_at, now); self.take_node_sync_part(n, read_at, now); true } /// What events also carry: identity, state, head, labels, requests, - /// each person's latest review and the checks. - fn take_node_events_part(&mut self, n: &Value, now: i64) { + /// each person's latest review and the checks; each only when no event + /// wrote it after the search was read. + fn take_node_events_part(&mut self, n: &Value, read_at: i64, now: i64) { self.known = true; - self.title = s(&n["title"]); - self.url = s(&n["url"]); + let may = |f: Field| self.sync_may(f, read_at); + let (title, draft, state, head, base, labels, requested, reviews, checks, size) = ( + may(Field::Title), + may(Field::Draft), + may(Field::State), + may(Field::Head), + may(Field::Base), + may(Field::Labels), + may(Field::Requested), + may(Field::Reviews), + may(Field::Checks), + may(Field::Size), + ); + if title { + self.title = s(&n["title"]); + self.url = s(&n["url"]); + } let author = login(&n["author"]); if !author.is_empty() { self.author = author.clone(); self.role(&author, "author"); } - self.draft = n["isDraft"].as_bool().unwrap_or(false); - self.status = match n["state"].as_str() { - Some("MERGED") => "merged", - Some("CLOSED") => "closed", - _ => "open", + if draft { + self.draft = n["isDraft"].as_bool().unwrap_or(false); } - .into(); - let head = s(&n["headRefOid"]); - if head != self.head_sha { - self.checks.clear(); + if state { + self.status = match n["state"].as_str() { + Some("MERGED") => "merged", + Some("CLOSED") => "closed", + _ => "open", + } + .into(); + if let Some(t) = [ts(&n["mergedAt"]), ts(&n["closedAt"])] + .into_iter() + .find(|t| *t > 0) + { + self.closed_at = t; + } + if let Some(by) = n["mergedBy"]["login"].as_str() { + self.merged_by = by.to_string(); + } + } + // The node's checks are for the node's head: they land only with it. + let head_sha = s(&n["headRefOid"]); + let checks = checks && (head || head_sha == self.head_sha); + if head { + if head_sha != self.head_sha && checks { + self.checks.clear(); + } + self.new_head(&head_sha); + self.head_ref = s(&n["headRefName"]); + self.head_repo = s(&n["headRepository"]["nameWithOwner"]); + } + if base { + self.base_ref = s(&n["baseRefName"]); } - self.new_head(&head); - self.checks_sha = self.head_sha.clone(); - self.head_ref = s(&n["headRefName"]); - self.head_repo = s(&n["headRepository"]["nameWithOwner"]); - self.base_ref = s(&n["baseRefName"]); self.created_at = ts(&n["createdAt"]); - self.updated_at = ts(&n["updatedAt"]); - if let Some(t) = [ts(&n["mergedAt"]), ts(&n["closedAt"])] - .into_iter() - .find(|t| *t > 0) - { - self.closed_at = t; + self.updated_at = ts(&n["updatedAt"]).max(self.updated_at); + if size { + self.additions = n["additions"].as_u64().unwrap_or(0) as u32; + self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; } - if let Some(by) = n["mergedBy"]["login"].as_str() { - self.merged_by = by.to_string(); + if labels { + self.labels = n["labels"]["nodes"] + .as_array() + .into_iter() + .flatten() + .map(|l| s(&l["name"])) + .collect(); } - self.additions = n["additions"].as_u64().unwrap_or(0) as u32; - self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; - self.labels = n["labels"]["nodes"] - .as_array() - .into_iter() - .flatten() - .map(|l| s(&l["name"])) - .collect(); + if requested { + self.take_node_requests(n); + } + if reviews { + self.take_node_reviews(n); + } + if checks { + self.checks_sha = self.head_sha.clone(); + self.take_node_checks(n, now); + } + } + + /// The review requests the node lists, replacing the record's. + fn take_node_requests(&mut self, n: &Value) { self.requested.clear(); self.requested_teams.clear(); for r in n["reviewRequests"]["nodes"] @@ -1352,8 +1480,11 @@ impl PrRecord { for r in self.requested.clone() { self.role(&r, "requested"); } - // Each person's latest review that took a side, as GitHub has it - // now: a review dismissed or gone leaves the record too. + } + + /// Each person's latest review that took a side, as GitHub has it now: + /// a review dismissed or gone leaves the record too. + fn take_node_reviews(&mut self, n: &Value) { self.reviews.clear(); self.coderhelm_verdict = None; for r in n["latestOpinionatedReviews"]["nodes"] @@ -1386,6 +1517,10 @@ impl PrRecord { } self.role(&who, "reviewer"); } + } + + /// The head's checks the node lists. + fn take_node_checks(&mut self, n: &Value, now: i64) { let rollup = &n["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]; if let Some(list) = rollup["nodes"].as_array() { let partial = rollup["pageInfo"]["hasNextPage"].as_bool() == Some(true); @@ -1510,19 +1645,27 @@ impl PrRecord { self.role(&l, "commenter"); } } - self.review_decision = n["reviewDecision"].as_str().map(str::to_string); - self.decision_at = read_at; - self.conflict = match n["mergeable"].as_str() { - Some("CONFLICTING") => Some(true), - Some("MERGEABLE") => Some(false), - _ => None, - }; - self.merge_state = n["mergeStateStatus"] - .as_str() - .unwrap_or("") - .to_ascii_lowercase(); - self.auto_merge = !n["autoMergeRequest"].is_null(); - self.in_queue = n["isInMergeQueue"].as_bool().unwrap_or(false); + if self.sync_may(Field::ReviewDecision, read_at) { + self.review_decision = n["reviewDecision"].as_str().map(str::to_string); + self.decision_at = read_at; + } + if self.sync_may(Field::Conflict, read_at) { + self.conflict = match n["mergeable"].as_str() { + Some("CONFLICTING") => Some(true), + Some("MERGEABLE") => Some(false), + _ => None, + }; + self.merge_state = n["mergeStateStatus"] + .as_str() + .unwrap_or("") + .to_ascii_lowercase(); + } + if self.sync_may(Field::AutoMerge, read_at) { + self.auto_merge = !n["autoMergeRequest"].is_null(); + } + if self.sync_may(Field::Queue, read_at) { + self.in_queue = n["isInMergeQueue"].as_bool().unwrap_or(false); + } let rule = &n["baseRef"]["branchProtectionRule"]; if rule.is_object() { self.approvals_required = @@ -2360,6 +2503,75 @@ mod tests { assert!(r.decision_fresh()); } + /// A record opened an hour back, then one event at `NOW`; the sync's + /// page was read 30 seconds before that event and written after it. + fn event_after_the_read(event_type: &str, payload: Value) -> PrRecord { + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW - 3600); + assert!(r.apply_event(event_type, &payload, NOW)); + r + } + + #[test] + fn a_queue_event_after_the_read_survives_the_sync() { + let mut enqueued = opened(); + enqueued["action"] = json!("enqueued"); + let mut r = event_after_the_read("pull_request", enqueued); + assert!(r.in_queue); + let mut stale = node("OPEN", "APPROVED"); + stale["isInMergeQueue"] = json!(false); + assert!(r.apply_node(&stale, NOW - 30, NOW + 5)); + assert!(r.in_queue, "the page predates the enqueue"); + // A page read after the event is the authority again. + r.apply_node(&stale, NOW + 60, NOW + 65); + assert!(!r.in_queue); + } + + #[test] + fn an_auto_merge_event_after_the_read_survives_the_sync() { + let mut enabled = opened(); + enabled["action"] = json!("auto_merge_enabled"); + let mut r = event_after_the_read("pull_request", enabled); + assert!(r.auto_merge); + let mut stale = node("OPEN", "APPROVED"); + stale["autoMergeRequest"] = Value::Null; + // Labels the same event carried survive too; the decision, which + // no event wrote, still lands. + stale["labels"] = json!({"nodes": []}); + assert!(r.apply_node(&stale, NOW - 30, NOW + 5)); + assert!(r.auto_merge, "the page predates turning auto-merge on"); + assert_eq!(r.labels, vec!["bookstore"]); + assert_eq!(r.review_decision.as_deref(), Some("APPROVED")); + r.apply_node(&stale, NOW + 60, NOW + 65); + assert!(!r.auto_merge); + } + + #[test] + fn a_review_decision_from_an_event_after_the_read_survives_the_sync() { + let review = json!({"action": "submitted", "pull_request": {"number": 318}, + "review": {"user": {"login": "mara"}, "state": "approved", "commit_id": "aaaaaaa1111111", + "submitted_at": "2026-01-10T11:00:00Z"}}); + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW - 3600); + r.approvals_required = 1; + assert!(r.apply_event("pull_request_review", &review, NOW)); + assert_eq!(r.review_decision.as_deref(), Some("APPROVED")); + let stale = node("OPEN", "REVIEW_REQUIRED"); + assert!(r.apply_node(&stale, NOW - 30, NOW + 5)); + assert_eq!( + r.review_decision.as_deref(), + Some("APPROVED"), + "the page predates the approval" + ); + assert!( + r.reviews.contains_key("mara"), + "and so does its review list" + ); + assert!(r.decision_fresh()); + r.apply_node(&stale, NOW + 60, NOW + 65); + assert_eq!(r.review_decision.as_deref(), Some("REVIEW_REQUIRED")); + } + #[test] fn one_pointer_helper_names_every_pointer() { assert_eq!(