fix(watchpr): pause on GitHub rate limits and skip settled CI reads

This commit is contained in:
2026-11-22 02:01:16 +11:00
parent 2332cf4b5f
commit 05c665857d
4 changed files with 217 additions and 13 deletions
+60 -5
View File
@@ -2,12 +2,14 @@ package agent
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
// DefaultGitHubAgentLogins are the GitHub identities whose activity watchpr
@@ -37,6 +39,49 @@ 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.
const maxRateLimitWait = 15 * time.Minute
// RateLimitError is a GitHub 403/429 rate limit, which clears at Reset.
type RateLimitError struct {
Path string
Status int
Reset time.Time
}
func (e *RateLimitError) Error() string {
return fmt.Sprintf("github GET %s: rate limited (HTTP %d) until %s", e.Path, e.Status, e.Reset.Format(time.RFC3339))
}
// rateLimitReset reads Retry-After (seconds), then X-RateLimit-Reset (epoch
// seconds), falling back to a minute from now.
func rateLimitReset(h http.Header, now time.Time) time.Time {
if s, err := strconv.Atoi(h.Get("Retry-After")); err == nil {
return now.Add(time.Duration(s) * time.Second)
}
if s, err := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64); err == nil {
return time.Unix(s, 0)
}
return now.Add(time.Minute)
}
// RateLimitWait reports whether err is a rate limit and how long from now to
// wait it out, between a second and maxRateLimitWait.
func RateLimitWait(err error, now time.Time) (time.Duration, bool) {
var rl *RateLimitError
if !errors.As(err, &rl) {
return 0, false
}
return min(max(rl.Reset.Sub(now), time.Second), maxRateLimitWait), true
}
// NewGitHubClient builds an anonymous client for GITHUB_API_URL.
@@ -105,7 +150,7 @@ func (c *GitHubClient) attempt(path, token string, out any) error {
// A rate limit is a 403/429 that clears on its own, so it must not end a watch as an auth failure.
if resp.StatusCode == http.StatusTooManyRequests || resp.Header.Get("X-RateLimit-Remaining") == "0" ||
(resp.StatusCode == http.StatusForbidden && strings.Contains(strings.ToLower(body), "rate limit")) {
return fmt.Errorf("github GET %s: rate limited (HTTP %d)", path, resp.StatusCode)
return &RateLimitError{Path: path, Status: resp.StatusCode, Reset: rateLimitReset(resp.Header, time.Now())}
}
return &APIError{Service: "github", Method: http.MethodGet, Path: path, StatusCode: resp.StatusCode, Body: body}
}
@@ -274,9 +319,19 @@ func (c *GitHubClient) FetchState(ref PRRef, _ string) (PRState, error) {
}
return PRState{}, err
}
ci, err := c.ciState(repo, pr.Head.Sha)
if err != nil {
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
}
comments := 0
for _, path := range []string{"/issues/" + n + "/comments", "/pulls/" + n + "/comments", "/pulls/" + n + "/reviews"} {
@@ -294,7 +349,7 @@ func (c *GitHubClient) FetchState(ref PRRef, _ string) (PRState, error) {
BaseSHA: pr.Base.Sha,
Mergeable: githubMergeability(pr.Mergeable),
MergeableState: pr.MergeableState,
CIStatus: ci,
CIStatus: ci.state,
NonAgentComments: comments,
Title: pr.Title,
URL: pr.HTMLURL,
+115 -2
View File
@@ -87,6 +87,7 @@ type fakeGitHubPR struct {
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)) {
@@ -124,6 +125,7 @@ func (f *fakeGitHubPR) serve(t *testing.T) *httptest.Server {
f.authSeen = append(f.authSeen, auth)
if f.rateLimit {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("Retry-After", "120")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"API rate limit exceeded"}`))
return
@@ -137,6 +139,7 @@ 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))
@@ -215,8 +218,8 @@ func TestGitHubFetchStateErrors(t *testing.T) {
f.set(func(f *fakeGitHubPR) { f.rateLimit = true })
_, err := c.FetchState(ghRef, "")
if err == nil || IsAuthError(err) || !strings.Contains(err.Error(), "rate limited") {
t.Errorf("rate limit err = %v, want a transient non-auth error", err)
if d, ok := RateLimitWait(err, time.Now()); !ok || IsAuthError(err) || d < 110*time.Second || d > 120*time.Second {
t.Errorf("rate limit err = %v (wait %v), want a ~120s rate limit that is not an auth error", err, d)
}
f.set(func(f *fakeGitHubPR) { f.rateLimit = false })
@@ -379,3 +382,113 @@ func TestWatchGitHubMergeAlerts(t *testing.T) {
t.Errorf("result = %+v, want merged", res)
}
}
func TestRateLimitWait(t *testing.T) {
now := time.Unix(1_000_000, 0)
tests := []struct {
name string
header http.Header
want time.Duration
}{
{"retry-after", http.Header{"Retry-After": {"30"}, "X-Ratelimit-Reset": {"1000600"}}, 30 * time.Second},
{"reset epoch", http.Header{"X-Ratelimit-Reset": {"1000600"}}, 10 * time.Minute},
{"capped", http.Header{"X-Ratelimit-Reset": {"1003600"}}, maxRateLimitWait},
{"already reset", http.Header{"X-Ratelimit-Reset": {"999000"}}, time.Second},
{"no header", http.Header{}, time.Minute},
}
for _, tt := range tests {
err := fmt.Errorf("wrapped: %w", &RateLimitError{Reset: rateLimitReset(tt.header, now)})
if d, ok := RateLimitWait(err, now); !ok || d != tt.want {
t.Errorf("%s: wait = %v, %v; want %v", tt.name, d, ok, tt.want)
}
}
if _, ok := RateLimitWait(errors.New("boom"), now); ok {
t.Error("a plain error is not a rate limit")
}
}
// 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)
}
}
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
// counts towards MaxPollFailures.
func TestWatchGitHubRidesOutRateLimit(t *testing.T) {
f := pendingPR()
f.rateLimit = true
c := newFakeGitHubClient(f.serve(t))
ticks := make(chan time.Time)
baseline := make(chan struct{})
var warnings int
done := make(chan error, 1)
var res WatchResult
go func() {
var err error
res, err = Watch(c, []PRRef{ghRef}, "", ticks, func([]PRState) { close(baseline) }, func(PRRef, error) { warnings++ })
done <- err
}()
now := time.Now()
tick := func(d time.Duration) {
t.Helper()
now = now.Add(d)
select {
case ticks <- now:
case err := <-done:
t.Fatalf("watch ended early: %+v, %v", res, err)
}
}
tick(time.Minute)
f.set(func(f *fakeGitHubPR) { f.rateLimit = false })
tick(2 * time.Minute)
select {
case <-baseline:
case err := <-done:
t.Fatalf("watch ended at baseline: %+v, %v", res, err)
}
// Ticks run a day behind the fake's reset, so every pause is the 15m cap.
// The 1m tick inside each pause is skipped, and its send completing proves
// the previous poll is done before the fake changes.
now = now.Add(-24 * time.Hour)
f.set(func(f *fakeGitHubPR) { f.rateLimit = true })
for i := 0; i < 2*MaxPollFailures; i++ {
tick(15 * time.Minute)
tick(time.Minute)
}
f.set(func(f *fakeGitHubPR) {
f.rateLimit = false
f.pr = strings.Replace(f.pr, `"merged":false`, `"merged":true`, 1)
})
tick(15 * time.Minute)
close(ticks)
if err := <-done; err != nil {
t.Fatal(err)
}
if res.Reason != "PR merged" {
t.Errorf("result = %+v, want merged", res)
}
if warnings != 1+2*MaxPollFailures {
t.Errorf("warnings = %d, want one per rate-limited fetch (%d)", warnings, 1+2*MaxPollFailures)
}
}
+33 -1
View File
@@ -277,15 +277,35 @@ const MaxPollFailures = 20
// failure surviving a token re-mint, a 404 from the PR lookup itself (the repo
// is gone, renamed, or no longer visible), and MaxPollFailures consecutive
// failures of one PR all abort, because a watcher that sees nothing must not
// look healthy.
// look healthy. A GitHub rate limit is none of these: the baseline fetch or the
// PR's polls pause until it resets (see RateLimitWait), handing it to onError,
// and the pause never counts towards MaxPollFailures.
// onBaseline, if set, receives every captured baseline once, before the first
// tick, so a caller can show what state the watch started from.
// A closed ticks channel ends the watch with a TimedOut result.
func Watch(f StateFetcher, refs []PRRef, agentLogin string, ticks <-chan time.Time, onBaseline func([]PRState), onError func(PRRef, error)) (WatchResult, error) {
watches := make(map[string]*prWatch, len(refs))
baselines := make([]PRState, 0, len(refs))
clock := time.Now()
for _, ref := range refs {
st, err := f.FetchState(ref, agentLogin)
for {
d, limited := RateLimitWait(err, clock)
if !limited {
break
}
if onError != nil {
onError(ref, err)
}
for until := clock.Add(d); clock.Before(until); {
t, ok := <-ticks
if !ok {
return WatchResult{TimedOut: true, States: baselines}, nil
}
clock = t
}
st, err = f.FetchState(ref, agentLogin)
}
if err != nil {
return WatchResult{}, err
}
@@ -300,13 +320,25 @@ func Watch(f StateFetcher, refs []PRRef, agentLogin string, ticks <-chan time.Ti
}
latest := append([]PRState(nil), baselines...)
fails := make(map[string]int, len(refs))
pausedUntil := make(map[string]time.Time, len(refs))
// The tick carries the time it fired, which is the clock the conflict
// window is measured on.
for now := range ticks {
for i, ref := range refs {
key := ref.String()
if now.Before(pausedUntil[key]) {
continue
}
cur, err := f.FetchState(ref, agentLogin)
if err != nil {
if d, limited := RateLimitWait(err, now); limited {
pausedUntil[key] = now.Add(d)
watches[key].missed()
if onError != nil {
onError(ref, err)
}
continue
}
if IsAuthError(err) || IsPRGone(err) {
return WatchResult{}, fmt.Errorf("polling %s: %w", key, err)
}