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
I'll start by exploring the repository structure to understand the codebase and locate the relevant file. Let's first check the current directory and list files.
- Assistant
Let me explore the repository structure to understand the codebase and find the relevant files mentioned in the issue.
- Assistant
I need to find the file mentioned in the issue:
src/notebooklm/_auth/refresh.py. Let's open it and examine the relevant function_coalesced_run_refresh_cmd. - Assistant
Let me look at the
_coalesced_run_refresh_cmdfunction to understand the issue. I'll search for it in the file. - Assistant
Now let me scroll up to see the
_coalesced_run_refresh_cmdfunction itself. - Assistant
Let me look at the
_coalesced_run_refresh_cmdfunction specifically. - Assistant
Now let me look at the
_coalesced_run_refresh_cmdfunction definition. - Assistant
Now let me look at the caller in
_fetch_tokens_with_refreshmore carefully. Let me scroll to see the cancel-recovery loop. - Assistant
Now I can see the issue clearly. Let me read the cancel-recovery loop in the caller more carefully.
- Assistant
Now I understand the issue clearly. Let me trace through the race condition:
await _coalesced_run_refresh_cmd(...)is called at line 489- Inside
_coalesced_run_refresh_cmd, the future is registered at line 172-177 (insidewith _REFRESH_STATE_LOCK:) - The task is cancelled BETWEEN
try:(line 488) and the lock acquisition inside_coalesced_run_refresh_cmd(line 172) - This means NO future was registered in the registry
- Control jumps to
except asyncio.CancelledError:at line 493 registry.get(refresh_key)returnsNonebecause no future was ever registeredinflight is Noneis True, so we enter theif inflight is None or inflight.done():branchinflight is not Noneis False, sosubprocess_excstaysNone- We break, and
subprocess_exc is Nonecauses generation bump at line 538 - But no subprocess actually ran!
The fix: When
inflight is Nonein the cancel handler, it means the subprocess was never registered. We should raise immediately (the subprocess never ran, so we can't be the "leader-cancel-before-await" case).Let me apply the fix:
- Assistant
Wait, I see an issue with my fix. When
inflight is Noneand webreak,subprocess_excis stillNoneandcaller_cancelledisTrue. This means the code will still fall through to the generation bump at line 546! I need to also setsubprocess_excto something non-None to prevent the bump. Let me update the fix: - Assistant
Let me trace through the fix to verify it's correct:
Before the fix (bug):
- Task cancelled before
_coalesced_run_refresh_cmdregisters future inflight = None,subprocess_excstaysNonebreak→ falls through to generation bump →raise CancelledError()- Generation bumped spuriously!
After the fix:
- Task cancelled before
_coalesced_run_refresh_cmdregisters future inflight = None→subprocess_exc = asyncio.CancelledError()→breaksubprocess_exc is not None→caller_cancelled is True→raise CancelledError() from subprocess_exc- Generation NOT bumped ✓
Now let me verify the fix doesn't break other scenarios. Let me look at the existing tests:
- Task cancelled before
- Assistant
Let me check the existing tests to make sure our change doesn't break them:
- Assistant
Need to install the package first.
- Assistant
Now let me run the tests to verify the fix doesn't break anything.
- Assistant
Let me just run the unit tests:
- Assistant
Let me see the actual error for the test that failed.
- Assistant
Let me check what the actual error is:
- Assistant
Missing test dependencies. Let me install the dev/test dependencies.
- Assistant
Now let me run the tests again.
- Assistant
The error is unrelated to our change - it's a missing
playwrightmodule. Let me run just the relevant refresh/auth tests to verify our change doesn't break anything: - Assistant
All 432 related tests pass with 0 failures. Let me also check if the same issue exists in
auth.py(the issue mentions it was moved from there): - Assistant
Good, the issue doesn't exist in
auth.py- that's just a facade. The actual logic is only inrefresh.py. Let me verify the final state of my fix: - Assistant
Now let me verify the diff to make sure the change is exactly what we want:
- Assistant
The diff looks correct. Let me trace through the scenarios:
-
Bug case (cancel before future registered):
inflight is None→subprocess_exc = CancelledError()→break→subprocess_exc is not None→caller_cancelled→raise CancelledError(). No generation bump ✓ -
Cancel while subprocess running:
inflightis notNone,inflight.done()isFalse→ neither branch matches → "Otherwise loop — re-await the shielded future" ✓ -
Cancel after subprocess settled:
inflightis notNone,inflight.done()isTrue→ inspect terminal state, setsubprocess_excaccordingly ✓ (unchanged behavior)
The fix also simplifies the code in the
inflight.done()branch by removing the now-unnecessaryif inflight is not None:guard.Let me run the refresh-cancellation-specific tests:
-
- Assistant
All the refresh cancellation and race condition tests pass. Let me also run the state machine and all other refresh tests to be thorough:
- Assistant
All tests pass. Now let me verify the fix by creating a small reproducer script that demonstrates the fix works. The issue describes a race condition, so we need to simulate it:
- Assistant
Let me write a proper reproducer script that focuses on testing the specific code path in question:
- Assistant
Let me look at how the
_should_try_refreshfunction works and how it determines when to try refresh: - Assistant
Let me look at the
_should_try_refreshfunction: - Assistant
I see -
_should_try_refreshrequiresNOTEBOOKLM_REFRESH_CMD_ENVto be set. Let me check the existing refresh-cancellation tests to see how they test this: - Assistant
Now let me look at the cancel-settle race test:
- Assistant
Let me run the existing tests one more time to be sure my fix is solid:
- Assistant
All 25 tests pass. Let me run a broader set of tests to be thorough:
- Assistant
The one failure is in
test_playwright_initializes_on_non_windowswhich is unrelated to my change (it's about playwright initialization). Let me verify this test also fails on the original code: - Assistant
Good, the test fails before my change too (missing playwright module). Let me restore my change:
- Assistant
Now let me also check if the same issue exists in
auth.pyas the issue mentions the code may have been moved. Let me check if auth.py has its own copy: - Assistant
Good, the code is only in
_auth/refresh.py. Let me also run the public shims test: - Assistant
Let me verify the final diff one more time:
- Assistant
The fix looks correct. Let me clean up the temporary test files and verify the final state:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.