Repository navigation
Conversation
dab4b5f to
0a2f567
Compare
Greptile SummaryThis PR fixes a real production race condition: when 18+ agents share one OAuth profile, all of them could race to refresh the single-use refresh token simultaneously, causing Key observations:
Confidence Score: 4/5
Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts
Line: 165-212
Comment:
**Test does not exercise the `refresh_token_reused` catch path**
This test never actually triggers the `refresh_token_reused` mock. Here is why:
1. `ensureAuthProfileStore(subAgentDir)` merges main + sub-agent stores; the sub-agent's expired creds override main in the merge result.
2. `resolveApiKeyForProfile` then calls `adoptNewerMainOAuthCredential`, which reads the main store directly and finds the fresh credentials. `oauthCred` becomes fresh.
3. Because `Date.now() < oauthCred.expires` is `true`, the function returns immediately — `refreshOAuthTokenWithLock` (and therefore `performOAuthRefresh`) is never called.
The mock is set up but silently ignored, and the result comes entirely from the pre-existing `adoptNewerMainOAuthCredential` code path that predates this PR. The new `refresh_token_reused` catch block (lines 284–307 of `oauth.ts`) has no test coverage.
To actually test the recovery path the test name describes, the main store would need to have **expired** creds at the point `adoptNewerMainOAuthCredential` runs but **fresh** creds by the time `performOAuthRefresh` throws (simulating a race outside the lock). One way to force this is to initialize the main store with expired creds before calling `resolveApiKeyForProfile`, then have the mock mutate the main store to contain fresh creds before throwing — or by mocking `loadAuthProfileStoreForAgent` to return different values at different call sites.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/agents/auth-profiles/paths.ts
Line: 37-39
Comment:
**Lock-path collision between different profile IDs**
The sanitiser replaces every character outside `[a-zA-Z0-9_.-]` with `_`, so the colon separator is also replaced. This means `openai-codex:default` and the (unusual but valid) profile ID `openai-codex_default` both map to the same lock file `openai-codex_default`.
Two semantically distinct profiles would therefore share a lock and serialise against each other unnecessarily. In practice this is very unlikely (profile IDs rarely use underscores as separators), but a disambiguating separator — such as preserving the colon, or inserting a hash segment — would eliminate the ambiguity entirely:
```suggestion
const safeId = profileId.replace(/[^a-zA-Z0-9_.-]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
return path.join(resolveStateDir(), "locks", "oauth-refresh", safeId);
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/agents/auth-profiles/constants.ts
Line: 23-32
Comment:
**`OAUTH_REFRESH_LOCK_OPTIONS` is identical to `AUTH_STORE_LOCK_OPTIONS`**
Both objects have the same `retries`, `factor`, `minTimeout`, `maxTimeout`, `randomize`, and `stale` values. Keeping them separate is fine if you anticipate tuning them independently (e.g., the global refresh lock may eventually need a longer `maxTimeout` or more retries than the per-store lock), but right now it introduces silent duplication. At minimum, a short comment explaining why they are separate would clarify intent for future maintainers.
How can I resolve this? If you propose a fix, please make it concise.Last reviewed commit: "fix: use global OAut..." |
0a2f567 to
29b0d6b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0a2f5674c2
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 29b0d6b421
ℹ️ 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".
29b0d6b to
f8d6cc6
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f8d6cc68e1
ℹ️ 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".
fbe9baf to
62689b9
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 62689b958d
ℹ️ 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".
7c82fc5 to
3d0fc67
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3d0fc67651
ℹ️ 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".
3d0fc67 to
22495c9
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 22495c9a64
ℹ️ 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".
22495c9 to
a1f3564
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a1f35640b5
ℹ️ 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".
a1f3564 to
394f747
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 394f747dc4
ℹ️ 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".
394f747 to
a11018b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a11018b0db
ℹ️ 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".
a11018b to
7f7ee3e
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0c41c9782e
ℹ️ 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".
4a3253d to
c154ef0
Compare
c154ef0 to
44f4041
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 44f4041fe4
ℹ️ 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".
| expectedCurrent: cred, | ||
| newCred: mainCred, | ||
| }); | ||
| if (adopted.current && Date.now() < adopted.current.expires) { |
There was a problem hiding this comment.
Return fresh main OAuth creds even when local CAS write fails
This branch has already verified that mainCred is a fresh, share-safe OAuth credential, but it only returns success when writeCredentialToAgentStore succeeds. If the sub-agent auth store lock times out (lock_failed), the code falls through to performOAuthRefresh(cred) with stale tokens; for providers that rotate/single-use refresh tokens, that can raise refresh_token_reused and fail the request even though a valid main-store credential was already available. In that lock-contention scenario, the current request should still use the proven fresh main credential (while keeping write-back best-effort).
Useful? React with 👍 / 👎.
…law#26322) Replace the per-agentDir file lock in refreshOAuthTokenWithLock with a global per-profile lock at ~/.openclaw/locks/oauth-refresh/<profileId>. This serializes token refresh across all agents sharing the same OAuth profile, preventing refresh_token_reused 401 errors that cascade to expensive model fallback. Changes: - Global lock keyed by profileId (resolveOAuthRefreshLockPath) - Fresh disk reads via loadAuthProfileStoreForAgent (bypasses runtime cache) - Recovery on refresh_token_reused: re-read main store, adopt fresher creds - Write-back refreshed creds to main store so peer agents benefit - Identity guard (isSameOAuthIdentity) prevents cross-account overwrites - All store writes go through updateAuthProfileStoreWithLock (file-lock safe) Tests: 3 new tests covering recovery, no-recovery, and write-back scenarios. Docs: Updated oauth.md, multi-agent.md, multi-agent-sandbox-tools.md.
- Add accountId to isSameOAuthIdentity for stronger identity matching - Switch lock path sanitization to percent-encoding to prevent collisions - Fix refresh_token_reused test to actually exercise the catch path - Use isSameOAuthIdentity in adoptNewerMainOAuthCredential and error fallback - Use loadAuthProfileStoreForAgent in updateAuthProfileStoreWithLock for fresh disk reads - Add comment explaining separate OAUTH_REFRESH_LOCK_OPTIONS
…verwrites - Replace loadProviderRuntime() (removed during rebase) with direct static import - Scope access/refresh comparison in write condition to equal-expiry case only, preventing a stale refresh from clobbering newer re-auth credentials
44f4041 to
6e37369
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e37369565
ℹ️ 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".
| maxTimeout: 10_000, | ||
| randomize: true, | ||
| }, | ||
| stale: 30_000, |
There was a problem hiding this comment.
Raise OAuth refresh lock stale window for network refreshes
OAUTH_REFRESH_LOCK_OPTIONS keeps stale at 30 seconds even though this lock now wraps the full OAuth network refresh path. In withFileLock, a lock is considered stale once its createdAt age exceeds staleMs even if the owning PID is still alive (src/plugin-sdk/file-lock.ts), so a slow refresh (>30s) lets another process delete the live lock and run a second refresh concurrently. That reintroduces the same refresh_token_reused race this global lock is intended to prevent.
Useful? React with 👍 / 👎.
| const currentCred = writeResult.current; | ||
| if ( | ||
| currentCred && | ||
| canShareOAuthCredentialAcrossAgents(params.cred, currentCred) && | ||
| Number.isFinite(currentCred.expires) && |
There was a problem hiding this comment.
Return main credential when local adopt CAS cannot lock
adoptNewerMainOAuthCredential already has a fresher mainCred, but it only adopts when writeResult.current is populated. If the local auth store lock times out (updateAuthProfileStoreWithLock returns null and writeResult.status stays lock_failed), this branch falls through and returns null, so resolveApiKeyForProfile keeps using the older local OAuth credential. Under store-lock contention, that can cause avoidable auth failures or unnecessary refresh attempts even though a valid main-agent credential was already available for the current request.
Useful? React with 👍 / 👎.
|
Adding a data point to raise reviewer-attention priority: hitting #26322 on 2026.4.11 (commit |
Before: each agent held its own per-agentDir file lock during refresh, so N agents sharing a single OAuth profile would all refresh in parallel when the token expired. Because OpenAI rotates the refresh token on every successful call, the losers of that race get HTTP 401 refresh_token_reused and cascade to model fallback even though auth is actually valid. With 18 codex agents this caused a token-expiry storm every ~12h. After: - refreshOAuthTokenWithLock now takes a cross-agent file lock at $STATE_DIR/locks/oauth-refresh/sha256-<hex64>. All agents sharing a profileId serialize on this single coordination point. - An in-process Promise queue keyed on profileId chains same-PID callers so the re-entrant file lock cannot let two concurrent refreshes slip through within the same process. - Inside the lock, an explicit main-store recheck adopts a freshly mirrored credential from the main agent instead of issuing a duplicate HTTP refresh. This collapses N serialized refreshes into 1 refresh + (N-1) adoptions. - After a successful refresh from a secondary agent, the new credential is mirrored best-effort back into the main-agent store so peers adopt rather than race. Main-agent refreshes are unchanged. Adapted from HeroSizy's approach in #51476; that PR's head was 7,755 commits behind origin/main and the surrounding auth-profiles files had been split/refactored, so this is a port against the current shape of oauth.ts/store.ts/path-resolve.ts, not a rebase. Tests: - oauth.concurrent-20-agents.test.ts: 20 distinct agentDirs sharing one profileId/accountId fire resolveApiKeyForProfile concurrently; exactly one refresh call is observed and all 20 receive the same fresh token. - oauth.mirror-refresh.test.ts: sub-agent refresh mirrors into the main store; main-agent self-refresh is unchanged. - oauth-lock-path.test.ts: unit + fuzz coverage for resolveOAuthRefreshLockPath (path-safety invariants, hashing, length bound, no separators/.. in basename, 2,700+ random adversarial inputs). Co-authored-by: HeroSizy <[email protected]>
|
The PR has been ported and merged in #67876, will close this PR. |
|
Many thanks for your work on this @HeroSizy glad we could get it updated @ merged! |
Summary
Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause / Regression History (if applicable)
git blame, prior PR, issue, or refactor if known): this PR started as a fix for the shared-profilerefresh_token_reusedrace described in OAuth token refresh race condition causes spurious failovers (refresh_token_reused) #26322. Review then surfaced the post-refresh corruption paths introduced by shortening the lock scope.Regression Test Plan (if applicable)
src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts,src/agents/auth-profiles/oauth.fallback-to-main-agent.test.ts,src/agents/auth-profiles.paths.test.tsnullrefresh result, current-request success when auth-store CAS persistence times out after refresh, and distinct, dot-safe, bounded-length lock path encoding.src/agents/auth-profiles/oauth.test.tsstill covers the baseline OAuth resolution behavior.User-visible / Behavior Changes
refresh_token_reusedstampedes.token/api_keyre-auth.accountIdor matching email) or exact credential equivalence, preserving per-agent account isolation.Diagram (if applicable)
Security Impact (required)
NoYesNoNoNoYes, explain risk + mitigation: token persistence rules are stricter now. Cross-agent sharing only happens with positive identity evidence or exact credential equivalence; persisted writes are compare-and-set against the expected OAuth snapshot; reads under the global refresh lock are read-only; and refresh lock ids now use deterministic SHA-256 filenames that stay dot-safe and bounded in length.Repro + Verification
Environment
openai-codex,anthropic)Steps
Expected
Actual (before fix)
token/api_keyentry or recreate a deleted profile.ENAMETOOLONG.nulleven after valid main-store updates.Evidence
Focused regressions now cover:
refresh_token_reusedrecovery against a fresher main-store credentialnull-retry re-resolutionHuman Verification (required)
bun run test -- src/agents/auth-profiles.paths.test.ts src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts src/agents/auth-profiles/oauth.fallback-to-main-agent.test.ts src/agents/auth-profiles/oauth.test.ts(4 files, 40 tests passing), plusoxlintandoxfmt --checkon the touched files.null, auth-store CAS lock timeout after refresh, and lock-path collision/dot-segment safety.pnpm test,pnpm check, andpnpm buildwere not rerun as part of this final update.Review Conversations
Compatibility / Migration
YesNoNoRisks and Mitigations