Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8510: fix(ghsnapshot): drop cancelled workflow runs that a newer run of the same workflow replaced from the PR rollup (#9860)

Bohan Jiang82492f94d669
diff --git a/apps/docs/content/docs/github-integration.fr.mdx b/apps/docs/content/docs/github-integration.fr.mdx
index f623fd8e26..1fe5783235 100644
--- a/apps/docs/content/docs/github-integration.fr.mdx
+++ b/apps/docs/content/docs/github-integration.fr.mdx
@@ -152,13 +152,14 @@ Permissions de dépôt (Repository permissions) :
| Pull requests | Read-only |
| Checks | Read-only ; sert à afficher le statut CI |
| Commit statuses | Read-only ; sert à agréger la CI basée sur les statuts hérités (legacy statuses) |
+| Actions | Facultatif, Read-only ; permet au statut CI d'ignorer une exécution annulée remplacée par une exécution plus récente du même workflow sur le même commit |
Abonnez-vous à ces événements :
- **Pull request** ;
- **Check suite**, **Check run** et **Status**, qui déclenchent l'actualisation de la CI et de la possibilité de fusion.
-Les instantanés de PR utilisent les API REST Pull requests, Checks et Commit statuses. La permission Contents n'est pas nécessaire.
+Les instantanés de PR utilisent les API REST Pull requests, Checks et Commit statuses. La permission Contents n'est pas nécessaire. Avec la permission facultative Actions, Multica lit aussi les exécutions de workflow du commit. Sans elle, une exécution annulée compte toujours comme un échec, même après la réussite d'une exécution plus récente du même workflow.
<Callout type="warning">
Il s'agit du **Webhook secret**, et non du Client secret OAuth. Si les deux côtés n'ont pas le même secret de webhook, les livraisons GitHub renvoient `401 invalid signature`.
diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdx
index 7ef0f87b31..a5b03bd3fa 100644
--- a/apps/docs/content/docs/github-integration.ja.mdx
+++ b/apps/docs/content/docs/github-integration.ja.mdx
@@ -150,13 +150,14 @@ Repository permissions:
| Pull requests | Read-only |
| Checks | Read-only。CI の状態表示に使用 |
| Commit statuses | Read-only。legacy status 形式の CI 集計に使用 |
+| Actions | 任意。Read-only。同じコミットで同じワークフローの新しい実行に置き換えられた、キャンセル済みの実行を CI 状態から除外するために使用 |
次のイベントを購読します。
- **Pull request**
- **Check suite**、**Check run**、**Status**。CI とマージ可能性を更新するために使用します。
-PR スナップショットは Pull requests、Checks、Commit statuses の REST API から取得します。Contents 権限は不要です。
+PR スナップショットは Pull requests、Checks、Commit statuses の REST API から取得します。Contents 権限は不要です。任意の Actions 権限を付与すると、そのコミットのワークフロー実行も読み取ります。付与しない場合、同じワークフローの新しい実行が成功しても、キャンセルされた古い実行は失敗として数えられます。
<Callout type="warning">
必要なのは **Webhook secret** であり、OAuth Client secret ではありません。GitHub と Multica に入力した Webhook secret が異なる場合、GitHub delivery は `401 invalid signature` を返します。
diff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdx
index 6fcd668e00..2578ab007e 100644
--- a/apps/docs/content/docs/github-integration.ko.mdx
+++ b/apps/docs/content/docs/github-integration.ko.mdx
@@ -150,13 +150,14 @@ Repository permissions:
| Pull requests | Read-only |
| Checks | Read-only. CI 상태 표시에 사용 |
| Commit statuses | Read-only. legacy status 형식의 CI 집계에 사용 |
+| Actions | 선택 사항. Read-only. 같은 커밋에서 같은 워크플로의 새 실행으로 대체된, 취소된 실행을 CI 상태에서 제외하는 데 사용 |
다음 이벤트를 구독합니다.
- **Pull request**
- CI와 merge 가능 여부 새로 고침을 트리거할 **Check suite**, **Check run**, **Status**
-PR snapshot은 Pull requests, Checks 및 Commit statuses REST API로 가져옵니다. Contents 권한은 필요하지 않습니다.
+PR snapshot은 Pull requests, Checks 및 Commit statuses REST API로 가져옵니다. Contents 권한은 필요하지 않습니다. 선택 사항인 Actions 권한을 부여하면 해당 커밋의 워크플로 실행도 읽습니다. 부여하지 않으면 같은 워크플로의 새 실행이 통과해도 취소된 이전 실행은 실패로 계산됩니다.
<Callout type="warning">
여기에는 OAuth Client secret이 아니라 **Webhook secret**이 필요합니다. 양쪽에 입력한 Webhook secret이 다르면 GitHub delivery가 `401 invalid signature`를 반환합니다.
diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdx
index 27672e8e50..9f9a731252 100644
--- a/apps/docs/content/docs/github-integration.mdx
+++ b/apps/docs/content/docs/github-integration.mdx
@@ -152,13 +152,14 @@ Repository permissions:
| Pull requests | Read-only |
| Checks | Read-only; used to show CI status |
| Commit statuses | Read-only; used to aggregate legacy-status CI |
+| Actions | Optional, read-only; lets CI status ignore a cancelled run that a newer run of the same workflow replaced on the same commit |
Subscribe to these events:
- **Pull request**;
- **Check suite**, **Check run**, and **Status**, which trigger CI and mergeability refreshes.
-PR snapshots use the Pull requests, Checks, and Commit statuses REST APIs. Contents access is not required.
+PR snapshots use the Pull requests, Checks, and Commit statuses REST APIs. Contents access is not required. With the optional Actions permission, Multica also reads the commit's workflow runs. Without it, a cancelled run still counts as failed even after a newer run of the same workflow passes.
<Callout type="warning">
This is the **Webhook secret**, not the OAuth Client secret. If the two sides have different webhook secrets, GitHub deliveries return `401 invalid signature`.
diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdx
index 1918d3c841..15880f189a 100644
--- a/apps/docs/content/docs/github-integration.zh.mdx
+++ b/apps/docs/content/docs/github-integration.zh.mdx
@@ -152,13 +152,14 @@ Repository permissions:
| Pull requests | Read-only |
| Checks | Read-only;用于显示 CI 状态 |
| Commit statuses | Read-only;用于汇总 legacy status 形式的 CI |
+| Actions | 可选,Read-only;同一提交上,被同一工作流的新运行取代的已取消运行不再计入 CI 状态 |
订阅以下事件:
- **Pull request**;
- **Check suite**、**Check run** 和 **Status**,用于触发 CI 与可合并性刷新。
-PR 快照通过 Pull requests、Checks 和 Commit statuses 的 REST API 获取,不需要 Contents 权限。
+PR 快照通过 Pull requests、Checks 和 Commit statuses 的 REST API 获取,不需要 Contents 权限。授予可选的 Actions 权限后,还会读取该提交的工作流运行记录;未授予时,即使同一工作流的新运行已通过,被取消的旧运行仍按失败计算。
<Callout type="warning">
这里需要的是 **Webhook secret**,不是 OAuth Client secret。两边填写的 Webhook secret 不一致时,GitHub delivery 会返回 `401 invalid signature`。
diff --git a/server/internal/integrations/ghsnapshot/client.go b/server/internal/integrations/ghsnapshot/client.go
index b3e65d5ecc..75daff750f 100644
--- a/server/internal/integrations/ghsnapshot/client.go
+++ b/server/internal/integrations/ghsnapshot/client.go
@@ -76,6 +76,8 @@ type Client struct {
type cachedToken struct {
token string
expiry time.Time
+ // permissions is what GitHub granted this token, e.g. {"checks": "read"}.
+ permissions map[string]string
}
// NewClientFromEnv builds a Client from GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY.
@@ -187,8 +189,9 @@ func (c *Client) mintInstallationToken(ctx context.Context, installationID int64
return "", fmt.Errorf("github installation token: unexpected status %d", resp.StatusCode)
}
var parsed struct {
- Token string `json:"token"`
- ExpiresAt string `json:"expires_at"`
+ Token string `json:"token"`
+ ExpiresAt string `json:"expires_at"`
+ Permissions map[string]string `json:"permissions"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
return "", errors.New("github installation token: malformed response")
@@ -203,11 +206,24 @@ func (c *Client) mintInstallationToken(ctx context.Context, installationID int64
}
}
c.mu.Lock()
- c.tokens[installationID] = cachedToken{token: parsed.Token, expiry: expiry}
+ c.tokens[installationID] = cachedToken{token: parsed.Token, expiry: expiry, permissions: parsed.Permissions}
c.mu.Unlock()
return parsed.Token, nil
}
+// tokenCanRead reports whether the installation's cached token was granted at
+// least read access to permission. It answers false until a request on this
+// installation has minted a token, so callers ask after their first request.
+func (c *Client) tokenCanRead(installationID int64, permission string) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch c.tokens[installationID].permissions[permission] {
+ case "read", "write", "admin":
+ return true
+ }
+ return false
+}
+
// restGet authenticates against a fixed API path. Response bodies and tokens
// never appear in errors; permission failures must not pause an installation.
func (c *Client) restGet(ctx context.Context, installationID int64, path string) (json.RawMessage, error) {
diff --git a/server/internal/integrations/ghsnapshot/rest_snapshot_test.go b/server/internal/integrations/ghsnapshot/rest_snapshot_test.go
index 1628dd9224..ebc29cf6a9 100644
--- a/server/internal/integrations/ghsnapshot/rest_snapshot_test.go
+++ b/server/internal/integrations/ghsnapshot/rest_snapshot_test.go
@@ -14,6 +14,11 @@ import (
// Only the REST endpoints covered by the App's existing permissions are served.
// Fork PRs deliberately have a head repository outside the installation.
func snapshotServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {
+ t.Helper()
+ return snapshotServerWithPermissions(t, map[string]string{"pull_requests": "read", "checks": "read", "statuses": "read"}, handler)
+}
+
+func snapshotServerWithPermissions(t *testing.T, permissions map[string]string, handler http.HandlerFunc) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
@@ -21,7 +26,7 @@ func snapshotServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{
"token": "ghs_secret", "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339),
- "permissions": map[string]string{"pull_requests": "read", "checks": "read", "statuses": "read"},
+ "permissions": permissions,
})
return
}
@@ -225,3 +230,228 @@ func TestFetchPRSnapshotRESTRejectsPartialResults(t *testing.T) {
})
}
}
+
+// A second workflow run on the same head is a separate check suite that
+// `filter=latest` keeps. Only a cancelled run that a newer run of the same
+// workflow and event replaced may leave the rollup, and only when the Actions
+// API can confirm that.
+func TestFetchPRSnapshotRESTSupersededSuites(t *testing.T) {
+ check := func(id, suite int, name, status, conclusion string) map[string]any {
+ r := map[string]any{"id": id, "head_sha": "sha1", "name": name, "status": status,
+ "check_suite": map[string]any{"id": suite}, "app": map[string]any{"slug": "github-actions"}}
+ if conclusion != "" {
+ r["conclusion"] = conclusion
+ }
+ return r
+ }
+ done := func(id, suite int, name, conclusion string) map[string]any {
+ return check(id, suite, name, "completed", conclusion)
+ }
+ otherApp := func(r map[string]any) map[string]any {
+ r["app"] = map[string]any{"slug": "other-ci"}
+ return r
+ }
+ workflowRun := func(id, workflow int, event string, suite int, status, conclusion string) map[string]any {
+ r := map[string]any{"id": id, "head_sha": "sha1", "workflow_id": workflow, "event": event,
+ "check_suite_id": suite, "status": status, "conclusion": nil}
+ if conclusion != "" {
+ r["conclusion"] = conclusion
+ }
+ return r
+ }
+ const ci, docs = 1, 2
+ // The case from #9830: run 1 is cancelled and its always() gate fails,
+ // run 2 of the same workflow passes.
+ replacedByGreenRun := []map[string]any{
+ done(1, 10, "test", "cancelled"), done(2, 10, "gate", "failure"),
+ done(3, 20, "test", "success"), done(4, 20, "gate", "success"),
+ }
+ cases := []struct {
+ name string
+ runs []map[string]any
+ workflowRuns []map[string]any
+ noActions bool
+ runsFail bool
+ want string
+ wantNames []string
+ wantFetch bool
+ wantErr bool
+ }{
+ {
+ name: "cancelled run replaced by a green run of the same workflow",
+ runs: replacedByGreenRun,
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "cancelled"),
+ workflowRun(200, ci, "pull_request", 20, "completed", "success"),
+ },
+ want: "SUCCESS", wantNames: []string{"test", "gate"}, wantFetch: true,
+ },
+ {
+ name: "independent workflow with the same check name",
+ runs: []map[string]any{
+ done(1, 10, "test", "cancelled"), done(2, 10, "gate", "failure"),
+ done(3, 20, "test", "success"),
+ },
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "cancelled"),
+ workflowRun(200, docs, "pull_request", 20, "completed", "success"),
+ },
+ want: "FAILURE", wantNames: []string{"test", "gate", "test"}, wantFetch: true,
+ },
+ {
+ name: "same workflow for another event",
+ runs: []map[string]any{done(1, 10, "test", "cancelled"), done(2, 20, "test", "success")},
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "push", 10, "completed", "cancelled"),
+ workflowRun(200, ci, "pull_request", 20, "completed", "success"),
+ },
+ want: "FAILURE", wantNames: []string{"test", "test"}, wantFetch: true,
+ },
+ {
+ name: "matrix cancelled before expansion",
+ runs: []map[string]any{
+ done(1, 10, "changes", "cancelled"), done(2, 10, "build (${{ matrix.os }})", "cancelled"),
+ done(3, 20, "changes", "success"), done(4, 20, "build (ubuntu)", "success"),
+ },
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "cancelled"),
+ workflowRun(200, ci, "pull_request", 20, "completed", "success"),
+ },
+ want: "SUCCESS", wantNames: []string{"changes", "build (ubuntu)"}, wantFetch: true,
+ },
+ {
+ name: "replacement still running",
+ runs: []map[string]any{done(1, 10, "test", "cancelled"), check(2, 20, "test", "in_progress", "")},
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "cancelled"),
+ workflowRun(200, ci, "pull_request", 20, "in_progress", ""),
+ },
+ want: "PENDING", wantNames: []string{"test"}, wantFetch: true,
+ },
+ {
+ name: "replacement has not reported checks yet",
+ runs: []map[string]any{done(1, 10, "test", "cancelled"), done(2, 30, "lint", "success")},
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "cancelled"),
+ workflowRun(200, ci, "pull_request", 20, "queued", ""),
+ workflowRun(300, docs, "pull_request", 30, "completed", "success"),
+ },
+ want: "FAILURE", wantNames: []string{"test", "lint"}, wantFetch: true,
+ },
+ {
+ name: "replacement between jobs",
+ runs: []map[string]any{done(1, 10, "test", "cancelled"), done(2, 20, "test", "success")},
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "cancelled"),
+ workflowRun(200, ci, "pull_request", 20, "in_progress", ""),
+ },
+ want: "FAILURE", wantNames: []string{"test", "test"}, wantFetch: true,
+ },
+ {
+ name: "failed run is never dropped",
+ runs: []map[string]any{
+ done(1, 10, "test (a)", "failure"), done(2, 10, "test (b)", "cancelled"),
+ done(3, 20, "test (a)", "success"), done(4, 20, "test (b)", "success"),
+ },
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "failure"),
+ workflowRun(200, ci, "pull_request", 20, "completed", "success"),
+ },
+ want: "FAILURE", wantNames: []string{"test (a)", "test (b)", "test (a)", "test (b)"}, wantFetch: true,
+ },
+ {
+ name: "newest run cancelled",
+ runs: []map[string]any{done(1, 10, "test", "success"), done(2, 20, "test", "cancelled")},
+ workflowRuns: []map[string]any{
+ workflowRun(100, ci, "pull_request", 10, "completed", "success"),
+ workflowRun(200, ci, "pull_request", 20, "completed", "cancelled"),
+ },
+ want: "FAILURE", wantNames: []string{"test", "test"}, wantFetch: true,
+ },
+ {
+ name: "without Actions permission",
+ runs: replacedByGreenRun, noActions: true,
+ want: "FAILURE", wantNames: []string{"test", "gate", "test", "gate"},
+ },
+ {
+ name: "passing checks make no extra request",
+ runs: []map[string]any{done(1, 10, "test", "success"), done(2, 20, "lint", "success")},
+ want: "SUCCESS", wantNames: []string{"test", "lint"},
+ },
+ {
+ name: "checks from another app make no extra request",
+ runs: []map[string]any{otherApp(done(1, 10, "test", "cancelled")), otherApp(done(2, 20, "test", "success"))},
+ want: "FAILURE", wantNames: []string{"test", "test"},
+ },
+ {
+ name: "workflow runs page failed",
+ runs: replacedByGreenRun, runsFail: true,
+ wantFetch: true, wantErr: true,
+ },
+ {
+ name: "workflow run on another head",
+ runs: replacedByGreenRun,
+ workflowRuns: []map[string]any{
+ {"id": 100, "head_sha": "sha2", "workflow_id": ci, "event": "pull_request", "check_suite_id": 10, "status": "completed", "conclusion": "cancelled"},
+ workflowRun(200, ci, "pull_request", 20, "completed", "success"),
+ },
+ wantFetch: true, wantErr: true,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ permissions := map[string]string{"pull_requests": "read", "checks": "read", "statuses": "read", "actions": "read"}
+ if tc.noActions {
+ delete(permissions, "actions")
+ }
+ workflowCalls := 0
+ srv := snapshotServerWithPermissions(t, permissions, func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/repos/o/r/pulls/5":
+ writeTestPR(w, "sha1", true, "clean")
+ case "/repos/o/r/commits/sha1/check-runs":
+ _ = json.NewEncoder(w).Encode(map[string]any{"total_count": len(tc.runs), "check_runs": tc.runs})
+ case "/repos/o/r/commits/sha1/status":
+ _, _ = w.Write([]byte(`{"total_count":0,"statuses":[]}`))
+ case "/repos/o/r/actions/runs":
+ workflowCalls++
+ if q := r.URL.Query(); q.Get("head_sha") != "sha1" || q.Get("exclude_pull_requests") != "true" {
+ t.Errorf("workflow runs query = %s", r.URL.RawQuery)
+ }
+ if tc.runsFail {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"total_count": len(tc.workflowRuns), "workflow_runs": tc.workflowRuns})
+ default:
+ t.Errorf("unexpected request: %s", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ })
+ defer srv.Close()
+ snap, err := FetchPRSnapshot(context.Background(), newTestClient(t, srv.URL), 1, "o", "r", 5)
+ switch {
+ case tc.wantErr:
+ if err == nil || snap != nil {
+ t.Fatalf("snapshot=%+v err=%v; partial results must be rejected", snap, err)
+ }
+ case err != nil:
+ t.Fatal(err)
+ default:
+ var names []string
+ for _, cc := range snap.Contexts {
+ names = append(names, cc.Name)
+ }
+ if snap.RollupState != tc.want || strings.Join(names, ",") != strings.Join(tc.wantNames, ",") {
+ t.Fatalf("rollup = %q contexts = %q, want %q %q", snap.RollupState, names, tc.want, tc.wantNames)
+ }
+ }
+ // The workflow runs list costs a request and needs the optional
+ // Actions permission, so it is read only when it can change the
+ // result.
+ if (workflowCalls > 0) != tc.wantFetch {
+ t.Fatalf("workflow runs calls = %d, want fetch %v", workflowCalls, tc.wantFetch)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/ghsnapshot/snapshot.go b/server/internal/integrations/ghsnapshot/snapshot.go
index 1807a00f07..30895e8658 100644
--- a/server/internal/integrations/ghsnapshot/snapshot.go
+++ b/server/internal/integrations/ghsnapshot/snapshot.go
@@ -81,6 +81,24 @@ type restCheckRun struct {
Status string `json:"status"`
Conclusion string `json:"conclusion"`
DetailsURL string `json:"details_url"`
+ CheckSuite struct {
+ ID int64 `json:"id"`
+ } `json:"check_suite"`
+ App struct {
+ Slug string `json:"slug"`
+ } `json:"app"`
+}
+
+// restWorkflowRun is one GitHub Actions workflow run; each run owns exactly one
+// check suite.
+type restWorkflowRun struct {
+ ID int64 `json:"id"`
+ HeadSHA string `json:"head_sha"`
+ WorkflowID int64 `json:"workflow_id"`
+ Event string `json:"event"`
+ Status string `json:"status"`
+ Conclusion string `json:"conclusion"`
+ CheckSuiteID int64 `json:"check_suite_id"`
}
type restStatusContext struct {
@@ -122,6 +140,15 @@ func FetchPRSnapshot(ctx context.Context, c *Client, installationID int64, owner
return nil, errors.New("ghsnapshot: duplicate check run during pagination")
}
seenRuns[run.ID] = struct{}{}
+ }
+ superseded, err := fetchSupersededSuites(ctx, c, installationID, base, snap.HeadSHA, runs)
+ if err != nil {
+ return nil, err
+ }
+ for _, run := range runs {
+ if _, drop := superseded[run.CheckSuite.ID]; drop {
+ continue
+ }
status := normalizeRunStatus(run.Status)
conclusion := strings.ToLower(run.Conclusion)
if status != "completed" {
@@ -172,6 +199,87 @@ func FetchPRSnapshot(ctx context.Context, c *Client, installationID int64, owner
return snap, nil
}
+// actionsAppSlug identifies GitHub Actions check runs; only Actions exposes
+// which workflow and trigger a check suite belongs to.
+const actionsAppSlug = "github-actions"
+
+// fetchSupersededSuites returns the check suites on this head that a newer run
+// of the same workflow has replaced, so their check runs stay out of the
+// rollup. `filter=latest` only drops older attempts inside one suite; a second
+// workflow run on the same head (cancel-in-progress, a re-trigger on `edited`)
+// is a separate suite, and its cancelled predecessor would otherwise keep the
+// rollup at FAILURE after the newer run goes green.
+//
+// A suite is dropped only when its workflow run concluded cancelled and a newer
+// run of the same workflow for the same event exists on this head. That newer
+// run must already have check runs in this snapshot, and must be finished or
+// still have one running, so the rollup reads PENDING rather than passing
+// before the replacement has reported. A failed run is never dropped.
+//
+// Workflow identity is only available through the Actions API. Without the
+// optional Actions read permission nothing is dropped and the cancelled run
+// still fails the rollup: no Checks-only signal (check name, app, suite order)
+// proves two suites come from the same workflow. The lookup also runs only
+// when a failing Actions check sits beside another Actions suite.
+func fetchSupersededSuites(ctx context.Context, c *Client, installationID int64, base, headSHA string, runs []restCheckRun) (map[int64]struct{}, error) {
+ shown := make(map[int64]struct{})
+ running := make(map[int64]struct{})
+ failing := false
+ for _, run := range runs {
+ if run.App.Slug != actionsAppSlug || run.CheckSuite.ID <= 0 {
+ continue
+ }
+ shown[run.CheckSuite.ID] = struct{}{}
+ if normalizeRunStatus(run.Status) != "completed" {
+ running[run.CheckSuite.ID] = struct{}{}
+ } else if rollupConclusion(strings.ToLower(run.Conclusion)) == "FAILURE" {
+ failing = true
+ }
+ }
+ if len(shown) < 2 || !failing || !c.tokenCanRead(installationID, "actions") {
+ return nil, nil
+ }
+ workflowRuns, err := fetchSnapshotPages[restWorkflowRun](ctx, c, installationID,
+ base+"/actions/runs?exclude_pull_requests=true&head_sha="+url.QueryEscape(headSHA), "workflow_runs")
+ if err != nil {
+ return nil, err
+ }
+ type trigger struct {
+ workflow int64
+ event string
+ }
+ newest := make(map[trigger]restWorkflowRun, len(workflowRuns))
+ seen := make(map[int64]struct{}, len(workflowRuns))
+ for _, wr := range workflowRuns {
+ if wr.ID <= 0 || wr.WorkflowID <= 0 || wr.CheckSuiteID <= 0 || wr.HeadSHA != headSHA {
+ return nil, errors.New("ghsnapshot: invalid workflow run or mismatched head")
+ }
+ if _, dup := seen[wr.ID]; dup {
+ return nil, errors.New("ghsnapshot: duplicate workflow run during pagination")
+ }
+ seen[wr.ID] = struct{}{}
+ key := trigger{wr.WorkflowID, wr.Event}
+ if cur, ok := newest[key]; !ok || wr.ID > cur.ID {
+ newest[key] = wr
+ }
+ }
+ superseded := make(map[int64]struct{})
+ for _, wr := range workflowRuns {
+ latest := newest[trigger{wr.WorkflowID, wr.Event}]
+ if latest.ID == wr.ID || !strings.EqualFold(wr.Conclusion, "cancelled") {
+ continue
+ }
+ if _, ok := shown[latest.CheckSuiteID]; !ok {
+ continue
+ }
+ if _, ok := running[latest.CheckSuiteID]; !ok && !strings.EqualFold(latest.Status, "completed") {
+ continue
+ }
+ superseded[wr.CheckSuiteID] = struct{}{}
+ }
+ return superseded, nil
+}
+
func fetchSnapshotPR(ctx context.Context, c *Client, installationID int64, path string) (*restPullRequest, error) {
data, err := c.restGet(ctx, installationID, path)
if err != nil {