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 start by understanding the issue and the codebase. The issue describes a race condition in
_coalesced_run_refresh_cmdinsrc/notebooklm/_auth/refresh.pywhere_REFRESH_GENERATIONS[refresh_key]can be bumped even when no real refresh happened, in a narrow cancel-before-await race.Let me first explore the repository structure and find the relevant file.
Assistant
Let me find and open the relevant file to understand the code structure.
<tool_call> <function=bash_terminal> <parameter=command> find /notebooklm-py -name "refresh.py" -path "/_auth/" </tool_call>
Assistant
Let me try again to find the refresh.py file in the _auth directory.
Assistant
Found the file. Let me open it and examine the
_coalesced_run_refresh_cmdfunction.Assistant
Let me try using the bash command to look at the file.
Assistant
The file is 744 lines. Let me look at the specific section around lines 487-537 mentioned in the issue description.
Assistant
Now I need to look at more of this function to understand the complete context. Let me search for the function definition.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "_coalesced_run_refresh_cmd" /notebooklm-py/src/notebooklm/_auth/refresh.py | head -20 </tool_call>
Assistant
Let me run the grep command properly to find where _coalesced_run_refresh_cmd is defined.
Assistant
Let me look at the complete function from line 144 onwards.
Assistant
Now I understand the function
_coalesced_run_refresh_cmd. Let me look at the context around where the generation bump happens and understand the issue better. The issue says that when the caller is cancelled between thetry:block and the firstwith _REFRESH_STATE_LOCK:block, and then in the cancel handler, ifinflight is None(because no future was registered), the generation bump at line ~545 still happens even though no refresh occurred.Let me see more of the calling code to understand the full picture.
<tool_call> <function=bash_terminal> <parameter=command> sed -n '400,560p' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
I need to keep running bash commands. Let me try again.
Assistant
Now I understand the issue completely. Let me analyze the race condition:
- In
_fetch_tokens_with_refresh, theawait _coalesced_run_refresh_cmd(...)is called inside awhile True:loop - If the task is cancelled between the
try:and entering_coalesced_run_refresh_cmd, theexcept asyncio.CancelledError:block runs - In the exception handler, we check
registry.get(refresh_key)which can returnNoneif the task was cancelled BEFORE_coalesced_run_refresh_cmdregistered anything in the registry - If
inflight is None, the code does NOT setsubprocess_exc(the innerif inflight is not None:block is skipped) - Then
breakhappens, andsubprocess_exc is None - So the code continues to the generation bump at the end
The fix suggested is to track whether
inflightwas ever non-None during the cancel-recovery loop. Only bump generation ifsubprocess_exc is None AND observed_inflight is True.Let me first check what test files exist for this module to understand the testing patterns.
- In
Assistant
Let me fix the command syntax.
Assistant
Let me look at the test for refresh_cmd_race to understand how they test race conditions.
<tool_call> <function=bash_terminal> <parameter=command> cat /notebooklm-py/tests/unit/test_concurrency_refresh_race.py </tool_call>
Assistant
Let me try running the cat command properly.
Assistant
Now I understand the issue completely. Let me analyze it:
- The problem occurs in
_fetch_tokens_with_refreshin the cancel handler for_coalesced_run_refresh_cmd - When the task is cancelled BEFORE
_coalesced_run_refresh_cmdregisters anything in the registry,inflightisNone - Since
inflight is None, the innerif inflight is not None:block is skipped, leavingsubprocess_exc = None - The code then continues to the generation bump even though no refresh happened
The fix is to track whether we ever observed a non-None inflight task, and only bump generation if we did observe one AND the subprocess succeeded.
Let me first write a test to reproduce the issue, then apply the fix.
- The problem occurs in
Assistant
Now let me look at the exact code that needs to be fixed and understand the context better.
Assistant
Now I need to see the complete while loop to understand the structure better. Let me look at lines 500-530.
Assistant
Now I understand the issue clearly. The fix is to add a flag
observed_inflightthat tracks whether we ever saw a non-None inflight future. Ifobserved_inflightis False (meaning the task was cancelled before it could register anything), we should NOT bump the generation.Let me implement the fix:
Assistant
Now I need to apply the fix. The fix should:
- Add an
observed_inflightflag initialized toFalse - Set
observed_inflight = Truewheninflight is not None - Only bump the generation when
subprocess_exc is None AND observed_inflight is True
Let me create the edit:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '485,542p' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
- Add an
Assistant
Let me use the sed command to find the exact lines I need to edit. The key change is to add an
observed_inflightflag and use it when deciding whether to bump the generation.The lines to modify are:
- Line ~486: Add
observed_inflight = Falseinitialization aftersubprocess_exc: BaseException | None = None - Line ~509: Add
observed_inflight = Trueinside theif inflight is not None:block - Line ~540: Change
if subprocess_exc is not None:to also check forobserved_inflight
Let me use the edit command to make these changes.
- Line ~486: Add
Assistant
Now let me see the exact structure around line 486 and 509 to plan my edits.
Assistant
Now I need to make the edits. I'll need to:
- Add
observed_inflight = Falseaftersubprocess_exc: BaseException | None = None(after line 486) - Add
observed_inflight = Trueinside theif inflight is not None:block (after line 509) - Modify the generation bump condition
Let me use the
editcommand with the special syntax for this task.<tool_call> <function=bash_terminal> <parameter=command> sed -n '486:512' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
- Add
Assistant
I keep forgetting to use proper bash syntax. Let me fix this and run the sed command properly.
Assistant
Let me use the special
editcommand to apply the fix. I'll modify the code to track whether we ever observed a non-None inflight task.Assistant
Let me continue using the bash commands properly. I need to see lines 510-525 to understand the full structure before applying the fix.
Assistant
Now I understand the code structure. Let me apply the fix using the
editcommand. The fix needs to:- Initialize
observed_inflight = Falseaftersubprocess_exc - Set
observed_inflight = Truewheninflight is not None - Only bump generation if
subprocess_exc is None AND observed_inflight is True
- Initialize
Assistant
Now I understand the exact structure. Let me apply the fix. The fix needs to:
- Add
observed_inflight = Falseaftersubprocess_exc: BaseException | None = None - Add
observed_inflight = Truewheninflight is not None - Only bump generation if
observed_inflightis True
- Add
Assistant
Now I need to apply the fix. Let me use the
editcommand with the correct syntax to modify the code.Assistant
Let me use the sed command to make the fix. First, I'll add the
observed_inflightvariable initialization:Assistant
Now let me verify the first change was applied correctly:
Assistant
Now I need to add
observed_inflight = Truewheninflight is not None. Let me find the exact location:Assistant
Now let me add
observed_inflight = Truewheninflight is not None:Assistant
I need to add
observed_inflight = Trueright after theif inflight is not None:line. Let me use sed to insert the line after line 510.Assistant
Let me verify the change was applied correctly:
Assistant
The line
observed_inflight = Truewas added correctly after line 510. Now I need to find the line where we checkif subprocess_exc is not None:and modify it to also check forobserved_inflight. The check is now at line 524 (since we added a line). Let me find the current line number.Assistant
Assistant
Let me run the sed command properly to see lines 524-550.
Assistant
Now I understand the code structure. The fix needs to:
- Change the condition to also check
not observed_inflight - Handle the case where
subprocess_exc is None and observed_inflight is False- we should raiseCancelledErrorwithout bumping the generation
Let me modify the condition at line 524. I'll use sed to replace the condition:
<tool_call> <function=bash_terminal> <parameter=command> sed -i 's/if subprocess_exc is not None:/if subprocess_exc is not None or not observed_inflight:/' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
- Change the condition to also check
Assistant
The sed command ran but I need to verify it worked. Let me check the result.
Assistant
The sed replacement didn't work due to whitespace issues. Let me try a different approach - I'll use sed with a more specific pattern:
Assistant
Let me verify the change:
Assistant
Now I need to fix the code inside this block to handle the case where
subprocess_exc is Nonebutobserved_inflight is False. Currently, the code would raiseNonewhich would fail. Let me see more context:Assistant
I need to fix the exception handling logic. When
subprocess_exc is Nonebutobserved_inflight is False, the code would try to raiseNonewhich would fail. Let me update the exception handling:Assistant
I need to fix the exception handling to handle the case where
subprocess_exc is Nonebutobserved_inflight is False. Let me update the logic:Assistant
That sed command was too complex. Let me check what happened:
Assistant
The sed command created duplicates. Let me restore the file and apply the fix more carefully:
Assistant
Let me start fresh and apply the fix more carefully using the special edit command.
Assistant
Let me use Python to apply the fix more reliably:
Assistant
Now let me verify the changes were applied correctly:
Assistant
The fix looks correct. Let me verify there are no syntax errors by running Python on the file:
Assistant
The syntax is valid. Now let me create a test to verify the fix works correctly:
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 try running the tests again. But first, let me check if pytest is installed:
Assistant
Let me run the existing tests for the refresh module:
Assistant
Good! The tests pass. Now let me run the other refresh-related tests to make sure the fix doesn't break anything:
Assistant
Let me check if these test failures existed before my changes:
Assistant
The test passed without my changes, so my changes may have introduced a regression. Let me restore my changes and investigate.
Assistant
Let me investigate the failing tests more closely. First, let me check the test that failed:
Assistant
I see the issue. The test is failing because in the scenario where the subprocess successfully completes,
observed_inflightisTrue, but the conditionnot observed_inflightevaluates toFalse, so the inner block is not entered. However, my conditionsubprocess_exc is not None or not observed_inflightshould evaluate toFalsewhen bothsubprocess_exc is Noneandobserved_inflight is True.Wait, let me re-read the error. It seems like the test is raising a
CancelledErroreven though the subprocess should have succeeded. Let me check what's happening.The issue might be that is being set to in some cases where it should be . Let me trace through the logic:
Assistant
The issue is that when the task completes successfully, the loop exits via the
breakin thetryblock, andobserved_inflightis never set toTrue. I need to track whether we ever saw a non-None inflight task, not just in the cancel handler.The fix should be:
- Set
observed_inflight = Truewhenever we have a non-None inflight task
- Set
Assistant
Let me run the python command properly.
Assistant
Let me verify the change was applied correctly:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '488,498p' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
Let me run the sed command properly to verify the change.
Assistant
Now let me verify the syntax is valid and run the tests again:
<tool_call> <function=bash_terminal> <parameter=command> python3 -m py_compile /notebooklm-py/src/notebooklm/_auth/refresh.py && echo "Syntax OK" </tool_call>
Assistant
Let me run the syntax check command properly.
Assistant
Now let me run the failing tests again to see if the fix works:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python -m pytest tests/unit/test_refresh_lock_registry.py::TestResolvedPathEquivalence::test_symlink_and_real_path_share_lock_via_refresh tests/unit/test_refresh_lock_registry.py::TestCrossLoopGenerationGuard::test_two_loops_at_most_two_refreshes -v 2>&1 </tool_call>
Assistant
I keep forgetting to properly run bash commands. Let me run them correctly this time.
Assistant
The previously failing tests now pass. Let me run all refresh-related tests to verify the fix is correct:
Assistant
All refresh-related tests pass. Now let me run the concurrency tests as well:
Assistant
Let me install vcr and run the integration tests:
<tool_call> <function=bash_terminal> <parameter=command> pip install vcrpy pytest-vcr 2>&1 | tail -5 </tool_call>
Assistant
I need to properly format my bash command. Let me fix this.
Assistant
Now let me run the integration tests:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python -m pytest tests/unit/test_concurrency_refresh_race.py tests/integration/concurrency/test_refresh_cancellation_propagation.py tests/integration/concurrency/test_refresh_cmd_race.py -v 2>&1 | tail -40 </tool_call>
Assistant
I need to run the bash command properly. The command I just typed seems correct, but I should try again to see the output.
Assistant
Assistant
Let me run the Python test to verify the fix works correctly. The command I just typed should work, but let me make sure the output is displayed.
Assistant
All tests pass. Now let me also check the changes I made to make sure they are complete and correct:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && git diff src/notebooklm/_auth/refresh.py </tool_call>
Assistant
I need to properly run the bash command. The command I just typed should work to see the git diff.
Assistant
The diff shows the changes I made to fix the issue:
- Added
observed_inflight: bool = Falseinitialization - Added
observed_inflight = Truewhen the task completes successfully - Added
observed_inflight = Truewheninflight is not Nonein the cancel handler - Changed the condition from
if subprocess_exc is not None:toif subprocess_exc is not None or not observed_inflight: - Added proper handling for the case where
observed_inflight is Falseandsubprocess_exc is None
Let me run more comprehensive tests to make sure I haven't broken anything:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python -m pytest tests/unit/ -v --tb=short 2>&1 | tail -80 </tool_call>
- Added
Assistant
I need to properly format the bash command to run the tests.
Assistant
Let me install the missing dependency and run the tests that are most relevant to the fix:
Assistant
Now let me run the tests that are most relevant to my fix - specifically the refresh-related tests:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python -m pytest tests/unit/test_refresh*.py tests/unit/test_concurrency*.py tests/unit/concurrency/test_core_close_refresh_race.py -v 2>&1 | tail -50 </tool_call>
Assistant
I need to properly format the bash command to run the tests.
Assistant
All the refresh-related tests pass. Now let me run a few more tests to make sure the fix doesn't break anything else:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python -m pytest tests/unit/test_auth.py -v 2>&1 | tail -50 </tool_call>
Assistant
The command I just typed should work to run the auth tests. Let me make sure the output is displayed.
Assistant
All auth-related tests pass. Now let me verify that my fix handles all edge cases correctly by reviewing the code once more:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '480,560p' /notebooklm-py/src/notebooklm/_auth/refresh.py </tool_call>
Assistant
I need to properly format the bash command to show the code. The command I just typed should work to display lines 480-560 of the file.
Assistant
The fix looks correct. Let me now run a comprehensive test to make sure the fix works correctly:
<tool_call> <function=bash_terminal> <parameter=command> cd /notebooklm-py && python -m pytest tests/unit/test_refresh*.py tests/unit/test_concurrency*.py tests/unit/concurrency/test_core_close_refresh_race.py tests/integration/concurrency/ -v 2>&1 | tail -60 </tool_call>
Assistant
Let me run the tests properly. The command I just typed should work to run all the relevant tests.
Assistant
All 144 tests pass. The fix is working correctly. Let me submit the changes.
Assistant
Now let me submit the changes:
Assistant
Let me try running the submit command properly.
<tool_call> <function=bash_terminal> <parameter=command> submit </tool_call>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.