From 48c45e3cc5ed3c7b153567748f745102dab8b5cf Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 22:37:00 -0500 Subject: [PATCH 1/3] The pull request sync reads every repository and keeps pages GitHub answers in part A field the installation's permissions don't cover comes back null with a FORBIDDEN error per node; the sync threw the whole page away and paused the backfill. It now keeps the data beside the errors: refused fields leave the node, so the record keeps what webhooks stored and conversations read as unknown, and the following pages leave them out of the query (a page whose nodes were nulled is read again without them). The sync read only repositories enabled for CoderHelm's work, and repository rows are stored not enabled, so a team with none enabled was never read. It now reads every repository the installation can see. The pull requests page and the overview ask for the team's first read when it never finished (installs from before the view never send an install event), claimed so one ask goes out per ten minutes, and return its progress as first_read (repositories read of all). One INFO line per team says the repositories read, pull requests written and fields unavailable. --- docs/pull-requests.md | 4 +- docs/pull-requests/api_contract.md | 8 +- services/common/src/pr_record.rs | 341 +++++++++++++++++++- services/gateway/src/routes/prs.rs | 61 +++- services/gateway/src/routes/prs_overview.rs | 11 +- services/worker/src/clients/github.rs | 21 ++ services/worker/src/passes/pr_records.rs | 120 ++++++- 7 files changed, 542 insertions(+), 24 deletions(-) diff --git a/docs/pull-requests.md b/docs/pull-requests.md index 7ab21dc7..d1180f5e 100644 --- a/docs/pull-requests.md +++ b/docs/pull-requests.md @@ -7,7 +7,7 @@ Every open pull request in a team's connected repositories, people's as much as 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). +- **Kept honest by a sync** (`services/worker/src/passes/pr_records.rs`): one GraphQL search per organization of every repository the installation can see, enabled for CoderHelm's work or not, CoderHelm's own included; nothing is filtered by author or label. 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). - **Events and the sync never undo each other.** The sync never reopens a record an event closed; each field both write (state, title, draft, head, base, labels, review requests, reviews, review decision, checks, mergeability, auto-merge, the merge queue, size) keeps the time an event last wrote it, and the sync writes that field only when its search was read after that time. A queue, auto-merge or review change that lands while a page is in flight survives the page. The reviews and review requests the sync reads replace the record's lists, so a dismissed review leaves it. A list cut short by its page size is marked partial: a required check that may be on a later page reads as unknown, never as running. The review decision is also worked out at each review and review request event, and bypass and coverage use it only when it is newer than the last review. - **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). @@ -42,5 +42,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 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. +- 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, once at install, and once when the page finds the team's first read never finished (an install from before this view): that ask is claimed so one goes out per ten minutes, and the page shows the read's progress, repositories read of all. 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 4ab3857e..a76571a0 100644 --- a/docs/pull-requests/api_contract.md +++ b/docs/pull-requests/api_contract.md @@ -24,7 +24,8 @@ 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": "..."}], + "first_read": {"reading": true, "repos_read": 3, "repos_total": 7, "done": false}, +"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"}] } @@ -114,8 +115,11 @@ All settings-table rows, `pk` = team id, body JSON in `doc`. Types live in `serv 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. +## First read (`first_read`) +`GET /api/prs` and `GET /api/prs/overview` return `first_read {reading, repos_read, repos_total, done}`: the team's first read of every open pull request in every repository the installation can see (`PRFIRST`, `pr_record::FirstRead`). While `reading`, the page says "reading your repositories (repos_read of repos_total)"; `repos_read` moves an organization at a time. When the read never finished and nothing asked for it in the last ten minutes (an install from before this view), the request asks the worker for it (`PrRecordsSync`), claimed with a conditional write so one ask goes out at a time. + ## 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. +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 repositories the installation can see (every repository row of the team, enabled for CoderHelm's work or not). 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`): diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs index 5175a3a0..486d4f11 100644 --- a/services/common/src/pr_record.rs +++ b/services/common/src/pr_record.rs @@ -1440,7 +1440,10 @@ impl PrRecord { self.additions = n["additions"].as_u64().unwrap_or(0) as u32; self.deletions = n["deletions"].as_u64().unwrap_or(0) as u32; } - if labels { + // A field GitHub refused is absent from the node: what the record + // holds for it stays (`strip_refused`). + let has = |k: &str| n.get(k).is_some(); + if labels && has("labels") { self.labels = n["labels"]["nodes"] .as_array() .into_iter() @@ -1448,10 +1451,10 @@ impl PrRecord { .map(|l| s(&l["name"])) .collect(); } - if requested { + if requested && has("reviewRequests") { self.take_node_requests(n); } - if reviews { + if reviews && has("latestOpinionatedReviews") { self.take_node_reviews(n); } if checks { @@ -1645,11 +1648,12 @@ impl PrRecord { self.role(&l, "commenter"); } } - if self.sync_may(Field::ReviewDecision, read_at) { + let has = |k: &str| n.get(k).is_some(); + if self.sync_may(Field::ReviewDecision, read_at) && has("reviewDecision") { self.review_decision = n["reviewDecision"].as_str().map(str::to_string); self.decision_at = read_at; } - if self.sync_may(Field::Conflict, read_at) { + if self.sync_may(Field::Conflict, read_at) && has("mergeable") { self.conflict = match n["mergeable"].as_str() { Some("CONFLICTING") => Some(true), Some("MERGEABLE") => Some(false), @@ -1660,10 +1664,10 @@ impl PrRecord { .unwrap_or("") .to_ascii_lowercase(); } - if self.sync_may(Field::AutoMerge, read_at) { + if self.sync_may(Field::AutoMerge, read_at) && has("autoMergeRequest") { self.auto_merge = !n["autoMergeRequest"].is_null(); } - if self.sync_may(Field::Queue, read_at) { + if self.sync_may(Field::Queue, read_at) && has("isInMergeQueue") { self.in_queue = n["isInMergeQueue"].as_bool().unwrap_or(false); } let rule = &n["baseRef"]["branchProtectionRule"]; @@ -1682,6 +1686,12 @@ impl PrRecord { .collect(); } let threads = &n["reviewThreads"]; + if !has("reviewThreads") { + // Refused: the conversations are unknown, never "none open". + self.threads_partial = true; + self.synced_at = now; + return; + } let mut open = 0; let mut authors = Vec::new(); for t in threads["nodes"].as_array().into_iter().flatten() { @@ -1883,6 +1893,106 @@ pub const SEARCH_QUERY: &str = "query($q: String!, $after: String) { } }"; +/// Pure: [`SEARCH_QUERY`] without the pull request fields in `omit` (by +/// their name in the answer): the fields GitHub refused this installation +/// are left out of its next pages, so a refused field that would null the +/// whole node never costs a pull request. +pub fn search_query(omit: &std::collections::BTreeSet) -> String { + if omit.is_empty() { + return SEARCH_QUERY.to_string(); + } + let mut out = Vec::new(); + let mut inside = false; + for line in SEARCH_QUERY.lines() { + let t = line.trim_start(); + if t.starts_with("... on PullRequest") { + inside = true; + out.push(line.to_string()); + continue; + } + if !inside || t == "}" { + if t == "}" { + inside = false; + } + out.push(line.to_string()); + continue; + } + let first = t.split([' ', '(', '{']).next().unwrap_or(""); + if t.contains('{') || t.contains('(') { + if !omit.contains(first) { + out.push(line.to_string()); + } + } else { + let indent = &line[..line.len() - t.len()]; + let kept: Vec<&str> = t + .split_whitespace() + .filter(|f| !omit.contains(*f)) + .collect(); + if !kept.is_empty() { + out.push(format!("{indent}{}", kept.join(" "))); + } + } + } + out.join("\n") +} + +/// Pure: a GraphQL answer as its data and its errors. GitHub answers a +/// field the installation's permissions don't cover with null and a +/// `FORBIDDEN` error ("Resource not accessible by integration") beside the +/// rest of the data; that is a partial answer, not a failed one. Only an +/// answer with no data is an error. +pub fn split_graphql(v: Value) -> Result<(Value, Vec), String> { + let errors: Vec = v["errors"].as_array().cloned().unwrap_or_default(); + let data = v["data"].clone(); + if data.is_null() + || data + .as_object() + .is_some_and(|o| o.values().all(Value::is_null)) + { + let msg: Vec<&str> = errors + .iter() + .filter_map(|e| e["message"].as_str()) + .collect(); + return Err(if msg.is_empty() { + "GitHub answered with no data".into() + } else { + msg.join("; ") + }); + } + Ok((data, errors)) +} + +/// Takes out of the search's nodes each field GitHub refused (its error's +/// path, `search.nodes..`), so the field reads as absent, which +/// [`PrRecord::apply_node`] keeps as it was, rather than as null, which +/// would read as empty. Returns the refused fields by name, for the log. +pub fn strip_refused(data: &mut Value, errors: &[Value]) -> std::collections::BTreeSet { + let mut refused = std::collections::BTreeSet::new(); + for e in errors { + let Some(path) = e["path"].as_array() else { + continue; + }; + let at = |i: usize| path.get(i); + if at(0).and_then(Value::as_str) != Some("search") + || at(1).and_then(Value::as_str) != Some("nodes") + { + continue; + } + let (Some(i), Some(field)) = (at(2).and_then(Value::as_u64), at(3).and_then(Value::as_str)) + else { + continue; + }; + if let Some(node) = data["search"]["nodes"] + .get_mut(i as usize) + .and_then(Value::as_object_mut) + { + node.remove(field); + } + refused.insert(field.to_string()); + } + refused +} + /// 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; @@ -1953,6 +2063,118 @@ pub async fn get_doc( .and_then(|d| serde_json::from_str(d).ok())) } +/// The settings-table row of a team's first read of its pull requests. +pub const FIRST_READ_SK: &str = "PRFIRST"; +/// How long an ask for the first read holds before the page may ask again +/// (a lost message, or the budget held the read part way). +pub const FIRST_READ_RETRY_SECS: i64 = 600; + +/// A team's first read of every open pull request in the repositories the +/// installation can see: asked by the pull requests page when it finds the +/// read never finished, written by the worker as each organization's search +/// is read to its end, so the page can say how far it is. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct FirstRead { + pub asked_at: i64, + pub repos_total: u32, + pub repos_read: u32, + pub done: bool, + pub updated_at: i64, +} + +impl FirstRead { + /// What the API answers: `reading` until the read finished. + pub fn json(&self) -> Value { + serde_json::json!({ + "reading": !self.done, + "repos_read": self.repos_read.min(self.repos_total), + "repos_total": self.repos_total, + "done": self.done, + }) + } +} + +/// Pure: the page should ask for the first read now: it never finished, and +/// no ask or progress is newer than [`FIRST_READ_RETRY_SECS`]. +pub fn first_read_due(f: Option<&FirstRead>, now: i64) -> bool { + match f { + None => true, + Some(f) => !f.done && now - f.asked_at.max(f.updated_at) >= FIRST_READ_RETRY_SECS, + } +} + +pub async fn load_first_read( + dynamo: &DynamoClient, + table: &str, + team_id: &str, +) -> Result, Err> { + get_doc(dynamo, table, team_id, FIRST_READ_SK).await +} + +/// Claim the ask: a conditional write that only one caller wins per +/// [`FIRST_READ_RETRY_SECS`], so two pages (or two gateways) never ask +/// twice. True when this caller should send the read. +pub async fn claim_first_read( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + prev: Option<&FirstRead>, + now: i64, +) -> Result { + let mut f = prev.cloned().unwrap_or_default(); + f.asked_at = now; + let r = dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(FIRST_READ_SK.into())) + .item("doc", AttributeValue::S(serde_json::to_string(&f)?)) + .item("touched", AttributeValue::N(now.to_string())) + .item("done", AttributeValue::Bool(false)) + .condition_expression("attribute_not_exists(sk) OR (done = :no AND touched < :cut)") + .expression_attribute_values(":no", AttributeValue::Bool(false)) + .expression_attribute_values( + ":cut", + AttributeValue::N((now - FIRST_READ_RETRY_SECS + 1).to_string()), + ) + .send() + .await; + match r { + Ok(_) => Ok(true), + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()) => + { + Ok(false) + } + Err(e) => Err(e.into()), + } +} + +/// The worker's progress on the first read. +pub async fn save_first_read( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + f: &FirstRead, +) -> Result<(), Err> { + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(FIRST_READ_SK.into())) + .item("doc", AttributeValue::S(serde_json::to_string(f)?)) + .item( + "touched", + AttributeValue::N(f.updated_at.max(f.asked_at).to_string()), + ) + .item("done", AttributeValue::Bool(f.done)) + .send() + .await?; + Ok(()) +} + pub async fn load( dynamo: &DynamoClient, table: &str, @@ -2572,6 +2794,111 @@ mod tests { assert_eq!(r.review_decision.as_deref(), Some("REVIEW_REQUIRED")); } + /// GitHub's answer when the installation may not read one field: the + /// field is null in each node, with one FORBIDDEN error per node. + fn forbidden(nodes: Vec, field: &str) -> Value { + let errors: Vec = (0..nodes.len()) + .map(|i| { + json!({"type": "FORBIDDEN", "path": ["search", "nodes", i, field], + "extensions": {"saml_failure": false}, "locations": [{"line": 1, "column": 1}], + "message": "Resource not accessible by integration"}) + }) + .collect(); + json!({"data": {"search": {"issueCount": nodes.len(), + "pageInfo": {"hasNextPage": false, "endCursor": null}, "nodes": nodes}}, + "errors": errors}) + } + + #[test] + fn a_refused_field_keeps_the_page_and_reads_as_unknown() { + let mut n = node("OPEN", "APPROVED"); + n["reviewThreads"] = Value::Null; + n["labels"] = Value::Null; + n["repository"] = json!({"nameWithOwner": "acme/web"}); + let answer = forbidden(vec![n.clone(), n], "reviewThreads"); + let (mut data, errors) = split_graphql(answer).expect("a partial answer is an answer"); + assert_eq!(errors.len(), 2); + let refused = strip_refused(&mut data, &errors); + assert_eq!( + refused.into_iter().collect::>(), + vec!["reviewThreads"] + ); + let nodes = data["search"]["nodes"].as_array().unwrap(); + assert_eq!(nodes.len(), 2, "no pull request is dropped"); + + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW - 3600); + r.open_threads = 2; + assert!(r.apply_node(&nodes[0], NOW, NOW)); + assert_eq!(r.title, "Round cart totals", "the rest of the node lands"); + assert_eq!(r.open_threads, 2, "a refused field keeps what was stored"); + assert!(r.threads_partial, "and reads as unknown"); + 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 an_answer_with_no_data_is_still_an_error() { + let e = split_graphql(json!({"data": null, "errors": [{"type": "FORBIDDEN", + "message": "Resource not accessible by integration"}]})) + .unwrap_err(); + assert!(e.contains("Resource not accessible")); + assert!(split_graphql(json!({"data": {"search": null}})).is_err()); + } + + #[test] + fn the_next_pages_leave_refused_fields_out() { + let omit: std::collections::BTreeSet = + ["commits", "reviewRequests", "reviewDecision"] + .into_iter() + .map(String::from) + .collect(); + let q = search_query(&omit); + assert!(!q.contains("statusCheckRollup")); + assert!(!q.contains("reviewRequests(")); + assert!(!q.contains("reviewDecision")); + assert!(q.contains("mergeable mergeStateStatus"), "{q}"); + assert!(q.contains("latestOpinionatedReviews")); + assert!(crate::live::graphql::check_read_only(&q).is_ok()); + assert_eq!(q.matches('{').count(), q.matches('}').count()); + assert_eq!(search_query(&Default::default()), SEARCH_QUERY); + } + + #[test] + fn the_first_read_is_asked_until_it_finishes_and_never_twice_at_once() { + assert!(first_read_due(None, NOW), "never read: ask now"); + let asked = FirstRead { + asked_at: NOW, + ..Default::default() + }; + assert!(!first_read_due(Some(&asked), NOW + 60), "one ask at a time"); + assert!( + first_read_due(Some(&asked), NOW + FIRST_READ_RETRY_SECS), + "a lost ask is made again" + ); + let reading = FirstRead { + asked_at: NOW, + repos_total: 5, + repos_read: 2, + updated_at: NOW + FIRST_READ_RETRY_SECS - 1, + ..Default::default() + }; + assert!( + !first_read_due(Some(&reading), NOW + FIRST_READ_RETRY_SECS), + "progress counts as alive" + ); + assert_eq!(reading.json()["repos_read"], 2); + assert_eq!(reading.json()["reading"], true); + let done = FirstRead { + done: true, + ..reading + }; + assert!(!first_read_due(Some(&done), NOW + 86_400)); + assert_eq!(done.json()["reading"], false); + } + #[test] fn one_pointer_helper_names_every_pointer() { assert_eq!( diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 7041aed0..104c39a8 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -653,9 +653,13 @@ pub async fn list_prs( p.counts = counts; p }; - let backfill = backfill_progress(&state, &claims.team_id).await; + let (backfill, first) = futures::join!( + backfill_progress(&state, &claims.team_id), + first_read(&state, &claims.team_id) + ); Ok(Json(json!({ "backfill": backfill, + "first_read": first, "prs": page.rows, "total": page.total, "next": page.next, @@ -714,6 +718,61 @@ pub fn backfill_json(items: &[Item]) -> Vec { .collect() } +/// The team's first read of its open pull requests, as the page shows it +/// ("reading your repositories, n of m"). When it never finished and no ask +/// is in flight (an install from before the view, whose install event came +/// long ago), it asks the worker for it now: claimed with a conditional +/// write so one ask goes out per ten minutes however many pages poll, and +/// the read itself spends the shared budget like the hourly sweep. +pub(crate) async fn first_read(state: &AppState, team_id: &str) -> Value { + let table = &state.config.settings_table_name; + let now = now(); + let prev = match pr_record::load_first_read(&state.dynamo, table, team_id).await { + Ok(f) => f, + Err(e) => { + warn!(team_id, error = %e, "Pull requests: first read not loaded"); + return Value::Null; + } + }; + if pr_record::first_read_due(prev.as_ref(), now) { + ask_first_read(state, team_id, prev.as_ref(), now).await; + } + let shown = prev.unwrap_or(pr_record::FirstRead { + asked_at: now, + ..Default::default() + }); + shown.json() +} + +async fn ask_first_read( + state: &AppState, + team_id: &str, + prev: Option<&pr_record::FirstRead>, + now: i64, +) { + let Ok(installation_id) = super::api::get_team_installation_id(state, team_id).await else { + return; + }; + let table = &state.config.settings_table_name; + match pr_record::claim_first_read(&state.dynamo, table, team_id, prev, now).await { + Ok(true) => {} + Ok(false) => return, + Err(e) => { + warn!(team_id, error = %e, "Pull requests: first read not claimed"); + return; + } + } + let msg = crate::models::WorkerMessage::PrRecordsSync(common::messages::PrRecordsSyncMessage { + team_id: team_id.to_string(), + installation_id, + }); + if let Err(e) = + super::github_webhook::send_to_queue(state, &state.config.ticket_queue_url, &msg).await + { + warn!(team_id, error = ?e, "Pull requests: first read not asked"); + } +} + 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), diff --git a/services/gateway/src/routes/prs_overview.rs b/services/gateway/src/routes/prs_overview.rs index 8880c9a2..8dd15631 100644 --- a/services/gateway/src/routes/prs_overview.rs +++ b/services/gateway/src/routes/prs_overview.rs @@ -98,8 +98,13 @@ pub async fn get_overview( ), ); let at = Instant::now(); + // Outside the cache: the first read is asked, and its progress shown, on + // every visit. + let first = super::prs::first_read(&state, team_id).await; if let Some(hit) = OVERVIEW.get(&key, at) { - return Ok(Json((*hit).clone())); + let mut out = (*hit).clone(); + out["first_read"] = first; + return Ok(Json(out)); } let now = chrono::Utc::now().timestamp(); @@ -229,7 +234,9 @@ pub async fn get_overview( out["sources"] = json!(sources); let out = Arc::new(out); OVERVIEW.put(key, out.clone(), OVERVIEW_TTL, at); - Ok(Json((*out).clone())) + let mut out = (*out).clone(); + out["first_read"] = first; + Ok(Json(out)) } #[cfg(test)] diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 7e873788..286e5890 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -4796,6 +4796,27 @@ impl GitHubClient { Ok(v["data"].clone()) } + /// [`Self::graphql_read`] that keeps what GitHub answered beside its + /// errors: a field the installation's permissions don't cover comes + /// back null with a `FORBIDDEN` error naming its path, and the rest of + /// the page is still good. The errors are returned with the data; only + /// an answer with no data at all is an error. + pub async fn graphql_read_partial( + &self, + query: &str, + variables: serde_json::Value, + ) -> Result<(serde_json::Value, Vec), Box> + { + let read = common::live::graphql::check_read_only(query).map_err(|e| e.message)?; + let v = self + .post( + &format!("{API_BASE}/graphql"), + &serde_json::json!({ "query": read.text, "variables": variables }), + ) + .await?; + common::pr_record::split_graphql(v).map_err(Into::into) + } + // ─── Pull requests ───────────────────────────────────────── /// Get a single pull request. diff --git a/services/worker/src/passes/pr_records.rs b/services/worker/src/passes/pr_records.rs index 3d6a4026..db6bfd5d 100644 --- a/services/worker/src/passes/pr_records.rs +++ b/services/worker/src/passes/pr_records.rs @@ -5,8 +5,12 @@ //! 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 +//! removes the records of pull requests no longer open. It reads every +//! repository the installation can see (the team's repository rows, enabled +//! for CoderHelm's work or not; CoderHelm's own included), with no filter by +//! author or label. It runs when the app is installed or repositories are +//! added, when the pull requests page finds the team's first read never +//! finished (`PrRecordsSync`, claimed once per ten minutes), and on the //! sweep tick at most once an hour per team. //! //! Bounds: [`pr_record::MAX_PAGES`] pages of 30 per organization, each one @@ -17,7 +21,7 @@ use std::collections::HashSet; use common::github_budget::caller as who; use common::pr_record; -use serde_json::json; +use serde_json::{json, Value}; use tracing::{info, warn}; use crate::clients::github::GitHubClient; @@ -121,7 +125,7 @@ pub async fn sync_message(state: &WorkerState, msg: &common::messages::PrRecords written = report.written, removed = report.removed, pages = report.pages, - "Pull request records read at install" + "Pull request records read (install or first read)" ); } @@ -138,6 +142,12 @@ pub fn owners_of(repos: &[String]) -> (Vec, HashSet) { (owners, keep) } +/// Pure: how many of the kept repositories belong to `owner`. +pub fn repos_of(keep: &HashSet, owner: &str) -> u32 { + let prefix = format!("{}/", owner.to_ascii_lowercase()); + keep.iter().filter(|r| r.starts_with(&prefix)).count() as u32 +} + async fn sync_team( state: &WorkerState, team_id: &str, @@ -145,16 +155,43 @@ async fn sync_team( gate: &mut SweepGate, report: &mut SweepReport, ) { + // Every repository the installation can see, not only those enabled for + // CoderHelm's work: the view is of the team's pull requests, all of them. 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() { + info!( + team_id, + repos = 0, + "Pull request sync: team read (no repositories stored for the team)" + ); return; } + let table = &state.config.settings_table_name; + // The first read's progress, for the page: repositories read of all. + let mut first = match pr_record::load_first_read(&state.dynamo, table, team_id).await { + Ok(f) => f.unwrap_or_default(), + Err(e) => { + warn!(team_id, error = %e, "Pull request sync: first read not loaded"); + pr_record::FirstRead::default() + } + }; + let tracking = !first.done; + if tracking { + first.repos_total = keep.len() as u32; + first.repos_read = 0; + first.updated_at = chrono::Utc::now().timestamp(); + let _ = pr_record::save_first_read(&state.dynamo, table, team_id, &first).await; + } + let mut all_complete = true; + // Fields GitHub refused this installation (its permissions), left out of + // the following pages; logged once per team. + let mut refused: std::collections::BTreeSet = Default::default(); + let written_before = report.written; let github = match GitHubClient::new( &state.secrets.github_app_id, &state.secrets.github_private_key, @@ -167,7 +204,6 @@ async fn sync_team( return; } }; - let table = &state.config.settings_table_name; for owner in owners.clone() { let mut seen: HashSet = HashSet::new(); let mut complete = false; @@ -182,8 +218,22 @@ async fn sync_team( // 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, + let query = pr_record::search_query(&refused); + let data = match github.graphql_read_partial(&query, vars).await { + Ok((mut d, errors)) => { + let lost = pr_record::strip_refused(&mut d, &errors); + let new: Vec = lost.difference(&refused).cloned().collect(); + let nulled = d["search"]["nodes"] + .as_array() + .is_some_and(|n| n.iter().any(Value::is_null)); + refused.extend(lost); + // A refused field that nulled whole pull requests: the + // page is read again without it (once per new field). + if !new.is_empty() && nulled { + continue; + } + d + } // A personal account's repositories are searched by user. Err(_) if as_org && page == 0 => { as_org = false; @@ -230,8 +280,14 @@ async fn sync_team( after = info["endCursor"].as_str().map(str::to_string); } if !complete { + all_complete = false; continue; } + if tracking { + first.repos_read += repos_of(&keep, &owner); + first.updated_at = chrono::Utc::now().timestamp(); + let _ = pr_record::save_first_read(&state.dynamo, table, team_id, &first).await; + } // 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 { @@ -258,6 +314,23 @@ async fn sync_team( } } } + info!( + team_id, + repos = keep.len(), + organizations = owners.len(), + written = report.written - written_before, + complete = all_complete, + fields_unavailable = %refused.iter().cloned().collect::>().join(","), + "Pull request sync: team read" + ); + if tracking && all_complete { + first.done = true; + first.repos_read = first.repos_total; + first.updated_at = chrono::Utc::now().timestamp(); + if let Err(e) = pr_record::save_first_read(&state.dynamo, table, team_id, &first).await { + warn!(team_id, error = %e, "Pull request sync: first read not marked done"); + } + } // 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 { @@ -314,6 +387,7 @@ async fn backfill_owner( let today = chrono::Utc::now().format("%Y-%m-%d").to_string(); let mut as_org = true; let mut pages = 0; + let mut refused: std::collections::BTreeSet = Default::default(); while pages < CLOSED_PAGES_PER_SWEEP { let (from, to) = if b.done { if b.reconciled_to == today && b.cursor.is_none() { @@ -335,8 +409,22 @@ async fn backfill_owner( } 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, + let data = match github + .graphql_read_partial(&pr_record::search_query(&refused), vars) + .await + { + Ok((mut d, errors)) => { + let lost = pr_record::strip_refused(&mut d, &errors); + let new = lost.iter().any(|f| !refused.contains(f)); + let nulled = d["search"]["nodes"] + .as_array() + .is_some_and(|n| n.iter().any(Value::is_null)); + refused.extend(lost); + if new && nulled { + continue; + } + d + } Err(_) if as_org && pages == 0 && b.cursor.is_none() => { as_org = false; continue; @@ -409,4 +497,16 @@ mod tests { assert!(keep.contains("acme/web")); assert!(!keep.contains("acme/infra")); } + + #[test] + fn the_first_read_counts_repositories_by_organization() { + let (_, keep) = owners_of(&[ + "CoderHelm/web".to_string(), + "coderhelm/api".to_string(), + "octocat/bookstore".to_string(), + ]); + assert_eq!(repos_of(&keep, "CoderHelm"), 2); + assert_eq!(repos_of(&keep, "octocat"), 1); + assert_eq!(repos_of(&keep, "octo"), 0, "a prefix of a name is not it"); + } } From fb03a3c11f04c25084518b469dfd1e21605859a7 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 23:00:42 -0500 Subject: [PATCH 2/3] Test both readings of conversations a refused field leaves Two open conversations already stored still hold the merge; none known reads as unknown. --- services/common/src/pr_record.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs index 486d4f11..728dab63 100644 --- a/services/common/src/pr_record.rs +++ b/services/common/src/pr_record.rs @@ -2835,6 +2835,10 @@ mod tests { assert!(r.threads_partial, "and reads as unknown"); r.threads_required = true; r.required_checks.clear(); + // Two known open still hold it; none known is unknown, never clear. + let n = pr_needs::decide("acme/web", &r.facts()); + assert_eq!(n.state, pr_needs::State::OpenThreads, "{n:?}"); + r.open_threads = 0; let n = pr_needs::decide("acme/web", &r.facts()); assert_eq!(n.state, pr_needs::State::Unknown, "{n:?}"); } From 142735e3523d9660872c6e20de412b46046d81dc Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 6 Dec 2026 01:49:24 -0500 Subject: [PATCH 3/3] A listing GitHub answered in part never prunes, and a first read with nothing to read ends A page with a pull request GitHub returned as null, or an error that names no single refused field, no longer counts the listing complete: those pull requests are read from the REST list of each repository's open pull requests, and records are removed only when the listing is whole. The history backfill pauses on such a page instead of passing the window over. A team with no repositories stored, or whose GitHub can't be reached, ends its first read with the reason, so the page says it rather than reading and asking again every ten minutes. --- docs/pull-requests/api_contract.md | 6 +- services/common/src/pr_record.rs | 119 ++++++++++++++++++++- services/gateway/src/routes/prs.rs | 10 +- services/worker/src/passes/pr_records.rs | 126 ++++++++++++++++++++++- 4 files changed, 250 insertions(+), 11 deletions(-) diff --git a/docs/pull-requests/api_contract.md b/docs/pull-requests/api_contract.md index a76571a0..e62dcbad 100644 --- a/docs/pull-requests/api_contract.md +++ b/docs/pull-requests/api_contract.md @@ -24,8 +24,8 @@ 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", - "first_read": {"reading": true, "repos_read": 3, "repos_total": 7, "done": false}, -"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": "..."}], + "first_read": {"reading": true, "repos_read": 3, "repos_total": 7, "done": false, "outcome": null}, + "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"}] } @@ -116,7 +116,7 @@ All settings-table rows, `pk` = team id, body JSON in `doc`. Types live in `serv Weekly counts are the 7 days to the snapshot. `pr_history::snapshots_of(team, scope, since_day)` reads them oldest first. ## First read (`first_read`) -`GET /api/prs` and `GET /api/prs/overview` return `first_read {reading, repos_read, repos_total, done}`: the team's first read of every open pull request in every repository the installation can see (`PRFIRST`, `pr_record::FirstRead`). While `reading`, the page says "reading your repositories (repos_read of repos_total)"; `repos_read` moves an organization at a time. When the read never finished and nothing asked for it in the last ten minutes (an install from before this view), the request asks the worker for it (`PrRecordsSync`), claimed with a conditional write so one ask goes out at a time. +`GET /api/prs` and `GET /api/prs/overview` return `first_read {reading, repos_read, repos_total, done, outcome}`: the team's first read of every open pull request in every repository the installation can see (`PRFIRST`, `pr_record::FirstRead`). While `reading`, the page says "reading your repositories (repos_read of repos_total)"; `repos_read` moves an organization at a time. A read with nothing to read ends done with `outcome` saying why (`no repositories to read`, `GitHub is not connected`), and the page says that instead of reading. A page GitHub answered only in part (a pull request returned null, or an error not naming one refused field) never counts the listing complete: those pull requests are read from the REST list of each repository's open pull requests, and nothing is removed unless the listing is whole. When the read never finished and nothing asked for it in the last ten minutes (an install from before this view), the request asks the worker for it (`PrRecordsSync`), claimed with a conditional write so one ask goes out at a time. ## 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 repositories the installation can see (every repository row of the team, enabled for CoderHelm's work or not). 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. diff --git a/services/common/src/pr_record.rs b/services/common/src/pr_record.rs index 728dab63..a51ad0b6 100644 --- a/services/common/src/pr_record.rs +++ b/services/common/src/pr_record.rs @@ -1373,6 +1373,19 @@ impl PrRecord { true } + /// One pull request from GitHub's REST list of open pull requests, read + /// at `read_at`: what fills a pull request the search answered as null. + /// Never reopens a closed record, and leaves a record an event wrote + /// after the read as it is. False when it changed nothing. + pub fn apply_rest_pr(&mut self, pr: &Value, read_at: i64) -> bool { + if self.known && (!self.is_open() || self.event_at > read_at) { + return false; + } + // Stamped at 0: a list read is not an event. + self.take_pr(pr, 0); + self.known + } + /// What events also carry: identity, state, head, labels, requests, /// each person's latest review and the checks; each only when no event /// wrote it after the search was read. @@ -2081,20 +2094,60 @@ pub struct FirstRead { pub repos_read: u32, pub done: bool, pub updated_at: i64, + /// Why it ended with nothing read, in words the page shows ("no + /// repositories to read", "GitHub is not connected"); empty when it read. + pub outcome: String, } +/// The first read's ending when the team has no repositories stored. +pub const NO_REPOSITORIES: &str = "no repositories to read"; +/// The first read's ending when CoderHelm can't reach the team's GitHub. +pub const NOT_CONNECTED: &str = "GitHub is not connected"; + impl FirstRead { - /// What the API answers: `reading` until the read finished. + /// A read that ended with nothing to read: done, so the page says why + /// and stops asking, rather than reading forever. + pub fn ended(why: &str, now: i64) -> FirstRead { + FirstRead { + asked_at: now, + done: true, + updated_at: now, + outcome: why.to_string(), + ..Default::default() + } + } + + /// What the API answers: `reading` until the read finished, and why it + /// ended with nothing read when it did. pub fn json(&self) -> Value { serde_json::json!({ "reading": !self.done, "repos_read": self.repos_read.min(self.repos_total), "repos_total": self.repos_total, "done": self.done, + "outcome": (!self.outcome.is_empty()).then_some(&self.outcome), }) } } +/// Pure: a search page GitHub answered whole: no pull request came back +/// null, and every error names one field of one node (a refused field, +/// already taken out by [`strip_refused`], its node kept). Anything else +/// means pull requests may be missing from the page, so the listing is not +/// complete and nothing may be pruned from it. +pub fn page_whole(data: &Value, errors: &[Value]) -> bool { + let nulls = data["search"]["nodes"] + .as_array() + .is_some_and(|n| n.iter().any(Value::is_null)); + let unexplained = errors.iter().any(|e| { + let p = e["path"].as_array(); + !p.is_some_and(|p| { + p.len() >= 4 && p[0] == "search" && p[1] == "nodes" && p[2].is_u64() && p[3].is_string() + }) + }); + !nulls && !unexplained +} + /// Pure: the page should ask for the first read now: it never finished, and /// no ask or progress is newer than [`FIRST_READ_RETRY_SECS`]. pub fn first_read_due(f: Option<&FirstRead>, now: i64) -> bool { @@ -2843,6 +2896,70 @@ mod tests { assert_eq!(n.state, pr_needs::State::Unknown, "{n:?}"); } + #[test] + fn a_page_with_a_null_pull_request_is_never_whole() { + let mut n = node("OPEN", "APPROVED"); + n["reviewThreads"] = Value::Null; + // A refused field, its node kept: whole once the field is taken out. + let (mut d, errors) = split_graphql(forbidden(vec![n.clone()], "reviewThreads")).unwrap(); + strip_refused(&mut d, &errors); + assert!(page_whole(&d, &errors)); + // A node GitHub nulled (a timeout, a limit, a non-null field refused). + let nulled = json!({"data": {"search": {"pageInfo": {"hasNextPage": false}, + "nodes": [n, null]}}, + "errors": [{"type": "FORBIDDEN", "path": ["search", "nodes", 1, "commits"], + "message": "Resource not accessible by integration"}]}); + let (mut d, errors) = split_graphql(nulled).unwrap(); + strip_refused(&mut d, &errors); + assert!( + !page_whole(&d, &errors), + "a null pull request may be missing" + ); + // An error that names no node's field. + let odd = json!({"data": {"search": {"nodes": []}}, + "errors": [{"type": "MAX_NODE_LIMIT_EXCEEDED", "message": "too many"}]}); + let (d, errors) = split_graphql(odd).unwrap(); + assert!(!page_whole(&d, &errors)); + } + + #[test] + fn the_rest_list_fills_a_pull_request_but_never_undoes_one() { + let pr = opened()["pull_request"].clone(); + let mut r = PrRecord::new("acme/web", 318); + assert!(r.apply_rest_pr(&pr, NOW)); + assert!(r.known && r.is_open()); + assert_eq!(r.requested, vec!["mara"]); + assert!( + r.sync_may(Field::Title, NOW + 1), + "a list read is not an event" + ); + // Closed by an event: the open list never reopens it. + let mut closed = opened(); + closed["action"] = json!("closed"); + closed["pull_request"]["state"] = json!("closed"); + r.apply_event("pull_request", &closed, NOW + 10); + assert!(!r.apply_rest_pr(&pr, NOW + 20)); + assert_eq!(r.status, "closed"); + // An event after the list was read wins. + let mut r = PrRecord::new("acme/web", 318); + r.apply_event("pull_request", &opened(), NOW); + assert!(!r.apply_rest_pr(&pr, NOW - 30)); + } + + #[test] + fn a_first_read_with_nothing_to_read_ends_and_says_why() { + let f = FirstRead::ended(NO_REPOSITORIES, NOW); + assert!(!first_read_due(Some(&f), NOW + 86_400), "never asked again"); + let j = f.json(); + assert_eq!(j["reading"], false, "never shown as reading"); + assert_eq!(j["outcome"], NO_REPOSITORIES); + assert_eq!( + FirstRead::ended(NOT_CONNECTED, NOW).json()["outcome"], + NOT_CONNECTED + ); + assert!(FirstRead::default().json()["outcome"].is_null()); + } + #[test] fn an_answer_with_no_data_is_still_an_error() { let e = split_graphql(json!({"data": null, "errors": [{"type": "FORBIDDEN", diff --git a/services/gateway/src/routes/prs.rs b/services/gateway/src/routes/prs.rs index 104c39a8..5f1b8433 100644 --- a/services/gateway/src/routes/prs.rs +++ b/services/gateway/src/routes/prs.rs @@ -735,7 +735,11 @@ pub(crate) async fn first_read(state: &AppState, team_id: &str) -> Value { } }; if pr_record::first_read_due(prev.as_ref(), now) { - ask_first_read(state, team_id, prev.as_ref(), now).await; + let Ok(installation_id) = super::api::get_team_installation_id(state, team_id).await else { + // Nothing to read with: said, never shown as reading. + return pr_record::FirstRead::ended(pr_record::NOT_CONNECTED, now).json(); + }; + ask_first_read(state, team_id, installation_id, prev.as_ref(), now).await; } let shown = prev.unwrap_or(pr_record::FirstRead { asked_at: now, @@ -747,12 +751,10 @@ pub(crate) async fn first_read(state: &AppState, team_id: &str) -> Value { async fn ask_first_read( state: &AppState, team_id: &str, + installation_id: u64, prev: Option<&pr_record::FirstRead>, now: i64, ) { - let Ok(installation_id) = super::api::get_team_installation_id(state, team_id).await else { - return; - }; let table = &state.config.settings_table_name; match pr_record::claim_first_read(&state.dynamo, table, team_id, prev, now).await { Ok(true) => {} diff --git a/services/worker/src/passes/pr_records.rs b/services/worker/src/passes/pr_records.rs index db6bfd5d..b08c0cb1 100644 --- a/services/worker/src/passes/pr_records.rs +++ b/services/worker/src/passes/pr_records.rs @@ -163,15 +163,16 @@ async fn sync_team( .map(|r| r.full_name) .collect(); let (owners, keep) = owners_of(&repos); + let table = &state.config.settings_table_name; if owners.is_empty() { info!( team_id, repos = 0, "Pull request sync: team read (no repositories stored for the team)" ); + end_first_read(state, team_id, pr_record::NO_REPOSITORIES).await; return; } - let table = &state.config.settings_table_name; // The first read's progress, for the page: repositories read of all. let mut first = match pr_record::load_first_read(&state.dynamo, table, team_id).await { Ok(f) => f.unwrap_or_default(), @@ -180,8 +181,11 @@ async fn sync_team( pr_record::FirstRead::default() } }; - let tracking = !first.done; + // A read that ended with nothing to read starts again once there is. + let tracking = !first.done || !first.outcome.is_empty(); if tracking { + first.done = false; + first.outcome.clear(); first.repos_total = keep.len() as u32; first.repos_read = 0; first.updated_at = chrono::Utc::now().timestamp(); @@ -201,12 +205,17 @@ async fn sync_team( Ok(g) => g, Err(e) => { warn!(team_id, error = %e, "Pull request sync: no GitHub client"); + if tracking { + end_first_read(state, team_id, pr_record::NOT_CONNECTED).await; + } return; } }; for owner in owners.clone() { let mut seen: HashSet = HashSet::new(); let mut complete = false; + // Every page answered whole: only then may the listing prune. + let mut whole = true; let mut after: Option = None; let mut as_org = true; let mut page = 0; @@ -232,6 +241,9 @@ async fn sync_team( if !new.is_empty() && nulled { continue; } + if !pr_record::page_whole(&d, &errors) { + whole = false; + } d } // A personal account's repositories are searched by user. @@ -279,7 +291,30 @@ async fn sync_team( } after = info["endCursor"].as_str().map(str::to_string); } - if !complete { + // Pull requests the search answered as null are read from GitHub's + // REST list of each repository's open pull requests instead. + if complete && !whole { + whole = rest_fill( + state, + team_id, + installation_id, + &github, + &owner, + &keep, + gate, + &mut seen, + report, + ) + .await; + } + if !complete || !whole { + warn!( + team_id, + owner = %owner, + complete, + whole, + "Pull request sync: listing not whole, nothing removed" + ); all_complete = false; continue; } @@ -348,6 +383,80 @@ async fn sync_team( } } +/// The first read ended with nothing to read: done, with why, so the page +/// says it and stops asking. +async fn end_first_read(state: &WorkerState, team_id: &str, why: &str) { + let table = &state.config.settings_table_name; + let f = pr_record::FirstRead::ended(why, chrono::Utc::now().timestamp()); + if let Err(e) = pr_record::save_first_read(&state.dynamo, table, team_id, &f).await { + warn!(team_id, error = %e, "Pull request sync: first read's end not written"); + } +} + +/// Reads each of `owner`'s repositories' open pull requests from the REST +/// list (up to 300 each), for pull requests the search answered as null; +/// each one is applied like a page's node and counted as seen. True when +/// every repository was read in full, so the listing is whole. +#[allow(clippy::too_many_arguments)] +async fn rest_fill( + state: &WorkerState, + team_id: &str, + installation_id: u64, + github: &GitHubClient, + owner: &str, + keep: &HashSet, + gate: &mut SweepGate, + seen: &mut HashSet, + report: &mut SweepReport, +) -> bool { + let table = &state.config.settings_table_name; + let prefix = format!("{}/", owner.to_ascii_lowercase()); + let mut all = true; + for full in keep.iter().filter(|r| r.starts_with(&prefix)) { + let Some((o, name)) = full.split_once('/') else { + continue; + }; + if !gate.allows(state, installation_id, 1).await { + return false; + } + let read_at = chrono::Utc::now().timestamp(); + let prs = match github.list_open_pulls_all(o, name, 3).await { + Ok(p) => p, + Err(e) => { + warn!(team_id, repo = %full, error = %e, "Pull request sync: REST list failed"); + all = false; + continue; + } + }; + if prs.len() >= 300 { + all = false; + } + let now = chrono::Utc::now().timestamp(); + for pr in &prs { + let Some(number) = pr["number"].as_u64() else { + continue; + }; + let repo = pr["base"]["repo"]["full_name"].as_str().unwrap_or(full); + seen.insert(format!("{}#{number}", repo.to_ascii_lowercase())); + match pr_record::update(&state.dynamo, table, team_id, repo, number, now, |r| { + r.apply_rest_pr(pr, read_at) + }) + .await + { + 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 filled") + } + } + } + } + all +} + /// 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 @@ -423,6 +532,17 @@ async fn backfill_owner( if new && nulled { continue; } + if !pr_record::page_whole(&d, &errors) { + // Pull requests may be missing from it: the window is + // read again next sweep, never passed over. + b.paused_until = now + 3600; + b.paused_why = "GitHub answered only part of a page".into(); + warn!( + team_id, + owner, "History backfill paused: a page answered in part" + ); + break; + } d } Err(_) if as_org && pages == 0 && b.cursor.is_none() => {