Skip to content

fix: keep large Gmail searches from failing when one request runs out of rate-limit retries - #1357

Merged
steipete merged 4 commits into
mainfrom
fix/shared-rate-limit-backoff
Nov 28, 2026
Merged

steipete merged 4 commits into
mainfrom
fix/shared-rate-limit-backoff

Conversation

@steipete

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Large Gmail searches such as gog gmail search 'in:inbox' --max 300 (or --all on a big inbox) can fail outright with 403 rateLimitExceeded ("Units per minute per user"). The search fetches thread details 10 at a time; each request backs off on its own, so a burst of rejections makes one unlucky request use up all six retries, and that single failure fails the whole search with no partial results.

User Impact

Large Gmail searches and other concurrent Google API work now wait out per-minute quota pressure instead of failing. Rate-limited requests pause together (at most 8 seconds per pause unless Google sends Retry-After, which is still honored up to 60 seconds) and a request only gives up after 12 rate-limit responses or a 2-minute budget. No flags or output change; the debug log message for a rate-limit wait is now rate limited, waiting to retry.

Why This Change Was Made

All requests on one transport now share a single pause: when any request is rate limited, new attempts and retries wait together and are released with a small random spread, instead of every worker retrying on its own schedule. The shared backoff escalates only for rejections from requests sent after the last escalation, so a single burst of concurrent rejections does not jump to the maximum pause. A first version with longer shared pauses (up to 48 seconds) was measurably slower against a real inbox, so the pause is capped at 8 seconds.

The Gmail guide also notes that gmail messages search ... --ids-only piped to gmail batch modify uses far less quota than per-thread gmail thread modify for bulk label changes, and AGENTS.md no longer points to the removed committer helper.

Evidence

Live checks against a real Gmail account (one inbox, 300-thread gmail search, 75-second cool-down before each run, verbose logs; no mail contents recorded):

Run This branch Released 0.48.1
1 29 s, worst request used 3 of 12 rate-limit responses 21 s, worst used 4 of 6 retries
2 72 s, worst 6 of 12 47 s, worst 5 of 6
3 52 s, worst 4 of 12 failed after 98 s (403 rateLimitExceeded, retries exhausted, no results)

Across all heavy runs that day, 0.48.1 failed 1 of 5 times and used its final retry in 2 more; this branch completed every run with at least half of its rate-limit allowance left. When 0.48.1 succeeds it is somewhat faster in this small sample (median about 36 s vs 52 s), with wide run-to-run variance (21–76 s).

Local: make lint (0 issues), go test -race ./internal/googleapi/..., the focused rate-limit tests 30 times under -race, go test ./..., and make test pass. New unit tests cover the shared pause, release spread, streak escalation and decay, in-flight rejection waves, the time budget and response ceiling, Retry-After, WithoutRetries, and cancellation while waiting. make ci was not run locally; PR CI covers it.

Requests already in flight when a pause starts come back rate-limited too.
Escalating the shared streak for each of them pushed a single burst of
concurrent rejections straight to the maximum backoff. Escalate only for
requests sent after the last escalation; earlier responses extend the pause
only when Google sends Retry-After.
Live runs against a real Gmail inbox showed shared pauses of 16-48s made
300-thread searches slower than short independent retries without adding
reliability. Cap the exponential pause at 8s (Retry-After still up to 60s);
a request that keeps getting rejected still waits more than a minute before
its 12-response ceiling.

Also replace the AGENTS.md instruction to use the removed committer helper.
@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-28T02:46:18.435206Z 7331fa0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added P1 Urgent regression or broken agent/channel workflow affecting real users now. impact:auth-provider This issue is about auth, provider routing, model choice, or SecretRef resolution. impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. labels Nov 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7331fa0e83

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +223 to +228
if resp.StatusCode == http.StatusTooManyRequests {
if _, _, err := peekResponseBody(resp); err != nil {
slog.Debug("could not buffer rate-limit response", "err", err)
}
}
lastRateLimit = resp

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Close unbuffered rate-limit bodies before retrying

When a 429 body exceeds the 1 MiB inspection limit, peekResponseBody returns ok=false without closing the underlying body, but this code ignores that result and retains the live response while starting another attempt. Unlike the previous drainAndClose path, this prevents the connection from being released before retrying. I reproduced a blocked retry with a 2 MiB 429 response and an HTTP transport configured with MaxConnsPerHost: 1: the request fails at its context deadline instead of reaching the next successful response, and without a deadline it can hang indefinitely. Handle unsuccessful buffering explicitly so an unread network body is not retained across attempts.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 28, 2026
@clawsweeper

clawsweeper Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

Concurrent Google API requests share rate-limit backoff, with a 12-response ceiling and a two-minute retry budget.

Example: Run gog gmail search 'in:inbox' --max 300 against a rate-limited inbox.

  • Before: Independent retries can exhaust one request’s allowance, failing the entire search without results.
  • After: Requests share pauses and a larger allowance; the PR reports successful completion in its real-inbox comparisons.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Detailed live-run reporting and passing checks support the change, but the confirmed response-lifecycle defect blocks merge.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the contributor proof gate; its body reports real Gmail CLI comparisons exercising RetryTransport under quota pressure, although raw verbose logs are not attached.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Large Gmail metadata searches can fail completely when a single concurrent detail request exhausts its rate-limit retries.
Reason: The real-inbox report establishes user value, and maintainer authorship approves the shared-pause direction and documented latency tradeoff.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it addresses a current Gmail reliability problem and has maintainer-approved direction, but an unclosed 429 response body can block retries.

Reviewed head: b1ad316f7b1a45d276d03259776de13ec90488c5

Before merge

  • Close unbuffered 429 bodies before starting another attempt (P2) - For a 429 body larger than 1 MiB, peekResponseBody returns ok=false and leaves the network body open; read failures also retain its closer. This call ignores ok and continues with that live body stored in lastRateLimit. With MaxConnsPerHost: 1, the next attempt waits for the connection held by its own previous response, so the request reaches its context deadline instead of recovering, or hangs without one. The deferred close cannot run while that attempt is blocked. Handle unsuccessful buffering before retrying, either returning the intact response or closing it with an explicit bounded-response fallback, and cover this with a real HTTP transport regression. This confirms the existing discussion at fix: keep large Gmail searches from failing when one request runs out of rate-limit retries #1357 (comment).

Findings

  • [P2] Close unbuffered 429 bodies before starting another attempt — internal/googleapi/transport.go:223-228
Agent review details

How this fits together

The shared HTTP retry transport receives authenticated Google API requests, coordinates retry waits, and returns responses or errors to commands such as Gmail search.

flowchart TD
  A[Gmail search command] --> B[Concurrent thread fetches]
  B --> C[Shared retry transport]
  C --> D[Rate limit pause]
  D --> C
  C --> E[Authenticated HTTP transport]
  E --> F[Google API]
  F --> C
Loading

Technical review

Best possible solution:

Retain the shared transport pause while ensuring every abandoned network response is closed before another attempt begins.

Do we have a high-confidence way to reproduce the issue?

Main’s independent six-retry budget and all-or-error Gmail fan-out explain the reported failure, and the body records an affected v0.48.1 run; this review ran no target code.

Is this the best way to solve the issue?

Coordinating backoff in the shared transport addresses the common cause without changing search output, provided unsuccessful response buffering releases its network resources.

Full review comments:

  • [P2] Close unbuffered 429 bodies before starting another attempt — internal/googleapi/transport.go:223-228
    For a 429 body larger than 1 MiB, peekResponseBody returns ok=false and leaves the network body open; read failures also retain its closer. This call ignores ok and continues with that live body stored in lastRateLimit. With MaxConnsPerHost: 1, the next attempt waits for the connection held by its own previous response, so the request reaches its context deadline instead of recovering, or hangs without one. The deferred close cannot run while that attempt is blocked. Handle unsuccessful buffering before retrying, either returning the intact response or closing it with an explicit bounded-response fallback, and cover this with a real HTTP transport regression. This confirms the existing discussion at fix: keep large Gmail searches from failing when one request runs out of rate-limit retries #1357 (comment).
    Confidence: 0.99
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against cfee06622536.

Provenance checked

Testing

Proof path: unit tests only.

Security

None.

Evidence

Acceptance criteria:

  • go test ./internal/googleapi -run TestRetryTransport_RateLimit_UnbufferedBody -count=1
  • go test -race ./internal/googleapi/...
  • make ci

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 60ae623 adds internal/googleapi/transport.go:367 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 60ae623da5b5; files: internal/googleapi/transport.go)
  • Jatin Bansal: Raw commit 6ad392f adds internal/googleapi/transport_test.go:719 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6ad392fcc58e; files: internal/googleapi/transport_test.go)
  • salmonumbrella: Raw commit d2be673 adds internal/googleapi/transport.go:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d2be673d1004; files: internal/googleapi/transport.go)

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production and test changes Production +165/-31 lines; tests +425/-124 lines The shared coordination logic has substantial timing and concurrency coverage, but the tests omit unsuccessful 429 buffering through a real connection pool.

Labels

Label changes:

  • add merge-risk: 🚨 availability: An oversized 429 response can retain the only available connection, preventing the retry from progressing until cancellation.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • merge-risk: 🚨 availability: An oversized 429 response can retain the only available connection, preventing the retry from progressing until cancellation.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 27, 2026, 9:56 PM ET / November 28, 2026, 02:56 UTC.

@steipete
steipete merged commit ad83355 into main Nov 28, 2026
20 checks passed
@steipete
steipete deleted the fix/shared-rate-limit-backoff branch November 28, 2026 03:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact:auth-provider This issue is about auth, provider routing, model choice, or SecretRef resolution. impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P1 Urgent regression or broken agent/channel workflow affecting real users now. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant