From 87a2329f606b2364c57d38127a8f8589ec41c837 Mon Sep 17 00:00:00 2001 From: Tryanks Date: Sun, 25 Oct 2026 03:29:30 +0800 Subject: [PATCH] Hold a watch's "checks passed" until every required check has reported GitHub creates a job that waits on others only once they finish. Since #941 CI's required platform checks are such jobs, so for minutes at a time the head showed every required check reported so far as passed while macOS arm64 and Windows x64 did not exist yet, and the watch woke the agent mid-run. When the checks read would pass, the GitHub detail read now adds the checks the base branch requires but that have not reported, as pending: those of its rulesets come with the GraphQL detail, those of its branch protection from REST, which any reader may see (GraphQL shows them to admins alone). Core owns the gate both use. --- crates/core/src/pull_request_watch.rs | 44 ++++--- .../src/app/pull_request_watch_tests.rs | 68 ++++++++++ .../services/src/github/pull_request_watch.rs | 119 +++++++++++++++--- 3 files changed, 201 insertions(+), 30 deletions(-) diff --git a/crates/core/src/pull_request_watch.rs b/crates/core/src/pull_request_watch.rs index dfda8258e..1461be957 100644 --- a/crates/core/src/pull_request_watch.rs +++ b/crates/core/src/pull_request_watch.rs @@ -172,6 +172,31 @@ fn millis(at: &str) -> Option { .map(|at| at.timestamp_millis()) } +/// The checks that decide "passed": the required ones, or all of them where none is required; +/// and whether they are the required ones. +fn gate(checks: &[PullRequestCheck]) -> (Vec<&PullRequestCheck>, bool) { + let required: Vec<_> = checks + .iter() + .filter(|check| check.required == Some(true)) + .collect(); + if required.is_empty() { + (checks.iter().collect(), false) + } else { + (required, true) + } +} + +fn gate_passed(gate: &[&PullRequestCheck]) -> bool { + gate.iter() + .all(|check| check.status != CheckStatus::Pending && !check.status.failed()) +} + +/// Whether `checks` would be reported passed. A host consults the checks it requires but has +/// not reported only then: they can only hold that verdict back. +pub fn checks_pass(checks: &[PullRequestCheck]) -> bool { + !checks.is_empty() && gate_passed(&gate(checks).0) +} + /// Compare a read with what the agent was last told. Each check is reported as soon as it fails, /// so a check that never finishes cannot hold the news back. "Passed" is reported once the /// required checks all passed, or all checks where none is required. Remarks count when someone @@ -214,19 +239,8 @@ pub fn evaluate( // A check that runs again leaves the list, so a rerun that fails again is reported. failed_checks = failed.into_iter().map(|check| check.name).collect(); - let required: Vec<_> = read - .checks - .iter() - .filter(|check| check.required == Some(true)) - .collect(); - let gate = if required.is_empty() { - read.checks.iter().collect() - } else { - required.clone() - }; - let passed_now = gate - .iter() - .all(|check| check.status != CheckStatus::Pending && !check.status.failed()); + let (gate, required) = gate(&read.checks); + let passed_now = gate_passed(&gate); let gate_names: Vec<_> = gate.iter().map(|check| check.name.clone()).collect(); // A watch saved before passed_checks existed takes the current names, so it does not wake. let told = if passed && passed_checks.is_empty() { @@ -236,11 +250,11 @@ pub fn evaluate( }; // A required job created and finished between two passes is never seen pending. Without // required checks any check counts, and advisory bots keep adding passed ones: no wake. - let gate_grew = !required.is_empty() && gate_names.iter().any(|name| !told.contains(name)); + let gate_grew = required && gate_names.iter().any(|name| !told.contains(name)); if passed_now && (!passed || gate_grew) { changes.push(WatchChange::ChecksPassed { count: gate.len(), - required: !required.is_empty(), + required, }); } passed = passed_now; diff --git a/crates/runtime/src/app/pull_request_watch_tests.rs b/crates/runtime/src/app/pull_request_watch_tests.rs index 9f803ad8a..eaf7f1532 100644 --- a/crates/runtime/src/app/pull_request_watch_tests.rs +++ b/crates/runtime/src/app/pull_request_watch_tests.rs @@ -17,6 +17,7 @@ const ACTIVITY: &str = "PullRequestWatchActivity"; const THREADS: &str = "PullRequestWatchThreads"; const TAIL: &str = "PullRequestWatchThreadComments"; const FINGERPRINTS: &str = "PullRequestWatchFingerprints"; +const BRANCH: &str = "GET /repos/sample/project/branches/main"; struct ReviewThread { id: &'static str, @@ -28,6 +29,10 @@ struct Host { state: &'static str, head: &'static str, checks: Vec, + /// The checks main's branch protection requires. + protected: Vec<&'static str>, + /// The checks a ruleset on main requires. + ruled: Vec<&'static str>, mergeable: &'static str, comments: Vec, /// The comment list always has another page. @@ -50,6 +55,11 @@ fn check(name: &str, conclusion: &str) -> Value { "detailsUrl": format!("https://ci.test/{name}"), }) } +fn required(name: &str, conclusion: &str) -> Value { + let mut check = check(name, conclusion); + check["isRequired"] = json!(true); + check +} fn comment(id: &str, author: &str, at: &str) -> Value { json!({ "id": id, @@ -61,6 +71,15 @@ fn comment(id: &str, author: &str, at: &str) -> Value { }) } fn reply(host: &Mutex, exchange: fixture::Exchange) { + if exchange.request.starts_with(BRANCH) { + let mut host = host.lock().unwrap(); + host.requests.push(BRANCH.into()); + let body = json!({"name": "main", "protection": { + "enabled": true, + "required_status_checks": {"contexts": host.protected}, + }}); + return exchange.reply(200, "", &serde_json::to_vec(&body).unwrap()); + } let sent: Value = serde_json::from_slice(&exchange.body).unwrap(); let operation = sent["query"] .as_str() @@ -147,6 +166,11 @@ fn reply(host: &Mutex, exchange: fixture::Exchange) { "mergeable": host.mergeable, "headRefOid": host.head, "baseRefName": "main", + "baseRef": {"rules": {"nodes": [{"parameters": {"requiredStatusChecks": host + .ruled + .iter() + .map(|context| json!({"context": context})) + .collect::>()}}]}}, "author": {"login": "tcode-bot"}, "commits": {"nodes": [{"commit": {"statusCheckRollup": {"contexts": page(&host.checks, false)}}}]}, }}, @@ -456,6 +480,8 @@ impl Default for Host { state: "OPEN", head: "1111111aaaa", checks: Vec::new(), + protected: Vec::new(), + ruled: Vec::new(), mergeable: "MERGEABLE", comments: Vec::new(), endless_comments: false, @@ -609,6 +635,48 @@ fn a_merge_the_sync_records_wakes_the_watching_thread_once_and_ends_the_watch() ); } +/// GitHub creates a job that waits on others only once they finish, so a check main requires can +/// be missing from the head while every check reported so far has passed. +#[test] +fn checks_pass_only_once_every_check_main_requires_has_reported() { + let mut harness = Harness::new("tcode-watch-required"); + harness.host().protected = vec!["Web", "Linux x64"]; + harness.host().ruled = vec!["macOS arm64"]; + harness.host().checks = vec![ + required("Web", "SUCCESS"), + check("Linux x64 / tests", "PENDING"), + check("macOS arm64 / tests", "PENDING"), + ]; + harness.watch_thread("thread", START); + harness.pass(); + assert!( + harness.commands.is_empty(), + "Linux x64, which the branch protection requires, has not reported" + ); + harness.host().checks[1] = check("Linux x64 / tests", "SUCCESS"); + harness.host().checks.push(required("Linux x64", "SUCCESS")); + harness.pass(); + assert!( + harness.commands.is_empty(), + "macOS arm64, which the ruleset requires, has not reported" + ); + + harness.host().checks[2] = check("macOS arm64 / tests", "SUCCESS"); + harness + .host() + .checks + .push(required("macOS arm64", "SUCCESS")); + harness.pass(); + let (delivery, text) = harness.delivered(); + assert!( + text.contains("- All 3 required checks passed on 1111111."), + "{text}" + ); + harness.accept(delivery); + harness.pass(); + assert!(harness.commands.is_empty(), "the pass is told once"); +} + #[test] fn two_threads_share_one_read_with_separate_watermarks() { let mut harness = Harness::new("tcode-watch-shared"); diff --git a/crates/services/src/github/pull_request_watch.rs b/crates/services/src/github/pull_request_watch.rs index c5c5e0fce..c28dac8d1 100644 --- a/crates/services/src/github/pull_request_watch.rs +++ b/crates/services/src/github/pull_request_watch.rs @@ -2,8 +2,9 @@ use super::{ GitHubApi, GitHubError, RequestOptions, - api::Authentication, + api::{Authentication, RestRequest}, graphql::{self, AliasItem, Document, Variables}, + pull_request_reads::percent_encode, repository::Repository, }; use crate::forge::{Fingerprint, Tail, Tails}; @@ -11,7 +12,9 @@ use serde_json::{Value, json}; use std::collections::{BTreeMap, HashMap, HashSet}; use tcode_core::{ pull_request::{Mergeability, PullRequestKey, PullRequestState}, - pull_request_watch::{CheckStatus, PullRequestCheck, PullRequestRemark, PullRequestWatchRead}, + pull_request_watch::{ + self as watch, CheckStatus, PullRequestCheck, PullRequestRemark, PullRequestWatchRead, + }, }; /// Past this many requests a list is reported incomplete rather than read on. @@ -200,14 +203,19 @@ fn decode_fingerprint(pr: &Value) -> Option { /// State, head, checks, mergeability and the authenticated account, in one point. pub fn detail(api: &GitHubApi, key: &PullRequestKey) -> Result { let options = options(api, &key.host, "PullRequestWatchDetail")?; - // GitHub Enterprise Server has no per-pull-request required flag. - let required = if key.host == "github.com" { - " isRequired(pullRequestNumber: $number)" + // GitHub Enterprise Server has no per-pull-request required flag, so nothing there is known + // to be required. + let github_com = key.host == "github.com"; + let (required, rules) = if github_com { + ( + " isRequired(pullRequestNumber: $number)", + " baseRef { rules(first: 100) { nodes { parameters { ... on RequiredStatusChecksParameters { requiredStatusChecks { context } } } } } }", + ) } else { - "" + ("", "") }; let document = format!( - "query PullRequestWatchDetail($owner: String!, $name: String!, $number: Int!, $checksAfter: String) {{ viewer {{ login }} repository(owner: $owner, name: $name) {{ pullRequest(number: $number) {{ number state mergedAt mergeable headRefOid baseRefName author {{ login }} commits(last: 1) {{ nodes {{ commit {{ statusCheckRollup {{ contexts(first: 100, after: $checksAfter) {{ pageInfo {{ hasNextPage endCursor }} nodes {{ __typename ... on StatusContext {{ context state targetUrl createdAt{required} }} ... on CheckRun {{ name status conclusion startedAt completedAt detailsUrl{required} checkSuite {{ workflowRun {{ workflow {{ name }} }} }} }} }} }} }} }} }} }} }} }} }}" + "query PullRequestWatchDetail($owner: String!, $name: String!, $number: Int!, $checksAfter: String) {{ viewer {{ login }} repository(owner: $owner, name: $name) {{ pullRequest(number: $number) {{ number state mergedAt mergeable headRefOid baseRefName author {{ login }}{rules} commits(last: 1) {{ nodes {{ commit {{ statusCheckRollup {{ contexts(first: 100, after: $checksAfter) {{ pageInfo {{ hasNextPage endCursor }} nodes {{ __typename ... on StatusContext {{ context state targetUrl createdAt{required} }} ... on CheckRun {{ name status conclusion startedAt completedAt detailsUrl{required} checkSuite {{ workflowRun {{ workflow {{ name }} }} }} }} }} }} }} }} }} }} }} }} }}" ); let mut variables = repository_variables(key)?; let mut contexts = Vec::new(); @@ -259,18 +267,29 @@ pub fn detail(api: &GitHubApi, key: &PullRequestKey) -> Result return Err(GitHubError::InvalidResponse), } }; + let base_branch = pr["baseRefName"].as_str().unwrap_or_default().to_owned(); + // A list cut short could hide a pending check behind a passing gate; an empty one keeps + // what the agent was told. + let mut checks = if complete { + checks(&contexts) + } else { + Vec::new() + }; + if github_com && state == PullRequestState::Open && watch::checks_pass(&checks) { + checks.extend(unreported_required( + api, + key, + &base_branch, + &pr["baseRef"], + &contexts, + )?); + } let login = |value: &Value| value["login"].as_str().map(str::to_owned); Ok(PullRequestWatchRead { state, head_sha: pr["headRefOid"].as_str().map(str::to_owned), - base_branch: pr["baseRefName"].as_str().unwrap_or_default().to_owned(), - // A list cut short could hide a pending check behind a passing gate; an empty one keeps - // what the agent was told. - checks: if complete { - checks(&contexts) - } else { - Vec::new() - }, + base_branch, + checks, mergeability: match pr["mergeable"].as_str() { Some("MERGEABLE") => Mergeability::Clean, Some("CONFLICTING") => Mergeability::Conflicting, @@ -283,6 +302,76 @@ pub fn detail(api: &GitHubApi, key: &PullRequestKey) -> Result Result, GitHubError> { + let repository = Repository::from_key(key).ok_or(GitHubError::Request)?; + let path = format!( + "/repos/{}/{}/branches/{}", + repository.owner, + repository.name, + percent_encode(base_branch) + ); + let branch: Value = match api.rest( + &key.host, + RestRequest { + answers: &[403], + ..RestRequest::get(&path) + }, + &options(api, &key.host, "PullRequestWatchRequiredChecks")?, + ) { + Ok(response) if response.status == 403 => Value::Null, + Ok(response) => response.json()?, + Err(GitHubError::NotFound) => Value::Null, + Err(error) => return Err(error), + }; + let reported: HashSet = contexts + .iter() + .filter_map(|raw| trimmed(&raw["name"]).or_else(|| trimmed(&raw["context"]))) + .collect(); + let mut expected: Vec = Vec::new(); + let protection = &branch["protection"]; + let protected = protection["required_status_checks"]["contexts"] + .as_array() + .filter(|_| protection["enabled"].as_bool() != Some(false)) + .into_iter() + .flatten() + .filter_map(trimmed); + let ruled = base_ref["rules"]["nodes"] + .as_array() + .into_iter() + .flatten() + .flat_map(|rule| { + rule["parameters"]["requiredStatusChecks"] + .as_array() + .into_iter() + .flatten() + }) + .filter_map(|check| trimmed(&check["context"])); + for context in protected.chain(ruled) { + if !reported.contains(&context) && !expected.contains(&context) { + expected.push(context); + } + } + Ok(expected + .into_iter() + .map(|name| PullRequestCheck { + name, + status: CheckStatus::Pending, + url: None, + required: Some(true), + }) + .collect()) +} + fn trimmed(value: &Value) -> Option { value .as_str()