From 9dda8aad0b317b44e8464386d44cac9b6f34d762 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Wed, 27 May 2026 13:43:04 -0400 Subject: [PATCH 1/4] fix(e2e): fix stale lock recovery and improve lock debugging Two bugs prevented stale e2e lock recovery from working with the live GitHub API: 1. APIErrorDetail was missing the Message field, so GitHub's 422 response ("name already exists on this account") was not included in the error string. This caused isRepoAlreadyExists to never match for the live client, making tryCreateLock return an error instead of (false, nil) for existing repos. 2. In acquireOrg, when tryCreateLock returned an error, the code skipped tryReclaimStaleLock entirely (via continue). Now stale lock recovery runs even when tryCreateLock fails with an unexpected error. Also adds logging throughout the lock management code: - Log DeleteRepo failures instead of silently discarding them - Log each step of lock acquisition (create attempt, write, race loss) - Include staleLockTimeout value in stale lock log messages Signed-off-by: Ryan Bean Assisted-by: Claude Opus 4.6 Signed-off-by: Ralph Bean --- e2e/admin/lock.go | 30 ++++++++++++++++++++-------- e2e/admin/testutil.go | 18 +++++++++++++++-- internal/forge/github/github.go | 9 ++++++++- internal/forge/github/github_test.go | 13 ++++++++++++ 4 files changed, 59 insertions(+), 11 deletions(-) diff --git a/e2e/admin/lock.go b/e2e/admin/lock.go index fe1704a4b1..8d802cbf9e 100644 --- a/e2e/admin/lock.go +++ b/e2e/admin/lock.go @@ -59,7 +59,9 @@ func acquireLock(ctx context.Context, client forge.Client, token, org, runID str // content like "# e2e-lock"), treat the lock as stale. if !isValidUUID(holder) { logf("[e2e-lock] Lock contains invalid holder %q, force-acquiring", truncateUUID(holder)) - _ = client.DeleteRepo(ctx, org, lockRepo) + if delErr := client.DeleteRepo(ctx, org, lockRepo); delErr != nil { + logf("[e2e-lock] Warning: failed to delete invalid lock repo: %v", delErr) + } acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { return fmt.Errorf("force-acquiring invalid lock: %w", err) @@ -78,8 +80,10 @@ func acquireLock(ctx context.Context, client forge.Client, token, org, runID str // Stale lock recovery. if age > staleLockTimeout { - logf("[e2e-lock] Lock appears stale (age: %s), force-acquiring", age) - _ = client.DeleteRepo(ctx, org, lockRepo) + logf("[e2e-lock] Lock appears stale (age: %s > %s), force-acquiring", age, staleLockTimeout) + if delErr := client.DeleteRepo(ctx, org, lockRepo); delErr != nil { + logf("[e2e-lock] Warning: failed to delete stale lock repo: %v", delErr) + } acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { return fmt.Errorf("force-acquiring stale lock: %w", err) @@ -115,10 +119,11 @@ func acquireLock(ctx context.Context, client forge.Client, token, org, runID str // tryCreateLock attempts to create the lock repo and write our UUID. // Returns (true, nil) if the lock was successfully acquired. func tryCreateLock(ctx context.Context, client forge.Client, org, runID string, logf func(string, ...any)) (bool, error) { + logf("[e2e-lock] Attempting to create lock repo %s/%s", org, lockRepo) _, err := client.CreateRepo(ctx, org, lockRepo, "E2E test lock — do not delete manually", false) if err != nil { if isRepoAlreadyExists(err) { - // Repo already exists — someone else got it. + logf("[e2e-lock] Lock repo %s/%s already exists (repo locked by another run)", org, lockRepo) return false, nil } // Unexpected error (rate limit, auth failure, network). Propagate @@ -126,6 +131,8 @@ func tryCreateLock(ctx context.Context, client forge.Client, org, runID string, return false, fmt.Errorf("creating lock repo in %s: %w", org, err) } + logf("[e2e-lock] Lock repo %s/%s created, writing run ID", org, lockRepo) + // Use CreateOrUpdateFile since auto_init creates a default README.md. // Retry — newly created repos may not be immediately ready for file // operations due to GitHub's eventual consistency. @@ -133,7 +140,10 @@ func tryCreateLock(ctx context.Context, client forge.Client, org, runID string, return client.CreateOrUpdateFile(ctx, org, lockRepo, "README.md", "acquire lock", []byte(runID)) }) if createErr != nil { - _ = client.DeleteRepo(ctx, org, lockRepo) + logf("[e2e-lock] Failed to write lock file, cleaning up repo: %v", createErr) + if delErr := client.DeleteRepo(ctx, org, lockRepo); delErr != nil { + logf("[e2e-lock] Warning: cleanup delete of %s/%s also failed: %v", org, lockRepo, delErr) + } return false, fmt.Errorf("writing lock file after retries: %w", createErr) } @@ -147,7 +157,7 @@ func tryCreateLock(ctx context.Context, client forge.Client, org, runID string, return true, nil } - // Lost the race. + logf("[e2e-lock] Lost lock race for %s/%s (holder: %s)", org, lockRepo, truncateUUID(strings.TrimSpace(string(content)))) return false, nil } @@ -186,8 +196,12 @@ func tryReclaimStaleLock(ctx context.Context, client forge.Client, token, org, r logf("[org-pool] %s lock is fresh (age: %s), skipping", org, age.Round(time.Second)) return false } - logf("[org-pool] %s lock is stale (age: %s > %s), force-acquiring", org, age.Round(time.Second), staleLockTimeout) - _ = client.DeleteRepo(ctx, org, lockRepo) + logf("[org-pool] %s lock is stale (age: %s > %s), deleting stale lock repo", org, age.Round(time.Second), staleLockTimeout) + if delErr := client.DeleteRepo(ctx, org, lockRepo); delErr != nil { + logf("[org-pool] Warning: failed to delete stale lock repo %s/%s: %v", org, lockRepo, delErr) + return false + } + logf("[org-pool] Stale lock repo %s/%s deleted, attempting re-creation", org, lockRepo) acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { logf("[org-pool] Error force-acquiring %s: %v", org, err) diff --git a/e2e/admin/testutil.go b/e2e/admin/testutil.go index 961164f7aa..2d12afed45 100644 --- a/e2e/admin/testutil.go +++ b/e2e/admin/testutil.go @@ -73,7 +73,16 @@ func acquireOrg(ctx context.Context, client forge.Client, token, runID string, p logf("[org-pool] Trying to acquire %s...", org) acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { - logf("[org-pool] Error trying %s: %v", org, err) + logf("[org-pool] Error trying %s: %v — will check for stale lock", org, err) + // tryCreateLock may return an error when the repo exists but the + // error message doesn't match isRepoAlreadyExists (e.g. GitHub + // returns "422 Validation Failed" without "already exists" in + // the top-level message). Still attempt stale lock recovery. + if token != "" { + if reclaimed := tryReclaimStaleLock(ctx, client, token, org, runID, logf); reclaimed { + return org, nil + } + } continue } if acquired { @@ -107,7 +116,12 @@ func acquireOrg(ctx context.Context, client forge.Client, token, runID string, p for _, org := range shuffled { acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { - logf("[org-pool] Error trying %s: %v", org, err) + logf("[org-pool] Error trying %s: %v — will check for stale lock", org, err) + if token != "" { + if reclaimed := tryReclaimStaleLock(ctx, client, token, org, runID, logf); reclaimed { + return org, nil + } + } continue } if acquired { diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index cc8da6d6e7..3afdab85a7 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -58,10 +58,17 @@ type APIErrorDetail struct { Resource string `json:"resource"` Field string `json:"field"` Code string `json:"code"` + Message string `json:"message"` } func (e *APIError) Error() string { - return fmt.Sprintf("github api: %d %s", e.StatusCode, e.Message) + s := fmt.Sprintf("github api: %d %s", e.StatusCode, e.Message) + for _, d := range e.Errors { + if d.Message != "" { + s += fmt.Sprintf(" (%s)", d.Message) + } + } + return s } // Unwrap returns forge.ErrNotFound for 404 errors, enabling errors.Is checks. diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index acf7229f5e..208ee82623 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -554,6 +554,19 @@ func TestAPIError_ErrorString(t *testing.T) { assert.Contains(t, err.Error(), "Not Found") } +func TestAPIError_ErrorStringWithDetails(t *testing.T) { + err := &APIError{ + StatusCode: 422, + Message: "Validation Failed", + Errors: []APIErrorDetail{ + {Resource: "Repository", Field: "name", Code: "custom", Message: "name already exists on this account"}, + }, + } + assert.Contains(t, err.Error(), "422") + assert.Contains(t, err.Error(), "Validation Failed") + assert.Contains(t, err.Error(), "name already exists on this account") +} + func TestCreateFileOnBranch(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "PUT", r.Method) From 3683bdff523b3ea7f2c04e577fb04f2521ac933a Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Wed, 27 May 2026 13:49:48 -0400 Subject: [PATCH 2/4] fix(forge): retry on secondary rate limits without Retry-After header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitHub's secondary rate limit can return 403 without a Retry-After header. The previous code only retried 403 responses that had a Retry-After header, so these "body-only" secondary rate limits were treated as permission errors and not retried. Now isRetryable reads the 403 response body and checks for "secondary rate limit" text. When detected, retryDelay uses a 60-second minimum backoff (plus exponential), matching GitHub's recommendation. For non-rate-limit 403s (permission denied), the body is preserved and returned to the caller without retry — no behavior change for those. Signed-off-by: Ryan Bean Assisted-by: Claude Opus 4.6 Signed-off-by: Ralph Bean --- internal/forge/github/github.go | 48 +++++++++++++++++++++------- internal/forge/github/github_test.go | 39 ++++++++++++++++++++++ 2 files changed, 76 insertions(+), 11 deletions(-) diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 3afdab85a7..e9523d86aa 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -117,12 +117,18 @@ func (c *LiveClient) do(ctx context.Context, method, path string, body any) (*ht return nil, fmt.Errorf("http %s %s: %w", method, path, err) } - if !isRetryable(resp) { + retryable, respBody := isRetryable(resp) + if !retryable { + if respBody != nil { + // We read the body to check for secondary rate limit; + // replace it so callers can still read it. + resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(respBody)) + } return resp, nil } - // Drain and close the body before retrying. - io.Copy(io.Discard, resp.Body) + // Body already read or drained by isRetryable. resp.Body.Close() if attempt == maxRetries-1 { @@ -142,19 +148,35 @@ func (c *LiveClient) do(ctx context.Context, method, path string, body any) (*ht } // isRetryable returns true for responses that should trigger a retry. -// GitHub uses 429 for primary rate limits and 403 with Retry-After for -// secondary rate limits. A plain 403 (e.g., permission denied) is not retried. -func isRetryable(resp *http.Response) bool { +// GitHub uses 429 for primary rate limits and 403 for secondary rate limits. +// Secondary rate limits may include a Retry-After header, or may only be +// identifiable by the response body containing "secondary rate limit". +func isRetryable(resp *http.Response) (bool, []byte) { if resp.StatusCode == http.StatusTooManyRequests { - return true + io.Copy(io.Discard, resp.Body) + return true, nil } - // GitHub secondary rate limit: 403 + Retry-After header. - if resp.StatusCode == http.StatusForbidden && resp.Header.Get("Retry-After") != "" { - return true + if resp.StatusCode == http.StatusForbidden { + if resp.Header.Get("Retry-After") != "" { + io.Copy(io.Discard, resp.Body) + return true, nil + } + // Check body for secondary rate limit without Retry-After header. + data, _ := io.ReadAll(resp.Body) + if strings.Contains(string(data), "secondary rate limit") { + return true, nil + } + // Not a rate limit — return the body so the caller can still use it. + return false, data } - return false + return false, nil } +// secondaryRateLimitBackoff is the minimum backoff for secondary rate limits +// when no Retry-After header is present. GitHub's secondary rate limits +// typically require waiting at least 60 seconds. +var secondaryRateLimitBackoff = 60 * time.Second + // retryDelay calculates how long to wait before retrying. // It uses the Retry-After header if present, otherwise exponential backoff. func retryDelay(resp *http.Response, attempt int) time.Duration { @@ -163,6 +185,10 @@ func retryDelay(resp *http.Response, attempt int) time.Duration { return time.Duration(secs) * time.Second } } + // For secondary rate limits (403), use a longer backoff. + if resp.StatusCode == http.StatusForbidden { + return secondaryRateLimitBackoff + time.Duration(math.Pow(2, float64(attempt)))*time.Second + } // Exponential backoff: 1s, 2s, 4s return time.Duration(math.Pow(2, float64(attempt))) * time.Second } diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 208ee82623..075aa2e8d8 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -567,6 +568,44 @@ func TestAPIError_ErrorStringWithDetails(t *testing.T) { assert.Contains(t, err.Error(), "name already exists on this account") } +func TestSecondaryRateLimit_RetriedWithoutRetryAfterHeader(t *testing.T) { + attempts := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempts++ + if attempts <= 2 { + w.WriteHeader(http.StatusForbidden) + json.NewEncoder(w).Encode(map[string]string{ + "message": "You have exceeded a secondary rate limit", + }) + return + } + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "name": "test-repo", + "full_name": "org/test-repo", + "default_branch": "main", + "private": false, + }) + })) + defer srv.Close() + + client := &LiveClient{ + token: "test-token", + baseURL: srv.URL, + http: srv.Client(), + } + + // Override the backoff for testing — we don't want to wait 60s. + origBackoff := secondaryRateLimitBackoff + defer func() { secondaryRateLimitBackoff = origBackoff }() + secondaryRateLimitBackoff = 10 * time.Millisecond + + repo, err := client.CreateRepo(context.Background(), "org", "test-repo", "desc", false) + require.NoError(t, err) + assert.Equal(t, "test-repo", repo.Name) + assert.Equal(t, 3, attempts, "should have retried twice before succeeding") +} + func TestCreateFileOnBranch(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "PUT", r.Method) From 58e6938e515ca6b50edc336a873c200a0a634fa4 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Wed, 27 May 2026 14:09:41 -0400 Subject: [PATCH 3/4] fix(forge): include retry details in rate limit error messages When retries are exhausted, include the method, path, last delay, and Retry-After header value (if present) in the error message. This makes rate limit failures visible in e2e test logs without adding a logger dependency to the HTTP layer. Signed-off-by: Ryan Bean Assisted-by: Claude Opus 4.6 Signed-off-by: Ralph Bean --- internal/forge/github/github.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index e9523d86aa..6eee25c6d7 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -131,11 +131,17 @@ func (c *LiveClient) do(ctx context.Context, method, path string, body any) (*ht // Body already read or drained by isRetryable. resp.Body.Close() + delay := retryDelay(resp, attempt) + retryAfter := resp.Header.Get("Retry-After") + if attempt == maxRetries-1 { - return nil, &APIError{StatusCode: resp.StatusCode, Message: "rate limited after retries"} + msg := fmt.Sprintf("rate limited after %d retries on %s %s (last delay: %s", maxRetries, method, path, delay) + if retryAfter != "" { + msg += fmt.Sprintf(", Retry-After: %s", retryAfter) + } + msg += ")" + return nil, &APIError{StatusCode: resp.StatusCode, Message: msg} } - - delay := retryDelay(resp, attempt) select { case <-time.After(delay): case <-ctx.Done(): From 1b0e86698dbdb5845ad75cea8c12539644a35639 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Wed, 27 May 2026 16:57:42 -0400 Subject: [PATCH 4/4] fix(forge): harden rate limit detection and stale lock recovery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review feedback on #1612: - Bound io.ReadAll with LimitReader (64KB) and handle read errors in isRetryable to avoid unbounded memory use and corrupt body passthrough - Use case-insensitive match for secondary rate limit body detection - Cap Retry-After header at 300s to prevent unreasonable sleep durations - Gate stale lock recovery on 422 errors only — rate limits, auth failures, and network errors would just waste more API quota - Allow 404 on DeleteRepo in tryReclaimStaleLock so concurrent runners that already cleaned up the stale lock don't block re-creation Assisted-by: Claude claude-opus-4-6 Signed-off-by: Ralph Bean --- e2e/admin/lock.go | 7 +++++-- e2e/admin/testutil.go | 20 ++++++++++++-------- internal/forge/github/github.go | 9 ++++++--- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/e2e/admin/lock.go b/e2e/admin/lock.go index 8d802cbf9e..0abf2f5905 100644 --- a/e2e/admin/lock.go +++ b/e2e/admin/lock.go @@ -198,8 +198,11 @@ func tryReclaimStaleLock(ctx context.Context, client forge.Client, token, org, r } logf("[org-pool] %s lock is stale (age: %s > %s), deleting stale lock repo", org, age.Round(time.Second), staleLockTimeout) if delErr := client.DeleteRepo(ctx, org, lockRepo); delErr != nil { - logf("[org-pool] Warning: failed to delete stale lock repo %s/%s: %v", org, lockRepo, delErr) - return false + if !forge.IsNotFound(delErr) { + logf("[org-pool] Warning: failed to delete stale lock repo %s/%s: %v", org, lockRepo, delErr) + return false + } + logf("[org-pool] Stale lock repo %s/%s already deleted", org, lockRepo) } logf("[org-pool] Stale lock repo %s/%s deleted, attempting re-creation", org, lockRepo) acquired, err := tryCreateLock(ctx, client, org, runID, logf) diff --git a/e2e/admin/testutil.go b/e2e/admin/testutil.go index 2d12afed45..80d083629b 100644 --- a/e2e/admin/testutil.go +++ b/e2e/admin/testutil.go @@ -5,6 +5,7 @@ package admin import ( "context" "encoding/json" + "errors" "fmt" "io" "math/rand/v2" @@ -73,12 +74,13 @@ func acquireOrg(ctx context.Context, client forge.Client, token, runID string, p logf("[org-pool] Trying to acquire %s...", org) acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { - logf("[org-pool] Error trying %s: %v — will check for stale lock", org, err) - // tryCreateLock may return an error when the repo exists but the - // error message doesn't match isRepoAlreadyExists (e.g. GitHub - // returns "422 Validation Failed" without "already exists" in - // the top-level message). Still attempt stale lock recovery. - if token != "" { + logf("[org-pool] Error trying %s: %v", org, err) + // Only attempt stale lock recovery for 422 errors (repo + // likely exists). Rate limits, auth failures, and network + // errors would just waste more API quota. + var apiErr *gh.APIError + if token != "" && errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnprocessableEntity { + logf("[org-pool] 422 on %s — will check for stale lock", org) if reclaimed := tryReclaimStaleLock(ctx, client, token, org, runID, logf); reclaimed { return org, nil } @@ -116,8 +118,10 @@ func acquireOrg(ctx context.Context, client forge.Client, token, runID string, p for _, org := range shuffled { acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { - logf("[org-pool] Error trying %s: %v — will check for stale lock", org, err) - if token != "" { + logf("[org-pool] Error trying %s: %v", org, err) + var apiErr *gh.APIError + if token != "" && errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnprocessableEntity { + logf("[org-pool] 422 on %s — will check for stale lock", org) if reclaimed := tryReclaimStaleLock(ctx, client, token, org, runID, logf); reclaimed { return org, nil } diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 6eee25c6d7..5afa8a364f 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -168,8 +168,11 @@ func isRetryable(resp *http.Response) (bool, []byte) { return true, nil } // Check body for secondary rate limit without Retry-After header. - data, _ := io.ReadAll(resp.Body) - if strings.Contains(string(data), "secondary rate limit") { + data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<16)) // 64KB max + if readErr != nil { + return false, nil + } + if strings.Contains(strings.ToLower(string(data)), "secondary rate limit") { return true, nil } // Not a rate limit — return the body so the caller can still use it. @@ -187,7 +190,7 @@ var secondaryRateLimitBackoff = 60 * time.Second // It uses the Retry-After header if present, otherwise exponential backoff. func retryDelay(resp *http.Response, attempt int) time.Duration { if ra := resp.Header.Get("Retry-After"); ra != "" { - if secs, err := strconv.Atoi(ra); err == nil { + if secs, err := strconv.Atoi(ra); err == nil && secs > 0 && secs <= 300 { return time.Duration(secs) * time.Second } }