Repository navigation
fix(auth): proactively refresh OAuth token before expiry to prevent concurrent-agent race condition - #60673
fix(auth): proactively refresh OAuth token before expiry to prevent concurrent-agent race condition#60673wiliyam wants to merge 4 commits into
Conversation
Greptile SummaryThis PR wires up the already-defined The core fix is sound —
Confidence Score: 3/5Safe to merge for the primary race condition, but the fix is incomplete — the fallback profile path in The two most critical expiry checks (the hot path in src/agents/auth-profiles/oauth.ts — specifically the expiry check inside
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c980ed6c28
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // Use EXTERNAL_CLI_NEAR_EXPIRY_MS buffer: refresh proactively before expiry to avoid | ||
| // race condition where multiple concurrent agents all attempt to refresh the same | ||
| // single-use refresh token at the exact moment it expires. | ||
| if (Date.now() < oauthCred.expires - EXTERNAL_CLI_NEAR_EXPIRY_MS) { |
There was a problem hiding this comment.
Keep valid OAuth token when proactive refresh is unsupported
This new near-expiry gate sends every OAuth profile with <10m remaining into refreshOAuthTokenWithLock, and if refresh returns null the caller immediately returns null (resolveApiKeyForProfile), even though the access token is still valid until oauthCred.expires. That regresses providers/auth paths without a working refresher (for example plugin providers that register OAuth but no refreshOAuth, such as extensions/google/gemini-cli-provider.ts), causing avoidable auth failures during the final 10 minutes of token lifetime.
Useful? React with 👍 / 👎.
…oncurrent-agent race EXTERNAL_CLI_NEAR_EXPIRY_MS (10 min) was defined in constants but never used in the refresh logic. Both refresh check sites used `Date.now() < cred.expires` which only returns the cached token if it is not yet expired. When multiple agents run in parallel (e.g. parallel Claude Code builds across a monorepo), they all reach token expiry at the same instant and simultaneously enter refreshOAuthTokenWithLock. Even though the lock serialises the refreshes, the first agent to succeed invalidates the single-use refresh token. Every subsequent agent then fails with invalid_grant, wiping credentials.json and killing all running sessions. Fix: apply the EXTERNAL_CLI_NEAR_EXPIRY_MS (10 min) buffer to both expiry checks so tokens are treated as stale before they actually expire. The lock ensures exactly one agent performs the refresh while others wait and then re-read the already-refreshed credentials — rather than all rushing to refresh the same dying token at the same moment. The constant was added specifically for this use-case but was never wired into the oauth.ts expiry checks.
…k path Greptile review caught a missed expiry check in tryResolveOAuthProfile (the error-fallback path). Apply the same EXTERNAL_CLI_NEAR_EXPIRY_MS buffer for consistency — all three expiry check sites now proactively refresh before the token actually expires.
6be280e to
3b4c9e4
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b4c9e4857
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (Date.now() < cred.expires) { | ||
| // Apply EXTERNAL_CLI_NEAR_EXPIRY_MS buffer here too for consistency with the other | ||
| // expiry checks — ensures fallback profile path also proactively refreshes. | ||
| if (Date.now() < cred.expires - EXTERNAL_CLI_NEAR_EXPIRY_MS) { |
There was a problem hiding this comment.
Keep fallback OAuth profile usable near expiry
The new near-expiry check in tryResolveOAuthProfile forces a refresh attempt for the last 10 minutes of token lifetime, so fallback profiles now fail when they use OAuth providers that cannot refresh (refreshOAuth missing and no core getOAuthApiKey provider). In that case refreshOAuthTokenWithLock returns null, tryResolveOAuthProfile drops the fallback, and the caller rethrows the original error even though the fallback access token is still valid; this turns a recoverable primary-profile refresh failure into an auth outage during the near-expiry window.
Useful? React with 👍 / 👎.
|
The CI failures are pre-existing and unrelated to this PR's changes:
This PR only modifies |
…handle null refresh gracefully Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…sh returns null Mirrors the same null-refresh guard already in resolveApiKeyForProfile. If refreshOAuthTokenWithLock returns null (e.g. provider has no refreshOAuth implementation) but the access token is still valid until cred.expires, return the existing credentials instead of dropping the fallback profile. Prevents auth outages in the near-expiry window for providers without refresh support (e.g. gemini-cli-provider). Addresses chatgpt-codex-connector P2 review comment on PR openclaw#60673.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 783df3d0f7
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (!refreshed) { | ||
| // If refresh returned null (e.g. provider has no refreshOAuth implementation) | ||
| // but the token hasn't actually expired yet, fall back to the existing token | ||
| // rather than dropping the fallback profile entirely. | ||
| if (Date.now() < cred.expires) { |
There was a problem hiding this comment.
Catch refresh exceptions for fallback OAuth profiles
This block only recovers when refreshOAuthTokenWithLock returns null, but the new near-expiry path now calls refresh for still-valid fallback tokens and that helper can throw (for example when cred.managedBy is set but readManagedExternalCliCredential is unavailable). In that case tryResolveOAuthProfile throws instead of using the still-valid fallback token, so resolveApiKeyForProfile discards the fallback and rethrows the original error during the last 10 minutes before expiry.
Useful? React with 👍 / 👎.
|
Pushed
Both the primary hot-path ( |
|
Closing this as implemented after Codex review. Current What I checked:
So I’m closing this as already implemented rather than keeping a duplicate issue open. Review notes: reviewed against 6bc0dc8fb671; fix evidence: release v2026.4.23, commit a9797214338b. |
Summary
Fixes the OAuth token refresh race condition that occurs when multiple agents run in parallel.
Root Cause
EXTERNAL_CLI_NEAR_EXPIRY_MS(10 min) was defined inconstants.tsbut never used in the actual refresh logic inoauth.ts. Both expiry check sites used:This means tokens are only considered stale at the exact moment they expire. When multiple agents (e.g. 3–5 parallel
claude --printjobs building different services in a monorepo) all run past the 3-hour mark simultaneously, they all reachcred.expiresat the same instant.Even though
withFileLockserialises the refresh attempts, the first agent successfully uses the single-userefreshToken, making it invalid. Every subsequent agent then fails withinvalid_grant, wipescredentials.json, and crashes — killing all running sessions and hours of work.Fix
Wire up the already-defined
EXTERNAL_CLI_NEAR_EXPIRY_MSconstant into both expiry checks inoauth.ts:Now tokens are refreshed proactively while still valid. The file lock ensures exactly one agent performs the refresh, saves the new token, and releases. All waiting agents then re-read the freshly refreshed credentials instead of racing on the same dying refresh token.
Affected files
src/agents/auth-profiles/oauth.ts— 2 expiry checks + importReal-world reproduction
Running 3+ parallel Claude Code agents across a monorepo (UTP platform with 5 services) consistently triggered this bug after ~3 hours. Every agent died simultaneously with token errors requiring manual re-login.