Skip to content

[dynamo] Concurrency and contract tests for the ExtraState lock - #196120

Closed
bobrenjc93 wants to merge 49 commits into
gh/bobrenjc93/1132/basefrom
gh/bobrenjc93/1132/head
Closed

bobrenjc93 wants to merge 49 commits into
gh/bobrenjc93/1132/basefrom
gh/bobrenjc93/1132/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

test_recompile_ux.py pins the token/compare-and-set contract including the
zero-token case, region strategy inheritance (SKIP inherited, RUN_ONLY not),
region-exact cache clearing and precompile-entry queries, the
force-callback-on-miss marker, the thread-local region id, a faulthandler-free
concurrency smoke test of four callers against the lock (joined with a timeout
so a wedge fails rather than hangs), and the binding-only concurrency cases: a
reset run from Python inside a lookup, an invalidation parked against a held
lock and drained, a region clear parked from inside a lookup, concurrent install
and reset against lookups, the one-way cache-key gate, and owner-scoped
precompile-entry removal. The cross-thread reset-racing-a-lookup case is written
(test_reset_code_racing_lookup_does_not_destroy_the_cache_state) but skipped
pending #196394, since it SIGSEGVs at this commit, so the summary
above does not count it among the pinned properties.

Test Plan:

python test/dynamo/test_recompile_ux.py

Authored with an AI assistant.

FAQ

Q: The concurrency docstrings mention lookup() and the cache lock around guard
evaluation, and the exec-strategy commit added cache_python_depth. Which is the
real mechanism -- a held lock, or the depth counter?

A: lookup() does NOT hold cache_mutex across guard evaluation. CacheLock
snapshots the candidate entries under the mutex, raises cache_python_depth, then
RELEASES the mutex; guards (which run Python) evaluate lock-free, and the mutex
is re-taken only for the LRU splice at the end. cache_python_depth is what makes
that release safe: while it is non-zero every node destroy/free path parks, so
the raw entry pointers snapshotted under the lock cannot be freed out from under
the lock-free walk. No lookup path holds cache_mutex across a Python comparison:
try_lookup_without_guard_eval() mirrors lookup() -- it snapshots candidates under
the mutex, raises the depth, releases the lock, and runs backend_match lock-free,
re-locking only for the LRU splice. cache_python_depth is the sole node-lifetime
mechanism on both paths, and it is what these tests' eq hooks fire under. This
matches extra_state.cpp (the CacheLock scope opens and closes around the
snapshot, guard eval runs outside it, depth parks destroys) and the test
docstrings in this commit.

Q: Does test_reset_code_from_python_run_by_lookup_is_safe end in a bare
assertTrue(False) that can never pass?

A: No -- there is no assertTrue(False) in this suite. The reset-from-lookup test
drives a ResettingBackend whose eq calls reset_code on the same thread mid
guard-comparison and then asserts the surviving cache state, and the assertTrue
calls in the file wait on real threading.Events (e.g. assertTrue(in_eq.wait(...))).

Q: On the failure path the per-thread join(timeout=120) calls could burn
600-1200s against the per-file budget -- how is that bounded?

A: The joins share a single deadline (time.monotonic() + 120 computed once, each
join taking the time remaining), so a wedge caps the whole test at ~120s
regardless of thread count rather than N*120s. On the green path the threads
finish in well under a second and the joins return immediately. A wedge still
fails loudly and attributably: after the joins each worker's queued exception is
re-raised first (its traceback is the finding), and only if none was recorded
does a liveness assertion report a bare wedge, so a real error is never masked.
The earlier faulthandler dump was dropped -- the join-plus-assertion already
catches a wedge, while dump_traceback_later fired on merely slow green runs and
its process-global timer slot could clobber one the harness installed.

Q: The tests do not pin every precompile-marker transition. Why not?

A: They pin the landable subset at this commit; the remaining marker
transitions are exercised indirectly through the strategy-inheritance and
region-exec tests. Asserting on internal marker values that are not part of a
stable contract would make the suite brittle.

Q: Neither marker test runs under fullgraph=True, so the
fullgraph_compiled_frame_count >= 0 clause #195911 added to the force-callback
condition in eval_frame_cpp.cpp is never exercised -- deleting it would fail
nothing here. Add a fullgraph case or explain why it is unreachable.

A: Unreachable from a test, and the reviewer reached the same conclusion trying
to build one. The clause makes a fullgraph compile stop forcing the sub-frame
callback and fall back to the run-only demotion, because eval_custom() would
otherwise turn the sub-frame callback fully off. But a non-inlined sub-frame
under fullgraph=True graph-breaks and raises before that demotion can matter, so
there is no execution in which the third clause changes an observable result --
it is a defensive guard on a path fullgraph forecloses upstream, not a branch
with a distinct outcome to assert. Pinning it would require a fullgraph sub-frame
that both survives to the demotion and is observably steered by it, which the
graph-break-and-raise makes impossible. Verified by inspection against #195911's
condition rather than a test.

Q: region_frame_state_map clearing on reset is not directly asserted.

A: It has no public accessor, so a direct assertion would reach into a private
map and be brittle against the storage layout. It is covered indirectly:
test_isolate_recompiles_reset_clears_region_strategy and the reset tests observe
the post-clear behavior (a region recompiling from scratch).

Q: The thread-spawning harness (set the switch interval, start threads, compute a
shared deadline, join under it, drain the error queue, _reraise_worker_error,
assert none alive) is copied three times and the copies have drifted -- only the
third grants a second wave of threads a fresh window. Fold it into one
_run_threads helper.

A: The genuinely identical piece is already extracted -- _reraise_worker_error is
a module-level helper all three sites call. What remains differs on purpose in the
load-bearing middle: the deadlock test carries a threading.Event stop flag its
hammer loop breaks on, the install/reset test counts per-caller iterations into a
queue and asserts a floor, and the invalidation test runs two waves where the
second is joined under a fresh window precisely because the first wave must reach
the park before the second starts. The 'drift' the comment points at (the
second-wave window) is that intentional difference, not an accident. A single
_run_threads(threads, timeout) would have to grow a flag for each case or hide it
behind the call, making three different bodies read as identical when they are
not -- more dangerous than the visible repetition. The truly shared piece is
already shared.

Q: Does anything in the suite actually fail if lookup() regresses to holding
cache_mutex across guard/backend evaluation -- the property #195355 exists
for?

A: Yes. test_invalidation_racing_an_in_flight_lookup_parks_and_drains uses the
blocking _get_cache_entries_for_region read as the probe: that read takes
cache_mutex, so it returns (rather than deadlocking the test thread) only
because lookup() released the mutex before running the racing __eq__. If
lookup() held the mutex across guard evaluation the probe would block until the
join deadline and the test would fail as a wedge. The test comment now records
that this blocking read IS the regression probe, so its intent is explicit rather
than incidental.

Q: The generation compare-and-set test is single-threaded; the real property (N
threads read the same generation and exactly one compare_and_set wins) is
unpinned. Why not spawn threads?

A: compare_and_set_code_exec_strategy is a pure monotonic-idempotent CAS, and
that contract is fully determined by the single-threaded state machine the test
walks: a never-touched object reads generation 0 and a set@0 fails; a
set_with_token bumps the generation; a set with the current token wins and
bumps again; the now-stale token loses; a reset invalidates every outstanding
token and must NOT return the generation to 0 (the zero-token resurrection case
is pinned explicitly). Spawning threads would exercise the OS scheduler, not a
new contract state, and add flakiness without new coverage. Genuinely concurrent
install/reset behavior is covered by the threaded stress tests elsewhere in this
suite.

