diff --git a/e2e/admin/lock.go b/e2e/admin/lock.go index fe1704a4b1..0abf2f5905 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,15 @@ 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 { + 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) 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..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" @@ -74,6 +75,16 @@ func acquireOrg(ctx context.Context, client forge.Client, token, runID string, p acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { 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 + } + } continue } if acquired { @@ -108,6 +119,13 @@ func acquireOrg(ctx context.Context, client forge.Client, token, runID string, p acquired, err := tryCreateLock(ctx, client, org, runID, logf) if err != nil { 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 + } + } continue } if acquired { diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index cc8da6d6e7..5afa8a364f 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. @@ -110,19 +117,31 @@ 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() + 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(): @@ -135,27 +154,50 @@ 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, 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. + 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 { 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 } } + // 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 acf7229f5e..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" @@ -554,6 +555,57 @@ 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 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)