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
I'll start by exploring the repository structure and understanding the code that needs to be fixed.
Assistant
I'll start by exploring the repository structure and understanding the code that needs to be fixed.
Assistant
Let me look at the relevant file mentioned in the issue.
Assistant
Let me look at the full
_fetch_tokens_with_refreshfunction in detail, particularly the cancel-recovery loop.Assistant
Now I can see the cancel-recovery loop clearly. Let me look at the exact lines and the test files to understand the test patterns.
Assistant
I'll combine these into a single command.
Assistant
Let me look at the relevant tests, especially the cancellation propagation and race tests.
Assistant
Now let me look at the unit test that covers the refresh race / state machine, to understand the test patterns for the coalescing logic.
Assistant
Let me look at the unit test for the concurrency refresh race which likely covers the coalescing logic.
Assistant
Let me look at the integration tests for the refresh cmd race and auto refresh, which likely test the coalescing logic more directly.
Assistant
Now I have a good understanding of the issue. Let me look at the facade module to understand how monkeypatching flows through, and check the exact code structure around the cancel-recovery loop.
Assistant
Let me run these as a single command.
Assistant
Now let me check the exact line numbers of the cancel-recovery loop and confirm where
_fetch_tokens_with_refreshlives.Assistant
Let me check whether the facade
auth.pyhas its own copy of_fetch_tokens_with_refreshor re-exports from_auth/refresh.py.Assistant
Let me examine the facade's
__setattr__to understand how monkeypatching flows through to the refresh module's bare names.Assistant
Let me first run the existing relevant tests to establish a baseline.
Assistant
The venv has notebooklm installed. Let me activate it and run the tests.
Assistant
Now let me write a reproducer script to confirm the bug. I'll simulate the cancel-before-registration window by injecting a yield before
_coalesced_run_refresh_cmdregisters its future.Assistant
I've reproduced the bug — the generation is bumped to 1 even though no subprocess ran. Now let me apply the fix. Let me view the exact code to edit.
Assistant
I've confirmed the bug. Now let me apply the fix using the
observed_inflightapproach (the primary suggestion in the issue). Let me view the exact line numbers first.Assistant
Let me open the file and make the edits.
Assistant
Now let me make the edits. First, add the
observed_inflightflag initialization:Assistant
Now let me make the targeted edits. First, add the
observed_inflightflag initialization:Assistant
Now add
observed_inflight = Trueon the success path:Assistant
Now add the
observed_inflighttracking in the cancel handler after the registry lookup:Assistant
Now guard the generation bump with
if observed_inflight::Assistant
The edits look good. Let me verify the syntax compiles and run the reproducer test.
Assistant
The reproducer now passes. Let me run the full set of existing refresh-related tests to ensure nothing broke.
Assistant
All pass. Let me also run the VCR-based auth refresh tests and broader auth suite to be thorough.
Assistant
That's a pre-existing collection issue with the VCR test's conftest path resolution. Let me run the VCR test from the integration directory context and the unit auth tests separately.
Assistant
Let me run these sequentially as a single command.
Assistant
All tests pass. Now let me think about edge cases and verify the logic handles all scenarios correctly. Let me trace through each scenario in the cancel-recovery loop:
-
Normal success path:
await _coalesced_run_refresh_cmdcompletes →observed_inflight = True→ break →subprocess_exc is None→ bump happens (correct, subprocess ran). -
Cancel-before-await race (the bug):
await _coalesced_run_refresh_cmdraisesCancelledErrorbefore registering future →inflight = registry.get(...)returnsNone→observed_inflight = False or (None is not None)=False→inflight is Nonebranch →subprocess_excstaysNone→ break →subprocess_exc is None→observed_inflightisFalse→ no bump (correct!). -
Cancel during in-flight subprocess (success): subprocess registered future, then caller cancelled → is the (now-done or pending) future → → if done and succeeded, stays → break → bump happens (correct).
-
Assistant
The legitimate bump path still works. Now let me clean up my temporary test files since I'm not supposed to add new tests to the repository.
Assistant
Only the source file is modified. Let me view the final diff to review my changes.
Assistant
The diff looks clean and correct. Let me verify the logic once more by tracing through all the scenarios, then run a broader test sweep to ensure nothing else broke.
Assistant
There are some failures. Let me check whether these are pre-existing (unrelated to my change) by examining the failures.
Assistant
These failures are all in Playwright/browser login tests (
test_session.py,test_windows_compatibility.py), unrelated to the auth refresh logic I modified. Let me confirm they're pre-existing by stashing my change and running one.Assistant
Confirmed — these failures are pre-existing and caused by
playwrightnot being installed in the environment (ModuleNotFoundError: No module named 'playwright'), completely unrelated to my change. Let me run the auth/refresh-related tests one final time to confirm everything passes with my change.Assistant
The VCR test has a conftest path resolution issue when run alongside unit tests (the unit conftest shadows). Let me run it separately from the integration directory and run the rest without it.
Assistant
All auth/refresh tests pass. Let me do a final review of the complete modified section to ensure correctness.
Assistant
The fix is complete and correct. Let me do a final cleanup check to ensure no temporary files remain and only the source file is modified.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.