diff --git a/design/workstreams/provider-github/LLD/github-provider.md b/design/workstreams/provider-github/LLD/github-provider.md index 71c6b83b..7e52d503 100644 --- a/design/workstreams/provider-github/LLD/github-provider.md +++ b/design/workstreams/provider-github/LLD/github-provider.md @@ -72,7 +72,7 @@ Untrusted text (issue/PR bodies, comments) is stored as **content refs** (`githu - Issue: state, labels, sub-issues, linked PRs, comments count. - Deploy: for work items with merged PRs, the latest `github-pages` deployment of the default branch → `item.deploy{state, sha, url, containsMerge}` (`containsMerge`: every merge commit of the item's PRs is an ancestor of `sha`, via the compare API). docs' Pages workflow cancels in-progress deploys, so only the latest one matters. -- PR: `isDraft`, `headRefOid`, `baseRefName`, labels, `reviews(last:20){author, state, commit{oid}}` → `approvedBy[]{identity, commit}`, `reviewThreads(first:100){isResolved}` → `unresolvedThreads`, `commits(last:1){checkSuites(first:100){status, conclusion, checkRuns{totalCount}}}` → `checks{state, settled}`, merged/mergedAt/mergeCommit, author (factory or not). +- PR: `isDraft`, `headRefOid`, `baseRefName`, labels, `reviews(last:20){author, state, commit{oid}}` → `approvedBy[]{identity, commit}`, `reviewThreads(first:100){isResolved}` → `unresolvedThreads`, `commits(last:1){checkSuites(first:100){databaseId, createdAt, status, conclusion, app{databaseId}, workflowRun{runNumber, event, workflow{databaseId}}, checkRuns{totalCount}}}` → `checks{state, settled}` (only the latest suite per workflow and event counts: see the roll-up below), merged/mergedAt/mergeCommit, author (factory or not). There is no `List`, and `Observe` doesn't read the markers back: the work-item rebuild that used them is gone (P3 §No rebuild from markers), and the store is the authority. The markers and labels are for people to read. Only `Project` reads the App's own markers, to find the one it updates and which labels other work items own. @@ -160,12 +160,12 @@ Implemented in GH-S1-T04; the details are in [§Decisions taken in GH-S1-T04](#d - **GraphQL by hand, no new dependency.** The queries are constants in `observe.go`, posted by the new `tokens.Minter.GraphQL(ctx, token, op, query, vars, out)` and decoded with `encoding/json`, rather than through `githubv4`: errors then map like every other call (HTTP errors as in T01; a response with `errors` is a `*tokens.GraphQLError`, `NOT_FOUND` → `ErrNotFound`, `FORBIDDEN` → `tokens.ErrForbidden` and `provider.ErrForbidden`, a permission problem callers can tell from a transient one, `RATE_LIMITED` → `*provider.RetryableError`), the recorded responses under `testdata/graphql` are plain JSON, and `githubtest` answers by operation name. **A response with errors fails even with partial data**: an observation missing a field could make a rule merge. The endpoint is `/graphql`, or `https:///api/graphql` for a GHE REST base `…/api/v3` (`tokens.GraphQLURL`). `tokens` also gained `Do` (any method with an installation token, optional body and decoding), `NextPage` (the Link `rel="next"` query), and 410 (a deleted issue) now maps to `ErrNotFound`. - **`Observe(ref)`** is one `Observe` query on `repository.issueOrPullRequest(number)`, so a ref of the other kind (an issue ref naming a PR) is `ErrNotFound`, as the fake does, and an empty kind is filled in. Follow-up queries (`ObserveComments`, `ObserveThreads`, by node ID and cursor) read comments and review threads past the first 100, up to 10 more pages each (`ObserveComments` went with the markers' read-back: [§P3](#decisions-taken-with-p3-no-list-no-marker-read-back)). Labels (first 100), sub-issues (GitHub caps them at 100) and reviews (`last: 100`, not the LLD's 20, so an old approval isn't cut off by a chatty review) are one page. - Issue: state, labels, author, `subIssues` → `SubIssues`, `closedByPullRequestsReferences` (open and closed) → `LinkedPRs`, `comments.totalCount` → `Comments`. - - PR: `isDraft`, `headRefOid`, `baseRefName`, labels, author, `mergedAt`, `mergeCommit` (only once merged). `checks` rolls up the last commit's check suites that have check runs: `failure` once one concluded failing (failure, timed out, cancelled, action required, startup failure, stale), else `pending` while one runs, else `success` (success, neutral, skipped); `settled` for `success` and `failure`; no such suite leaves `checks` empty. **Not `statusCheckRollup`** (fx/gh-observe-perms): it also covers commit statuses (`statuses: read`), which the Apps aren't granted, and check suites are what `pr.checks.completed` reports, so commit statuses don't count. `approvedBy` is each reviewer's **latest opinion** (`APPROVED`, `CHANGES_REQUESTED`, `DISMISSED`; comments and pending reviews don't change it) when it is an approval, at that review's commit, sorted. The factory's Apps map to their identity (`ccf-factory-reviewer[bot]` → `reviewer`, `ccf-factory[bot]` → `author`, from the slugs T02 learns), anyone else to their login; a deleted account counts for nobody. `unresolvedThreads` counts `isResolved: false` across all pages. + - PR: `isDraft`, `headRefOid`, `baseRefName`, labels, author, `mergedAt`, `mergeCommit` (only once merged). `checks` rolls up the last commit's check suites that have check runs, **keeping only the latest suite of each workflow** (fx/checks-latest-suite): a GitHub Actions suite's kind is its App, workflow and event (`app{databaseId}`, `workflowRun{workflow{databaseId}, event}`); the latest is the highest workflow run number, then the newest `createdAt`, then the highest `databaseId`, and a suite with runs isn't superseded by a later one without. A suite whose workflow can't be told (no App, a null `workflowRun`: another App's suite such as CodeRabbit's, or an Actions suite whose run was deleted; a null `workflow`) is **never superseded and supersedes nothing**, so a failing suite can't hide behind an unrelated green one. So a run cancelled by its concurrency group, or a failed run re-triggered by a later green one, no longer turns a green PR into `failure` (compliance-framework/api#584: a cancelled `preview` run beside its green successor). A re-run (`rerun-failed-jobs`, re-run all jobs) is a new attempt of the same workflow run and GitHub keeps it in the same check suite, whose status and conclusion are the latest attempt's (checked on GitHub: a run's `check_suite_id` is unchanged by a re-run, and that suite went from failure to success), so attempts need no handling. The event is part of the kind because a `push` and a `pull_request` run of one workflow are separate checks (separate concurrency groups in practice): a failing `push` run isn't hidden by a green `pull_request` one. Of the kept suites: `failure` once one concluded failing (failure, timed out, cancelled, action required, startup failure, stale), else `pending` while one runs, else `success` (success, neutral, skipped); `settled` for `success` and `failure`; no such suite leaves `checks` empty. **Not `statusCheckRollup`** (fx/gh-observe-perms): it also covers commit statuses (`statuses: read`), which the Apps aren't granted, and check suites are what `pr.checks.completed` reports, so commit statuses don't count. `approvedBy` is each reviewer's **latest opinion** (`APPROVED`, `CHANGES_REQUESTED`, `DISMISSED`; comments and pending reviews don't change it) when it is an approval, at that review's commit, sorted. The factory's Apps map to their identity (`ccf-factory-reviewer[bot]` → `reviewer`, `ccf-factory[bot]` → `author`, from the slugs T02 learns), anyone else to their login; a deleted account counts for nobody. `unresolvedThreads` counts `isResolved: false` across all pages. - Author: `:` with REST's spelling (GraphQL's Bot `ccf-factory` is `ccf-factory[bot]`, as in webhooks), `isBot`, and `isFactory`/`identity` for the factory's Apps; nil for a deleted account. - Projections (removed with P3: [§P3](#decisions-taken-with-p3-no-list-no-marker-read-back)): the v1 markers among the comments **written by the projecting App** (the author identity); a look-alike by anyone else, or a marker of another version, is ignored (the latter with a warning). Of two markers for one work item the oldest comment wins. Comment bodies are read only for that and never returned. - **Other kinds**, because the work-item view and the rule controller's probe treat any error but `ErrNotFound` as fatal: a `repo` link (an event without an object) is open, or closed once archived (`ObserveRepo`, `metadata: read`); releases and deployments are immutable records, `closed` with no call. Any other kind is `ErrInvalid`. - **Deploy** is set on **merged PRs only**: the latest deployment (REST `GET …/deployments?environment=&ref=&per_page=1`) to `Options.DeployEnvironment` (default `github-pages`), its latest status's `state` (`pending` when it has none) and `environment_url` (else `target_url`), its `sha`, and `containsMerge` when this PR's merge commit is ahead-or-identical by the compare API (shared with T02's deployment linking). Observe is per object, so "every merge commit of the item's PRs" can't be computed here. **Gap for RT:** `buildView` takes `item.deploy` from the primary link, else the first link with one, so for a stack it reflects one PR; `announce-ptbr-live` should see `containsMerge` ANDed over the item's merged PRs (the controller can combine the PRs' `Deploy`). -- **Tokens and identities.** Everything is the author identity (`readIdentity`, as in T02). Observe and List read with `{issues, pull_requests, contents, checks: read}` on the object's repo (`contents` for the Commit objects the query reaches: head, merge commit, reviews' commits; `checks` for the head's check suites) (one cache key, so List's token serves the Observes that follow); the deployment with `{contents, deployments: read}`. Project reads the issue and its comments with the read token (a `pull_requests`-only token can't tell an issue from a missing one) and writes with **`issues: write` on an issue, `pull_requests: write` on a PR**, nothing else. +- **Tokens and identities.** Everything is the author identity (`readIdentity`, as in T02). Observe and List read with `{issues, pull_requests, contents, checks, actions: read}` on the object's repo (`contents` for the Commit objects the query reaches: head, merge commit, reviews' commits; `checks` for the head's check suites; `actions` for each suite's `workflowRun`, which the App's **actions: read** grant covers, fx/checks-latest-suite) (one cache key, so List's token serves the Observes that follow); the deployment with `{contents, deployments: read}`. Project reads the issue and its comments with the read token (a `pull_requests`-only token can't tell an issue from a missing one) and writes with **`issues: write` on an issue, `pull_requests: write` on a PR**, nothing else. - **Marker format v1** (`marker.go`), as the LLD's, with what round-tripping needed: `links` are `provider:ref[:kind[:primary]]`, so the rebuild gets kinds and the primary back; a new **`labels=`** field records the factory-owned labels this work item put on the object; every key and value is percent-encoded (only `A-Z a-z 0-9 . _ ~ -` stay), so no value can hold a space, comma, colon, `>` or `-->`; non-string state values (numbers, bools, maps, lists) are `b64:` base64url JSON, and parse back as a JSON round trip gives them (`float64`, `[]any`), as the controller's state already is. Unknown fields are ignored, so v1 can grow. The visible line links to `/workitems/` when the new `Options.UIBaseURL` is set (`serve` wiring is GH-S1-T04), else it has no link. Over 60 KB the marker is written without `state` and a warning is logged; still over is `ErrInvalid`. - **`Project(ref, p)`**: (1) labels, then (2) the marker, so a failed marker write is retried with the old ownership still on record. Labels: add the projection's labels the object lacks; remove those the work item's **previous marker** owned that the projection dropped, unless another work item's marker on the object owns them too. Nothing else is ever removed, a human's `factory:stop` included. Names compare case-insensitively, as GitHub does; a 404 on removal is success. Marker: the oldest marker the author App wrote for the work item is edited (`PATCH …/issues/comments/{id}`) when its body differs, else one is created. The same projection again makes no write. Releases, deployments and repos carry no marker: projecting onto them is a no-op (the controller would otherwise fail the reconcile). - **`List(scope)`** (removed with P3: [§P3](#decisions-taken-with-p3-no-list-no-marker-read-back)): per repo, two searches (`GET /search/issues`, 100 per page, at most 10 pages: GitHub's 1000-result cap, with a warning): `repo: is:open updated:>=` and `repo: "Tracked by CCF Factory" in:comments updated:>=` (the marker's visible text, rather than the hidden header, which search may not index). **The marker search is bounded by the same 90 days**, unlike the LLD: an item older than that is past the work items' retention, so rebuilding it would only retire it again. The kind comes from the result's `pull_request` key; refs are unique and sorted. diff --git a/internal/provider/github/githubtest/objects.go b/internal/provider/github/githubtest/objects.go index 2fdd1aa3..0644c69d 100644 --- a/internal/provider/github/githubtest/objects.go +++ b/internal/provider/github/githubtest/objects.go @@ -93,11 +93,21 @@ type Object struct { } // CheckSuite is one check suite of a commit: Status (QUEUED, IN_PROGRESS, COMPLETED, …), -// Conclusion once completed (SUCCESS, FAILURE, …) and how many check runs it has. +// Conclusion once completed (SUCCESS, FAILURE, …) and how many check runs it has. ID, Created +// and App are the suite's databaseId, createdAt and App (zero: null, an App not read); a +// workflow run's suite (GitHub Actions) also has Workflow (the workflow's databaseId), +// RunNumber and Event; without both Workflow and RunNumber its workflowRun is null, and with a +// RunNumber but no Workflow the run's workflow is null. type CheckSuite struct { Status string Conclusion string Runs int + ID int64 + Created time.Time + App int64 + Workflow int64 + RunNumber int + Event string } // Merge blocks (Object.MergeBlock). @@ -665,15 +675,17 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) { // fieldPerms are the permissions an installation token needs for GraphQL fields, as GitHub // checks them: Commit objects (a PR's commits, its merge commit, a review's commit) need -// contents, a commit's check suites checks, its status rollup and status statuses. The server -// matches the query text, so it is stricter than GitHub, which checks only the fields it -// resolves (an issue's observation doesn't reach the PR fragment's commits). +// contents, a commit's check suites checks, a check suite's workflow run actions, its status +// rollup and status statuses. The server matches the query text, so it is stricter than +// GitHub, which checks only the fields it resolves (an issue's observation doesn't reach the +// PR fragment's commits). var fieldPerms = []struct { field *regexp.Regexp perm string }{ {regexp.MustCompile(`\b(?:commit|mergeCommit)\s*\{`), "contents"}, {regexp.MustCompile(`\b(?:checkSuites|checkRuns)\b`), "checks"}, + {regexp.MustCompile(`\bworkflowRun\s*\{`), "actions"}, {regexp.MustCompile(`\b(?:statusCheckRollup|status)\s*\{`), "statuses"}, } @@ -751,7 +763,19 @@ func (s *Server) gqlObserve(repo string, n int) map[string]any { if cs.Conclusion != "" { conclusion = cs.Conclusion } - suites[i] = map[string]any{"status": cs.Status, "conclusion": conclusion, "checkRuns": map[string]any{"totalCount": cs.Runs}} + suite := map[string]any{"databaseId": cs.ID, "createdAt": cs.Created.UTC().Format(time.RFC3339), "status": cs.Status, "conclusion": conclusion, + "app": nil, "workflowRun": nil, "checkRuns": map[string]any{"totalCount": cs.Runs}} + if cs.App != 0 { + suite["app"] = map[string]any{"databaseId": cs.App} + } + if cs.Workflow != 0 || cs.RunNumber != 0 { + var workflow any // null: a run without its workflow + if cs.Workflow != 0 { + workflow = map[string]any{"databaseId": cs.Workflow} + } + suite["workflowRun"] = map[string]any{"runNumber": cs.RunNumber, "event": cs.Event, "workflow": workflow} + } + suites[i] = suite } obj["commits"] = map[string]any{"nodes": []any{map[string]any{"commit": map[string]any{"oid": o.Head, "checkSuites": map[string]any{"nodes": suites}}}}} } else { diff --git a/internal/provider/github/observe.go b/internal/provider/github/observe.go index 4ef85b67..14cd3be4 100644 --- a/internal/provider/github/observe.go +++ b/internal/provider/github/observe.go @@ -22,11 +22,13 @@ const maxFollowPages = 10 // observePerms are the read identity's permissions for Observe, exactly what observeQuery // reads: the issue or the PR with its reviews and threads (issues, pull_requests), the -// commits it reaches (the head, the merge commit, each review's commit: contents) and the head -// commit's check suites (checks). ReadContent and Project's reads share the set, so one -// cached token per repo serves them all. No statuses: the head's statusCheckRollup also -// covers commit statuses, which the factory's Apps aren't granted (see checksOf). -var observePerms = map[string]string{"issues": "read", "pull_requests": "read", "contents": "read", "checks": "read"} +// commits it reaches (the head, the merge commit, each review's commit: contents), the head +// commit's check suites (checks) and the workflow run behind each Actions suite (actions: which +// workflow it is, so a superseded run doesn't count, see checksOf). ReadContent and Project's +// reads share the set, so one cached token per repo serves them all. No statuses: the head's +// statusCheckRollup also covers commit statuses, which the factory's Apps aren't granted (see +// checksOf). +var observePerms = map[string]string{"issues": "read", "pull_requests": "read", "contents": "read", "checks": "read", "actions": "read"} // observeQuery reads one issue or PR (github-provider.md §Observe): whichever the number is, // so a ref of the wrong kind is told apart from a missing one. @@ -62,7 +64,7 @@ const observeQuery = `query Observe($owner: String!, $name: String!, $number: In labels(first: 100) { nodes { name } } reviews(last: 100) { nodes { author { __typename login } state commit { oid } } } reviewThreads(first: 100) { pageInfo { hasNextPage endCursor } nodes { isResolved } } - commits(last: 1) { nodes { commit { oid checkSuites(first: 100) { nodes { status conclusion checkRuns(first: 1) { totalCount } } } } } } + commits(last: 1) { nodes { commit { oid checkSuites(first: 100) { nodes { databaseId createdAt status conclusion app { databaseId } workflowRun { runNumber event workflow { databaseId } } checkRuns(first: 1) { totalCount } } } } } } } } } @@ -155,11 +157,23 @@ type ( } `json:"commits"` } // gqlCheckSuite is one check suite of a commit: an App's checks (GitHub Actions: one - // workflow run's jobs). + // workflow run's jobs, WorkflowRun). gqlCheckSuite struct { - Status string `json:"status"` - Conclusion string `json:"conclusion"` - CheckRuns struct { + DatabaseID int64 `json:"databaseId"` + CreatedAt time.Time `json:"createdAt"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + App *struct { + DatabaseID int64 `json:"databaseId"` + } `json:"app"` + WorkflowRun *struct { + RunNumber int `json:"runNumber"` + Event string `json:"event"` + Workflow *struct { + DatabaseID int64 `json:"databaseId"` + } `json:"workflow"` + } `json:"workflowRun"` + CheckRuns struct { TotalCount int `json:"totalCount"` } `json:"checkRuns"` } @@ -393,16 +407,21 @@ func prObservation(o *gqlObject, bots map[string]string) *provider.PRObservation // with runs leaves checks empty. The first 100 suites are read (one page; a commit has one per // App and workflow run). // +// Only the latest suite of each workflow counts (latestSuites): a workflow run superseded by a +// later run of the same workflow for the same event (a concurrency group cancelling it, a +// re-trigger) no longer makes a green PR "failure". Re-running a run (rerun-failed-jobs, re-run +// all jobs) is a new attempt of the same run, and GitHub reports it in the same check suite, +// whose status and conclusion are the latest attempt's (checked against a re-run on GitHub: +// the run's check_suite_id is the same suite, which went from failure to success), so a +// re-run that passed counts as passed without any attempt handling here. +// // Check suites are what checks: read reaches, and what pr.checks.completed (check_suite // webhooks) reports; commit statuses (the statuses API) aren't read: the App isn't granted // them, so a status-only CI doesn't count here (branch protection still gates the merge on // required statuses). func checksOf(suites []gqlCheckSuite) provider.Checks { var counted, failed, pending bool - for _, s := range suites { - if s.CheckRuns.TotalCount == 0 { - continue - } + for _, s := range latestSuites(suites) { counted = true if s.Status != "COMPLETED" { pending = true @@ -427,6 +446,63 @@ func checksOf(suites []gqlCheckSuite) provider.Checks { return provider.Checks{State: "success", Settled: true} } +// latestSuites are the suites with check runs that no later suite of the same kind supersedes, +// in their order. A suite's kind (suiteKind) is its App, workflow and event: only workflow runs +// (GitHub Actions) supersede each other. Of a kind, the latest is the highest run number, then +// the newest createdAt, then the highest databaseId. A suite whose workflow can't be told (no +// App, no workflow run: another App's suite, or an Actions suite whose run was deleted; or a +// run without its workflow) is its own kind: it always counts and supersedes nothing, so a +// failing suite can't hide behind an unrelated green one. +func latestSuites(suites []gqlCheckSuite) []gqlCheckSuite { + latest := map[string]int{} // kind → index of its latest suite + for i, s := range suites { + if s.CheckRuns.TotalCount == 0 { + continue + } + kind, ok := suiteKind(s) + if !ok { + continue + } + if j, seen := latest[kind]; !seen || newerSuite(s, suites[j]) { + latest[kind] = i + } + } + var out []gqlCheckSuite + for i, s := range suites { + if s.CheckRuns.TotalCount == 0 { + continue + } + if kind, ok := suiteKind(s); ok && latest[kind] != i { + continue // superseded + } + out = append(out, s) + } + return out +} + +// suiteKind is what a later suite of the same kind supersedes: "//" for a +// workflow run. ok is false when the suite's workflow can't be told (no App, a null +// workflowRun, a null workflow): nothing supersedes it and it supersedes nothing. +func suiteKind(s gqlCheckSuite) (string, bool) { + w := s.WorkflowRun + if s.App == nil || s.App.DatabaseID == 0 || w == nil || w.Workflow == nil || w.Workflow.DatabaseID == 0 { + return "", false + } + return strconv.FormatInt(s.App.DatabaseID, 10) + "/" + strconv.FormatInt(w.Workflow.DatabaseID, 10) + "/" + w.Event, true +} + +// newerSuite reports whether a is later than b, two suites of one kind: the higher workflow +// run number, then the newer createdAt, then the higher databaseId. +func newerSuite(a, b gqlCheckSuite) bool { + if a.WorkflowRun != nil && b.WorkflowRun != nil && a.WorkflowRun.RunNumber != b.WorkflowRun.RunNumber { + return a.WorkflowRun.RunNumber > b.WorkflowRun.RunNumber + } + if !a.CreatedAt.Equal(b.CreatedAt) { + return a.CreatedAt.After(b.CreatedAt) + } + return a.DatabaseID > b.DatabaseID +} + // objectState maps an issue's or PR's GraphQL state. func objectState(s string) provider.ObjectState { switch s { diff --git a/internal/provider/github/observe_test.go b/internal/provider/github/observe_test.go index f0d263f0..c37f6582 100644 --- a/internal/provider/github/observe_test.go +++ b/internal/provider/github/observe_test.go @@ -36,6 +36,7 @@ var observeCases = []struct { {"issue-train", objRef(provider.KindIssue, workflows+"#123")}, {"pr-review", objRef(provider.KindPR, docs+"#90")}, {"pr-draft", objRef(provider.KindPR, docs+"#91")}, + {"pr-superseded", objRef(provider.KindPR, docs+"#92")}, {"pr-merged", objRef(provider.KindPR, docs+"#89")}, {"pr-closed", objRef("", docs+"#88")}, } @@ -238,12 +239,13 @@ func TestObserveFields(t *testing.T) { t.Run("tokens", func(t *testing.T) { // Observe reads with the author identity's read-only token on the object's repo (the - // commits it reaches need contents, their check suites checks; never statuses, which - // the App isn't granted), and the deployment with contents and deployments read. + // commits it reaches need contents, their check suites checks, the suites' workflow + // runs actions; never statuses, which the App isn't granted), and the deployment with + // contents and deployments read. var sawObserve, sawDeploy bool for _, r := range e.srv.TokenRequests() { switch { - case reflect.DeepEqual(r.Permissions, map[string]string{"checks": "read", "contents": "read", "issues": "read", "pull_requests": "read"}): + case reflect.DeepEqual(r.Permissions, map[string]string{"actions": "read", "checks": "read", "contents": "read", "issues": "read", "pull_requests": "read"}): sawObserve = true case reflect.DeepEqual(r.Permissions, map[string]string{"contents": "read", "deployments": "read"}): sawDeploy = true @@ -364,6 +366,39 @@ func TestObserveChecks(t *testing.T) { suite := func(status, conclusion string, runs int) githubtest.CheckSuite { return githubtest.CheckSuite{Status: status, Conclusion: conclusion, Runs: runs} } + // The Apps and workflows of compliance-framework/api#584's head commit. + const ( + actions = 15368 + coderabbit = 347564 + advancedSecurity = 57789 + previewWF = 379691137 + ciWF = 67470646 + ) + created := time.Date(2026, 11, 24, 14, 0, 0, 0, time.UTC) + // app is a suite of an App that isn't Actions; run one of an Actions workflow run on a + // pull_request event. id orders them in time too (createdAt). + app := func(appID, id int64, status, conclusion string, runs int) githubtest.CheckSuite { + s := suite(status, conclusion, runs) + s.ID, s.Created, s.App = id, created.Add(time.Duration(id)*time.Second), appID + return s + } + run := func(workflow int64, number int, id int64, status, conclusion string, runs int) githubtest.CheckSuite { + s := app(actions, id, status, conclusion, runs) + s.Workflow, s.RunNumber, s.Event = workflow, number, "pull_request" + return s + } + at := func(s githubtest.CheckSuite, t time.Time) githubtest.CheckSuite { + s.Created = t + return s + } + noWorkflow := func(s githubtest.CheckSuite) githubtest.CheckSuite { + s.Workflow = 0 + return s + } + event := func(s githubtest.CheckSuite, ev string) githubtest.CheckSuite { + s.Event = ev + return s + } for i, tc := range []struct { name string suites []githubtest.CheckSuite @@ -387,6 +422,61 @@ func TestObserveChecks(t *testing.T) { {"startup failure", []githubtest.CheckSuite{suite("COMPLETED", "STARTUP_FAILURE", 1)}, provider.Checks{State: "failure", Settled: true}}, {"stale", []githubtest.CheckSuite{suite("COMPLETED", "STALE", 1)}, provider.Checks{State: "failure", Settled: true}}, {"unknown conclusion", []githubtest.CheckSuite{suite("COMPLETED", "SOMETHING_NEW", 1)}, provider.Checks{State: "pending"}}, + // Only the latest suite of a workflow (per event), or of another App, counts. + {"api#584: a cancelled run superseded by a green one", []githubtest.CheckSuite{ + app(coderabbit, 1, "COMPLETED", "SKIPPED", 1), + run(previewWF, 372, 2, "COMPLETED", "CANCELLED", 4), + run(previewWF, 373, 3, "COMPLETED", "SUCCESS", 4), + run(ciWF, 2512, 4, "COMPLETED", "SUCCESS", 10), + run(ciWF, 2513, 5, "COMPLETED", "SUCCESS", 10), + app(advancedSecurity, 6, "COMPLETED", "SUCCESS", 1), + run(ciWF, 2516, 7, "COMPLETED", "SUCCESS", 8), + }, provider.Checks{State: "success", Settled: true}}, + {"cancelled then failed, same workflow", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "CANCELLED", 3), run(ciWF, 11, 2, "COMPLETED", "FAILURE", 3), + }, provider.Checks{State: "failure", Settled: true}}, + {"failed then succeeded, same workflow (re-triggered)", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), run(ciWF, 11, 2, "COMPLETED", "SUCCESS", 3), + }, provider.Checks{State: "success", Settled: true}}, + {"the latest by run number, whatever the order", []githubtest.CheckSuite{ + run(ciWF, 11, 2, "COMPLETED", "SUCCESS", 3), run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), + }, provider.Checks{State: "success", Settled: true}}, + {"two workflows: a cancelled one not superseded still fails", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "SUCCESS", 3), run(previewWF, 20, 2, "COMPLETED", "CANCELLED", 2), + }, provider.Checks{State: "failure", Settled: true}}, + {"the latest run in progress, an older one failed", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), run(ciWF, 11, 2, "IN_PROGRESS", "", 3), + }, provider.Checks{State: "pending"}}, + {"a later run without check runs doesn't supersede", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), run(ciWF, 11, 2, "QUEUED", "", 0), + }, provider.Checks{State: "failure", Settled: true}}, + {"another event's run of the same workflow still counts", []githubtest.CheckSuite{ + event(run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), "push"), run(ciWF, 11, 2, "COMPLETED", "SUCCESS", 3), + }, provider.Checks{State: "failure", Settled: true}}, + {"one run number: the newer suite", []githubtest.CheckSuite{ + run(ciWF, 10, 2, "COMPLETED", "SUCCESS", 3), run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), + }, provider.Checks{State: "success", Settled: true}}, + {"one run number and createdAt: the higher databaseId", []githubtest.CheckSuite{ + at(run(ciWF, 10, 9, "COMPLETED", "FAILURE", 3), created), at(run(ciWF, 10, 8, "COMPLETED", "SUCCESS", 3), created), + }, provider.Checks{State: "failure", Settled: true}}, + {"another App's suites never supersede each other", []githubtest.CheckSuite{ + app(coderabbit, 1, "COMPLETED", "FAILURE", 1), app(coderabbit, 2, "COMPLETED", "SUCCESS", 1), + }, provider.Checks{State: "failure", Settled: true}}, + {"an Actions suite with a null workflowRun is never superseded", []githubtest.CheckSuite{ + app(actions, 1, "COMPLETED", "FAILURE", 3), run(ciWF, 10, 2, "COMPLETED", "SUCCESS", 3), + }, provider.Checks{State: "failure", Settled: true}}, + {"an Actions suite with a null workflowRun supersedes nothing", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), app(actions, 2, "COMPLETED", "SUCCESS", 3), + }, provider.Checks{State: "failure", Settled: true}}, + {"two Actions suites with null workflowRuns both count", []githubtest.CheckSuite{ + app(actions, 1, "COMPLETED", "FAILURE", 3), app(actions, 2, "COMPLETED", "SUCCESS", 3), + }, provider.Checks{State: "failure", Settled: true}}, + {"a run with a null workflow is never superseded", []githubtest.CheckSuite{ + noWorkflow(run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3)), run(ciWF, 11, 2, "COMPLETED", "SUCCESS", 3), + }, provider.Checks{State: "failure", Settled: true}}, + {"a run with a null workflow supersedes nothing", []githubtest.CheckSuite{ + run(ciWF, 10, 1, "COMPLETED", "FAILURE", 3), noWorkflow(run(ciWF, 11, 2, "COMPLETED", "SUCCESS", 3)), + }, provider.Checks{State: "failure", Settled: true}}, } { t.Run(tc.name, func(t *testing.T) { e := newEnv(t) @@ -421,11 +511,11 @@ func TestObserveFieldPermissions(t *testing.T) { if q := e.srv.GraphQLRequests(); len(q) != 1 || q[0].Operation != "Observe" { t.Errorf("GraphQL requests = %+v", q) } - for _, missing := range []string{"contents", "checks"} { + for _, missing := range []string{"contents", "checks", "actions"} { t.Run("installation without "+missing, func(t *testing.T) { e := newEnv(t) e.srv.AddObject(pr) - perms := map[string]string{"contents": "write", "pull_requests": "write", "issues": "write", "metadata": "read", "members": "read", "checks": "read"} + perms := map[string]string{"contents": "write", "pull_requests": "write", "issues": "write", "metadata": "read", "members": "read", "checks": "read", "actions": "read"} delete(perms, missing) e.srv.SetInstallationPermissions(1, perms) _, err := e.connect(t).Observe(ctx, ref) diff --git a/internal/provider/github/testdata/golden/observe/pr-superseded.json b/internal/provider/github/testdata/golden/observe/pr-superseded.json new file mode 100644 index 00000000..64ecd9fd --- /dev/null +++ b/internal/provider/github/testdata/golden/observe/pr-superseded.json @@ -0,0 +1,22 @@ +{ + "ref": { + "provider": "github-public", + "kind": "pr", + "ref": "compliance-framework/docs#92" + }, + "state": "open", + "author": { + "id": "github-public:renovate[bot]", + "isBot": true + }, + "updatedAt": "2026-11-24T14:12:03Z", + "pr": { + "draft": false, + "head": "5e68fb002a163814ca570130838187423532fb60", + "base": "main", + "checks": { + "state": "success", + "settled": true + } + } +} diff --git a/internal/provider/github/testdata/graphql/pr-superseded.json b/internal/provider/github/testdata/graphql/pr-superseded.json new file mode 100644 index 00000000..9cd3b02b --- /dev/null +++ b/internal/provider/github/testdata/graphql/pr-superseded.json @@ -0,0 +1,35 @@ +{ + "data": { + "repository": { + "nameWithOwner": "compliance-framework/docs", + "defaultBranchRef": { "name": "main" }, + "issueOrPullRequest": { + "__typename": "PullRequest", + "id": "PR_kwDOLq7d2c5zQ2cD", + "number": 92, + "state": "OPEN", + "isDraft": false, + "updatedAt": "2026-11-24T14:12:03Z", + "headRefOid": "5e68fb002a163814ca570130838187423532fb60", + "baseRefName": "main", + "merged": false, + "mergedAt": null, + "mergeCommit": null, + "author": { "__typename": "Bot", "login": "renovate" }, + "labels": { "nodes": [] }, + "reviews": { "nodes": [] }, + "reviewThreads": { "pageInfo": { "hasNextPage": false, "endCursor": null }, "nodes": [] }, + "commits": { "nodes": [ { "commit": { "oid": "5e68fb002a163814ca570130838187423532fb60", "checkSuites": { "nodes": [ + {"databaseId": 122870589751, "createdAt": "2026-11-24T14:00:57Z", "status": "COMPLETED", "conclusion": "SKIPPED", "app": {"databaseId": 347564}, "workflowRun": null, "checkRuns": {"totalCount": 1}}, + {"databaseId": 122870649391, "createdAt": "2026-11-24T14:01:04Z", "status": "COMPLETED", "conclusion": "CANCELLED", "app": {"databaseId": 15368}, "workflowRun": {"runNumber": 372, "event": "pull_request", "workflow": {"databaseId": 379691137}}, "checkRuns": {"totalCount": 4}}, + {"databaseId": 122870651416, "createdAt": "2026-11-24T14:01:04Z", "status": "COMPLETED", "conclusion": "SUCCESS", "app": {"databaseId": 15368}, "workflowRun": {"runNumber": 373, "event": "pull_request", "workflow": {"databaseId": 379691137}}, "checkRuns": {"totalCount": 4}}, + {"databaseId": 122870653629, "createdAt": "2026-11-24T14:01:05Z", "status": "COMPLETED", "conclusion": "SUCCESS", "app": {"databaseId": 15368}, "workflowRun": {"runNumber": 2512, "event": "pull_request", "workflow": {"databaseId": 67470646}}, "checkRuns": {"totalCount": 10}}, + {"databaseId": 122870654416, "createdAt": "2026-11-24T14:01:05Z", "status": "COMPLETED", "conclusion": "SUCCESS", "app": {"databaseId": 15368}, "workflowRun": {"runNumber": 2513, "event": "pull_request", "workflow": {"databaseId": 67470646}}, "checkRuns": {"totalCount": 10}}, + {"databaseId": 122871061681, "createdAt": "2026-11-24T14:01:52Z", "status": "COMPLETED", "conclusion": "SUCCESS", "app": {"databaseId": 57789}, "workflowRun": null, "checkRuns": {"totalCount": 1}}, + {"databaseId": 122876027225, "createdAt": "2026-11-24T14:11:49Z", "status": "COMPLETED", "conclusion": "SUCCESS", "app": {"databaseId": 15368}, "workflowRun": {"runNumber": 2516, "event": "pull_request", "workflow": {"databaseId": 67470646}}, "checkRuns": {"totalCount": 8}}, + {"databaseId": 122876027300, "createdAt": "2026-11-24T14:11:49Z", "status": "QUEUED", "conclusion": null, "app": {"databaseId": 29110}, "workflowRun": null, "checkRuns": {"totalCount": 0}} + ] } } } ] } + } + } + } +}