Skip to content

pkg/llm: fix withPreemptiveRefresh composition and stale _AT on rotation - #5052

Merged
yrobla merged 3 commits into
mainfrom
yrobla/fix-5051-preemptive-refresh
Apr 27, 2026
Merged

yrobla merged 3 commits into
mainfrom
yrobla/fix-5051-preemptive-refresh

Conversation

@yrobla

@yrobla yrobla commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two bugs in pkg/llm/tokensource.go flagged in PR review on the thv-llm-token branch (#5051).

Bug 1: withPreemptiveRefresh composition is broken

Both callers passed a source already wrapped in oauth2.ReuseTokenSource (from oauth.NewResourceTokenSource and oauth2Cfg.TokenSource), creating a double-caching chain. In the preemptive window the inner ReuseTokenSource returned the same cached real-expiry token, preemptiveTokenSource shifted it to already-expired, and every Token() call re-entered the inner chain indefinitely — no actual IdP refresh occurred.

Fix: replace both inner sources with oauth.NonCachingRefresher (in pkg/auth/oauth), a type that always performs a network round-trip when Token() is called, on both the resource path (Audience != "") and the standard path (Audience == ""). The outer ReuseTokenSource (via withPreemptiveRefresh) is now the sole caching layer. Target stacking:

ReuseTokenSource(nil, preemptiveTokenSource{inner: PersistingTokenSource{source: NonCachingRefresher}})

NonCachingRefresher consolidates the RFC 8707 resource-indicator logic and standard OAuth 2.0 refresh into one type (branching on resource == ""), is safe for concurrent use via an internal sync.Mutex, and preserves the previous refresh token when the IdP does not rotate one.

resourceTokenSource in pkg/auth/oauth is refactored to delegate to NonCachingRefresher instead of duplicating the cfg.Exchange logic — the two shared the same RFC 8707 resource handling and explicit scope forwarding.

withPreemptiveRefreshFrom is added to pre-seed the outer ReuseTokenSource with the shifted initial token after the browser flow, so the just-obtained access token is served without an immediate network call.

Also extracts an oauth2ConfigFrom helper to reuse the already-discovered flowCfg in performBrowserFlow without a second OIDC round-trip.

Bug 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 (e.g. thv llm token) could read the stale _AT entry and serve a token minted against the now-invalidated refresh token.

Fix: after SetSecret for the refresh token succeeds, overwrite the _AT entry with an empty string so the next Token() call falls through to a fresh access token. Errors from this invalidation are now logged at Warn instead of silently discarded.

Closes #5051

Follow-up issues

Type of change

  • Bug fix

Test plan

  • Unit tests (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 and NonCachingRefresher with resource = "" — exercises the standard (non-resource) path and catches a revert to oauth2Cfg.TokenSource
  • TestWithPreemptiveRefreshFrom_PreSeededToken: verifies the initial token is served without hitting the inner source
  • TestWithPreemptiveRefreshFrom_NilInitial_BehavesLikeWithPreemptiveRefresh
  • TestNonCachingRefresher_EmptyRefreshToken_ReturnsError
  • TestNonCachingRefresher_StandardPath_NoResourceParam: exercises the standard path against a mock HTTP server, verifying no resource= param is sent and the previous RT is preserved when the IdP omits one
  • TestWithPreemptiveRefresh_CachingInnerSource_ThrashesAcrossOuterCalls: regression test documenting the failure mode (N outer Token() calls → N inner calls; contrast with the fixed behaviour above)

Updated TestTokenSource_MakeTokenPersister_StoresTokenAndCallsUpdater to expect the AT cache invalidation write in order after the refresh token write, and to align the refresh-token key with the AT key via CachedRefreshTokenRef.

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

  • The _AT invalidation uses SetSecret(..., "") rather than DeleteSecret for provider compatibility (some providers do not support delete; an empty value is treated as a cache miss by tryAccessTokenCache).
  • NonCachingRefresher holds a sync.Mutex so it is self-safe for concurrent use. It lives in pkg/auth/oauth and is now used by both pkg/llm and resourceTokenSource, eliminating the duplicate cfg.Exchange logic.
  • The non-resource path (Audience == "") is fully fixed by this PR. The stale hedge in earlier description drafts ("non-resource path still partially broken") was incorrect — NonCachingRefresher handles both paths unconditionally.

@yrobla
yrobla requested a review from JAORMX as a code owner April 24, 2026 14:09
@github-actions github-actions Bot added the size/S Small PR: 100-299 lines changed label Apr 24, 2026
@codecov

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.33333% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.81%. Comparing base (d8d58ca) to head (8d0ed1c).

Files with missing lines Patch % Lines
pkg/llm/tokensource.go 37.50% 14 Missing and 1 partial ⚠️
pkg/auth/oauth/non_caching_refresher.go 89.58% 2 Missing and 3 partials ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@yrobla
yrobla force-pushed the yrobla/fix-5051-preemptive-refresh branch from 7981211 to ca621b3 Compare April 27, 2026 07:14
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 27, 2026
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]>
@yrobla
yrobla force-pushed the yrobla/fix-5051-preemptive-refresh branch from ca621b3 to c5e3861 Compare April 27, 2026 07:15
@yrobla
yrobla requested a review from Copilot April 27, 2026 07:15
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 27, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 ReuseTokenSource composition.
  • Add _AT invalidation 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 _AT invalidation 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.

Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/llm/tokensource.go Resolved
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 27, 2026
@yrobla
yrobla requested a review from Copilot April 27, 2026 07:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread pkg/llm/tokensource_test.go Resolved
@yrobla
yrobla force-pushed the yrobla/fix-5051-preemptive-refresh branch from 2788339 to f07c076 Compare April 27, 2026 07:45
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/M Medium PR: 300-599 lines changed labels Apr 27, 2026

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 nonCachingRefresher covering 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_LoopRegression or strengthen the assertion to match the "loop" wording

Follow-up issues (link them here)

  • Factor a shared non-caching refresher into pkg/auth/oauth and migrate resourceTokenSource to it
  • Lift ensureOfflineAccess and DeriveSecretKey to pkg/auth/oauth (or wherever makes sense). The pkg/registry/auth and pkg/llm duplication is silently growing.
  • Consider giving pkg/llm retry/singleflight similar to MonitoredTokenSource

Otherwise, the fix is correct and the tests are a meaningful step forward. Thanks again!

Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/llm/tokensource_test.go Resolved
Comment thread pkg/llm/tokensource_test.go Resolved
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/M Medium PR: 300-599 lines changed labels Apr 27, 2026
@yrobla

yrobla commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

Filed #5066 to track extracting the shared non-caching refresher into pkg/auth/oauth and lifting the duplicated helpers — linked there so it doesn't get lost.

@github-actions github-actions Bot removed the size/M Medium PR: 300-599 lines changed label Apr 27, 2026
@github-actions github-actions Bot added the size/M Medium PR: 300-599 lines changed label Apr 27, 2026
@yrobla
yrobla requested a review from Copilot April 27, 2026 08:57
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/M Medium PR: 300-599 lines changed labels Apr 27, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread pkg/llm/tokensource_test.go Resolved
Comment thread pkg/llm/tokensource.go Resolved
Comment thread pkg/auth/oauth/non_caching_refresher.go Resolved
Comment thread pkg/auth/oauth/non_caching_refresher.go Resolved
@yrobla
yrobla force-pushed the yrobla/fix-5051-preemptive-refresh branch from 9adbc38 to 8d0ed1c Compare April 27, 2026 09:53
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/M Medium PR: 300-599 lines changed labels Apr 27, 2026
@yrobla
yrobla merged commit 68d29fb into main Apr 27, 2026
43 checks passed
@yrobla
yrobla deleted the yrobla/fix-5051-preemptive-refresh branch April 27, 2026 10:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pkg/llm: fix withPreemptiveRefresh composition and stale _AT cache on refresh token rotation

4 participants