Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions e2e/admin/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -115,25 +119,31 @@ 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
// so acquireOrg can distinguish "locked" from "broken".
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.
createErr := retryOnNotFound(ctx, 5, func() error {
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)
}

Expand All @@ -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
}

Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Inconsistent DeleteRepo error handling vs acquireLock (4/5 agents flagged)

Here in tryReclaimStaleLock, a DeleteRepo failure causes immediate return false, abandoning the org. But in acquireLock (lines 84-87), the same failure is logged and tryCreateLock still runs. This inconsistency means:

  • If another runner concurrently deletes the stale repo, DeleteRepo returns 404 here, and tryReclaimStaleLock gives up even though tryCreateLock would succeed.
  • In acquireLock, the same scenario correctly falls through to tryCreateLock.

Suggestion — check if the error is a 404 (repo already gone) and proceed in that case:

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)
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — forge.IsNotFound already exists so this was easy. 1b0e866 now lets 404 fall through to tryCreateLock.

}
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)
Expand Down
18 changes: 16 additions & 2 deletions e2e/admin/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Stale lock recovery called on any error type — wastes API quota (4/5 agents flagged, strongest consensus)

When tryCreateLock returns an error (rate limit, auth failure, network timeout), this unconditionally calls tryReclaimStaleLock, which issues 2-3 more API calls that will likely also fail. This wastes API quota and could accelerate rate limit exhaustion. tryReclaimStaleLock degrades gracefully (returns false), so it's not a correctness bug — just unnecessary work.

Same pattern repeats at line 122.

Suggestion — gate on error type so only 422s trigger stale recovery:

var apiErr *github.APIError
if token != "" && errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnprocessableEntity {
    if reclaimed := tryReclaimStaleLock(ctx, client, token, org, runID, logf); reclaimed {
        return org, nil
    }
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, gated on 422 via errors.As in 1b0e866. Both sites in acquireOrg now check apiErr.StatusCode == 422 before attempting stale recovery.

return org, nil
}
}
continue
}
if acquired {
Expand Down Expand Up @@ -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 {
Expand Down
69 changes: 54 additions & 15 deletions internal/forge/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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():
Expand All @@ -135,19 +154,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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Unbounded io.ReadAll + swallowed error (3/5 agents flagged)

Two issues on this line:

  1. Unbounded read — io.ReadAll(resp.Body) has no size limit. A malformed or proxy-intercepted 403 with a large body could exhaust memory.

  2. Swallowed error — the read error is discarded (_ =). If the body read fails (connection reset), data is empty/partial, strings.Contains returns false, and (false, data) is returned. The caller replaces resp.Body with this corrupt data, causing checkStatus to produce a confusing "unexpected end of JSON" error instead of surfacing the actual network problem.

Suggestion:

data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<16)) // 64KB max
if readErr != nil {
    return false, nil
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1b0e866. LimitReader at 64KB and return false, nil on read error so the caller doesn't get corrupt data.

if strings.Contains(string(data), "secondary rate limit") {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Case-sensitive substring match is fragile

strings.Contains(string(data), "secondary rate limit") is case-sensitive. If GitHub changes the casing or phrasing (e.g., "Secondary Rate Limit", "secondary_rate_limit"), this detection silently fails and the 403 is treated as a permanent permission error — no retry.

Suggestion:

if strings.Contains(strings.ToLower(string(data)), "secondary rate limit") {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Folded into the same fix — strings.ToLower before the match now.

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 {
Expand All @@ -156,6 +191,10 @@ func retryDelay(resp *http.Response, attempt int) time.Duration {
return time.Duration(secs) * time.Second

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Retry-After header parsed without upper bound

strconv.Atoi(ra) has no sanity check. A malformed response with Retry-After: 999999999 would cause the client to sleep for ~31 years. While unlikely from GitHub directly, a misconfigured proxy could produce this.

Suggestion — cap at a reasonable max:

if secs, err := strconv.Atoi(ra); err == nil && secs > 0 && secs <= 300 {
    return time.Duration(secs) * time.Second
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Capped at 300s in 1b0e866.

}
}
// 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
}
Expand Down
52 changes: 52 additions & 0 deletions internal/forge/github/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -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)
Expand Down
Loading