Q: Only the cur_action half of the marker contract is exercised here; the
recursive_action demotion branch (eval_frame_cpp.cpp) is never hit because
f(x) = x.sin() has no callee.

A: Correct that this single-frame test pins only cur_action. The
recursive_action path is covered by the strategy-inheritance tests in the same
file -- test_isolate_recompiles_inherits_default_skip and
test_region_exec_strategy_inherits_skip_but_not_run_only install a strategy
whose recursive_action a child frame inherits and assert the callee is skipped
-- so the demotion branch is exercised, just not in this one-frame test. Adding a
callee here would duplicate that coverage rather than reach a new branch.

Q: The install/reset stress test uses a bare range(300) installer loop and an
assertGreater(total_iters, 0) floor -- the same smoke-test anti-pattern the skipped
resetter above already diagnosed. Its finally also sets stop and returns rather
than granting the rejoin window its two siblings use, and the installers honor no
stop flag, so a tripped join leaves threads hammering a live code object into the
next test.

A: Fixed. The installers now run on a wall-clock budget (deadline =
time.monotonic() + 1.5) and break on the shared stop flag instead of a fixed
range(300), so the two phases actually overlap for the whole window rather than
finishing in under a millisecond. The floor is raised to assertGreater(total_iters,
20) -- a value the degraded single-pass shape cannot reach -- matching the skipped
test. And the finally now grants the same rejoin window as its siblings
(rejoin_deadline = time.monotonic() + 30, joining callers and installers) so no
worker survives into the next test.

Q: Roughly 14 of the 16 new tests exercise the ExtraState lock and the
region/owner APIs, not isolate_recompiles, so IsolateRecompilesTests becomes a
grab bag whose name no longer describes most of its contents. Why not move them
to a sibling ExtraStateLockTests class for a -k ExtraStateLock selector?

