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 step by step:
- The issue is about a race condition in
_coalesced_run_refresh_cmdfunction insrc/notebooklm/_auth/refresh.py - When a task is cancelled between the
try:block and the firstwith _REFRESH_STATE_LOCK:block, the generation can be bumped even though no real refresh happened - The suggested fix is to track whether
inflightwas ever non-None during the cancel-recovery loop, and only bump generation ifsubprocess_exc is None AND observed_inflight is True
Let me first explore the repository structure and find the relevant code.
- The issue is about a race condition in
Assistant
Let me look at the refresh.py file mentioned in the issue:
<tool_call> <function=bash_terminal> <parameter=command> ls -la /notebooklm-py/src/notebooklm/_auth/ </tool_call>
Assistant
Let me check what files are in the _auth directory:
Assistant
Good, the refresh.py file exists. Let me open it and look at the specific code around lines 487-537 which was mentioned in the issue:
<tool_call> <function=bash_terminal> <parameter=command> wc -l /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
Let me look at the refresh.py file using the open command to examine the relevant code around lines 487-537 as mentioned in the issue.
Assistant
Let me open the refresh.py file and examine the relevant section:
<tool_call> <function=bash_terminal> <parameter=command> cat -n /notebooklm-py/src/notebooklm/_auth/refresh.py | head -600 | tail -150 </tool_call>
Assistant
Let me try a different approach to read the file. I'll use sed to show specific line ranges.
Assistant
Now I need to see the
_coalesced_run_refresh_cmdfunction itself. Let me search for it in the file:<tool_call> <function=bash_terminal> <parameter=command> grep -n "_coalesced_run_refresh_cmd" /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
Let me search for the function definition of
_coalesced_run_refresh_cmdin the file.Assistant
Let me look at the
_coalesced_run_refresh_cmdfunction definition starting at line 144:<tool_call> <function=bash_terminal> <parameter=command> sed -n '144,230p' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
Let me try using grep and sed differently.
Assistant
Now I understand the issue better. Let me look at where
_coalesced_run_refresh_cmdis called and how the generation bump happens. Let me look at the relevant section around lines 487-580 where the cancel recovery logic is.Looking at the code I saw earlier (around lines 487-580), I can see the problem:
_coalesced_run_refresh_cmdis awaited inside awhile Trueloop withtry/except asyncio.CancelledError- If cancelled BEFORE being registered as inflight (between
try:andwith _REFRESH_STATE_LOCK:), theinflightwill beNone - When
inflight is None,subprocess_excremainsNone(no exception is set) - The loop breaks with
subprocess_exc is None - After the loop, the code checks
if subprocess_exc is not Nonewhich is False, so no exception is raised - Then the generation bump at line 566-572 happens anyway:
with _REFRESH_STATE_LOCK: ... _REFRESH_GENERATIONS[refresh_key] = max(existing, refresh_generation + 1)
Assistant
Let me use sed with proper syntax to view the code around lines 545-590 to see the generation bump logic.
Assistant
Let me see the code between lines 500-550 to understand the cancel handling logic:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '500,560p' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
I'm getting an error when running the sed command. Let me try using a different approach to view the file content.
Assistant
Let me see more of the code before line 500 to understand the full context of the cancel handling logic.
<tool_call> <function=bash_terminal> <parameter=command> awk 'NR >= 490 && NR <= 550' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
The sed command is failing again. Let me try using Python to read and display the file.
Assistant
Now I understand the issue clearly. Let me look at the beginning of the
whileloop to understand the full context:<tool_call> <function=bash_terminal> <parameter=command> python3 -c " with open('/notebooklm-py/src/notebooklm/_auth/refresh.py', 'r') as f: lines = f.readlines() for i in range(475-1, 495): if i < len(lines): print(f'{i+1}: {lines[i]}', end='') " </tool_call>
Assistant
Let me continue reading the code.
Assistant
Now I understand the issue. Let me trace through the problem:
- When
_coalesced_run_refresh_cmdis awaited and cancelled before registering in the inflight registry,inflightbecomesNone - The
subprocess_excstaysNonebecause no exception is set - After the loop, the generation is bumped (lines 538-543) even though no subprocess ran
The fix is to track whether we ever observed a non-None
inflightfuture and only bump the generation if we did. Let me implement this fix:- When
Assistant
Now I understand the issue. The problem is that when
_coalesced_run_refresh_cmdis cancelled before the inflight future is registered,inflightisNone, andsubprocess_excstaysNone. After the loop breaks, the code proceeds to bump the generation (lines 538-543) even though no subprocess ran.The fix is to track whether we ever observed a non-None
inflightduring the cancel-recovery loop. Only bump the generation ifsubprocess_exc is None AND observed_inflight is True.Let me apply the fix:
Assistant
Now I need to update the generation bump logic to also check
observed_inflight. Let me first verify the first change and then apply the second:Assistant
Assistant
I need to run the command to replace the generation bump logic. Let me try again with the python3 command.
Assistant
The first replacement was successful, so the file content has changed. Let me check the current state of the file and find the exact text to replace:
Assistant
Let me see more of this section to understand what needs to be replaced:
Assistant
The exact text is there. Let me try the replacement using the
sedcommand or by using the exact bytes:Assistant
The replacement was successful. Let me verify the changes by looking at the modified code section:
Assistant
The fix has been applied successfully. Now let me verify that the code still passes basic Python syntax checks and see if there are any tests related to this functionality:
<tool_call> <function=bash_terminal> <parameter=command> python3 -m py_compile /notebooklm-py/src/notebooklm/_auth/refresh.py && echo "Syntax check passed" </tool_call>
Assistant
I need to run a command to check the syntax. Let me continue with the python3 command.
Assistant
Now let me search for any existing tests related to the refresh functionality:
Assistant
Let me check if there are any tests specifically related to the _coalesced_run_refresh_cmd function or the race condition issue:
Assistant
I don't see any specific tests for the race condition. Let me check if there are any unit tests related to auth refresh:
Assistant
Let me look at the test file related to concurrency refresh race:
Assistant
This test is about concurrent refresh but not specifically about the race condition we're fixing. Let me look at the other tests:
<tool_call> <function=bash_terminal> <parameter=command> cat /notebooklm-py/tests/unit/test_auth_cookie_save_race.py </tool_call>
Assistant
I need to run the cat command to view the file. Let me continue.
Assistant
Now let me run the existing tests to make sure the fix doesn't break anything:
Assistant
Let me install the package first:
Assistant
Now let me run the tests:
Assistant
The async tests need pytest-asyncio. Let me install it and try again:
<tool_call> <function=bash_terminal> <parameter=command> pip install pytest-asyncio 2>&1 | tail -5 </tool_call>
Assistant
Let me install pytest-asyncio and then run the tests.
Assistant
Now let me run the tests again to verify the fix doesn't break existing tests:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_concurrency_refresh_race.py -v 2>&1 | head -60 </tool_call>
Assistant
I need to run the pytest command again. Let me continue with the command.
Assistant
All tests passed! Now let me also run other related tests to make sure the fix doesn't break anything else:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_auth_cookie_save_race.py -v 2>&1 | head -80 </tool_call>
Assistant
Let me run the auth cookie save race tests to verify the fix doesn't break any related functionality.
Assistant
There are some test errors and one failure. Let me look at the test that failed:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_auth_cookie_save_race.py::TestRefreshCmdSnapshotCapturedBeforeRetryFetch::test_retry_fetch_rotations_persist_to_disk -v 2>&1 </tool_call>
Assistant
I need to run the failing test to understand what's happening. Let me run it with more verbose output.
Assistant
I see the issue. My fix has a bug -
observed_inflightis only set toTruein theexcept asyncio.CancelledError:block, but it should also beTruewhen the normal flow completes successfully. Let me fix this:Assistant
Let me verify the fix and run the test again: <tool_call> <function=bash_terminal> <parameter=command> python3 -c " with open('/notebooklm-py/src/notebooklm/_auth/refresh.py', 'r') as f: lines = f.readlines() for i in range(484, 535): if i < len(lines): print(f'{i+1}: {lines[i]}', end='') " </tool_call>
Assistant
Let me run the command to verify the fix.
Assistant
I see the fix has been applied but I also need to check the generation bump logic section:
<tool_call> <function=bash_terminal> <parameter=command> python3 -c " with open('/notebooklm-py/src/notebooklm/_auth/refresh.py', 'r') as f: lines = f.readlines() for i in range(540, 580): if i < len(lines): print(f'{i+1}: {lines[i]}', end='') " </tool_call>
Assistant
Let me run the command to view the generation bump logic section.
Assistant
Good, the fix looks correct. Now let me run the failing test again to verify it passes:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_auth_cookie_save_race.py::TestRefreshCmdSnapshotCapturedBeforeRetryFetch::test_retry_fetch_rotations_persist_to_disk -v 2>&1 </tool_call>
Assistant
I need to run the pytest command again to verify the fix works.
Assistant
The test now passes. Let me also run the other tests that were failing (the ERROR ones) to see if they're related to my fix or other issues.
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_auth_cookie_save_race.py -v 2>&1 | tail -50 </tool_call>
Assistant
Let me run the full test suite for the auth cookie save race tests to see the overall status.
Assistant
The errors are due to a missing
httpx_mockfixture - this is a pre-existing issue in the test setup, not related to my fix. 51 tests passed and only 2 errors due to a missing fixture. Let me now install the missing pytest-httpx plugin and run the tests again to verify everything passes.<tool_call> <function=bash_terminal> <parameter=command> pip install pytest-httpx 2>&1 | tail -5 </tool_call>
Assistant
Let me install the pytest-httpx package and then run the tests again.
Assistant
Now let me run the tests again to verify all pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_auth_cookie_save_race.py -v 2>&1 | tail -20 </tool_call>
Assistant
I need to run the pytest command again to see if all tests pass now with pytest-httpx installed.
Assistant
All 53 tests in test_auth_cookie_save_race.py now pass. Let me also run the concurrency refresh race tests to make sure they still pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_concurrency_refresh_race.py -v 2>&1 | tail -20 </tool_call>
Assistant
I need to run the pytest command again to see the test results.
Assistant
All tests pass. Now let me also run a broader set of unit tests to make sure my changes don't break anything else:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/ -v 2>&1 | tail -50 </tool_call>
Assistant
Let me run the full unit test suite to verify everything still works with my changes.
Assistant
There are some missing dependencies (vcr, yaml) for some tests, but those are not related to my fix. Let me run the unit tests that are relevant to the auth/refresh functionality specifically:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python3 -m pytest tests/unit/test_concurrency_refresh_race.py tests/unit/test_auth_cookie_save_race.py tests/unit/test_refresh_lock_lazy_init.py tests/unit/test_client_keepalive.py -v 2>&1 | tail -30 </tool_call>
Assistant
Let me run the command to execute the relevant unit tests.
Assistant
All 90 tests pass! Now let me also verify the changes I made by looking at the final state of the fix:
<tool_call> <function=bash_terminal> <parameter=command> python3 << 'EOF' with open('/notebooklm-py/src/notebooklm/_auth/refresh.py', 'r') as f: lines = f.readlines() # Print the full context around the fix for i in range(484, 580): if i < len(lines): print(f'{i+1}: {lines[i]}', end='') EOF </tool_call>
Assistant
Let me verify the changes by displaying the relevant section of the fix:
Assistant
The fix looks good. Now let me check if there are any additional edge cases to consider. Let me trace through the fix:
-
Normal completion (lines 489-495): When
_coalesced_run_refresh_cmdcompletes normally, we setobserved_inflight = True. The generation bump at lines 562-567 will happen. -
Cancelled before inflight registration (lines 502-510): When cancelled before the future is registered in the registry,
inflightisNone. We setobserved_inflight = Falseand break. The early return at line 555 prevents the generation bump. -
Cancelled while inflight is in progress (lines 504-527): When cancelled after the future is registered but before it completes, is not and not done. We set and loop to re-await. This is correct - a subprocess is running.
-
Assistant
Let me verify the syntax check passes.
Assistant
The fix is complete and all relevant tests pass. Let me provide a summary of the changes:
Summary of Fix
The issue was a race condition in
_coalesced_run_refresh_cmdwhere_REFRESH_GENERATIONS[refresh_key]could be bumped even when no real refresh happened, in a narrow cancel-before-await race.Changes Made to
/notebooklm-py/src/notebooklm/_auth/refresh.py:-
Added
observed_inflightflag (line 487): Tracks whether an inflight future was ever registered during the cancel-recovery loop. -
Handle cancelled before registration (lines 504-510): When
inflight is None, the subprocess was never registered - likely cancelled before_coalesced_run_refresh_cmdadded the future. We explicitly setobserved_inflight = Falseand break to prevent the generation bump. -
Track inflight observation in all paths (lines 493-494, 511):
-
Assistant
The fix is complete. Let me provide a final verification by submitting the changes:
Assistant
All 90 tests pass. The fix is complete and verified. Let me submit the changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.