From 05c665857d6ebade2c48e01b87e3e2ea5182ab2c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 22 Nov 2026 02:01:16 +1100 Subject: [PATCH] fix(watchpr): pause on GitHub rate limits and skip settled CI reads --- README.md | 14 ++-- internal/agent/githubpr.go | 65 ++++++++++++++++-- internal/agent/githubpr_test.go | 117 +++++++++++++++++++++++++++++++- internal/agent/watch.go | 34 +++++++++- 4 files changed, 217 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index d97a3df..84ca5df 100644 --- a/README.md +++ b/README.md @@ -156,9 +156,12 @@ Gitea. GitHub is polled as the `reviewer` app (the same Vault creds as `agentgh`); its installation token is re-minted before it expires and again if GitHub rejects it. If no token can be minted, `watchpr` warns and polls anonymously, which works for public repos only: GitHub hides a private repo -behind a 404 (reported as `PR no longer visible`), and the anonymous rate limit -(60 requests/hour, ~6 per PR per poll) is rate limiting, retried like any -transient failure. CI combines the commit status +behind a 404 (reported as `PR no longer visible`), and the anonymous limit is +60 requests/hour. A poll costs 4 requests per PR, plus 2 for CI while the head +is new or CI is pending or unreported. When GitHub rate-limits, `watchpr` warns +and pauses that PR (or the baseline) until the `Retry-After` / +`X-RateLimit-Reset` time, capped at 15m; the pause never counts towards the +consecutive-failure limit. CI combines the commit status API with the check-runs API, and any failing status or check run (`failure`, `timed_out`, `cancelled`, `action_required`, `startup_failure`) counts as a failure. Issue comments, review comments and reviews (including changes @@ -192,8 +195,9 @@ Gitea tokens expire in ~1h, far shorter than a watch, so a rejected token is re-minted once and the request replayed; only a failure that survives that re-mint ends the watch. Anonymous polling of a public repo is unaffected — with no token there is nothing to reject and Vault is never reached for one. -Transient failures (5xx, network errors, rate limiting) are warned about and -retried, and give up after 20 consecutive failures of the same PR. +Transient failures (5xx, network errors) are warned about and retried, and +give up after 20 consecutive failures of the same PR. GitHub rate limits pause +instead (see GitHub refs) and never count towards that limit. ## agentws diff --git a/internal/agent/githubpr.go b/internal/agent/githubpr.go index dd93f62..6d04bf3 100644 --- a/internal/agent/githubpr.go +++ b/internal/agent/githubpr.go @@ -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, diff --git a/internal/agent/githubpr_test.go b/internal/agent/githubpr_test.go index 389df6c..c8f95bd 100644 --- a/internal/agent/githubpr_test.go +++ b/internal/agent/githubpr_test.go @@ -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) + } +} diff --git a/internal/agent/watch.go b/internal/agent/watch.go index 3cb5313..9863b84 100644 --- a/internal/agent/watch.go +++ b/internal/agent/watch.go @@ -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) }