fix(watchpr): re-read GitHub CI every poll and page through check runs
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

This commit is contained in:
2026-11-22 02:07:25 +11:00
parent 6261b8e8d3
commit 08340cce22
3 changed files with 78 additions and 70 deletions
+26 -32
View File
@@ -39,13 +39,6 @@ type GitHubClient struct {
Token func() (string, error)
// Refresh mints a replacement when GitHub rejects the current token.
Refresh func() (string, error)
lastCI map[string]githubCI
}
// githubCI is the CI state last fetched for a PR's head.
type githubCI struct {
sha, state string
}
// maxRateLimitWait caps how long a watch pauses for one rate limit.
@@ -162,13 +155,27 @@ func (c *GitHubClient) attempt(path, token string, out any) error {
const githubPageSize = 100
// listAll fetches every page of a list endpoint.
func listAll[T any](c *GitHubClient, path string) ([]T, error) {
// listAll fetches every page of a list endpoint; a non-empty key names the
// field holding the list when each page is wrapped in an object.
func listAll[T any](c *GitHubClient, path, key string) ([]T, error) {
var all []T
for page := 1; ; page++ {
var items []T
if err := c.do(path+"?per_page="+strconv.Itoa(githubPageSize)+"&page="+strconv.Itoa(page), &items); err != nil {
return nil, err
pagePath := path + "?per_page=" + strconv.Itoa(githubPageSize) + "&page=" + strconv.Itoa(page)
if key == "" {
if err := c.do(pagePath, &items); err != nil {
return nil, err
}
} else {
var wrapped map[string]json.RawMessage
if err := c.do(pagePath, &wrapped); err != nil {
return nil, err
}
if raw, ok := wrapped[key]; ok {
if err := json.Unmarshal(raw, &items); err != nil {
return nil, fmt.Errorf("github GET %s: decoding %s: %w", pagePath, key, err)
}
}
}
all = append(all, items...)
if len(items) < githubPageSize {
@@ -294,17 +301,14 @@ func (c *GitHubClient) ciState(repo, sha string) (string, error) {
}
return "", err
}
// Only the first page of check runs is read; a head with more than 100 is not expected.
var checks struct {
CheckRuns []githubCheckRun `json:"check_runs"`
}
if err := c.do("/repos/"+repo+"/commits/"+sha+"/check-runs?per_page="+strconv.Itoa(githubPageSize), &checks); err != nil {
checks, err := listAll[githubCheckRun](c, "/repos/"+repo+"/commits/"+sha+"/check-runs", "check_runs")
if err != nil {
if IsNotFound(err) {
return "", nil
}
return "", err
}
return mergeGitHubCI(status.State, status.TotalCount, checks.CheckRuns), nil
return mergeGitHubCI(status.State, status.TotalCount, checks), nil
}
// FetchState makes *GitHubClient a StateFetcher. The agent logins come from the
@@ -319,23 +323,13 @@ func (c *GitHubClient) FetchState(ref PRRef, _ string) (PRState, error) {
}
return PRState{}, err
}
// CI is re-read only while it can still change on its own: a new head, or a
// state that is pending or not yet reported.
ci, ok := c.lastCI[ref.String()]
if !ok || ci.sha != pr.Head.Sha || ci.state == "pending" || ci.state == "" {
state, err := c.ciState(repo, pr.Head.Sha)
if err != nil {
return PRState{}, err
}
ci = githubCI{sha: pr.Head.Sha, state: state}
if c.lastCI == nil {
c.lastCI = map[string]githubCI{}
}
c.lastCI[ref.String()] = ci
ci, err := c.ciState(repo, pr.Head.Sha)
if err != nil {
return PRState{}, err
}
comments := 0
for _, path := range []string{"/issues/" + n + "/comments", "/pulls/" + n + "/comments", "/pulls/" + n + "/reviews"} {
items, err := listAll[githubActivity](c, "/repos/"+repo+path)
items, err := listAll[githubActivity](c, "/repos/"+repo+path, "")
if err != nil {
return PRState{}, err
}
@@ -349,7 +343,7 @@ func (c *GitHubClient) FetchState(ref PRRef, _ string) (PRState, error) {
BaseSHA: pr.Base.Sha,
Mergeable: githubMergeability(pr.Mergeable),
MergeableState: pr.MergeableState,
CIStatus: ci.state,
CIStatus: ci,
NonAgentComments: comments,
Title: pr.Title,
URL: pr.HTMLURL,
+50 -36
View File
@@ -80,14 +80,13 @@ type fakeGitHubPR struct {
mu sync.Mutex
pr string
status string
checks string
checks []string
issue []string
review []string
reviews []string
authSeen []string
reject string // a token the server answers 401 for
rateLimit bool
ciReads int // commit-status requests served
}
func (f *fakeGitHubPR) set(fn func(*fakeGitHubPR)) {
@@ -110,13 +109,16 @@ func activity(logins ...string) []string {
func (f *fakeGitHubPR) serve(t *testing.T) *httptest.Server {
t.Helper()
page := func(w http.ResponseWriter, r *http.Request, items []string) {
slice := func(r *http.Request, items []string) string {
p, _ := strconv.Atoi(r.URL.Query().Get("page"))
if r.URL.Query().Get("per_page") != "100" || p < 1 {
t.Errorf("%s: unpaged list request", r.URL)
}
lo, hi := min((p-1)*100, len(items)), min(p*100, len(items))
_, _ = w.Write([]byte("[" + strings.Join(items[lo:hi], ",") + "]"))
return "[" + strings.Join(items[lo:hi], ",") + "]"
}
page := func(w http.ResponseWriter, r *http.Request, items []string) {
_, _ = w.Write([]byte(slice(r, items)))
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
@@ -139,10 +141,9 @@ func (f *fakeGitHubPR) serve(t *testing.T) *httptest.Server {
case "/repos/IUCLabs/app/pulls/5":
_, _ = w.Write([]byte(f.pr))
case "/repos/IUCLabs/app/commits/aaa/status", "/repos/IUCLabs/app/commits/bbb/status":
f.ciReads++
_, _ = w.Write([]byte(f.status))
case "/repos/IUCLabs/app/commits/aaa/check-runs", "/repos/IUCLabs/app/commits/bbb/check-runs":
_, _ = w.Write([]byte(f.checks))
_, _ = w.Write([]byte(`{"check_runs":` + slice(r, f.checks) + `}`))
case "/repos/IUCLabs/app/issues/5/comments":
page(w, r, f.issue)
case "/repos/IUCLabs/app/pulls/5/comments":
@@ -177,7 +178,7 @@ func TestGitHubFetchState(t *testing.T) {
f := &fakeGitHubPR{
pr: openPR("aaa", "null"),
status: `{"state":"success","total_count":1}`,
checks: `{"check_runs":[{"status":"completed","conclusion":"failure"}]}`,
checks: []string{`{"status":"completed","conclusion":"failure"}`},
issue: activity(humans...),
review: activity("iuclabs-coder[bot]", "alice"),
reviews: activity("review:alice", "iuclabs-reviewer[bot]"),
@@ -207,7 +208,7 @@ func TestGitHubFetchState(t *testing.T) {
}
func TestGitHubFetchStateErrors(t *testing.T) {
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"pending","total_count":0}`, checks: `{"check_runs":[]}`}
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"pending","total_count":0}`, checks: []string{}}
c := newFakeGitHubClient(f.serve(t))
gone := ghRef
@@ -245,7 +246,7 @@ func TestGitHubAnonymousRejectionIsNoCredential(t *testing.T) {
}
func TestGitHubReMintsRejectedToken(t *testing.T) {
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"success","total_count":1}`, checks: `{"check_runs":[]}`, reject: "old"}
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"success","total_count":1}`, checks: []string{}, reject: "old"}
c := newFakeGitHubClient(f.serve(t))
current := "old"
refreshes := 0
@@ -316,7 +317,11 @@ func runGitHubWatch(t *testing.T, f *fakeGitHubPR, steps ...func(*fakeGitHubPR))
select {
case ticks <- now:
case r := <-done:
t.Fatalf("step %d: watch ended early: %+v, %v", i, r.res, r.err)
// The previous step's poll may already see the last step's state.
if i < len(steps)-1 || r.err != nil {
t.Fatalf("step %d: watch ended early: %+v, %v", i, r.res, r.err)
}
return r.res
}
}
close(ticks)
@@ -331,7 +336,7 @@ func pendingPR() *fakeGitHubPR {
return &fakeGitHubPR{
pr: openPR("aaa", "true"),
status: `{"state":"pending","total_count":1}`,
checks: `{"check_runs":[{"status":"in_progress"}]}`,
checks: []string{`{"status":"in_progress"}`},
}
}
@@ -345,7 +350,7 @@ func TestWatchGitHubHumanReviewAlerts(t *testing.T) {
},
func(f *fakeGitHubPR) {
f.status = `{"state":"success","total_count":1}`
f.checks = `{"check_runs":[{"status":"completed","conclusion":"success"}]}`
f.checks = []string{`{"status":"completed","conclusion":"success"}`}
f.reviews = activity("iuclabs-reviewer[bot]")
},
)
@@ -364,7 +369,7 @@ func TestWatchGitHubCheckRunFailureAlerts(t *testing.T) {
res := runGitHubWatch(t, pendingPR(),
func(f *fakeGitHubPR) {
f.status = `{"state":"success","total_count":1}`
f.checks = `{"check_runs":[{"status":"completed","conclusion":"success"},{"status":"completed","conclusion":"failure"}]}`
f.checks = []string{`{"status":"completed","conclusion":"success"}`, `{"status":"completed","conclusion":"failure"}`}
},
)
if res.Reason != "CI failed (failure)" {
@@ -407,30 +412,39 @@ func TestRateLimitWait(t *testing.T) {
}
}
// CI is re-read only for a new head or a pending/absent state.
func TestGitHubCIReadOnlyWhileItCanChange(t *testing.T) {
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"pending","total_count":1}`, checks: `{"check_runs":[]}`}
c := newFakeGitHubClient(f.serve(t))
fetch := func(wantReads int, wantCI string) {
t.Helper()
st, err := c.FetchState(ghRef, "")
if err != nil {
t.Fatal(err)
}
f.mu.Lock()
reads := f.ciReads
f.mu.Unlock()
if reads != wantReads || st.CIStatus != wantCI {
t.Errorf("ci reads = %d, ci = %q; want %d, %q", reads, st.CIStatus, wantReads, wantCI)
}
// A re-run that fails on the same head after reporting success still alerts.
func TestWatchGitHubSameHeadSuccessToFailureAlerts(t *testing.T) {
res := runGitHubWatch(t, pendingPR(),
func(f *fakeGitHubPR) {
f.status = `{"state":"success","total_count":1}`
f.checks = []string{`{"status":"completed","conclusion":"success"}`}
},
// Sending this step's tick proves the success poll has finished.
func(*fakeGitHubPR) {},
func(f *fakeGitHubPR) {
f.checks = []string{`{"status":"completed","conclusion":"success"}`, `{"status":"completed","conclusion":"failure"}`}
},
)
if res.Reason != "CI failed (failure)" {
t.Errorf("result = %+v, want the late failure to alert", res)
}
}
// A failing check run past the first page of 100 still fails CI.
func TestGitHubCheckRunsPaginated(t *testing.T) {
checks := make([]string, 0, 101)
for i := 0; i < 100; i++ {
checks = append(checks, `{"status":"completed","conclusion":"success"}`)
}
checks = append(checks, `{"status":"completed","conclusion":"failure"}`)
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"success","total_count":1}`, checks: checks}
st, err := newFakeGitHubClient(f.serve(t)).FetchState(ghRef, "")
if err != nil {
t.Fatal(err)
}
if st.CIStatus != "failure" {
t.Errorf("ci = %q, want failure from page 2", st.CIStatus)
}
fetch(1, "pending")
f.set(func(f *fakeGitHubPR) { f.status = `{"state":"success","total_count":1}` })
fetch(2, "success")
f.set(func(f *fakeGitHubPR) { f.status = `{"state":"failure","total_count":1}` })
fetch(2, "success")
f.set(func(f *fakeGitHubPR) { f.pr = openPR("bbb", "true") })
fetch(3, "failure")
}
// A rate limit pauses the baseline and the polls until it resets and never