A: The mismatch is real and the class docstring already concedes it ("the
concurrency, lifetime, and exec-strategy tests below exercise the ExtraState
lock and the region/owner APIs, which are not specific to isolate_recompiles").
Splitting them into a sibling class is a pure move -- no test-body change -- and
would buy a -k ExtraStateLock selector, but it is deferred to keep this commit's
churn to the new tests themselves rather than reshuffling the existing class;
the docstring documents the intent in the meantime.

Q: The @unittest.skip reason on the reset-race test frames the ~12% SIGSEGV as
a test-harness lifetime wart, but the snapshot holder that matters is
ConvertFrameAssert.__call__ (convert_frame.py), so the crash is reachable from
user code (reset() / remove_from_cache() racing a compile). Does it predate
#195355?

A: Yes on both counts, and the skip reason now says so. Pre-#195355 the same race
crashed 30/30 (at base, remove_from_cache took no compile_lock and
_get_cache_entries_for_region returned the same non-owning wrappers under no
mutex); #195355's compile_lock on the reset paths narrows it to the parked-drain
residual (a reset parked on a third thread's cache_python_depth is drained later
by a lookup holding no compile_lock). The durable fix is owning references from
the C++ layer, tracked in #196394, which now records the
user-reachable path and the 30/30-vs-12% measurement.

Q: "A wedge fails this test: the joins are bounded by a shared deadline" is not
true for the regression the hammer guards: a CacheLock regressed to a plain
lock_guard blocks while HOLDING the GIL, so the main thread never reacquires the
GIL to return from join(timeout) and the outcome is a hang, not an attributable
failure.

A: Correct; both docstrings now say the joins catch a GIL-released wedge and that a
GIL-holding wedge surfaces as a process hang and job timeout instead.

Q: for _ in range(3): _clear_cache_entries_for_region(code, region) is
unexplained and unasserted; nothing distinguishes three parked clears from one.

A: Now explained and pinned: parks do not coalesce (three CACHE_REGION evictions
queue), so the drain must apply them idempotently, and the test asserts the total
cache entry count after the recompile is exactly 1.

Q: macos-py3-arm64 / test (default, 1, 3) is red on this PR.

A: Unrelated: the failing test is
test_cpp_extensions_jit.py::test_aoti_torch_call_dispatcher, a C++-extension JIT
compile hang on the macOS runner that also failed on main the same day; this PR
touches only test_recompile_ux.py, which does not appear in that shard.

Q: The invalidation test is the file's only test of invalidate_locked, yet it
never asserts the move_to_back relink (every assertion is order-independent for
a two-element list) and only ever invalidates entries[0] in region -1, so a walk
narrowed to one region or an off-by-one on a non-front entry would pass.

A: Both pinned now: after the invalidation the victim is asserted at the tail and
the survivor at the front, and a second scenario invalidates the SECOND entry of
an isolated region, asserting the marking order, the survivor's identity and that
the default region is untouched.

Q: The backend __eq__ hook is the suite's only deterministic way to drive an
eviction from inside a live lookup, and it is used for one of the five
PendingEviction kinds; OWNER, PRECOMPILE_REGION and PRECOMPILE_ALL are reached
only probabilistically.

A: Accurate for this commit. The next PR up (#195911) adds deterministic
hook-driven tests for PRECOMPILE_ALL
(test_precompile_reset_from_inside_a_lookup_is_parked) and OWNER
(test_reinstall_survives_an_eviction_parked_by_uninstall, via
package.uninstall()), leaving only the PRECOMPILE_REGION park site without a
deterministic caller; test_precompile_region_reset_from_inside_a_lookup_is_parked
here closes it. It is a separate test rather than a second call in the region-clear
hook because a precompile entry loaded into the region the lookup runs in can be
served by that lookup and break the len(compiles) == 2 recompile assertion.

Q: Neither half of the stress test's claim ("every lookup serves the right graph
or misses cleanly") is pinned: x.sin() + x.cos() makes every entry numerically
interchangeable (a forced shape-4-guard/shape-3-graph mis-dispatch goes
unnoticed), and the cache entries are never evicted so no caller ever misses.

A: Both fixed. The function bodies of this test and of the skipped reset-race
sibling are now x.sin() + x.numel(), so dynamic=False bakes the shape into
the graph and a mis-dispatched entry is a wrong answer (verified: the same forced
mis-dispatch is caught; still two static-shape entries). The docstring now states
what is actually pinned: a precompile hit must be the shape-matching graph and a
precompile guard miss falls through to the matching cache entry, with no
recompile.

Q: The two trailing _reset_precompile_entries_for_owner calls after the joins
are dead code: every installer ends its loop with its own owner reset, and the
entry reader drains whatever is still parked.

A: Confirmed (measured zero live entries before those resets across repeated
runs) and removed; the comment now says why the reader alone suffices.

Q: test_reset_code_from_python_run_by_lookup_is_safe records resets.append(True)
and asserts len(resets) > 0, which does not show the reset ran inside the lookup.

A: The hook now records _get_total_cache_entry_count(code) at the moment it
fires and the test asserts resets == [1]: exactly one firing, with the entry
still present when reset_code ran.

Q: The generation test never shows a region-created zero token being ACCEPTED.

A: Added: a third code object gets a region write only, its token is 0, and
compare_and_set_code_exec_strategy(code3, 0, skip) succeeds and installs SKIP.

Q: The comment "a global SKIP applies everywhere, except where a region's own
strategy wins" and the inherits_default_skip docstring describe a recorded
region strategy (even the DEFAULT/DEFAULT a compile records) shadowing a later
skip_code(). That is a correctness gap, not a design point.

A: Agreed that it is a gap in the pre-existing C++ (the per-region strategy split
is #178351); it is now filed as #196520 and both comments say
"regions with no recorded strategy of their own" and cite the issue. This test
suite documents today's precedence rather than changing it.

Q: In test_region_clear_from_inside_a_lookup_is_parked the post-drain strategy
read is confounded: the recompile's own apply_to_code write supplies DEFAULT,
so the assertion passes even if the drain never erased the region strategy.

A: Fixed by reading the strategy inside the backend during that recompile, i.e.
after the drain and before the compile's apply_to_code write lands:
compile_strategies == [FrameAction.DEFAULT] fails if the drain's
region_strategy_map.erase is removed (the seeded SKIP would still be there).

Q: The invalidation test's "names no victim" step asserts only that nothing was
marked, not that both entries are still there.

A: len(_get_cache_entries_for_region(code, -1)) == 2 added at that point.

Q: Comment nits: "drained by the reader" (which reader?), the missing "Basic
isolation" banner, the Backend class comment that says it has no __init__
while defining one, and the hoisted import gc.

A: All four fixed: the comment names the depth-zero fallback lookup(); the
banner is back above test_isolate_recompiles_basic; the class comment now says
nothing enables the gate before the OFF half is measured; gc is imported where
it is used. run() in the recursive-marker test also resets Dynamo first so its
two calls start from the same state.

Q: The stress test's cost is high for what it pins.

A: Noted; it runs a bounded installer loop against a reader pool and is the only
test that drives the parked-eviction drain from a real racing installer rather
than a hook. Kept.

Q: apply_pending_evictions erases the region strategy on every duplicate
CACHE_REGION record, so a strategy written between the park and the drain is
wiped by a duplicate.

A: The three-park loop in the region-clear test is what made this visible; the
per-record erase is faithful to what each _clear_cache_entries_for_region call
asked for (a clear resets the region's strategy too), and the window it describes
(a region strategy write racing a parked clear of the same region) has no
consumer today. Not changed here; noted on #196394.

Q: The invalidation test could also seed a second bucket so the "region-exact"
claim covers a non-empty default bucket.

A: Left as is: test_clear_cache_entries_for_region_is_region_exact already pins
the two-bucket case for the clear path, and the invalidation path iterates the
whole map by guard-manager identity, which the single-bucket fixture exercises
fully.

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196120

Note: Links to docs will display an error until the docs builds have been completed.

This comment was automatically generated by Dr. CI and updates every 15 minutes.

This was referenced Sep 5, 2026
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

[ghstack-poisoned]
Comment thread test/dynamo/test_recompile_ux.py Resolved
Comment thread test/dynamo/test_recompile_ux.py Resolved
Comment thread test/dynamo/test_recompile_ux.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

[ghstack-poisoned]
Comment thread test/dynamo/test_recompile_ux.py Resolved
Comment thread test/dynamo/test_recompile_ux.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

[ghstack-poisoned]
Comment thread test/dynamo/test_recompile_ux.py Resolved
Comment thread test/dynamo/test_recompile_ux.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 39m 43s —— View job


Claude PR Review

The new region-clear, invalidation-identity, precompile-park and recursive-marker tests all check out against extra_state.cpp/eval_frame_cpp.cpp — but the region-clear test's post-drain strategy assertion is satisfied by the recompile's own apply_to_code write, so the deferred-reset drain it claims to pin is still unpinned.

Full review

PR Review: #196120

Summary

Adds 1294 lines of contract and concurrency tests to test/dynamo/test_recompile_ux.py for the ExtraState cache lock, the exec-strategy token API, region/owner-scoped cache and precompile operations, and the eviction-parking mechanism.

I re-derived each newly-added or newly-strengthened assertion against the current base and found no false claim about the C++:

  • test_region_clear_from_inside_a_lookup_is_parked — three _clear_cache_entries_for_region calls really do queue three separate CACHE_REGION records (park_eviction is a bare push_back, extra_state.cpp:197-201, no dedup), and the drain is idempotent because the whole splice sits behind find() with cache_entry_map.erase(it) at :250, so applies 2 and 3 hit end() and skip the decrement at :247. _get_total_cache_entry_count(code) == 1 is therefore right (1 → 0 on the first apply, then create_cache_entry's total++), and the CHECK(total >= size) at :246 cannot fire. The mid-lookup strategy_seen == [FrameAction.SKIP] is load-bearing: the park path sets parked = true and skips the erase (:1150-1159), and neither in-hook reader can drain because apply_pending_evictions no-ops at depth > 0 (:207-211). len(compiles) == 2 holds because try_lookup_without_guard_eval releases its depth on return (guarded entry → false, :942-947), so the fallback lookup() drains at :744-746 before candidate scanning at :764-772. region_frame_state_map erasure is indeed unconditional (:1160-1177), matching the comment.
  • test_precompile_region_reset_from_inside_a_lookup_is_parked — parks as PRECOMPILE_REGION (:1250-1256); the region-7 entry is invisible to a region -1 lookup (first_precompile_entry stays null, :890-895), which is what lets control reach backend_match and fire the hook. seen == [True], then False after the drain. The assertFalse(hook, ...) guard is the right hook-fired check.
  • test_invalidate_targets_the_entry_by_guard_manager_identity — invalidate_locked iterates the whole cache_entry_map (:141-152) and matches live.guard_manager.ptr() == live_guard_manager.ptr() (:144), raw pointer identity, no __eq__. move_to_back splices within the victim's own region list (:125-130), and _get_cache_entries_for_region (:1052-1083) appends in std::list order with no sorting (the sort at :1036-1042 belongs to _debug_get_cache_entry_list and is not on this path), so entries[-1]/entries[0] are exact. CacheEntry::invalidate swaps the victim's guard_manager for the deleted wrapper (cache_entry.cpp:45) and never touches survivors, so assertIs(survived[0].guard_manager, w1) is sound. Capturing extra_state = w0.extra_state at :1106 before the invalidation nulls it is load-bearing and correctly ordered.
  • test_force_callback_on_cache_miss_marker_reaches_a_recursive_frame — this genuinely reaches the demotion-skip at eval_frame_cpp.cpp:562-567, which the cur_action sibling cannot: eval_custom() installs recursive_callback (:471) before dynamo_eval_custom_code (:490), so the resume frame is a child of f's shadow frame, and strategy.recursive_action != DEFAULT keeps the :711-715 override from firing. The counts are implied: IsolateRecompilesTests carries no recompile_limit=1 patch, and ContinueExecutionCache.lookup reuses the resume code object across the recompile (resume_execution.py:311-320) — though the counts hold either way, since a fresh resume code object short-circuits to eval_default at eval_frame_cpp.cpp:511-515. run(force=True) == 4 is the discriminating assertion; delete :562-564's guard and it becomes 3.
  • test_cache_key_lookup_is_off_...'s new on_same_key 1 — correct: get_backend returns the key object itself when present and truthy (cache_entry.cpp:131-133), so two backends sharing one key are one identity under backend_match.
  • test_clear_cache_entries_for_region_is_region_exact — total_before - 2 is sensitive to both the decrement (:1143) and a partial clear; seeding region B a distinct (DEFAULT, SKIP) makes the neighbour assertion non-vacuous, and cur_action == DEFAULT there is what keeps the frame_count == 3 check live.

Caveat: torch is not built in this checkout, so this is a static review — I could not run the suite or confirm pass/fail for the concurrency tests.

Testing

  • test/dynamo/test_recompile_ux.py:1258-1263 — the post-drain strategy assertion is confounded by the recompile that precedes it, so the deferred-reset half this round added is still unpinned. The comment says "Draining the parked eviction also applied the deferred strategy reset", but the fresh compile between the drain and the read writes the strategy itself: wrap_guarded_code returns frame_exec_strategy=FrameExecStrategy(DEFAULT, DEFAULT) with apply_to_code=True (torch/_dynamo/types.py:84, :91), and eval_frame_cpp.cpp:718-728 calls extra_state_set_region_exec_strategy, which for id >= 0 does region_strategy_map[region] = strategy (extra_state.cpp:571). So recursive_action == DEFAULT at :1261 is produced by the compile regardless of whether apply_pending_evictions' region_strategy_map.erase (extra_state.cpp:257-260) ran at all — delete those four lines of C++ and this assertion still passes. The mid-lookup strategy_seen == [SKIP] at :1251 remains load-bearing and pins the deferral; it is the drain that has no probe. Reading the strategy after the drain but before any recompile would pin it — e.g. drive the drain with a depth-zero reader (_get_cache_entries_for_region) and assert DEFAULT there, before the ctx(f)(x) call's compile. Fix this →

  • test/dynamo/test_recompile_ux.py:1116-1120 — the "names no victim" assertion passes if both entries were destroyed. invalidated() filters for trace_annotation == "Invalidated", so an invalidate that wrongly wiped the region returns [] and the assertion is satisfied. This is the scenario where "nothing was touched" is the whole claim, so it needs a count: self.assertEqual(len(_get_cache_entries_for_region(code, -1)), 2) alongside it. Fix this →

  • :1149-1153 — the second invalidation scenario adds a non-front victim but not a relink. Entries are front-inserted (extra_state.cpp:989-995), so entries[0] is the shape-4 (newest) entry and v1 is already the tail. move_to_back on v1 is therefore a no-op, and [False, True] holds whether or not the splice runs. The scenario does pin what its comment claims (the identity walk reaches a non-front entry in a positive-id bucket), but the ordering assertion carries no relink coverage there — that lives entirely in the first scenario at :1132-1133. Also note the first scenario's cache_entry_map holds exactly one bucket in both halves, so nothing here pins "picks the right bucket among several"; a two-region setup with entries in both would.

  • :1316 — "drained by the reader" names the wrong drainer. The in-hook _has_precompile_entries takes CacheLock and calls apply_pending_evictions (extra_state.cpp:1422-1424), but depth is still 1 from the in-flight try_lookup_without_guard_eval, so it cannot drain — which is exactly why seen == [True]. The actual drain is the fallback lookup() at extra_state.cpp:744-746 once depth fell to 0, before the post-call _has_precompile_entries at :1318 runs. Reword to name the fallback lookup.

Performance

  • test/dynamo/test_recompile_ux.py:536-608 went from a warm-only lookup hammer to ~200 real Dynamo compiles, all serialized on compile_lock under setswitchinterval(1e-6). Four threads × 50 fresh shapes, each miss walking a candidate list that grows toward ~203 entries, with recompile_limit=10000 raised specifically so none of them short-circuits to RUN_ONLY. This is the right way to reach create_cache_entry (the only locked region that runs Python), so the design is correct — but the cost is now dominated by compilation, which is nearly pure Python and therefore hit hardest by the 1e-6 convoy. test_recompile_ux.py is in neither CI_SERIAL_LIST nor RUN_PARALLEL_BLOCKLIST, so this runs alongside two other test files on the same runner, and under PYTORCH_TEST_RERUN_DISABLED_TESTS the flake-finder duplicates every test in the file 50× in-process. Worth a measured wall-clock number before landing, since tools/testing/test_selections.py re-shards this file by observed duration. (cnt.frame_count += 1 is safe despite the switch interval — the backend runs under compile_lock, convert_frame.py:2709.)

Code Quality

  • :534 — the # ===== Basic isolation: independent caches per compile call ===== banner was deleted rather than moved, so five unrelated tests sit under a concurrency heading. grep "Basic isolation" finds nothing in the file; the new # ===== ExtraState cache lock: concurrency and lifetime ===== was inserted at the old banner's position. The concurrency block correctly heads :536-1319, but test_isolate_recompiles_basic, ..._same_function_different_regions, ..._factory_pattern, ..._same_backend_different_regions and ..._string_backends (:1326-1456) then inherit it until the next banner at :1458. Raised in the two prior rounds. Fix this →

  • :2899-2941 — the recursive-marker test's finally resets f.__code__ but not the resume code object, whose ExtraState is shared across the two run() calls. ContinueExecutionCache is module-level and its key excludes lineno/init_offset (resume_execution.py:311-320), so run(force=True) starts with the entry run(force=False) left behind. It works — the backend differs, so backend_match misses and the frame_count == 2 assertion still holds — but the coupling is implicit and the leak is swept only by the harness reset(). Resetting the resume code object in the finally (or torch._dynamo.reset() between the two runs) would make the two cases independent.

  • :1231-1233 — the three-park comment is now accurate, but the asymmetry it sits next to is worth knowing about. In apply_pending_evictions the region_strategy_map.erase at extra_state.cpp:257-260 is outside the find() guard, so it runs on every duplicate CACHE_REGION record while the splice runs only once. Harmless in this test (all three applies are in one drain loop with no window between them), but it means a region strategy legitimately written between the park and the drain is wiped by a duplicate. Not this PR's job to fix; noting it because the 3× loop is the thing that made it visible.

  • :2489-2491 — "without an __init__ that would flip the gate" reads oddly next to a class that has an __init__. The point is that nothing in the constructor calls _enable_precompile_cache_keys, which is true and load-bearing for the OFF half. "whose constructor does not enable the gate" says it without the double take.

  • :2 — hoisting import gc to module scope remains unrelated churn. One use site; no test added here touches it. Noted across prior rounds, mentioning once.

Recommendation

Request Changes

Narrowly, and not about correctness of the contracts — I found no false assertion about the C++ in 1294 lines, and the four items called out for this round (the exact-2 region-clear count, the strategy-erase and mixed-field inheritance cases, the parked-vs-immediate invalidation probe, the shared deadline) all verify. What blocks is :1258-1263: the comment claims that assertion pins the deferred strategy reset applying on drain, and it does not — the recompile's own apply_to_code write supplies DEFAULT regardless, so deleting extra_state.cpp:257-260 would fail nothing here. That is the same "the assertion added to make this non-vacuous is itself vacuous" shape that blocked an earlier round, and the mid-lookup half being solid is what makes the missing half easy to overlook. The :1120 count is a one-liner in the same spirit; the banner and the three comment corrections are small.

| Branch: `gh/bobrenjc93/1132/head`

bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
ExtraState's cache had no lock, and lookup() walks it while evaluating
guards, which run Python, so the GIL can drop mid-iteration and another
thread can clear the list being walked. Once precompile artifacts are
installed and unloaded on live code objects at runtime this is no longer
survivable. ExtraState now has a recursive cache_mutex taken through
CacheLock, which try-locks first and releases the GIL only when it must
wait, so a waiter holding the GIL cannot wedge the owner that needs it. lookup() and try_lookup_without_guard_eval() hand back a
new reference to the cached code and copy trace_annotation out under the
lock, and the frame evaluator holds that reference before anything that can
drop the GIL.

Evictions that arrive under a live lookup park instead of splicing the list
being walked: invalidate() (reached from weakref.finalize) never blocks and
re-locates its entry by guard-manager identity, so its binding no longer
takes the raw CacheEntry pointer, and reset_code and the region/precompile
resets park on the state when cache_python_depth is non-zero, applied by the
next depth-zero holder. reset_code empties the state in place
(clear_in_place) rather than destroying a mutex another thread may be parked
on. The default exec strategy moves into a lock-free std::atomic with a
generation token behind get/set_with_token/compare_and_set bindings, the
current isolate_recompiles_id becomes thread-local, precompile entries carry
a region and an owner token, and get_backend honours a backend's
_torchdynamo_cache_key behind a one-way gate. The Python side of the
region/owner bindings follows in the next commit; guards.py only adopts the
new invalidate() signature.

Every path that hands cache state out does so under the lock: create_cache_entry
fills the new entry's code (owned) and trace annotation for its caller before
releasing, so the frame evaluator never dereferences the entry once a
concurrent clear could destroy it; _load_precompile_entry builds its
PrecompileEntry (which runs Python) before taking the lock and drains parked
evictions before appending, so a parked CLEAR_ALL cannot eat the install; and
_debug_get_precompile_entries raises the Python depth around its casts, so a
package finalizer reached from GC parks its eviction instead of splicing the
list being walked. remove_from_cache takes compile_lock like
torch._dynamo.reset(), which is the contract reset_extra_state's header states.

Test Plan:

This is the C++ locking change; it carries no tests of its own. Its
concurrency/contract coverage is added one commit up in #196120 (see the FAQ),
which adds ~787 lines to test/dynamo/test_recompile_ux.py. Verified at the stack
head by:

```
python test/dynamo/test_recompile_ux.py
python test/dynamo/test_package.py
python test/test_precompile.py
```

Authored with an AI assistant.

FAQ

Q: update_diff_guard_root_manager is a Python-reachable mutator that reassigns
diff_guard_root_mgr as a raw pointer, and the lock-free lookup() window
dereferences that field. Isn't that an unlocked write racing a lock-free read?

A: Reachable only under skip_guard_eval_unsafe with two threads recompiling one
code object concurrently, and it predates this PR -- base lookup() held no lock
at all. The lock added here reasons about node lifetime during guard evaluation,
not about this field's stability under concurrent recompile; closing that window
means taking cache_mutex in the binding (it runs at compile time, so the cost is
irrelevant) and is tracked as a follow-up. The comment scope is narrowed to say
so rather than implying the field mutation is already covered.

Q: Six sites still hold cache_mutex across arbitrary Python (create_cache_entry's
py::cast, the debug enumerators, drain_pending_invalidations), so the
lock-ordering invariant the header claims holds only for guard evaluation. Isn't
the header over-claiming?

A: The mitigation this commit lands does cover the hot path -- guard evaluation
under lookup() -- with one named residual on the frame-eval path: the
parked-invalidation drain lookup() runs at cache_python_depth 0, whose decrefs of
the old guard_manager can fire a user __del__ under the lock (extra_state.h says
exactly this); every other Python-under-cache_mutex site runs only at
compile/debug time. Rather than the full snapshot-release/park treatment of all six
(which needs care around user __del__ and backend __eq__), the header claim is
narrowed to state the mitigation covers guard evaluation and to name the
knowingly-exempt sites.

Q: This locking commit ships no tests of its own. Where is the coverage?

A: Added in the sibling commit, not missing. This ghstack splits the C++
locking change from its concurrency/contract suite so each reviews on its own;
the 14 tests (~787 lines) are added in "[dynamo] Concurrency and contract tests
for the ExtraState lock" (#196120), later on this same stack, in
test/dynamo/test_recompile_ux.py. This commit's own diff touches no test files;
the stack head has the full coverage. The deterministic (single-threaded) pin a reviewer would want for the park/drain path is there too: test_region_clear_from_inside_a_lookup_is_parked drives a CLEAR_ALL from inside a live lookup via a backend __eq__ hook and asserts the next depth-zero lookup drains the parked clear before it scans candidates, with no TORCH_CHECK fired; and the drain-before-read contract on _get_total_cache_entry_count / _debug_get_cache_entry_list is asserted across that suite.

Q: The region/ownership bindings this commit adds (14 of them, plus
_torchdynamo_cache_key / _torchdynamo_force_callback_on_cache_miss) have no
caller anywhere. Why add dead surface?

A: The consumers are higher in this stack, in the commits the reslice split
these bindings away from. Concretely, _get_cache_entry_count_for_region is
imported and called in convert_frame.py by #195913's capture/serve accounting
(total_count -= _get_cache_entry_count_for_region(code, region_id)), and the
region/owner install bindings by the precompile install/package layer above
that. The reslice deliberately keeps the C++ bindings with the locking change
they belong to rather than splitting a binding from its lock, and the stack
merges atomically, so no released commit ships a binding with no consumer. They
read as unused only in this PR's isolated diff.

Q: get_backend treats _torchdynamo_force_callback_on_cache_miss = False as still
forcing, because it only tests presence. Isn't False surprising?

A: Presence-only is intended and matches the hasattr convention these markers
use; the attribute is set to opt in and absent to opt out, and its value is not
read. Documented as presence-only.

Q: reset_code now empties the state in place instead of nulling the extra
pointer, so the run-only empty-cache fast path is gone on every reset. Isn't that
a permanent hot-path regression?

A: The null-out is unsafe once the mutex must outlive parked waiters: freeing the
extra state (and its mutex) under a thread parked on that mutex is a
use-after-free, so reset drains and clears in place instead. The lost fast path
is narrow (an empty cache after reset) and the correctness of not destroying a
mutex another thread holds is not negotiable. Correcting the cost
characterization from an earlier draft: it is per-frame and permanent, not
per-reset. The husk stays attached, so callback.is(Py_False) && extra == nullptr
never fires again for that code object; every subsequent run-only frame pays the
region-id lookup, the strategy read, get_backend, the callback set, and a
CacheLock acquire in try_lookup_without_guard_eval. Measured on this checkout
that is ~88 ns/frame over a NULL-extra-state frame (run-only, trivial body, best
of 7 x 200k). Small, and it does not outweigh refusing to free a mutex under a
parked waiter -- but a pr_time benchmark measures compile time and will never see
it, so tracking it needs a run-only-after-reset runtime benchmark, not pr_time.

Q: Every intercepted frame with a guarded cache entry now pays two full cache
snapshots and two cache_mutex acquisitions (try_lookup_without_guard_eval then
lookup, each snapshotting every entry in both buckets) where base held no lock
and allocated nothing. Bound the snapshot to the first backend match, and skip
building it when a precompile candidate was found.

A: The doubled snapshot+acquire on the guarded-hit path is real and structural
(distinct from the ~88 ns run-only-after-reset figure above, which does not cover
this path). The bounded-prefix half of the suggestion is unsound as stated:
backend_match runs lock-free after cache_mutex releases (that release before
guard/backend evaluation is the whole point of the snapshot), so the code cannot
know which entry is the first backend match while still holding the lock -- it
must capture a complete, stable snapshot and decide hit-vs-fallback afterward.
Stopping the snapshot loop early would require running backend_match under
cache_mutex, reintroducing exactly the Python-under-the-lock the design removes.
The precompile-skip half is a valid micro-optimization (the precompile branch
returns before cache_candidates is read), but both narrowings are subsumed by the
deferred RAII snapshot refactor tracked for this locking work, which collapses
the two acquisitions into one and is where the snapshot's shape should be tuned
with a runtime benchmark -- not guessed at here, since this checkout cannot build
to measure it.

Q: The per-region frame_state split changes CompileId.frame_id numbering -- each
region now allocates its own frame id for the same code object, shifting
tlparse/TORCH_LOGS labels and graph_id_filter's frame_id matching -- and the old
comment justified the split by dynamic-shape generalization, which frame_state no
longer drives. Why is it here, untested, in a locking commit?

A: The comment was stale and is corrected in this pass: the ExtraState
frame_state holds only "_id" (the frame-id counter); dynamic-shape generalization
moved to PGO's process-global code state, so the split does not touch it. The
split is kept deliberately -- an isolated region must number its compiles
independently so its tlparse/TORCH_LOGS labels stay coherent instead of
interleaving with the default scope. The renumbering is the intended observable;
a dedicated test for per-region numbering is worth adding and is tracked, but the
behavior is label/id bookkeeping, not guard or cache correctness.

Q: When reset() races a lookup on another thread, it parks a CLEAR_ALL (because
that lookup holds cache_python_depth > 0) and returns with the cache entries still
present and servable. Doesn't that break reset()'s clean-slate contract?

A: Yes, reset() becomes asynchronous under this specific race, and this is new
with releasing cache_mutex during guard evaluation (the old recursive mutex would
have blocked the peer instead). The window is bounded: every reader that matters
(lookup, _get_total_cache_entry_count, _debug_get_cache_entry_list) drains parked
evictions before it reads, so the first depth-zero holder wipes the entries and
the stale state is never observable from Python afterward. This is documented on
clear_in_place where the park happens.

Q: `apply_pending_evictions` has a thirteen-fold preamble -- all 13 call sites
repeat the same four lines declaring `reaped_precompile`/`reaped_cache`/
`reaped_evictions` before taking `CacheLock`, and `lookup()` now layers a fourth
ordering constraint (`reaped_*` before `python_depth`) enforced only by
declaration order, which a reformat could break silently. Why not an RAII holder?

A: An RAII holder owning the three containers and the lock, draining in its
destructor after unlocking, is the right structural fix and would replace the
comment-repeated-thirteen-times invariant with something the compiler enforces.
It is deferred deliberately: it touches all 13 sites and the drain ordering is
subtle enough that folding it into this locking commit would enlarge the diff
and the review surface without changing behavior. It is tracked as a follow-up
refactor; the current declaration-order discipline is correct, just not
structural.

Q: `torch/_dynamo/CLAUDE.md:274` still describes `ExtraState` as holding
"`frame_state` (dynamic shapes detection)", the same stale claim fixed in
`extra_state.h`. Why leave the doc twin stale?

A: Out of scope for this commit for a mechanical reason: a `.md` file under
`torch/_dynamo/` cannot be included in a commit here without crashing the
IMPORT_LINTER CI lint, so the doc twin cannot be touched from this stack. It is
noted so a maintainer can correct it in a separate, lint-safe change; the
load-bearing description in `extra_state.h` is already fixed.

Q: The region-exact lookup has no fallback to the default -1 bucket. Isn't that
a lost entry?

A: The region-exact lookup is the target end-state; the region-owned install
that passes a real id lands one PR up (#195911). At this commit every install
still passes the default id -1 (the region-owned install is #195911, higher in this stack), so the common precompile path is unaffected.
The one honest gap is transitional and not covered by "the stack merges
atomically": because ghstack lands PRs one at a time, in the window between this
PR and #195911 a frame under torch.compile(..., isolate_recompiles=True) gets a
region id >= 0 and a loaded CompilePackage on that code object matches nothing,
so it falls through to a normal compile (or is rejected under a serving stance
that forbids recompiles). This is deliberate -- keeping a -1 fallback here only
to delete it in #195911 would churn the exact bytes this PR establishes -- and
in that window (TORCH_CACHING_PRECOMPILE=1 plus isolate_recompiles=True, both
public knobs, so the combination IS reachable) the consequence is a recompile
instead of a served entry, or a fail_on_recompile error -- whose message, until
this round, listed precompiled guards the region-exact lookup never evaluated.
That message now filters the entries it prints by the frame's region (the filter
#195915 lands, pulled forward), so it blames the miss on nothing; rejecting the
combination outright was rejected because a hard error where base worked is worse
than a recompile. #195911 closes the window by installing into the context's
region. A permanent test cannot pin the miss, since by the stack head the same
frame is a hit.

Q: drain_pending_invalidations does a Py_INCREF on orig_code. Can that resurrect
a freed code object?

A: No. drain runs only at cache_python_depth 0, and every caller holds orig_code
alive for the duration -- the intercepted frame or the pybind handle owns a
reference -- so the INCREF always sees a live object. The invariant is
documented above drain_pending_invalidations.

Q: The cache counter (and use_lru) is a plain integer/bool, not an atomic. Isn't
that a race?

A: No, though the earlier phrasing of this answer overreached. It holds for
total_cache_entry_count, which is only ever touched under cache_mutex. use_lru
is looser: its setter takes no lock while the reads (create_cache_entry, both
move_to_front sites) are under cache_mutex. It is still safe -- a tearing-free
bool set once from a config knob -- so a plain type is correct, but the
justification is "benign unsynchronized publish of a config flag", not "always
under the lock".

Q: eval_frame_cpp.cpp does not check the PyUnicode intern for NULL. Bug?

A: It degrades safe: a NULL intern falls back to the slow lookup rather than
crashing, so it is a nit, not a correctness hazard.

Q: The PyThread_tss_set return value is ignored.

A: Intentional. The only failure mode is TSS-key-not-created, which cannot
happen after module init creates the key, and there is no meaningful recovery on
a per-frame hot path.

Q: compare_and_set_code_exec_strategy returns False when the code object has no
ExtraState, but get_code_exec_strategy_token reports generation 0 for an absent
state and set_code_exec_strategy_with_token creates one on demand. Can't a
read-then-CAS sequence then never succeed on a code object Dynamo has not
intercepted yet?

A: In the abstract yes, but no real caller hits it, and auto-creating the state
inside the CAS is worse. Every installer establishes state through
set_code_exec_strategy_with_token (which bumps the generation above 0) BEFORE it
ever calls compare_and_set, so the token it reads is never the absent-state 0.
Making the CAS create-on-absent was tried and reverted: init_and_set_extra_state
aborts if state already exists (a TOCTOU under concurrent first-touch), and
creating an ExtraState during a CAS resurrects state on a code object mid-
teardown. The absent-state case is genuinely "nothing to compare against", so
returning False -- caller re-reads, sees generation 0, and installs via
set_code_exec_strategy_with_token -- is the correct contract, not a lost race.

Q: The deferred-drain caveat's FAQ scopes the freed-snapshot window to "a third
thread", but ConvertFrameAssert.__call__ reaches it with the compiling thread
itself doing the freeing: it calls _get_cache_entries_for_region (twice, in the
isolate_recompiles_id >= 0 branch) and _get_total_cache_entry_count back to back,
each running apply_pending_evictions, while holding non-owning py::cast wrappers
from the first call; a parked CLEAR_ALL applied by the second call at depth 0
then frees the nodes behind those wrappers, and compute_cache_size reads a freed
node. compile_lock does not cover this prologue.

A: Correct, and the self-inflicted variant sharpens the caveat: the freeing
thread is the caller, not a third one, and the isolate_recompiles_id >= 0 branch
is the shortest path because it puts two drain-on-read calls in one statement
with the first result still live. The durable fix is the one the header already
names -- hand back owning references from _get_cache_entries_for_region the way
lookup()/create_cache_entry now do -- which closes both the third-thread and the
self-inflicted forms; short of that, draining once per __call__ or raising
cache_python_depth across the whole prologue removes the self-inflicted variant.
The finding is latent (no in-tree caller drives concurrent region reads against a
parked CLEAR_ALL yet) and the fix is C++ on the cache-lifetime path, which cannot
be authored or validated without a build here, so the caveat text is corrected to
drop the "third thread" scoping and the owning-reference fix is tracked as
follow-up.

Q: install() can finish with zero precompile entries: it drains then pushes, so if
a concurrent lookup holds cache_python_depth raised, install()'s own uninstall
parks a PRECOMPILE_ALL that the drain cannot apply, the pushed entry lands behind
it, and the next depth-zero holder splices it away -- the package installs and
serves nothing. The install-park comment also pointed at a PR FAQ that did not
exist.

A: Real. The comment is corrected to describe it precisely (install defeating its
own install under a concurrent lookup) and to drop the dead FAQ pointer. It is the
same non-owning / deferred-drain class as the caveats below: the durable fix is
C++ on the cache-lifetime path -- park the install behind the parked eviction, or
stamp installs with a sequence so a drained PRECOMPILE_ALL only removes entries
older than itself -- and cannot be authored or validated without a build here.
Latent: no in-tree caller drives a concurrent lookup against a self-parked
PRECOMPILE_ALL yet. Tracked with the owning-reference follow-up,
#196394.

Q: Parked evictions get no candidate-side filter. drop_pending_invalidated_candidates
keeps a parked invalidation from serving, but there is no equivalent for parked
evictions, so _reset_precompile_entries / _clear_cache_entries_for_region can
return having removed nothing while in-flight lookups keep serving -- and since
uninstall() pops the installed globals first, a stale serve LOAD_GLOBALs a name
that is gone (NameError).

A: Real, and not a regression (base cleared the list under the iterating thread, a
UAF). The symmetric one-line candidate-side eviction filter is the right fix and
is the same C++ cache-lifetime change deferred above. The uninstall() global-pop
ordering is separately addressed on the Python side by resetting entries before
popping globals (see #195911's teardown-loop swap). Deferred here because the only
observable consequence is unreproduced and the filter cannot be built or validated
in this environment. Tracked with #196394.

Q: extract_cache_entry is the one remaining borrowed-CacheEntry* handout: it
returns &it->second.front() after the reaped_* locals (whose destructors run
Python) go out of scope, and dynamo__custom_eval_frame hands that pointer to
dynamo_call_callback, which ConvertFrameAssert.__call__ carries through the whole
_compile at depth 0 with cache_mutex unheld. The header caveat and the FAQ name
only _get_cache_entries_for_region.

A: Correct -- same shape, same fix. The extra_state.h caveat now names
extract_cache_entry alongside _get_cache_entries_for_region as needing owning
references. The fix is C++ on the cache-lifetime path and is deferred with the
rest of that class; it cannot be authored or validated without a build here.
Tracked with #196394.

Q: _has_precompile_entries is the one region-taking binding without a
`region_id >= -1` TORCH_CHECK_VALUE, while every sibling got one -- and it runs on
every served call. Isn't it the odd one out?

A: Yes, and the omission is benign. An out-of-range id (say -5) simply fails the
`entry.isolate_recompiles_id ==` comparison and the function returns false, the
same result as any valid id with no matching entry -- there is no buffer indexing
or negative-index hazard behind it, unlike the paths that guard. Adding the check
to match the sibling sweep is correct and belongs with the other C++ range-check
hardening tracked in #196394 (this stack cannot build C++ to verify a behavioral
C++ change in isolation); it is a consistency nit, not a correctness gap, and the
hot-path comment already notes the function does no Python and takes no lock.

Q: `_load_precompile_entry`'s comment calls the install-defeats-itself race "a
tracked follow-up" with no link, and it reproduces: under a concurrent lookup a
raw `_reset_precompile_entries` + `_load_precompile_entry` sequence parks a
PRECOMPILE_ALL that the pushed entry then lands behind, so the install serves
nothing.

A: Real at this commit for that raw sequence, and closed for the only production
caller one PR up: #195911 keys `CompilePackage.uninstall()`'s eviction by owner
token and mints a fresh token per install, so the parked owner eviction cannot eat
the reinstall (`test_reinstall_survives_an_eviction_parked_by_uninstall` in
#196120 pins it). The raw sequence still loses and is now listed in
#196394 (sequence-stamping evictions is a C++ change that needs a
build to verify); the comment now says both.

Q: This diff introduces a parked-eviction state machine, a GIL-releasing
recursive cache lock, thread-local region ids, per-region frame state and 12 new
bindings, and its only test change is a docstring. Nothing here exercises any of
it.

A: The coverage is one PR up, in #196120, one test per bullet of the ask: eviction
parked behind a live lookup then applied by the next depth-zero holder
(`test_region_clear_from_inside_a_lookup_is_parked`,
`test_precompile_reset_from_inside_a_lookup_is_parked`); reset_code from Python
run by a guard (`test_reset_code_from_python_run_by_lookup_is_safe`, plus the
skipped racing variant tracked in #196394); invalidate mid-lookup
(`test_invalidation_racing_an_in_flight_lookup_parks_and_drains`,
`test_invalidate_targets_the_entry_by_guard_manager_identity`); install after a
parked reset (`test_reinstall_survives_an_eviction_parked_by_uninstall`); the
thread-local id (`test_isolate_recompiles_id_is_thread_local`); and the CAS's
stale generation across reset_code
(`test_exec_strategy_token_and_compare_and_set`). They live in the next PR so this
one stays a reviewable C++ change under the size gate.

Q: `torch._dynamo.reset()` now returns with a code object's cache entries still
present and servable whenever any thread is inside a lookup on it. That changes a
public API's contract; it should be an explicit decision, not only a C++ comment.

A: Agreed, and now stated where users read it: `torch._dynamo.reset()`'s docstring
carries an NB describing the asynchronous clear under a concurrent lookup and
pointing at `clear_in_place`. Making the clear synchronous (wait for depth zero,
or gate the Python-side clear on the C++ clear having applied) stays deferred in
#196394.

Q: Per-region `frame_state` makes the `frame_compile_id >=
accumulated_recompile_limit` fallback per-region, removing the only backstop for
non-growing recompiles (invalidated guard managers), and grows `FRAME_COUNTER` /
`FRAME_COMPILE_COUNTER` per (code object, region) -- measured +20/+20 for 20
`isolate_recompiles=True` wrappers of one function.

A: Correct, and the header comment says so verbatim. The growing case stays capped
globally by `total_cache_entries_all_regions`; the escape is exactly
region-minting loop plus invalidated guard managers. A per-code-object limit
counter kept separate from the per-region display id is the fix; it is filed as
#196495 and cited from the comment rather than folded into this
locking change.

Q: `_torchdynamo_force_callback_on_cache_miss`, `_torchdynamo_cache_key` and
`_enable_precompile_cache_keys` have no producer at this commit, so the marker
lookup, the run_only override and the recursive_callback demotion skip on the
per-frame hot path are unreachable here.

A: Their producers are higher in the stack: `_torchdynamo_force_callback_on_cache_miss`
is set by `eval_frame.py`'s fail_callback under the serving stance (#195915);
`_enable_precompile_cache_keys()` and `_torchdynamo_cache_key` are set by
`precompile_package.py` (#195917); and #196120 pins them
(`test_force_callback_on_cache_miss_marker_overrides_run_only`,
`..._reaches_a_recursive_frame`,
`test_cache_key_lookup_is_off_until_a_cache_key_backend_exists`). The C++ lands
first so each consumer is a Python-only change.

Q: The `compile_lock` requirement is enforced on one of three spellings of
`reset_code`: the raw `torch._C._dynamo.eval_frame.reset_code` and
`torch._dynamo.decorators.reset_code` (re-exported by the `dir()` loop) bypass it.

A: Fixed for the trap that mattered: `decorators.py` no longer re-exports the raw
binding (its TYPE_CHECKING import is gone and the loop skips the name), so
`torch._dynamo.reset_code` -- the wrapper that takes the lock -- is the one
Python-level spelling. Renaming the C binding to `_reset_code_unlocked` is the
structural version and touches init.cpp/.pyi; nothing in-tree calls the raw
spelling, so it is left for a build-verified follow-up.

Q: `_reset_precompile_entries_for_owner` uses `PyCode_Check` "matching the sibling
bindings added in this commit", but `_clear_cache_entries_for_region` and
`_reset_precompile_entries_for_region`, added in the same commit, use the
`py::module::import("types")` form.

A: Fixed: both now use `PyCode_Check`, and the comment says the pre-existing
bindings keep the import form (converting them would add lines for no behavior).

Q: The `drop_pending_invalidated_candidates` comment reads as if it closes the
wrong-graph hazard, but an `invalidate()` that arrives after `lookup()` releases
`cache_mutex` parks and the in-flight lookup can still serve the entry it named.

A: Comment fixed to say exactly that: the filter covers invalidations parked
BEFORE the snapshot; a later one rides to the next lookup.

Q: `lookup_optional`'s NULL-name branch returns without `PyErr_Clear()` although a
failed `PyUnicode_InternFromString` leaves a MemoryError set, breaking the "WITHOUT
raising" contract, and its comment says the statics are initialized "at module
init" when they are function-local.

A: Both fixed: the branch clears the error and the comment says "on its first
call".

Q: `CacheCandidate` is defined twice (`lookup` and `try_lookup_without_guard_eval`);
`fullgraph_compiled_frame_count` is consulted per frame with no comment on its
process-global scope; three readers skip the parked-invalidation filter.

A: The duplicate struct is a mechanical hoist that changes no behavior; it is left
for the owning-reference follow-up (#196394) that reworks the same two functions,
since C++ cannot be compiled here. The frame-count comment is a one-line nit left
as is. The three readers (`_get_cache_entries_for_region`,
`_get_total_cache_entry_count`, `_debug_get_cache_entry_list`) feed recompile
reporting, accounting and the collective gate, never serving, so a parked
invalidation cannot make them serve a wrong graph.

Q: pr-sanity-checks is red -- this commit is 2027 lines.

A: Trimmed under the gate by condensing the longest added comment blocks (same
facts, fewer lines) and by the `PyCode_Check` conversion above, while absorbing the
reset() docstring, the decorators.py fix and the two comment additions this round
asked for.

Q: Once `_enable_precompile_cache_keys()` fires, `get_backend()` returns the cache
key, so `CacheEntry::backend` holds the key while Python's `innermost_backend` only
follows `_torchdynamo_orig_backend`; `get_guard_fail_reason_helper` then reports
"different backend callables. Cached backend: str ..." with functools.partial
advice. A lying diagnostic?

A: Yes, for the description only: the classification is right (a key mismatch IS
a backend mismatch) and the C++ `backend_match` compares key-to-key, so no wrong
graph is served. Fixed here at the site named: `describe_backend` renders a
non-callable cached side as its `_torchdynamo_cache_key`, the reason says
"backend cache keys" instead of "callables", and `_CacheEntry.backend` is typed
`object` in the .pyi to match the header's "must not assume callable". Rendering
the NEW side as a key needs the un-unwrapped callback chain (a Python twin of
`get_backend`), which lands with the only producer, `_PrecompileBackend` in
#195917, together with a recompiles-log test; it has no producer at this commit.

Q: The `_has_precompile_entries` comment says no Python runs and the CacheLock
wait is the only place the GIL can drop, but the drained nodes' destructors
(`~CacheEntry` sets `guard_manager.cache_entry`, `~PrecompileEntry` drops three
py::objects) run Python once the lock releases, and the read-looking predicate
drains a parked CLEAR_ALL as a side effect on every served call.

A: Comment corrected on both counts: no Python UNDER the lock; the call drains
parked evictions first (a parked CLEAR_ALL empties the cache there, the
drain-before-read contract every reader follows) and the reaped nodes die after
the lock releases, where their destructors can run arbitrary Python.

Q: `drain_pending_invalidations` destroys its drained py::objects under
`cache_mutex` (a parked entry's old guard_manager can be the last reference, so
arbitrary user `__del__` runs under the lock), unlike its two siblings that hand
their records out to die after the lock. Unintentional asymmetry?

A: The hazard is the one the lock-ordering comment in extra_state.h already names
and accepts (a hot-path drain is rare); the asymmetry is real and the
`dead_invalidations` out-param at the eight call sites is the right symmetric fix
-- it belongs with the RAII reaper-holder rework tracked in #196394
(C++ that cannot be built or verified here). A `CachePythonDepth` spanning
`pending` would not fix the ABBA (Python still runs under the lock); it only turns
a re-entrant reset from apply into park, unnecessary at depth 0 with no live
iteration.

Q: On the guard-error returns, `e.restore()` runs before the `reaped_*`
containers die, so their Python destructors run with an exception set.

A: Real and latent (it needs a parked region/precompile eviction drained in the
same lookup plus a raising guard in a surviving bucket). The mechanism differs
from the review's: `cache_entry`/`extra_state` are plain instance attributes of
`GuardManagerWrapper`, not pybind setters, so nothing terminates; the risk is that
a generic setattr's `_PyType_Lookup` can clear the pending exception on a
method-cache miss, so `lookup()` returns NULL without an exception set and the
frame raises SystemError instead of the guard's error. The fix (restore after the
reaped nodes die, or clear them before `e.restore()`) is C++ and is tracked in
#196394; the comment above the declarations now records it.

Q: `id + 2` in `int64_t` is signed-overflow UB for `INT64_MAX`, reachable through
the private binding; the ASAN job builds with `-fno-sanitize-recover`.

A: Fixed on both sides of the TSS round trip with unsigned arithmetic
(`(uint64_t)id + 2` on the write, `(uint64_t)(uintptr_t)value - 2` on the read);
cast-only C99, unreachable from torch.compile.

ghstack-source-id: 971bf56
Pull-Request: #195355
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description).

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude PR Review

  • Gather context (diff against origin/gh/bobrenjc93/1132/base)
  • Verify the round-39 fixes (confounded strategy read, invalidation count, comment/banner nits, import gc)
  • Re-derive the asserted contracts against extra_state.cpp / eval_frame_cpp.cpp
  • Post review findings

View job run | Branch: gh/bobrenjc93/1132/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ).

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

@bobrenjc93 bobrenjc93 closed this Sep 19, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1132/head branch November 17, 2026 01:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant