Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

## Commit & Pull Request Guidelines

- Create commits with `committer "<msg>" <file...>`; avoid manual staging.
- Stage only the files you changed (`git add <file...>`, never `git add -A`) and commit with `git commit`.
- Follow Conventional Commits + action-oriented subjects (e.g. `feat(cli): add --verbose to send`).
- Group related changes; avoid bundling unrelated refactors.
- PRs should summarize scope, note testing performed, and mention any user-facing changes or new flags.
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 0.48.2 - Unreleased

- Reliability: concurrent Google API requests share one rate-limit pause (at most 8s without `Retry-After`) and give up after 12 rate-limit responses or a 2-minute budget instead of six retries, so large Gmail searches no longer fail when one request runs out of retries. (#1357)
- Auth: automatic reauthorization no longer replays a stored Google Ads (`adwords`) grant unless the failing command needs Ads, so an old Ads grant cannot trigger Google's passkey gate; restore it with `gog auth add <email> --services user,ads`. (#1353)
- Dependencies: refresh the MCP and Google API clients, networking libraries, and tracking-worker tooling while preserving the Go 1.26 minimum, 24-hour worker cooldown, and security overrides.

Expand Down
17 changes: 10 additions & 7 deletions docs/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,13 +165,16 @@ least-privilege read against the intended service.
## Exit codes

Google API rate-limit retries cover HTTP 429 and HTTP 403 responses whose
reason is `rateLimitExceeded` or `userRateLimitExceeded`. Each request is
retried up to six times with exponential backoff and jitter (1s, 2s, 4s, ...,
63s to just under 94.5s in total), long enough for per-minute quotas such as Gmail's "Units per
minute per user" to refill. They honor
`Retry-After` delays up to 60 seconds per retry, including numeric seconds and
HTTP dates. Cancelling the command also
cancels a pending retry wait. Upload bodies are closed even when a request is
reason is `rateLimitExceeded` or `userRateLimitExceeded`. Concurrent requests
using the same HTTP transport share one pause. Without `Retry-After`, the pause
doubles from 1 second to at most 8 seconds, with jitter, and responses from
requests already in flight when it started do not lengthen it. A pause holds new
attempts and retries, then spreads their release over as much as 250
milliseconds. gog honors `Retry-After` in seconds or as an HTTP date, up to 60
seconds per wait. A request returns the rate-limit error
if it reaches 12 rate-limit responses or runs out of its 120-second retry
budget, measured from its first rate-limit response. Cancelling the command
cancels a pending wait. Upload bodies are closed even when a request is
rejected by the circuit breaker or cannot be buffered for retry, so those
failures release the associated file or stream resources.

Expand Down
11 changes: 8 additions & 3 deletions docs/gmail-workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,17 @@ gog gmail messages search 'list:example.com' --all --max 500 --ids-only --json -
jq -r '.[].id' | xargs -n 1000 gog gmail batch modify --add-label Newsletters
```

For bulk label changes, this uses far fewer Gmail quota units than calling
`gmail thread modify` for each thread. The batch command labels the matching
messages. Thread modification applies to every message in the thread.

`--ids-only` rejects `--include-body`, `--full`, `--include-attachments`,
`--include-recipients`, `--headers`, `--sanitize-content`, and, for `gmail search`, `--oldest`.

Thread searches fail if any thread detail cannot be fetched, without emitting a
partial result list, and stop the detail requests still pending. Retry the
search after resolving the reported API error.
Concurrent thread detail requests share a pause when Gmail reports a rate
limit. If a thread detail still cannot be fetched, the search stops pending
requests and fails without emitting partial results. Retry the search after
resolving the reported API error.

Quoted operators such as `"is:unread"` are literal phrases and are passed to Gmail without adding a label filter. `gmail thread get` includes nonempty Cc and Bcc headers in its text output.

Expand Down
14 changes: 9 additions & 5 deletions internal/googleapi/retry_constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ package googleapi
import "time"

const (
// MaxRateLimitRetries is the maximum number of retries on rate-limit
// responses (429, or 403 with a rate-limit reason). Six doublings from
// RateLimitBaseDelay wait 63s to just under 94.5s in total, enough to outlast Google's
// per-minute quotas such as Gmail's "Units per minute per user".
MaxRateLimitRetries = 6
// MaxRateLimitRetries caps rate-limit responses per request, including the
// first one. The shared backoff may exhaust MaxRateLimitWait sooner.
MaxRateLimitRetries = 12
// MaxRateLimitWait bounds retry waits from a request's first rate-limit response.
MaxRateLimitWait = 120 * time.Second
// RateLimitBaseDelay is the initial delay for rate limit exponential backoff.
RateLimitBaseDelay = 1 * time.Second
// MaxRateLimitBackoff caps the shared exponential pause when Google sends no
// Retry-After. Gmail's per-user quota refills continuously; live runs with
// 16-48s pauses were slower than short independent retries, not more reliable.
MaxRateLimitBackoff = 8 * time.Second
// Max5xxRetries is the maximum retries for server errors.
Max5xxRetries = 1
// ServerErrorRetryDelay is the delay before retrying on 5xx errors.
Expand Down
182 changes: 156 additions & 26 deletions internal/googleapi/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"net/http"
"strconv"
"strings"
"sync"
"time"
)

Expand All @@ -21,7 +22,8 @@ const (
maxInspectedResponseBodyBytes = int64(1 << 20)
// maxRetryAfter caps Retry-After waits. Google may send delta-seconds
// or an HTTP-date far in the future; CLI contexts often have no deadline.
maxRetryAfter = 60 * time.Second
maxRetryAfter = 60 * time.Second
maxRateLimitSpread = 250 * time.Millisecond
)

var errRequestBodyTooLarge = errors.New("request body too large to buffer for retry")
Expand All @@ -48,7 +50,7 @@ func retriesDisabled(ctx context.Context) bool {
// rate limits (429, or 403 with a rate-limit reason) and server errors (5xx).
type RetryTransport struct {
Base http.RoundTripper
MaxRetries429 int
MaxRetries429 int // Maximum rate-limit responses per request, including the first.
MaxRetries5xx int
BaseDelay time.Duration
CircuitBreaker *CircuitBreaker
Expand All @@ -59,8 +61,14 @@ type RetryTransport struct {
// If Reauth is nil, invalid_grant errors are surfaced without retry.
Reauth func(context.Context) error

// sleepFn replaces the backoff wait in tests.
rateLimitMu sync.Mutex
pauseUntil time.Time
rateLimitStreak int
rateLimitEscalatedAt time.Time

// sleepFn and nowFn replace wall-clock timing in tests.
sleepFn func(context.Context, time.Duration) error
nowFn func() time.Time
}

// NewRetryTransport creates a RetryTransport with sensible defaults.
Expand Down Expand Up @@ -95,7 +103,16 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}

var resp *http.Response
retries429 := 0

var lastRateLimit *http.Response
defer func() {
if lastRateLimit != nil && lastRateLimit.Body != nil {
_ = lastRateLimit.Body.Close()
}
}()
var rateLimitDeadline time.Time
rateLimitResponses := 0
rateLimitCeiling := min(t.MaxRetries429, MaxRateLimitRetries)
retries5xx := 0
retriedAuth := false
retriedReauth := false
Expand All @@ -114,6 +131,25 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}
}

if !retryDisabled {
ready, waitErr := t.waitForRateLimit(req.Context(), rateLimitDeadline)
if !ready {
if req.Body != nil {
_ = req.Body.Close()
}

if waitErr != nil {
return nil, waitErr
}
// The budget expired while waiting. Hand the response back intact.
resp, lastRateLimit = lastRateLimit, nil

return resp, nil
}
}

sentAt := t.now()

resp, err = t.Base.RoundTrip(req)
if err != nil {
// Detect invalid_grant from the OAuth2 transport layer.
Expand Down Expand Up @@ -146,6 +182,10 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {

// Success
if resp.StatusCode < 400 {
t.rateLimitMu.Lock()
t.rateLimitStreak = max(0, t.rateLimitStreak-1)
t.rateLimitMu.Unlock()

if t.CircuitBreaker != nil {
t.CircuitBreaker.RecordSuccess()
}
Expand All @@ -155,24 +195,37 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {

// Rate limit (429, or 403 with a rate-limit reason)
if resp.StatusCode == http.StatusTooManyRequests || responseIndicatesRateLimit(resp) {
if retryDisabled || retries429 >= t.MaxRetries429 || !replayable {
return resp, nil // Return the rate-limit response after max retries
now, delay := t.recordRateLimit(resp, sentAt)

rateLimitResponses++
if rateLimitResponses == 1 {
rateLimitDeadline = now.Add(MaxRateLimitWait)
}

delay := t.calculateBackoff(retries429, resp)
slog.Debug("rate limited, retrying",
if retryDisabled || !replayable || rateLimitResponses >= rateLimitCeiling || now.After(rateLimitDeadline) {
return resp, nil
}

slog.Debug("rate limited, waiting to retry",
"status", resp.StatusCode,
"delay", delay,
"attempt", retries429+1,
"max_retries", t.MaxRetries429)
"rate_limit_responses", rateLimitResponses,
"max_rate_limit_responses", rateLimitCeiling)

drainAndClose(resp.Body)

if err := t.sleep(req.Context(), delay); err != nil {
return nil, err
// If a later retry runs out of time at the gate, return the latest
// rate-limit response even if a server or auth error prompted that retry.
if lastRateLimit != nil && lastRateLimit.Body != nil {
_ = lastRateLimit.Body.Close()
}

retries429++
// A rate-limited 403 is already buffered by responseIndicatesRateLimit.
// Buffer short 429 bodies too, so the next attempt can reuse the connection.
if resp.StatusCode == http.StatusTooManyRequests {
if _, _, err := peekResponseBody(resp); err != nil {
slog.Debug("could not buffer rate-limit response", "err", err)
}
}
lastRateLimit = resp
Comment on lines +223 to +228

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 👍 / 👎.


continue
}
Expand Down Expand Up @@ -231,6 +284,84 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}
}

func (t *RetryTransport) now() time.Time {
if t.nowFn != nil {
return t.nowFn()
}

return time.Now()
}

func (t *RetryTransport) recordRateLimit(resp *http.Response, sentAt time.Time) (time.Time, time.Duration) {
t.rateLimitMu.Lock()
defer t.rateLimitMu.Unlock()

now := t.now()

// Requests already in flight when the pause was set come back rejected too.
// Count that wave once, so a burst of concurrent rejections does not jump
// straight to the maximum backoff. Such responses only extend the pause
// when Google asks for a specific wait.
if sentAt.Before(t.rateLimitEscalatedAt) {
if resp.Header.Get("Retry-After") != "" {
if until := now.Add(t.calculateBackoff(0, resp, now)); until.After(t.pauseUntil) {
t.pauseUntil = until
}
}

return now, max(0, t.pauseUntil.Sub(now))
}

t.rateLimitStreak++
t.rateLimitEscalatedAt = now

delay := t.calculateBackoff(t.rateLimitStreak-1, resp, now)
if until := now.Add(delay); until.After(t.pauseUntil) {
t.pauseUntil = until
}

return now, delay
}

// waitForRateLimit returns false when the request's retry budget runs out.
// The deadline is zero until the request receives its first rate-limit response.
func (t *RetryTransport) waitForRateLimit(ctx context.Context, deadline time.Time) (bool, error) {
waited := false

for {
if err := ctx.Err(); err != nil {
return false, fmt.Errorf("rate-limit wait interrupted: %w", err)
}

t.rateLimitMu.Lock()
now := t.now()
delay := t.pauseUntil.Sub(now)
t.rateLimitMu.Unlock()

if !deadline.IsZero() && now.After(deadline) {
return false, nil
}

switch {
case delay > 0:
waited = true
case waited:
delay, _ = randomDurationBelow(maxRateLimitSpread)
waited = false
default:
return true, nil
}

if !deadline.IsZero() && delay > deadline.Sub(now) {
return false, t.sleep(ctx, deadline.Sub(now))
}
// Check again after sleeping in case another response extended the pause.
if err := t.sleep(ctx, delay); err != nil {
return false, err
}
}
}

func capRetryAfter(wait time.Duration) time.Duration {
if wait > maxRetryAfter {
return maxRetryAfter
Expand All @@ -239,7 +370,7 @@ func capRetryAfter(wait time.Duration) time.Duration {
return wait
}

func (t *RetryTransport) calculateBackoff(attempt int, resp *http.Response) time.Duration {
func (t *RetryTransport) calculateBackoff(exponent int, resp *http.Response, now time.Time) time.Duration {
// Check Retry-After header
if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" {
if seconds, err := strconv.ParseInt(retryAfter, 10, 64); err == nil || errors.Is(err, strconv.ErrRange) {
Expand All @@ -255,8 +386,8 @@ func (t *RetryTransport) calculateBackoff(attempt int, resp *http.Response) time
return time.Duration(seconds) * time.Second
}

if t, err := http.ParseTime(retryAfter); err == nil {
d := time.Until(t)
if at, err := http.ParseTime(retryAfter); err == nil {
d := at.Sub(now)
if d < 0 {
return 0
}
Expand All @@ -265,19 +396,18 @@ func (t *RetryTransport) calculateBackoff(attempt int, resp *http.Response) time
}
}

// Exponential backoff with jitter: 1s, 2s, 4s...
// Exponential backoff with jitter: 1s, 2s, 4s, then MaxRateLimitBackoff.
if t.BaseDelay <= 0 {
return 0
}

var baseDelay time.Duration

if bd := t.BaseDelay * time.Duration(1<<attempt); bd <= 0 {
return 0
} else {
baseDelay = bd
exponent = min(exponent, 3)
if t.BaseDelay >= MaxRateLimitBackoff>>exponent {
return MaxRateLimitBackoff
}

baseDelay := t.BaseDelay << exponent

jitterRange := baseDelay / 2
if jitterRange <= 0 {
return baseDelay
Expand All @@ -288,7 +418,7 @@ func (t *RetryTransport) calculateBackoff(attempt int, resp *http.Response) time
return baseDelay
}

return baseDelay + jitter
return min(baseDelay+jitter, MaxRateLimitBackoff)
}

func randomDurationBelow(upperBound time.Duration) (time.Duration, error) {
Expand Down
Loading
Loading