Repository navigation
pkg/llm: fix withPreemptiveRefresh composition and stale _AT on rotation - #5052
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5052 +/- ##
=======================================
Coverage 69.81% 69.81%
=======================================
Files 561 562 +1
Lines 56606 56647 +41
=======================================
+ Hits 39518 39548 +30
- Misses 14055 14063 +8
- Partials 3033 3036 +3 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
7981211 to
ca621b3
Compare
Two bugs in tokensource.go flagged in PR review (#5051): 1. withPreemptiveRefresh composition: both callers were passing a source already wrapped in oauth2.ReuseTokenSource (from CreateTokenSourceFromCached and flow.TokenSource()), creating a double-caching chain. In the preemptive window the inner ReuseTokenSource returned the same cached real token, causing preemptiveTokenSource to shift an already-expired expiry, so every Token() call re-entered the inner chain instead of one refresh per window. Fix: build the raw refresher directly (NewResourceTokenSource for the resource path, config.TokenSource for the non-resource path) without an inner ReuseTokenSource, then stack: ReuseTokenSource(nil, preemptive{Persisting{raw}}). Extract oauth2ConfigFrom helper to reuse the already-discovered flowCfg in performBrowserFlow without a second OIDC round-trip. 2. Stale _AT cache after refresh token rotation: makeTokenPersister wrote the new refresh token but left the _AT access-token cache entry unchanged. A concurrent process could read the stale _AT between the write and the next Token() call. Fix: after SetSecret for the refresh token succeeds, overwrite the _AT entry with an empty string so the next Token() call falls through to tier 2. Adds a regression test verifying that multiple Token() calls within the preemptive window produce exactly two inner calls: one for the initial short-lived token and one for the preemptive refresh that yields a fresh cached token. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
ca621b3 to
c5e3861
Compare
There was a problem hiding this comment.
Pull request overview
Fixes two token-caching bugs in pkg/llm/tokensource.go: (1) incorrect withPreemptiveRefresh stacking that causes repeated re-entry during the preemptive window, and (2) stale _AT access-token cache after refresh token rotation.
Changes:
- Rebuild token-source layering in both cache-restore and browser-flow paths to avoid the previously double-cached
ReuseTokenSourcecomposition. - Add
_ATinvalidation when persisting a rotated refresh token to prevent cross-process use of stale access tokens. - Add/adjust unit tests to lock in the intended preemptive-refresh behavior and the
_ATinvalidation write.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| pkg/llm/tokensource.go | Reworks token-source construction for preemptive refresh, adds oauth2ConfigFrom helper, and invalidates _AT on refresh token rotation. |
| pkg/llm/tokensource_test.go | Updates persister test expectations for _AT invalidation and adds a regression test for preemptive-refresh behavior. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
2788339 to
f07c076
Compare
JAORMX
left a comment
There was a problem hiding this comment.
Hey Yolanda! Thanks for chasing this one down... the trace through the broken composition is clear and the fix is correct as far as I can tell. Two inner Token() calls per window instead of N is exactly what we want.
So, a few things came out of reviewing this that I'd like us to talk through before stamping it.
The PR description doesn't match the code
The summary says "the non-resource path still wraps in reuseTokenSource internally (oauth2 library limitation). The fix fully applies on the resource path which is the expected LLM gateway configuration."
But the actual diff replaces oauth2Cfg.TokenSource(ctx, token) with newNonCachingRefresher(...) unconditionally on both call sites. nonCachingRefresher handles both paths in one type by branching on if n.resource != "". So Bug 1 is fixed on both paths, not just the resource one.
Could you update the description? It threw a couple of reviewers off and I had to cross-check the diff to be sure.
The bigger concern... are we duplicating things we already have?
This is what I really wanted to figure out before stamping. I had a hunch we were reinventing pieces of thv proxy's OAuth path, so I went and inventoried it.
nonCachingRefresher does almost exactly the same thing as pkg/auth/oauth/resourceTokenSource (same cfg.Exchange(ctx, "", opts...) trick, same RFC 8707 resource handling, same explicit scope= forwarding). The one real difference is resourceTokenSource.Token() short-circuits on r.token.Valid() (line 45), which is exactly the inner cache that breaks withPreemptiveRefresh.
I don't want to block this PR on a refactor, but the right shape here is a shared non-caching refresher in pkg/auth/oauth that both pkg/llm and resourceTokenSource use. Otherwise we'll have two implementations of the same RFC 6749 §6 trick and they'll drift. Please file a follow-up and link it here.
While we're at it: ensureOfflineAccess (pkg/llm/tokensource.go:411) is byte-identical to pkg/registry/auth/oauth_token_source.go:170, and DeriveSecretKey is the same formula in both packages with a different prefix. None of that's introduced by this PR... it predates it. But registry-OAuth + LLM-OAuth is two callers of the same shape already, and a third is likely down the road. Worth a follow-up to lift the shared bits to pkg/auth/oauth.
What's genuinely new and worth keeping in pkg/llm: the cross-process _AT cache (justified by thv llm token being short-lived per invocation, which thv proxy isn't), and the preemptive-refresh wrapper. MonitoredTokenSource (which thv proxy actually uses) only refreshes at expiry, not before, so the preemptive layer is a real new pattern, not a duplicate.
Note on the thv proxy comparison since it's relevant to where we want this codebase to land: thv proxy has retry, singleflight, and exponential backoff via MonitoredTokenSource, none of which pkg/llm has today. A transient blip mid-refresh is currently a hard 502 to the LLM client. Out of scope here, but file it.
In-PR (please address before merge)
- Update PR description (non-resource path is fixed too)
- Doc comment on
nonCachingRefreshercovering concurrency assumptions and RT preservation when the IdP returns none - Add a test for
Audience == "". The current regression test only exercises the resource path... which is precisely the path the stale description claims is "fully fixed". - Either rename
TestWithPreemptiveRefresh_CachingInnerSource_LoopRegressionor strengthen the assertion to match the "loop" wording
Follow-up issues (link them here)
- Factor a shared non-caching refresher into
pkg/auth/oauthand migrateresourceTokenSourceto it - Lift
ensureOfflineAccessandDeriveSecretKeytopkg/auth/oauth(or wherever makes sense). Thepkg/registry/authandpkg/llmduplication is silently growing. - Consider giving
pkg/llmretry/singleflight similar toMonitoredTokenSource
Otherwise, the fix is correct and the tests are a meaningful step forward. Thanks again!
|
Filed #5066 to track extracting the shared non-caching refresher into |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
9adbc38 to
8d0ed1c
Compare
Summary
Two bugs in
pkg/llm/tokensource.goflagged in PR review on thethv-llm-tokenbranch (#5051).Bug 1:
withPreemptiveRefreshcomposition is brokenBoth callers passed a source already wrapped in
oauth2.ReuseTokenSource(fromoauth.NewResourceTokenSourceandoauth2Cfg.TokenSource), creating a double-caching chain. In the preemptive window the innerReuseTokenSourcereturned the same cached real-expiry token,preemptiveTokenSourceshifted it to already-expired, and everyToken()call re-entered the inner chain indefinitely — no actual IdP refresh occurred.Fix: replace both inner sources with
oauth.NonCachingRefresher(inpkg/auth/oauth), a type that always performs a network round-trip whenToken()is called, on both the resource path (Audience != "") and the standard path (Audience == ""). The outerReuseTokenSource(viawithPreemptiveRefresh) is now the sole caching layer. Target stacking:NonCachingRefresherconsolidates the RFC 8707 resource-indicator logic and standard OAuth 2.0 refresh into one type (branching onresource == ""), is safe for concurrent use via an internalsync.Mutex, and preserves the previous refresh token when the IdP does not rotate one.resourceTokenSourceinpkg/auth/oauthis refactored to delegate toNonCachingRefresherinstead of duplicating thecfg.Exchangelogic — the two shared the same RFC 8707 resource handling and explicit scope forwarding.withPreemptiveRefreshFromis added to pre-seed the outerReuseTokenSourcewith the shifted initial token after the browser flow, so the just-obtained access token is served without an immediate network call.Also extracts an
oauth2ConfigFromhelper to reuse the already-discoveredflowCfginperformBrowserFlowwithout a second OIDC round-trip.Bug 2: Stale
_ATcache after refresh token rotationmakeTokenPersisterwrote the new refresh token but left the_ATaccess-token cache entry unchanged. A concurrent process (e.g.thv llm token) could read the stale_ATentry and serve a token minted against the now-invalidated refresh token.Fix: after
SetSecretfor the refresh token succeeds, overwrite the_ATentry with an empty string so the nextToken()call falls through to a fresh access token. Errors from this invalidation are now logged atWarninstead of silently discarded.Closes #5051
Follow-up issues
ensureOfflineAccessandDeriveSecretKeytopkg/auth/oauth(byte-identical with counterparts inpkg/registry/auth) and consider retry/singleflight forpkg/llmtoken refresh (parity withMonitoredTokenSource)Type of change
Test plan
task test)Added:
TestWithPreemptiveRefresh_ExactlyOneRefreshPerWindow: verifies exactly 2 inner calls (initial + one preemptive refresh), all subsequent calls from outer cache — exercises the resource path (Audience != "")TestWithPreemptiveRefresh_NoResource_ExactlyOneRefreshPerWindow: same assertion via a real HTTP test server andNonCachingRefresherwithresource = ""— exercises the standard (non-resource) path and catches a revert tooauth2Cfg.TokenSourceTestWithPreemptiveRefreshFrom_PreSeededToken: verifies the initial token is served without hitting the inner sourceTestWithPreemptiveRefreshFrom_NilInitial_BehavesLikeWithPreemptiveRefreshTestNonCachingRefresher_EmptyRefreshToken_ReturnsErrorTestNonCachingRefresher_StandardPath_NoResourceParam: exercises the standard path against a mock HTTP server, verifying noresource=param is sent and the previous RT is preserved when the IdP omits oneTestWithPreemptiveRefresh_CachingInnerSource_ThrashesAcrossOuterCalls: regression test documenting the failure mode (N outerToken()calls → N inner calls; contrast with the fixed behaviour above)Updated
TestTokenSource_MakeTokenPersister_StoresTokenAndCallsUpdaterto expect the AT cache invalidation write in order after the refresh token write, and to align the refresh-token key with the AT key viaCachedRefreshTokenRef.Does this introduce a user-facing change?
No — internal token caching logic. Users see fewer redundant network refreshes in the preemptive window and no stale access tokens after refresh token rotation.
Special notes for reviewers
_ATinvalidation usesSetSecret(..., "")rather thanDeleteSecretfor provider compatibility (some providers do not support delete; an empty value is treated as a cache miss bytryAccessTokenCache).NonCachingRefresherholds async.Mutexso it is self-safe for concurrent use. It lives inpkg/auth/oauthand is now used by bothpkg/llmandresourceTokenSource, eliminating the duplicatecfg.Exchangelogic.Audience == "") is fully fixed by this PR. The stale hedge in earlier description drafts ("non-resource path still partially broken") was incorrect —NonCachingRefresherhandles both paths unconditionally.