ISSUE DESCRIPTION auth: spurious REFRESHGENERATIONS bump on early-cancel in…
- User
ISSUE DESCRIPTION
auth: spurious _REFRESH_GENERATIONS bump on early-cancel in _coalesced_run_refresh_cmd
Summary
_coalesced_run_refresh_cmdinsrc/notebooklm/_auth/refresh.py(moved fromsrc/notebooklm/auth.pyin tier-10 PR-B-high #814, but the code is byte-identical to origin/main since tier-9 E #803) can bump_REFRESH_GENERATIONS[refresh_key]even when no real refresh happened, in a narrow cancel-before-await race.Reproducer (race condition)
- Caller invokes
await _coalesced_run_refresh_cmd(refresh_key, path, profile)from the cancel-recovery loop in_fetch_tokens_with_refresh. - Task is cancelled in the window between
try:and the firstwith _REFRESH_STATE_LOCK:block inside_coalesced_run_refresh_cmd— so NO future is registered in_REFRESH_INFLIGHT_BY_LOOP[loop][refresh_key]. - Control jumps to
except asyncio.CancelledError:in the caller. registry.get(refresh_key)returnsNone.- The inner
if inflight is None or inflight.done():is taken; theif inflight is not None:block is skipped;subprocess_excstaysNone;break. - Outer
if subprocess_exc is not None:is False, so no raise. - Generation is bumped at the
with _REFRESH_STATE_LOCK: ... max(existing, refresh_generation + 1)line, even though no subprocess ran. - Then
if caller_cancelled: raise asyncio.CancelledError().
Impact
A concurrent waiter on a different event loop sharing the same
refresh_keywould observe the phantom generation bump on its lock-re-acquire path, treat the storage as freshly-refreshed, and skip its own_run_refresh_cmd— proceeding tobuild_httpx_cookies_from_storageagainst STALE on-disk state.Bounded blast radius: the stale-storage caller will fail again on the next token fetch and trigger its own real refresh. No data corruption. But it's a wasted round-trip.
Suggested fix (from CodeRabbit on PR #814)
Track whether
inflightwas ever non-None during the cancel-recovery loop. Only bump generation ifsubprocess_exc is None AND observed_inflight is True. Or per the alternative suggestion: raise immediately wheninflight is Noneat the top of the cancel handler (the subprocess never registered, so we can't be the leader-cancel-before-await case for an actually-running refresh). - Caller invokes
Assistant
Let me analyze this issue. The problem is in
src/notebooklm/_auth/refresh.py(or possiblysrc/notebooklm/auth.py) where_coalesced_run_refresh_cmdcan incorrectly bump_REFRESH_GENERATIONS[refresh_key]even when no real refresh happened, due to a race condition with cancellation.Let me first explore the repository structure and find the relevant files.
Assistant
Let me open the refresh.py file and look at the relevant code around the
_coalesced_run_refresh_cmdfunction and_fetch_tokens_with_refresh:Assistant
Let me look at the specific code area more closely and also check the related test files:
Assistant
Now I understand the issue. Let me trace through the race condition described:
_coalesced_run_refresh_cmdis called- Task is cancelled between
try:and the firstwith _REFRESH_STATE_LOCK:inside_coalesced_run_refresh_cmd- so NO future is registered in_REFRESH_INFLIGHT_BY_LOOP - Control jumps to
except asyncio.CancelledError:in the caller (_fetch_tokens_with_refresh) registry.get(refresh_key)returnsNoneif inflight is None or inflight.done():is True (becauseinflight is None)- The inner
if inflight is not None:block is skipped - sosubprocess_excstaysNone breakexits the while loopif subprocess_exc is not None:is False, so no raise- Generation is bumped even though no subprocess ran
- Then
if caller_cancelled: raise asyncio.CancelledError()
The fix, as suggested, is to track whether
inflightwas ever non-None during the cancel-recovery loop. Only bump generation if AND . Or raise immediately when .Assistant
Now let me also look at the
test_refresh_cancellation_propagation.pytest to see if there's a test that covers the specific race condition described in the issue:Assistant
Now let me look more closely at the specific race condition described in the issue. The problem is when cancellation happens between
try:and the firstwith _REFRESH_STATE_LOCK:inside_coalesced_run_refresh_cmd. Let me trace through the code more carefully:Assistant
Now I have a clear understanding of the issue. Let me create a reproducer script to confirm the bug:
Assistant
Let me fix the reproducer to pass a Path object:
Assistant
I've confirmed the bug. Now let me understand exactly what happens in the code flow:
_fetch_tokens_with_jarraises auth expired error_fetch_tokens_with_refreshcatches it, enters the refresh branch- Inside the
while Trueloop, it callsawait _coalesced_run_refresh_cmd(...) _coalesced_run_refresh_cmdraisesCancelledError(simulated early cancel)- The
except asyncio.CancelledErrorhandler runs caller_cancelled = Trueregistry = _get_inflight_registry()gets the registry (empty since future was never registered)inflight = registry.get(refresh_key)returnsNoneif inflight is None or inflight.done():isTrue(becauseinflight is None)if inflight is not None:isFalse, sosubprocess_excstaysNonebreakexits the loopif subprocess_exc is not None:isFalse, so no raise
Assistant
Now I understand the fix needed. The issue is when
inflight is Nonein the cancel handler - this means no subprocess was ever registered (cancelled before registration). In this case, we should treat it as a failure (don't bump generation), because we can't distinguish between:- "We were the leader but cancelled before registration" - no subprocess ran
- "Another loop's subprocess finished and was cleaned up" - unlikely but possible
The fix per the suggested approach: when
inflight is None, we should NOT proceed to the success path (generation bump). We should either:- Set
subprocess_excto something (treat as failure), OR - Track whether we ever observed a non-None
inflightand only bump if we did
Let me implement the simpler fix: when
inflight is None, raise immediately as CancelledError (the subprocess never registered, so this can't be the leader-cancel-before-await case for an actually-running refresh):Assistant
The open command syntax seems wrong. Let me try the correct format.
Assistant
Now I understand the exact fix needed. The issue is in the
except asyncio.CancelledErrorblock. Wheninflight is None, the code falls through without settingsubprocess_exc, and then the loop breaks. The outer code seessubprocess_exc is Noneand bumps the generation.The fix: when
inflight is Noneandcaller_cancelledis True, we should treat this as a failure case (no subprocess ran), so we should setsubprocess_excto prevent the generation bump. Following the suggested fix from the issue, we should raiseasyncio.CancelledError()immediately wheninflight is Noneat the top of the cancel handler.Let me implement the fix:
Assistant
Now I need to replace this section. The fix is to handle the
inflight is Nonecase separately — wheninflight is None, the subprocess never registered (cancelled before awaiting the future), so we should treat it as a failure case and not bump the generation.Assistant
Let me verify the fix was applied correctly:
Assistant
The fix looks correct. Now let me run the reproducer to verify it's fixed:
Assistant
The fix works. Now let me run the existing tests to make sure I didn't break anything:
Assistant
I need to install the package first:
Assistant
I see the problem. My fix has a bug. When
inflightis not None but is done (not cancelled), I'm checkinginflight.cancelled()and theninflight.exception(). But when the subprocess fails, my code is accessinginflight.exception()which can raiseInvalidStateErrorif the future was cancelled.Wait, looking more carefully at the error: the issue is that my fix changed the control flow. Let me re-read the original code:
Original:
if inflight is None or inflight.done(): if inflight is not None: if inflight.cancelled(): subprocess_exc = asyncio.CancelledError() else: subprocess_exc = inflight.exception() break # Otherwise loop — re-await the shielded future.My fix splits this into two cases:
if inflight is None:→ raise immediately# inflight.done(): ...→ this should beelif inflight.done():but I left it as just a comment!
The problem is that the original code had
if inflight is None or inflight.done():which means bothNoneanddone()cases would enter the same block. But I split them incorrectly. When is not None but done, we should still enter the block. Let me fix this:Assistant
I see - after my
raise, the code flow is correct (raises immediately). But the problem is that the remaining code (after theraise) now assumesinflight is not Noneand is thedone()case. But wait, the original code was:if inflight is None or inflight.done(): ... break # Otherwise loop — re-await the shielded future.So when neither
inflight is Nonenorinflight.done(), we loop (re-await). My fix changes the condition:if inflight is None: raise # inflight.done(): subprocess already settled; ... if inflight.cancelled(): ...But this is wrong! The second part should only run when
inflight.done()is True. I need to add theelif inflight.done():condition back:Assistant
Let me verify the fix looks correct:
Assistant
Good. Now let me run the tests again:
Assistant
All 4 tests pass. Let me also verify the reproducer still works:
Assistant
Now let me also run the other related test file to make sure I didn't break anything:
Assistant
Let me also run a broader set of tests related to refresh functionality:
Assistant
Missing dependencies. Let me install them and try again:
Assistant
All refresh-related concurrency tests pass. Let me also run any unit tests related to auth/refresh:
Assistant
Excellent! All 126 refresh-related tests pass (126 passed, 2 skipped). Let me also clean up the reproducer script:
Assistant
Now let me review the final state of the fix by looking at the diff:
Assistant
The fix looks clean and correct. Let me also verify that the fix handles all the edge cases mentioned in the issue and the test suite:
- Early cancel (no future registered): When
inflight is None, we now immediately raiseCancelledError()instead of falling through to the generation bump. ✅ - Cancel with subprocess already done (success): When
inflight.done()is True andinflight.cancelled()is False, we checkinflight.exception(). If it's None,subprocess_excstays None... wait, let me re-check this case.
Actually, let me trace through more carefully. When the subprocess succeeds:
inflight.done()is Trueinflight.cancelled()is False
- Early cancel (no future registered): When
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.