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_cmdinsrc/notebooklm/_auth/refresh.py - When a task is cancelled between
try:and the firstwith _REFRESH_STATE_LOCK:block, no future is registered - This causes a 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 start by exploring the repository structure and understanding the code.
- The issue is about a race condition in
Assistant
The file structure is clear. Let me look at the relevant file mentioned in the issue:
src/notebooklm/_auth/refresh.py<tool_call> <function=bash_terminal> <parameter=command> ls -la /notebooklm-py/src/notebooklm/_auth/ </tool_call>
Assistant
Let me explore the repository structure to understand the codebase better.
Assistant
The file exists. Let me look at the content of the
refresh.pyfile to understand the_coalesced_run_refresh_cmdfunction.Assistant
Let me examine the issue more closely and understand the code flow. I'll start by viewing the relevant section of the code:
Assistant
Now I understand the issue. Let me look at the test file for the refresh_cmd_race:
Assistant
Now I understand the issue. Let me explore the relevant code more thoroughly to understand the cancel-recovery loop and then create a reproducer script.
Assistant
Now I have a clear understanding of the issue. Let me create a reproducer script to verify the bug:
Assistant
Let me use the correct tool to create the file.
Assistant
Let me run the reproducer to see if the bug exists.
Assistant
I need to install the package first. Let me check the project setup:
Assistant
Now let me run the reproducer to verify the bug exists:
Assistant
The bug is confirmed. The generation was bumped from 0 to 1 even though no subprocess ran (refresh_calls = 0).
Now let me analyze the fix needed. According to the issue description, the suggested fix is:
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 look at the exact code that needs to be fixed:
Assistant
I've confirmed the bug. Now let me implement the fix. The issue is that when the task is cancelled before
_coalesced_run_refresh_cmdregisters its future,inflightisNone, and the code skips to the generation bump without having run any subprocess.The fix: track whether an
inflightfuture was ever observed during the cancel-recovery loop. Only bump the generation ifsubprocess_exc is None AND observed_inflight is True.Assistant
Now I'll apply the fix. I need to:
- Track whether
inflightwas ever non-None during the cancel-recovery loop. - Only bump the generation if a future was actually observed (meaning a subprocess did run).
- Track whether
Assistant
I need to edit the file. Let me first open it and then use the edit command with the correct file path.
Assistant
Let me use bash to view the exact lines and then use sed to make the changes.
Assistant
I need to fix the sed syntax - use colon range syntax correctly.
Assistant
Now I understand the code structure. I'll implement the fix by:
- Adding an
observed_inflightflag to track whether an in-flight future was ever observed - Setting it to
Truewhen we successfully get a non-None inflight future - Only bumping the generation if a real future was observed (meaning a subprocess ran)
- Adding an
Assistant
The fix has been applied. Let me verify by running the reproducer again:
Assistant
The fix works. Now let me verify the modified code looks correct and run the existing tests:
Assistant
The fix looks correct. Now let me run the existing tests to ensure everything still works:
Assistant
I need to install the test dependencies to run the tests. Let me check the pyproject.toml for test dependencies.
Assistant
Let me run the tests now.
Assistant
Assistant
I need to use the bash_terminal tool correctly.
Assistant
I see the issue with my fix. When Task A is cancelled while the future is still running (not done yet), we loop back to re-await the shielded future, but
observed_inflightis not set to True because we only set it inside theif inflight is None or inflight.done():block.The correct approach is: set
observed_inflight = Truewhenever we observe a non-None inflight future, regardless of whether it's done or not. Let me fix this:Assistant
I see the problem. The
observed_inflightis only set inside theif inflight is not None:block which is inside theif inflight is None or inflight.done():block. When the inflight future is not done yet, we take the "Otherwise loop" branch, andobserved_inflightis never set to True.The fix should set
observed_inflight = Truewhenever we observe a non-None inflight future, regardless of whether it's done or not. Let me update the code:Assistant
Let me verify the changes look correct and run the tests:
Assistant
Now let me run all the tests:
Assistant
All 4 tests pass now. Let me also verify the reproducer still works:
Assistant
Wait, I need to reconsider the fix. Let me trace through the normal case (no cancellation) more carefully to make sure the generation bump still works:
Assistant
Assistant
Let me try again with the proper bash_terminal tool call.
Assistant
Now let me also remove the redundant
observed_inflight = Truein the "Otherwise loop" branch since it's now set in the success path:Assistant
Let me check the full context of the cancel handler to see the current state:
Assistant
Let me run the tests to verify the fix works correctly:
Assistant
All tests pass. Let me verify both scenarios work correctly:
Assistant
The reproducer test passed. Now let me verify that the normal refresh case (without cancellation) correctly bumps the generation:
Assistant
Excellent! The normal refresh case works correctly now - the generation is bumped from 0 to 1 after a successful refresh. Let me also verify the edge case where the subprocess fails (generation should NOT be bumped):
Assistant
All edge cases are working correctly:
- Normal refresh: Generation is bumped (0 → 1) ✓
- Failed refresh: Generation is NOT bumped (stays 0) ✓
- Early-cancel race: Generation is NOT bumped (stays 0) ✓
Let me view the final fix to make sure it's clean:
Assistant
Let me check if the rest of the file is correct too.
Assistant
Let me run a broader set of tests to make sure nothing else is broken:
Assistant
All refresh-related tests pass. Let me clean up the test file and review the final diff:
Assistant
Let me verify the final state of the fix by viewing the git diff.
Assistant
The fix is complete and all tests pass. Let me provide a summary of the reasoning and checklist:
Summary of Fix
Problem: A race condition in
_fetch_tokens_with_refresh()(which calls_coalesced_run_refresh_cmd()) could cause a spurious_REFRESH_GENERATIONSbump even when no subprocess ran. This happens when a task is cancelled in the window before_coalesced_run_refresh_cmd()registers its future.Root Cause: When cancelled before future registration:
registry.get(refresh_key)returnsNonesubprocess_excstaysNone- Code falls through to the generation bump unconditionally
Fix: Introduced an
observed_inflightflag that tracks whether an in-flight future was ever observed during the cancel-recovery loop. The generation is only bumped ifobserved_inflightisTrue, ensuring a subprocess actually ran.Key Changes:
- Added
observed_inflight = Falseinitialization
Assistant
All tests pass. Let me submit the fix.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.