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).Why not fixed in PR #814
That PR's scope was "extract verbatim from auth.py into _auth/refresh.py + facade-forward". Changing async semantics was explicitly out of scope (
must_not_do). Filing here for a dedicated follow-up.References
- CodeRabbit comment: https://github.com/teng-lin/notebooklm-py/pull/814#discussion_r3256142201
- Original code:
src/notebooklm/_auth/refresh.py:487-537(tier-10),src/notebooklm/auth.py:961-1026(tier-9 E origin)
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /notebooklm-py, current file: none) bash-$
- Caller invokes
Assistant
I'll start by exploring the repository structure and finding the relevant file mentioned in the issue.
Assistant
Let me explore the repository structure and the relevant file first.
Assistant
This shows the caller's cancel-recovery loop. Let me look at the actual
_coalesced_run_refresh_cmdfunction to understand the inflight registration.Assistant
Let me look at the
_coalesced_run_refresh_cmdfunction in detail.Assistant
Now let me look at the exact cancel-recovery loop in detail.
Assistant
Now I understand the structure. Let me look at the cancel-recovery loop and the surrounding context more carefully, and check the existing tests.
Assistant
Let me look at the relevant race/cancellation tests to understand testing patterns and ensure my fix aligns.
Assistant
Let me look at the most relevant tests for the refresh command race and cancellation.
Assistant
Let me understand the relationship between
notebooklm.authandnotebooklm._auth.refresh, and look at the state machine test.Assistant
I need to make a single tool call. Let me combine them.
Assistant
Now let me carefully analyze the issue. Let me re-read the cancel-recovery loop and understand the exact race scenario described.
Let me look at the exact lines in the file to understand the full flow:
Assistant
Now let me look at the broader
_fetch_tokens_with_refreshfunction structure and the conftest for tests.Assistant
Let me check the conftest for unit tests and how the environment runs tests.
Assistant
Now I understand the structure. Let me write a reproduction script to confirm the bug. I'll patch
_coalesced_run_refresh_cmdto simulate the cancel-before-await race (cancellation delivered before the future is registered).Assistant
I need to use the virtual environment or install the package. Let me check.
Assistant
I've reproduced the bug — generation bumped to 1 with no real refresh. Now let me apply the fix. I'll use the approach of raising immediately when
inflight is None(no subprocess ever registered). Let me view the exact lines to edit.Assistant
Now let me open the file and apply the fix.
Assistant
Now I'll apply the fix. I'll modify the cancel handler so that when
inflight is None(no subprocess ever registered — the cancel-before-await race), it raisesCancelledErrorimmediately without proceeding to the generation bump.Assistant
The fix is applied. Now let me run the reproduction script again to confirm the bug is fixed.
Assistant
The bug is fixed. Now let me run the existing relevant tests to ensure I didn't break anything.
Assistant
All passing. Let me run the broader auth/refresh test suite to be thorough.
Assistant
All tests pass. Let me also run a broader sweep of the unit and integration concurrency tests to be safe, and verify the cross-loop scenario mentioned in the issue.
Assistant
The error is unrelated to my change (missing
playwrightmodule for a CLI session test). Let me exclude those and run the rest.Assistant
The only failure is a
playwright-related test (missing module), unrelated to my change. Let me confirm it's pre-existing by checking it.Assistant
Confirmed — the
playwrightfailure is pre-existing and unrelated to my change. Let me review my final diff.Assistant
The diff is clean and minimal. Let me clean up the temporary reproduction script and run the most relevant tests one final time.
Assistant
All tests pass. Let me confirm the final git status shows only my intended change.
Assistant
The working tree contains only my intended change to
src/notebooklm/_auth/refresh.py, with no stray test files. Let me do a final review of the complete modified cancel-recovery loop to ensure correctness.Assistant
The fix is complete and verified. Let me summarize my work against the checklist before submitting.
Summary
Issue:
_coalesced_run_refresh_cmd's cancel-recovery loop insrc/notebooklm/_auth/refresh.pycould bump_REFRESH_GENERATIONS[refresh_key]even when no real refresh happened, in a narrow cancel-before-await race where the caller's task is cancelled before the in-flight future is registered in the per-loop registry.Root cause: In the
except asyncio.CancelledError:handler, wheninflight is None(no subprocess ever registered), the code fell through tobreakwithsubprocess_excstillNone, then proceeded to the generation-bump block — producing a phantom bump that could make a concurrent cross-loop waiter treat stale on-disk storage as freshly-refreshed.Fix: Split the
if inflight is None or inflight.done():check. Wheninflight is None, raiseasyncio.CancelledError()immediately — no subprocess ran on this loop, so no generation bump; the cancellation propagates and the next caller observesshould_run_refresh == Trueto run a real refresh. Theinflight.done()branch retains its original terminal-state inspection (now without the redundantif inflight is not None:guard, sinceNoneis already handled).Checklist
-
Reproduced the error: Yes — I wrote a temporary script that patched
_coalesced_run_refresh_cmdto yield (suspend) before registering the in-flight future, then cancelled the caller during that window. It confirmed the generation was bumped to 1 with no real refresh (BUG REPRODUCED: generation bumped to 1 with NO real refresh!). -
Confirmed the fix resolves the error: Yes — after the fix, the same script showed
generation: 0/OK: no phantom bump.and theCancelledErrorpropagated correctly. -
Considered edge cases: Yes — I traced all 7 control-flow paths through the cancel-recovery loop. The fix only alters the
inflight is Nonepath (immediate re-raise, no bump). Normal-success, cancel+inflight-not-done (re-await loop), cancel+inflight-done-with-exception (no bump, raise), cancel+inflight-done-success (bump, then raise cancel), and non-cancel exceptions all behave exactly as before — real successful refreshes still bump the generation. -
Ran existing tests: Yes — 331 refresh/auth/cancellation/state-machine tests pass, plus a broader sweep of 5216 unit+integration tests pass. The only failures (
test_playwright_initializes_on_non_windowsand a CLI session test) are pre-existing and caused by the missingplaywrightmodule; I confirmed they fail identically on the unmodified code viagit stash.
I removed the temporary reproduction script before submitting.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →