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 the issue:
- The issue is about a race condition in
_coalesced_run_refresh_cmdinsrc/notebooklm/_auth/refresh.py - The problem occurs when a task is cancelled between
try:and the firstwith _REFRESH_STATE_LOCK:block - This causes a phantom generation bump even when no real refresh happened
- The suggested fix is to track whether
inflightwas ever non-None during the cancel-recovery loop
Let me first explore the repository structure and find the relevant code.
- The issue is about a race condition in
Assistant
Let me explore the
_authdirectory and find therefresh.pyfile.Assistant
The issue says the code was moved from
src/notebooklm/auth.pytosrc/notebooklm/_auth/refresh.py. Let me look at therefresh.pyfile to find the_coalesced_run_refresh_cmdfunction.<tool_call> <function=bash_terminal> <parameter=command> wc -l /notebooklm-py/src/notebooklm/_auth/refresh.py /notebooklm-py/src/notebooklm/auth.py </tool_call>
Assistant
The user wants me to check the line counts of the two files to understand their structure.
Assistant
Let me open the
refresh.pyfile to examine the_coalesced_run_refresh_cmdfunction:Assistant
The tool path was incorrect. I need to use
opencommand properly.Assistant
Let me use the proper tool syntax for
open:Assistant
Let me view the specific section of the file that contains the
_coalesced_run_refresh_cmdfunction:Assistant
Now let me look at the
_fetch_tokens_with_refreshfunction to understand the cancel-recovery loop:Assistant
Let me continue viewing the file to find the
_fetch_tokens_with_refreshfunction which contains the cancel-recovery loop:Assistant
Now I can see the issue. Let me continue to view the rest of the cancel handler:
Assistant
Now I have a clear picture of the issue. Let me understand the bug:
- In the cancel-recovery loop (lines 487-520), when a CancelledError is caught
- If
inflightis None (the subprocess never registered in_coalesced_run_refresh_cmd), the code skips settingsubprocess_excand breaks - Then at lines 538-543, the generation is bumped even though no subprocess ever ran
- This is a "phantom generation bump"
Let me create a reproducer script first to understand the issue better, then implement the fix.
Assistant
Now I understand the bug completely. Let me analyze the race condition:
- When
_coalesced_run_refresh_cmdis called, there's a window betweentry:and the firstwith _REFRESH_STATE_LOCK:where cancellation can occur - If cancelled in this window, NO future is registered in
_REFRESH_INFLIGHT_BY_LOOP[loop][refresh_key] - When the CancelledError handler runs,
inflight is None subprocess_excstaysNone(because the innerif inflight is not None:block is skipped)- The generation bump at line 543 happens anyway, even though no subprocess ran
- This is a "phantom generation bump"
The fix: Track whether an inflight future was ever observed, and only bump generation if we actually observed an inflight future.
- When
Assistant
Let me look for existing tests related to the refresh functionality:
Assistant
Let me check if there are existing tests for the refresh module and understand the test structure.
Assistant
Let me look at the existing test files to understand the test patterns used in this project.
Assistant
Now I have a clear understanding of the issue. Let me trace through the bug:
- When
_coalesced_run_refresh_cmdis called, there's a window betweentry:and the firstwith _REFRESH_STATE_LOCK:where cancellation can occur - If cancelled in this window, NO future is registered in
_REFRESH_INFLIGHT_BY_LOOP[loop][refresh_key] - In the CancelledError handler (lines 493-517),
inflight = registry.get(refresh_key)returnsNone - The condition
if inflight is None or inflight.done():is True - But
if inflight is not None:is False, sosubprocess_excstaysNone - We break out of the loop
- Since
subprocess_exc is None, we proceed to line 538-543 and bump the generation - This is a phantom generation bump - no subprocess ever ran
Let me create a reproducer script to confirm this issue:
- When
Assistant
Let me install the package first:
Assistant
The package is installed. Let me run the reproducer script to confirm the bug exists.
Assistant
Let me fix the test to use pytest-asyncio properly:
Assistant
Let me install the required pytest plugin and check the configuration:
Assistant
The user wants me to run the test now that pytest-asyncio is installed. Let me run the reproducer test.
Assistant
Let me fix the missing import:
Assistant
The reproducer confirms the bug. The output clearly shows:
early_cancel_occurred: True- Our patched function simulated the early-cancel racesubprocess_called: False- No subprocess was actually runREFRESH_GENERATIONS[...] = 1- BUG: The generation was bumped to 1 even though no subprocess ran!
Now I'll implement the fix. The suggested approach is to track whether
inflightwas ever non-None during the cancel-recovery loop, and only bump generation if we actually observed an inflight future.Assistant
Let me view the exact section that needs to be modified:
Assistant
Now I'll implement the fix. The bug is that when a task is cancelled before
_coalesced_run_refresh_cmdregisters a future,inflightisNone,subprocess_excstaysNone, and the generation gets bumped anyway.The fix: Track whether an inflight future was ever observed during the cancel-recovery loop. Only bump generation if we actually observed an inflight future (i.e., the subprocess was actually started).
Assistant
Now I'll implement the fix. The approach is to track whether an inflight future was ever observed during the cancel-recovery loop, and only bump generation if we actually observed one (meaning a subprocess was started).
Assistant
The user wants me to continue with the fix. I need to:
- Set
observed_inflight = Truewhen we find a non-None inflight future - Only bump generation if
observed_inflightis True (or if the subprocess actually ran)
Let me continue editing the file.
- Set
Assistant
I've added the
observed_inflightvariable. Now I need to:- Set it to
Truewhen we find a non-None inflight future (meaning subprocess was started) - Also set
subprocess_excwheninflight is None(no subprocess was ever registered, so we should not bump generation)
Let me apply the fix properly. The cleanest approach is to set
subprocess_excwheninflight is None, indicating no subprocess was ever started:- Set it to
Assistant
Now I need to:
- Set
observed_inflight = Truewhen we find a non-None inflight future (meaning subprocess was started) - Change the condition at line 522 to also check if we observed an inflight future before bumping generation
- Set
Assistant
The user wants me to continue implementing the fix. Let me first verify the current state of the file after the previous edit, then continue with the remaining changes needed.
Assistant
Now I need to also:
- Set
observed_inflight = Truein the "loop back" path (when inflight is not None and not done) - Change the generation bump condition to also check
observed_inflight
Let me apply these changes:
- Set
Assistant
The user wants me to continue implementing the fix. Let me check the current state of the file and continue with the remaining changes.
Assistant
The
sedcommand inserted the line in the wrong place - afterbreak, which is unreachable. I need to fix this properly. Let me revert and apply the changes correctly.Assistant
The user wants me to continue implementing the fix. Let me first view the current state of the file after reverting, then apply all the changes correctly in one edit.
Assistant
Now let me apply the fix properly using a single edit operation. The fix involves:
- Adding
observed_inflight = Falsevariable - Setting
observed_inflight = Truewhen we find a non-None inflight future - Changing the generation bump condition to check
observed_inflight
- Adding
Assistant
The patch file had issues. Let me apply the fix directly using the
editcommand. The fix needs to:- Add
observed_inflight = Falsevariable - Set
observed_inflight = Truewhen we find a non-None inflight future - Change the generation bump condition to only bump if
observed_inflightis True
- Add
Assistant
Let me use a Python script to apply the fix more precisely:
Assistant
Now I need to also update the generation bump section. The fix is already tracking
observed_inflightand settingsubprocess_excwhen no inflight was observed. But I also need to make sure the generation bump at line 538-543 (now shifted due to the added lines) only happens ifobserved_inflightis True.Let me check the current state:
Assistant
The first part of the fix has been applied. Let me verify the complete logic flow by running the test:
Assistant
The test passes now. Let me verify the fix is complete by running the existing tests in the repository to ensure nothing is broken.
Assistant
Let me install the required test dependencies:
Assistant
The user wants me to run the existing tests to verify the fix doesn't break anything. Let me run the refresh cmd race tests.
Assistant
All existing refresh race tests pass. Let me run more related tests to ensure the fix is complete:
Assistant
The 2 errors are unrelated to my fix (missing
httpx_mockfixture). 58 tests passed. Let me also run the test_refresh_lock_registry.py tests more specifically:Assistant
All tests pass. Let me verify the final state of my fix by viewing the modified code:
Assistant
The fix is complete and verified. Let me clean up the test file I created and verify the final diff:
Assistant
The user wants me to verify the final diff and submit the solution. Let me check the git diff to see what changes I've made.
Assistant
The fix is complete. Here's a summary of the changes:
Summary of the Fix
Problem: In
_fetch_tokens_with_refresh(insrc/notebooklm/_auth/refresh.py), when a task is cancelled in the window betweentry:and the firstwith _REFRESH_STATE_LOCK:inside_coalesced_run_refresh_cmd, no future gets registered in the inflight registry. The CancelledError handler then seesinflight is None, skips settingsubprocess_exc, breaks out of the loop, and proceeds to bump_REFRESH_GENERATIONSeven though no subprocess ever ran - a "phantom generation bump."Solution: Added an
observed_inflightboolean variable that tracks whether any inflight future was ever observed during the cancel-recovery loop. Wheninflight is Noneat the point we're ready to break, we now checkelif not observed_inflightand setsubprocess_excto a sentinelCancelledError. This routes the code to the failure branch (line 533-542), preventing the phantom generation bump.Key changes:
Assistant
The fix is complete and verified. Let me provide a summary:
Fix Summary
Issue: Spurious
_REFRESH_GENERATIONSbump on early-cancel in_coalesced_run_refresh_cmdRoot Cause: When a task is cancelled between
try:and the firstwith _REFRESH_STATE_LOCK:inside_coalesced_run_refresh_cmd, no future gets registered in the inflight registry. The CancelledError handler seesinflight is None, skips settingsubprocess_exc, breaks out of the loop, and proceeds to bump_REFRESH_GENERATIONSeven though no subprocess ever ran.Solution: Added an
observed_inflightboolean to track whether any inflight future was ever observed during the cancel-recovery loop. Wheninflight is Noneand we haven't seen any inflight future, we setsubprocess_excto route the code to the failure branch, preventing the phantom generation bump.Changes Made ():
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.