Skip to content

[dynamo] Lock ExtraState and make the exec strategy atomic - #195355

Closed
bobrenjc93 wants to merge 65 commits into
gh/bobrenjc93/1095/basefrom
gh/bobrenjc93/1095/head
Closed

bobrenjc93 wants to merge 65 commits into
gh/bobrenjc93/1095/basefrom
gh/bobrenjc93/1095/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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.

Q: The extra_state.cpp comment calls _clear_cache_entries_for_region "the one
depth-zero op that does not drain first", but the _reset_precompile_entries*
bindings do not drain first either; and why not make every in-place erase drain
first for uniformity?

A: The comment now names all the in-place erases and states the actual
invariant: a parked eviction is an idempotent removal, so it commutes with erasing
the same entries in place, and a depth-zero insert drains before it pushes. A
uniform drain-first would be a behaviour-neutral C++ change of about twenty lines
in a commit sitting on the 2000-line gate; it is listed on #196394
with the other deferred C++ tidy-ups.

Q: The eval_frame_cpp.cpp NB block about "directly accessing extra->cache_entry"
because extract_cache_entry returns a borrowed reference describes code that no
longer exists.

A: Deleted.

Q: remove_from_cache re-implements the lock around _reset_code while the new
reset_code wrapper already takes compile_lock.

A: Reverted to its base shape: it calls reset_code, which locks per call, so the
function's diff against main is empty.

Q: fail_on_recompile's message filters precompile entries by region but reads
cache entries with _debug_get_cache_entry_list, so it prints guard failures the
region-exact lookup never evaluated.

A: Fixed: the diagnostic now reads exactly the buckets the lookup consulted --
_get_cache_entries_for_region(code, region_id) plus the default bucket when the
region is isolated -- and both filters share one region_id.

Q: In get_and_maybe_log_recompilation_reasons, kind is None when the cache
entry's backend is a cache key (non-callable) but the current backend is callable.

A: callable(cache_entry_backend or backend) now.

Q: reset_extra_state's ownership block lost the Ownership contract / args
split the other blocks in the header use.

A: Restored.

Q: _get_cache_entry_count_for_region has no caller.

A: It is consumed by #195913's per-region recompile-limit accounting in
convert_frame.py; kept here because the binding lands with the rest of the
region API.

Q: The region filter puts two drain-on-read calls in fail_callback with the
first result live, the same shape as ConvertFrameAssert.__call__'s prologue.

A: Yes, and it is the same latent class, not a new one: fail_callback runs
from the frame evaluator with no compile_lock, so a concurrent in-place clear
frees the py::cast wrappers whether or not a second drain sits between the
calls; the base's _debug_get_cache_entry_list read had the identical exposure.
The self-inflicted variant needs three threads (a lookup in flight to park the
clear, then exiting before the second read). The owning-reference fix in
#196394 closes both forms; fail_callback is now named there.

Q: describe_backend and kind can disagree when cache_entry_backend is
falsy; key describe_backend on isinstance(backend, str).

A: Unreachable, and the proposed key would be wrong. get_backend treats
None/False keys as absent, so a stored backend is a callable, a real key, or
None (an invalidated entry), and None short-circuits to "None" in both places.
Cache keys are object() instances (_torchdynamo_cache_key = object()), not
strings, so an isinstance(str) test would misdescribe every real key as a
callable.

Q: test/dynamo/test_trace_rules.py lists torch._dynamo.eval_frame.reset_code
under ignored_c_binding_in_graph_function_names, which is now false.

A: Removed. It was correct on the base (the name was the re-exported C builtin);
this commit makes it a Python wrapper, so the reconciliation entry would fail
test_torch_name_rule_map_updated if that skipped test were re-enabled.

Q: _get_cache_entries_for_region uses plain TORCH_CHECK for its type check
where _debug_get_cache_entry_list uses TORCH_CHECK_TYPE; and
fullgraph_compiled_frame_count is a process-global int consulted for a
per-frame decision.

A: Both pre-exist this commit byte for byte (the check is the parent's; the
counter is the base's eval_frame.c). The counter's cross-thread capture
argument is the same one the FAQ above makes for the isolate id and is left out
of this locking change; the check spelling is a one-line C++ tidy-up on
#196394.

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
The precompile PR at the top of this stack installs and unloads compiled
artifacts onto live code objects at runtime -- both through its package loader
and through the transparent caching_precompile path -- and ExtraState's cache
had no lock at all.

That was survivable while every mutation happened under the GIL between frame
evaluations. It stops being survivable once artifacts are installed at runtime,
because `lookup()` walks the cache while evaluating guards and guard evaluation
runs Python -- so the GIL can drop mid-iteration and another thread can clear
the list being walked.

ExtraState gets a recursive mutex, and taking it is the part that needs care.
A thread that blocks on the mutex while holding the GIL wedges the owner, who
needs the GIL to finish its guards. `CacheLock` therefore try_locks first and
releases the GIL only when it actually has to wait. The frame evaluator takes a
strong reference to the code object a lookup hands back before doing anything
that can drop the GIL, on both the served and the fresh-compile path, and
lookup copies `trace_annotation` out under the lock rather than handing back a
borrowed pointer into a CacheEntry's std::string that a concurrent clear could
free before `_pytorch_record_function_enter` reads it.

Releasing the GIL while waiting means `torch._dynamo.reset()` can run while
another thread is parked on a state's cache_mutex, so `reset_code` no longer
destroys the ExtraState: it empties the state in place
(`ExtraState::clear_in_place`), and the state is destroyed only from the code
object's dealloc, where no frame of that code can be mid-lookup.
`clear_in_place` builds the fresh frame_state dict BEFORE moving the member out
(PyDict_New can trigger a gen-0 GC whose finalizers run arbitrary Python, and
`extract_frame_state` would otherwise Py_INCREF a moved-from null), and draws a
fresh `strategy_generation` rather than resetting it to 0 -- 0 is what
`get_code_exec_strategy_token` hands out for a never-written state, so a
pre-write token holder used to win `compare_and_set` after a write plus a
reset. `remove_from_cache` holds compile_lock, closing the window where a
lock-free reset freed cache entries an in-flight compile's Python-side snapshot
still dereferences; `reset_extra_state`'s header states that caller contract.

The other hazard is eviction from Python that is itself running under a
lookup. `invalidate()` is reached from weakref.finalize, which GC can fire
during guard evaluation while ANOTHER ExtraState's cache_mutex is held; two
threads doing that against each other's states deadlock ABBA-style, and
CacheLock's GIL release cannot break a mutex/mutex cycle. It also receives a
raw CacheEntry pointer read before the lock, which a recycled list node would
pass on an address check. `invalidate` now re-establishes the entry under the
lock by the identity of the guard manager that owns it, and never blocks: it
try-locks and otherwise parks the request on the state
(`pending_invalidations`), which every cache-mutating or serving lock holder
(`lookup`, `try_lookup_without_guard_eval`, `create_cache_entry`,
`extract_cache_entry`) drains behind an atomic early-out flag, so a parked
invalidation can neither keep serving through the no-guard-eval fast path nor
stay parked forever. The brief window in which a parked entry can still serve
matches the pre-existing asynchrony of invalidation across threads.

The recursive mutex admits the same-thread version of that problem: Python run
BY A GUARD, or by a backend `__eq__` during cache-key comparison, can re-enter
this state's eviction paths while the interrupted lookup still holds iterators
into the lists. Splicing those lists out from under it is a use-after-free that
segfaults. Every eviction that can arrive under a live lookup
(`cache_python_depth > 0`) therefore parks on the state instead --
`reset_code`, `_clear_cache_entries_for_region`, `_reset_precompile_entries`,
`_reset_precompile_entries_for_region` and `_reset_precompile_entries_for_owner`
alike -- and the next depth-zero lock holder applies it, so the eviction lands
"just after" the interrupted lookup exactly as a reset racing from another
thread would. `PendingEviction` carries a `Kind` enum (CLEAR_ALL, OWNER,
PRECOMPILE_REGION, PRECOMPILE_ALL, CACHE_REGION) so each parked request removes
exactly what the direct path would have. When `clear_in_place` clears directly
it also drops whatever is parked, since nothing a parked eviction could still
remove survives the clear. Evicted CacheEntry/PrecompileEntry objects die AFTER
cache_mutex is released (moved out under the lock), so a `__del__` reached from
their decrefs cannot re-enter the containers mid-erase or block behind a lock
this thread still holds.

Most of the rest is compile-region plumbing. Cache entries and the exec
strategy already carried a region; this extends it to precompile entries and
frame state, so several artifacts can sit on one code object and each serves
only its own. Precompile entries match their region exactly and deliberately
do not fall back to the default bucket, because the identity guards that would
tell two artifacts apart are the ones precompile has to drop. That makes
teardown a question of ownership rather than of region: a library frame two
loaded models both call holds entries from both packages, so each entry
carries a token identifying its installer and uninstall removes only its own.
Each `install()` mints a FRESH `_install_owner` token rather than reusing the
package's: the uninstall that precedes a reinstall may have parked its
eviction (lock contended, or run from inside a lookup), and a parked eviction
keyed on a reused token would take the entries the reinstall had just added at
the next depth-zero holder.

The current `isolate_recompiles_id` is now thread-local (a Py_tss slot,
matching `eval_frame_callback_key`) rather than a process global. The compile
region is a property of the call in flight, and a process-global one let a
region entered on one thread capture unrelated frames on every other. The
consequence to be aware of: a thread that never enters a region reads the
default, so worker threads spawned from inside a region do NOT inherit it and
compile into the default bucket -- they must enter the region themselves.

Two changes are not about regions. `get_backend` returns a backend's
`_torchdynamo_cache_key` when it has one, behind a process-global one-way gate
that only a precompile backend flips, so two artifacts on one frame get
distinct cache entries. And a `_torchdynamo_force_callback_on_cache_miss`
marker lets a run-only frame still reach the callback on a miss, which is what
makes an uncovered served call raise instead of quietly running eager; the
marker check uses the interned-name no-raise `lookup_optional` that
`get_backend` already uses rather than `py::hasattr`, which allocates a str and
raises/clears per call.

On the Python side, `CompilePackage` used to leak its installed state when
dropped without `uninstall()`: every load+install of one artifact added a fresh
owner's precompile entries and two uuid-named resume globals, forever.
`install()` now registers a `weakref.finalize` (`_uninstall_abandoned_package`)
that pops only globals still holding the dead package's own values -- a later
load of the same artifact reuses the artifact's names, and its overwrite must
survive -- and tears entries down through `_reset_precompile_entries_for_owner`,
which parks rather than blocks, since finalize can fire mid-guard-evaluation.
Two behaviour changes come with this. `CompilePackage.__init__` no longer calls
`uninstall()` after `initialize()`: that reset EVERY precompile entry on the
function's code object, a neighbouring package's included, and ownership makes
it unnecessary. And `DynamoCache.load_and_install_package` takes an
`isolate_recompiles_id` (default -1) so a caller can install into a region.

Known limitation, unchanged: lookup still holds cache_mutex across guard
evaluation, so Python run BY A GUARD that blocks on a second ExtraState's lock
(e.g. a lambda guard calling another compiled function) can still form a
cycle. Fixing that means evaluating guards outside the lock, which is a design
change deferred to its own PR.

Review extra_state.h and extra_state.cpp first (the lock, `PendingEviction`,
`clear_in_place`, the park/drain paths), then eval_frame_cpp.cpp and
eval_frame.c (lookup ownership and the thread-local region), then
cache_entry.cpp and the init.cpp bindings, then the package.py/eval_frame.py
plumbing, then the tests.

Test Plan:

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

test_recompile_ux.py drives resets against concurrent lookups from several
threads, drives the exact finalize call against a lookup that holds the lock
and asserts it returns promptly and is applied by a later holder, and pins the
exec-strategy binding family: token/compare-and-set semantics including the
zero-token case, region strategy inheritance (SKIP inherited, RUN_ONLY not),
region-exact cache clearing, and the force-callback-on-miss marker. Three
tests run an eviction from a backend `__eq__` inside a lookup --
test_reinstall_survives_an_eviction_parked_by_uninstall,
test_region_clear_from_inside_a_lookup_is_parked and
test_precompile_reset_from_inside_a_lookup_is_parked -- and assert the lists
the lookup is walking are untouched until the next depth-zero holder applies
the parked eviction. test_package.py's test_abandoned_package_uninstalls_on_gc
pins the finalizer.

The deadlock does not fail when reintroduced, it hangs, so its test carries a
faulthandler timeout rather than an assertion. The use-after-free reproduces as
a SIGSEGV in under 7s with 8 caller threads against 2 installers, and survives
737k install/reset cycles after the fix.

Authored with an AI assistant.

ghstack-source-id: 080530e
Pull-Request: #195355
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
The precompile PR at the top of this stack installs and unloads compiled
artifacts onto live code objects at runtime -- both through its package loader
and through the transparent caching_precompile path -- and ExtraState's cache
had no lock at all.

That was survivable while every mutation happened under the GIL between frame
evaluations. It stops being survivable once artifacts are installed at runtime,
because `lookup()` walks the cache while evaluating guards and guard evaluation
runs Python -- so the GIL can drop mid-iteration and another thread can clear
the list being walked.

ExtraState gets a recursive mutex, and taking it is the part that needs care.
A thread that blocks on the mutex while holding the GIL wedges the owner, who
needs the GIL to finish its guards. `CacheLock` therefore try_locks first and
releases the GIL only when it actually has to wait. The frame evaluator takes a
strong reference to the code object a lookup hands back before doing anything
that can drop the GIL, on both the served and the fresh-compile path, and
lookup copies `trace_annotation` out under the lock rather than handing back a
borrowed pointer into a CacheEntry's std::string that a concurrent clear could
free before `_pytorch_record_function_enter` reads it.

Releasing the GIL while waiting means `torch._dynamo.reset()` can run while
another thread is parked on a state's cache_mutex, so `reset_code` no longer
destroys the ExtraState: it empties the state in place
(`ExtraState::clear_in_place`), and the state is destroyed only from the code
object's dealloc, where no frame of that code can be mid-lookup.
`clear_in_place` builds the fresh frame_state dict BEFORE moving the member out
(PyDict_New can trigger a gen-0 GC whose finalizers run arbitrary Python, and
`extract_frame_state` would otherwise Py_INCREF a moved-from null), and draws a
fresh `strategy_generation` rather than resetting it to 0 -- 0 is what
`get_code_exec_strategy_token` hands out for a never-written state, so a
pre-write token holder used to win `compare_and_set` after a write plus a
reset. `remove_from_cache` holds compile_lock, closing the window where a
lock-free reset freed cache entries an in-flight compile's Python-side snapshot
still dereferences; `reset_extra_state`'s header states that caller contract.

The other hazard is eviction from Python that is itself running under a
lookup. `invalidate()` is reached from weakref.finalize, which GC can fire
during guard evaluation while ANOTHER ExtraState's cache_mutex is held; two
threads doing that against each other's states deadlock ABBA-style, and
CacheLock's GIL release cannot break a mutex/mutex cycle. It also receives a
raw CacheEntry pointer read before the lock, which a recycled list node would
pass on an address check. `invalidate` now re-establishes the entry under the
lock by the identity of the guard manager that owns it, and never blocks: it
try-locks and otherwise parks the request on the state
(`pending_invalidations`), which every cache-mutating or serving lock holder
(`lookup`, `try_lookup_without_guard_eval`, `create_cache_entry`,
`extract_cache_entry`) drains behind an atomic early-out flag, so a parked
invalidation can neither keep serving through the no-guard-eval fast path nor
stay parked forever. The brief window in which a parked entry can still serve
matches the pre-existing asynchrony of invalidation across threads.

The recursive mutex admits the same-thread version of that problem: Python run
BY A GUARD, or by a backend `__eq__` during cache-key comparison, can re-enter
this state's eviction paths while the interrupted lookup still holds iterators
into the lists. Splicing those lists out from under it is a use-after-free that
segfaults. Every eviction that can arrive under a live lookup
(`cache_python_depth > 0`) therefore parks on the state instead --
`reset_code`, `_clear_cache_entries_for_region`, `_reset_precompile_entries`,
`_reset_precompile_entries_for_region` and `_reset_precompile_entries_for_owner`
alike -- and the next depth-zero lock holder applies it, so the eviction lands
"just after" the interrupted lookup exactly as a reset racing from another
thread would. `PendingEviction` carries a `Kind` enum (CLEAR_ALL, OWNER,
PRECOMPILE_REGION, PRECOMPILE_ALL, CACHE_REGION) so each parked request removes
exactly what the direct path would have. When `clear_in_place` clears directly
it also drops whatever is parked, since nothing a parked eviction could still
remove survives the clear. Evicted CacheEntry/PrecompileEntry objects die AFTER
cache_mutex is released (moved out under the lock), so a `__del__` reached from
their decrefs cannot re-enter the containers mid-erase or block behind a lock
this thread still holds.

Most of the rest is compile-region plumbing. Cache entries and the exec
strategy already carried a region; this extends it to precompile entries and
frame state, so several artifacts can sit on one code object and each serves
only its own. Precompile entries match their region exactly and deliberately
do not fall back to the default bucket, because the identity guards that would
tell two artifacts apart are the ones precompile has to drop. That makes
teardown a question of ownership rather than of region: a library frame two
loaded models both call holds entries from both packages, so each entry
carries a token identifying its installer and uninstall removes only its own.
Each `install()` mints a FRESH `_install_owner` token rather than reusing the
package's: the uninstall that precedes a reinstall may have parked its
eviction (lock contended, or run from inside a lookup), and a parked eviction
keyed on a reused token would take the entries the reinstall had just added at
the next depth-zero holder.

The current `isolate_recompiles_id` is now thread-local (a Py_tss slot,
matching `eval_frame_callback_key`) rather than a process global. The compile
region is a property of the call in flight, and a process-global one let a
region entered on one thread capture unrelated frames on every other. The
consequence to be aware of: a thread that never enters a region reads the
default, so worker threads spawned from inside a region do NOT inherit it and
compile into the default bucket -- they must enter the region themselves.

Two changes are not about regions. `get_backend` returns a backend's
`_torchdynamo_cache_key` when it has one, behind a process-global one-way gate
that only a precompile backend flips, so two artifacts on one frame get
distinct cache entries. And a `_torchdynamo_force_callback_on_cache_miss`
marker lets a run-only frame still reach the callback on a miss, which is what
makes an uncovered served call raise instead of quietly running eager; the
marker check uses the interned-name no-raise `lookup_optional` that
`get_backend` already uses rather than `py::hasattr`, which allocates a str and
raises/clears per call.

On the Python side, `CompilePackage` used to leak its installed state when
dropped without `uninstall()`: every load+install of one artifact added a fresh
owner's precompile entries and two uuid-named resume globals, forever.
`install()` now registers a `weakref.finalize` (`_uninstall_abandoned_package`)
that pops only globals still holding the dead package's own values -- a later
load of the same artifact reuses the artifact's names, and its overwrite must
survive -- and tears entries down through `_reset_precompile_entries_for_owner`,
which parks rather than blocks, since finalize can fire mid-guard-evaluation.
Two behaviour changes come with this. `CompilePackage.__init__` no longer calls
`uninstall()` after `initialize()`: that reset EVERY precompile entry on the
function's code object, a neighbouring package's included, and ownership makes
it unnecessary. And `DynamoCache.load_and_install_package` takes an
`isolate_recompiles_id` (default -1) so a caller can install into a region.

Known limitation, unchanged: lookup still holds cache_mutex across guard
evaluation, so Python run BY A GUARD that blocks on a second ExtraState's lock
(e.g. a lambda guard calling another compiled function) can still form a
cycle. Fixing that means evaluating guards outside the lock, which is a design
change deferred to its own PR.

Review extra_state.h and extra_state.cpp first (the lock, `PendingEviction`,
`clear_in_place`, the park/drain paths), then eval_frame_cpp.cpp and
eval_frame.c (lookup ownership and the thread-local region), then
cache_entry.cpp and the init.cpp bindings, then the package.py/eval_frame.py
plumbing, then the tests.

Test Plan:

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

test_recompile_ux.py drives resets against concurrent lookups from several
threads, drives the exact finalize call against a lookup that holds the lock
and asserts it returns promptly and is applied by a later holder, and pins the
exec-strategy binding family: token/compare-and-set semantics including the
zero-token case, region strategy inheritance (SKIP inherited, RUN_ONLY not),
region-exact cache clearing, and the force-callback-on-miss marker. The tests record, from inside a backend __eq__ run by the lookup, the length of the list that lookup is walking, and assert afterwards that it was untouched until the next depth-zero holder applied the parked eviction; an assertion raised inside __eq__ would be swallowed by the lookup as a mismatch.  test_package.py's test_abandoned_package_uninstalls_on_gc
pins the finalizer.

The deadlock does not fail when reintroduced, it hangs, so its test carries a
faulthandler timeout rather than an assertion. The use-after-free reproduces as
a SIGSEGV in under 7s with 8 caller threads against 2 installers, and survives
737k install/reset cycles after the fix.

Authored with an AI assistant.

ghstack-source-id: 0a69f34
Pull-Request: #195355
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
The precompile PR at the top of this stack installs and unloads compiled
artifacts onto live code objects at runtime -- both through its package loader
and through the transparent caching_precompile path -- and ExtraState's cache
had no lock at all.

That was survivable while every mutation happened under the GIL between frame
evaluations. It stops being survivable once artifacts are installed at runtime,
because `lookup()` walks the cache while evaluating guards and guard evaluation
runs Python -- so the GIL can drop mid-iteration and another thread can clear
the list being walked.

ExtraState gets a recursive mutex, and taking it is the part that needs care.
A thread that blocks on the mutex while holding the GIL wedges the owner, who
needs the GIL to finish its guards. `CacheLock` therefore try_locks first and
releases the GIL only when it actually has to wait. The frame evaluator takes a
strong reference to the code object a lookup hands back before doing anything
that can drop the GIL, on both the served and the fresh-compile path, and
lookup copies `trace_annotation` out under the lock rather than handing back a
borrowed pointer into a CacheEntry's std::string that a concurrent clear could
free before `_pytorch_record_function_enter` reads it.

Releasing the GIL while waiting means `torch._dynamo.reset()` can run while
another thread is parked on a state's cache_mutex, so `reset_code` no longer
destroys the ExtraState: it empties the state in place
(`ExtraState::clear_in_place`), and the state is destroyed only from the code
object's dealloc, where no frame of that code can be mid-lookup.
`clear_in_place` builds the fresh frame_state dict BEFORE moving the member out
(PyDict_New can trigger a gen-0 GC whose finalizers run arbitrary Python, and
`extract_frame_state` would otherwise Py_INCREF a moved-from null), and draws a
fresh `strategy_generation` rather than resetting it to 0 -- 0 is what
`get_code_exec_strategy_token` hands out for a never-written state, so a
pre-write token holder used to win `compare_and_set` after a write plus a
reset. `remove_from_cache` holds compile_lock, closing the window where a
lock-free reset freed cache entries an in-flight compile's Python-side snapshot
still dereferences; `reset_extra_state`'s header states that caller contract.

The other hazard is eviction from Python that is itself running under a
lookup. `invalidate()` is reached from weakref.finalize, which GC can fire
during guard evaluation while ANOTHER ExtraState's cache_mutex is held; two
threads doing that against each other's states deadlock ABBA-style, and
CacheLock's GIL release cannot break a mutex/mutex cycle. It also receives a
raw CacheEntry pointer read before the lock, which a recycled list node would
pass on an address check. `invalidate` now re-establishes the entry under the
lock by the identity of the guard manager that owns it, and never blocks: it
try-locks and otherwise parks the request on the state
(`pending_invalidations`), which every cache-mutating or serving lock holder
(`lookup`, `try_lookup_without_guard_eval`, `create_cache_entry`,
`extract_cache_entry`) drains behind an atomic early-out flag, so a parked
invalidation can neither keep serving through the no-guard-eval fast path nor
stay parked forever. The brief window in which a parked entry can still serve
matches the pre-existing asynchrony of invalidation across threads.

The recursive mutex admits the same-thread version of that problem: Python run
BY A GUARD, or by a backend `__eq__` during cache-key comparison, can re-enter
this state's eviction paths while the interrupted lookup still holds iterators
into the lists. Splicing those lists out from under it is a use-after-free that
segfaults. Every eviction that can arrive under a live lookup
(`cache_python_depth > 0`) therefore parks on the state instead --
`reset_code`, `_clear_cache_entries_for_region`, `_reset_precompile_entries`,
`_reset_precompile_entries_for_region` and `_reset_precompile_entries_for_owner`
alike -- and the next depth-zero lock holder applies it, so the eviction lands
"just after" the interrupted lookup exactly as a reset racing from another
thread would. `PendingEviction` carries a `Kind` enum (CLEAR_ALL, OWNER,
PRECOMPILE_REGION, PRECOMPILE_ALL, CACHE_REGION) so each parked request removes
exactly what the direct path would have. When `clear_in_place` clears directly
it also drops whatever is parked, since nothing a parked eviction could still
remove survives the clear. Evicted CacheEntry/PrecompileEntry objects die AFTER
cache_mutex is released (moved out under the lock), so a `__del__` reached from
their decrefs cannot re-enter the containers mid-erase or block behind a lock
this thread still holds.

Most of the rest is compile-region plumbing. Cache entries and the exec
strategy already carried a region; this extends it to precompile entries and
frame state, so several artifacts can sit on one code object and each serves
only its own. Precompile entries match their region exactly and deliberately
do not fall back to the default bucket, because the identity guards that would
tell two artifacts apart are the ones precompile has to drop. That makes
teardown a question of ownership rather than of region: a library frame two
loaded models both call holds entries from both packages, so each entry
carries a token identifying its installer and uninstall removes only its own.
Each `install()` mints a FRESH `_install_owner` token rather than reusing the
package's: the uninstall that precedes a reinstall may have parked its
eviction (lock contended, or run from inside a lookup), and a parked eviction
keyed on a reused token would take the entries the reinstall had just added at
the next depth-zero holder.

The current `isolate_recompiles_id` is now thread-local (a Py_tss slot,
matching `eval_frame_callback_key`) rather than a process global. The compile
region is a property of the call in flight, and a process-global one let a
region entered on one thread capture unrelated frames on every other. The
consequence to be aware of: a thread that never enters a region reads the
default, so worker threads spawned from inside a region do NOT inherit it and
compile into the default bucket -- they must enter the region themselves.

Two changes are not about regions. `get_backend` returns a backend's
`_torchdynamo_cache_key` when it has one, behind a process-global one-way gate
that only a precompile backend flips, so two artifacts on one frame get
distinct cache entries. And a `_torchdynamo_force_callback_on_cache_miss`
marker lets a run-only frame still reach the callback on a miss, which is what
makes an uncovered served call raise instead of quietly running eager; the
marker check uses the interned-name no-raise `lookup_optional` that
`get_backend` already uses rather than `py::hasattr`, which allocates a str and
raises/clears per call.

On the Python side, `CompilePackage` used to leak its installed state when
dropped without `uninstall()`: every load+install of one artifact added a fresh
owner's precompile entries and two uuid-named resume globals, forever.
`install()` now registers a `weakref.finalize` (`_uninstall_abandoned_package`)
that pops only globals still holding the dead package's own values -- a later
load of the same artifact reuses the artifact's names, and its overwrite must
survive -- and tears entries down through `_reset_precompile_entries_for_owner`,
which parks rather than blocks, since finalize can fire mid-guard-evaluation.
Two behaviour changes come with this. `CompilePackage.__init__` no longer calls
`uninstall()` after `initialize()`: that reset EVERY precompile entry on the
function's code object, a neighbouring package's included, and ownership makes
it unnecessary. And `DynamoCache.load_and_install_package` takes an
`isolate_recompiles_id` (default -1) so a caller can install into a region.

Known limitation, unchanged: lookup still holds cache_mutex across guard
evaluation, so Python run BY A GUARD that blocks on a second ExtraState's lock
(e.g. a lambda guard calling another compiled function) can still form a
cycle. Fixing that means evaluating guards outside the lock, which is a design
change deferred to its own PR.

Review extra_state.h and extra_state.cpp first (the lock, `PendingEviction`,
`clear_in_place`, the park/drain paths), then eval_frame_cpp.cpp and
eval_frame.c (lookup ownership and the thread-local region), then
cache_entry.cpp and the init.cpp bindings, then the package.py/eval_frame.py
plumbing, then the tests.

Test Plan:

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

test_recompile_ux.py drives resets against concurrent lookups from several
threads, drives the exact finalize call against a lookup that holds the lock
and asserts it returns promptly and is applied by a later holder, and pins the
exec-strategy binding family: token/compare-and-set semantics including the
zero-token case, region strategy inheritance (SKIP inherited, RUN_ONLY not),
region-exact cache clearing, and the force-callback-on-miss marker. The tests
record, from inside a backend __eq__ run by the lookup, the length of the list
that lookup is walking, and assert afterwards that it was untouched until the
next depth-zero holder applied the parked eviction; an assertion raised inside
__eq__ would be swallowed by the lookup as a mismatch.  test_package.py's
test_abandoned_package_uninstalls_on_gc pins the finalizer.

The deadlock does not fail when reintroduced, it hangs, so its test carries a
faulthandler timeout rather than an assertion. The use-after-free reproduces as
a SIGSEGV in under 7s with 8 caller threads against 2 installers, and survives
737k install/reset cycles after the fix.

Authored with an AI assistant.

ghstack-source-id: 0a69f34
Pull-Request: #195355
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
The precompile PR at the top of this stack installs and unloads compiled
artifacts onto live code objects at runtime -- both through its package loader
and through the transparent caching_precompile path -- and ExtraState's cache
had no lock at all.

That was survivable while every mutation happened under the GIL between frame
evaluations. It stops being survivable once artifacts are installed at runtime,
because `lookup()` walks the cache while evaluating guards and guard evaluation
runs Python -- so the GIL can drop mid-iteration and another thread can clear
the list being walked.

ExtraState gets a recursive mutex, and taking it is the part that needs care.
A thread that blocks on the mutex while holding the GIL wedges the owner, who
needs the GIL to finish its guards. `CacheLock` therefore try_locks first and
releases the GIL only when it actually has to wait. The frame evaluator takes a
strong reference to the code object a lookup hands back before doing anything
that can drop the GIL, on both the served and the fresh-compile path, and
lookup copies `trace_annotation` out under the lock rather than handing back a
borrowed pointer into a CacheEntry's std::string that a concurrent clear could
free before `_pytorch_record_function_enter` reads it.

Releasing the GIL while waiting means `torch._dynamo.reset()` can run while
another thread is parked on a state's cache_mutex, so `reset_code` no longer
destroys the ExtraState: it empties the state in place
(`ExtraState::clear_in_place`), and the state is destroyed only from the code
object's dealloc, where no frame of that code can be mid-lookup.
`clear_in_place` builds the fresh frame_state dict BEFORE moving the member out
(PyDict_New can trigger a gen-0 GC whose finalizers run arbitrary Python, and
`extract_frame_state` would otherwise Py_INCREF a moved-from null), and draws a
fresh `strategy_generation` rather than resetting it to 0 -- 0 is what
`get_code_exec_strategy_token` hands out for a never-written state, so a
pre-write token holder used to win `compare_and_set` after a write plus a
reset. `remove_from_cache` holds compile_lock, closing the window where a
lock-free reset freed cache entries an in-flight compile's Python-side snapshot
still dereferences; `reset_extra_state`'s header states that caller contract.

The other hazard is eviction from Python that is itself running under a
lookup. `invalidate()` is reached from weakref.finalize, which GC can fire
during guard evaluation while ANOTHER ExtraState's cache_mutex is held; two
threads doing that against each other's states deadlock ABBA-style, and
CacheLock's GIL release cannot break a mutex/mutex cycle. It also receives a
raw CacheEntry pointer read before the lock, which a recycled list node would
pass on an address check. `invalidate` now re-establishes the entry under the
lock by the identity of the guard manager that owns it, and never blocks: it
try-locks and otherwise parks the request on the state
(`pending_invalidations`), which every cache-mutating or serving lock holder
(`lookup`, `try_lookup_without_guard_eval`, `create_cache_entry`,
`extract_cache_entry`) drains behind an atomic early-out flag, so a parked
invalidation can neither keep serving through the no-guard-eval fast path nor
stay parked forever. The brief window in which a parked entry can still serve
matches the pre-existing asynchrony of invalidation across threads.

The recursive mutex admits the same-thread version of that problem: Python run
BY A GUARD, or by a backend `__eq__` during cache-key comparison, can re-enter
this state's eviction paths while the interrupted lookup still holds iterators
into the lists. Splicing those lists out from under it is a use-after-free that
segfaults. Every eviction that can arrive under a live lookup
(`cache_python_depth > 0`) therefore parks on the state instead --
`reset_code`, `_clear_cache_entries_for_region`, `_reset_precompile_entries`,
`_reset_precompile_entries_for_region` and `_reset_precompile_entries_for_owner`
alike -- and the next depth-zero lock holder applies it, so the eviction lands
"just after" the interrupted lookup exactly as a reset racing from another
thread would. `PendingEviction` carries a `Kind` enum (CLEAR_ALL, OWNER,
PRECOMPILE_REGION, PRECOMPILE_ALL, CACHE_REGION) so each parked request removes
exactly what the direct path would have. When `clear_in_place` clears directly
it also drops whatever is parked, since nothing a parked eviction could still
remove survives the clear. Evicted CacheEntry/PrecompileEntry objects die AFTER
cache_mutex is released (moved out under the lock), so a `__del__` reached from
their decrefs cannot re-enter the containers mid-erase or block behind a lock
this thread still holds.

Most of the rest is compile-region plumbing. Cache entries and the exec
strategy already carried a region; this extends it to precompile entries and
frame state, so several artifacts can sit on one code object and each serves
only its own. Precompile entries match their region exactly and deliberately
do not fall back to the default bucket, because the identity guards that would
tell two artifacts apart are the ones precompile has to drop. That makes
teardown a question of ownership rather than of region: a library frame two
loaded models both call holds entries from both packages, so each entry
carries a token identifying its installer and uninstall removes only its own.
Each `install()` mints a FRESH `_install_owner` token rather than reusing the
package's: the uninstall that precedes a reinstall may have parked its
eviction (lock contended, or run from inside a lookup), and a parked eviction
keyed on a reused token would take the entries the reinstall had just added at
the next depth-zero holder.

The current `isolate_recompiles_id` is now thread-local (a Py_tss slot,
matching `eval_frame_callback_key`) rather than a process global. The compile
region is a property of the call in flight, and a process-global one let a
region entered on one thread capture unrelated frames on every other. The
consequence to be aware of: a thread that never enters a region reads the
default, so worker threads spawned from inside a region do NOT inherit it and
compile into the default bucket -- they must enter the region themselves.

Two changes are not about regions. `get_backend` returns a backend's
`_torchdynamo_cache_key` when it has one, behind a process-global one-way gate
that only a precompile backend flips, so two artifacts on one frame get
distinct cache entries. And a `_torchdynamo_force_callback_on_cache_miss`
marker lets a run-only frame still reach the callback on a miss, which is what
makes an uncovered served call raise instead of quietly running eager; the
marker check uses the interned-name no-raise `lookup_optional` that
`get_backend` already uses rather than `py::hasattr`, which allocates a str and
raises/clears per call.

On the Python side, `CompilePackage` used to leak its installed state when
dropped without `uninstall()`: every load+install of one artifact added a fresh
owner's precompile entries and two uuid-named resume globals, forever.
`install()` now registers a `weakref.finalize` (`_uninstall_abandoned_package`)
that pops only globals still holding the dead package's own values -- a later
load of the same artifact reuses the artifact's names, and its overwrite must
survive -- and tears entries down through `_reset_precompile_entries_for_owner`,
which parks rather than blocks, since finalize can fire mid-guard-evaluation.
Two behaviour changes come with this. `CompilePackage.__init__` no longer calls
`uninstall()` after `initialize()`: that reset EVERY precompile entry on the
function's code object, a neighbouring package's included, and ownership makes
it unnecessary. And `DynamoCache.load_and_install_package` takes an
`isolate_recompiles_id` (default -1) so a caller can install into a region.

Known limitation, unchanged: lookup still holds cache_mutex across guard
evaluation, so Python run BY A GUARD that blocks on a second ExtraState's lock
(e.g. a lambda guard calling another compiled function) can still form a
cycle. Fixing that means evaluating guards outside the lock, which is a design
change deferred to its own PR.

Review extra_state.h and extra_state.cpp first (the lock, `PendingEviction`,
`clear_in_place`, the park/drain paths), then eval_frame_cpp.cpp and
eval_frame.c (lookup ownership and the thread-local region), then
cache_entry.cpp and the init.cpp bindings, then the package.py/eval_frame.py
plumbing, then the tests.

Test Plan:

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

test_recompile_ux.py drives resets against concurrent lookups from several
threads, drives the exact finalize call against a lookup that holds the lock
and asserts it returns promptly and is applied by a later holder, and pins the
exec-strategy binding family: token/compare-and-set semantics including the
zero-token case, region strategy inheritance (SKIP inherited, RUN_ONLY not),
region-exact cache clearing, and the force-callback-on-miss marker. The tests
record, from inside a backend __eq__ run by the lookup, the length of the list
that lookup is walking, and assert afterwards that it was untouched until the
next depth-zero holder applied the parked eviction; an assertion raised inside
__eq__ would be swallowed by the lookup as a mismatch.  test_package.py's
test_abandoned_package_uninstalls_on_gc pins the finalizer.

The deadlock does not fail when reintroduced, it hangs, so its test carries a
faulthandler timeout rather than an assertion. The use-after-free reproduces as
a SIGSEGV in under 7s with 8 caller threads against 2 installers, and survives
737k install/reset cycles after the fix.

Authored with an AI assistant.

ghstack-source-id: 0a69f34
Pull-Request: #195355
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread test/dynamo/test_recompile_ux.py Resolved
Comment thread torch/csrc/dynamo/extra_state.cpp Resolved
Comment thread torch/csrc/dynamo/extra_state.h Resolved
Comment thread torch/csrc/dynamo/eval_frame_cpp.cpp Resolved
Comment thread torch/_dynamo/eval_frame.py Resolved
Comment thread torch/csrc/dynamo/extra_state.cpp Resolved
Comment thread torch/csrc/dynamo/extra_state.cpp Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Re-reviewing at current HEAD

  • Confirm HEAD and scope the delta since 79e51b18
  • Verify each change against the code
  • Re-check carried-forward findings
  • Post review

View job run • branch gh/bobrenjc93/1095/head

[ghstack-poisoned]
Comment thread torch/csrc/dynamo/cache_entry.cpp Resolved
Comment thread torch/csrc/dynamo/extra_state.cpp 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 21m 20s —— View job


Re-reviewed at 0ef7730e. Both asks from my last pass landed, and this round adds a real diagnostic fix — the deferred-drain caveat now drops the "third thread" scoping and names the compiling thread's own prologue, lookup_optional's NULL-name branch clears the error, and describe_backend / the BACKEND_MATCH message no longer claim a cache key is a callable. Approving, with one small labeling nit on the new branch.

Full review — PR #195355

PR Review: #195355

Summary

Adds a recursive cache_mutex to dynamo's ExtraState plus an eviction/invalidation parking protocol so the frame cache survives concurrent install, lookup, eviction and reset, and moves the default exec strategy into a lock-free std::atomic with a generation token. git diff base...HEAD is now 1745 insertions / 254 deletions across 13 files (up from 1778/249 across 11 — the file count grew because torch/_dynamo/__init__.py and torch/_dynamo/decorators.py joined the diff). Restricted to this PR's files, git diff 79e51b18..HEAD is eval_frame.pyi | 2, __init__.py | 5, decorators.py | 5, guards.py, cache_entry.cpp | 6, extra_state.cpp, extra_state.h — the C++ deltas are comment condensations plus the two PyCode_Check conversions. Note this PR's guards.py diff is no longer just the one-line invalidate signature change; it now carries the describe_backend work too.

The seven changes — verified

1. PyErr_Clear() in lookup_optional's NULL-name branch (cache_entry.cpp:90-95) — correct. PyUnicode_InternFromString returns NULL with a MemoryError set, and the function's own contract at :84 is "empty when absent, WITHOUT raising". The branch now clears, matching the GetOptionalAttr branch at :99-101. The comment is also fixed: it now says "the caller's function-local PyUnicode_InternFromString hit OOM on its first call", which is accurate — all three interned names are function-local statics (cache_entry.cpp:113-116, eval_frame_cpp.cpp), initialized from the per-frame path, not at import.

2. The deferred-drain caveat drops "third thread" (extra_state.h:336-343) — this was my standing ask. It now reads: "Two non-owning handouts used after cache_mutex releases at depth 0 can race that drain: _get_cache_entries_for_region's py::cast wrappers (even on the compiling thread, whose prologue drains) and extract_cache_entry's borrowed CacheEntry."* That is the shape I traced: ConvertFrameAssert.__call__ calls _get_cache_entries_for_region at convert_frame.py:648, again at :653 in the isolate_recompiles_id >= 0 branch, then _get_total_cache_entry_count at :658, then consumes the first result in compute_cache_size at :659 — each of the first three drains, so a later depth-zero call can free the nodes behind the still-live wrappers. Naming the prologue rather than a three-thread interleaving is what a reader needs, and #196394 is the tracking issue.

3. reset()'s docstring carries the asynchrony NB (__init__.py:145-148) — correct, and in the right place. reset() takes compile_lock at :158 and clears orig_code_map at :163, while clear_in_place (extra_state.cpp:348-368) parks a CLEAR_ALL when any thread holds cache_python_depth raised. So the C++ entries genuinely outlive the call, and the docstring now says so and points at clear_in_place. This is the one behavioral contract change in the PR that a user could hit, and it was previously documented only in C++.

4. decorators.py no longer re-exports the raw reset_code (:65-71) — correct. The dir() loop skips the name and the TYPE_CHECKING import is gone, so torch._dynamo.decorators.reset_code no longer shadows the locked wrapper. torch._dynamo.reset_code resolves to eval_frame.reset_code (__init__.py:52-62), which takes compile_lock at :702-705 — so there is now one Python spelling and it is the locked one. Nothing in-tree imported the raw name, and reset_code is not in __all__, so this is not a public-surface removal. The skip is a string comparison, so it silently becomes dead if the binding is ever renamed; the FAQ's structural fix (_reset_code_unlocked) is the right follow-up.

5. _CacheEntry.backend: object in the stub (eval_frame.pyi:44) — correct. get_backend can return a str cache key (cache_entry.cpp:131-133), so Callable was a lie. guards.py:5711 is the only reader of the attribute in the tree and it does not call it.

6. describe_backend / the BACKEND_MATCH reason (guards.py:5642-5649, :5745-5747) — the classification fix is right. With _enable_precompile_cache_keys() fired, CacheEntry::backend holds the key while innermost_backend (eval_frame.py:777) only follows _torchdynamo_orig_backend, so the old message said "different backend callables. Cached backend: str ..." and offered functools.partial advice for something that is not a function. Rendering the non-callable cached side as its cache key and switching the noun to "cache keys" makes the diagnostic honest. The C++ backend_match compares key-to-key (extra_state.cpp:618-630), so no wrong graph was ever served — this was description-only, as the FAQ says. Leaving the NEW side rendered as a callable until its producer lands (_PrecompileBackend, #195917) is the right scoping.

7. PyCode_Check in _clear_cache_entries_for_region (:1111) and _reset_precompile_entries_for_region (:1239) — correct. Both were added by this commit, so converting them costs nothing and matches _reset_precompile_entries_for_owner, whose comment (:1275-1278) explains why the import form is unsafe from weakref.finalize. The five remaining py::module::import("types") sites (:1020, :1056, :1182, :1216, :1333) are all pre-existing on base — I checked base:extra_state.cpp — so the comment's claim that "the pre-existing ones keep the import form" is accurate.

Also verified: the drop_pending_invalidated_candidates comment (:643-654) now says the filter covers only invalidations parked before the snapshot and that a later one rides to the next lookup — which is what the code does, since the filter runs inside the CacheLock scope at :775 / :908, before the lock releases.

Code Quality — one nit

  • The non-callable branch attributes non-callability to a cache key unconditionally. describe_backend:5646-5649 renders any non-callable as _torchdynamo_cache_key {backend!r}, and :5745 picks "cache keys" on the same test. Two inputs reach it that are not cache keys: None (cache_entry_backend is None when guard_manager.cache_entry is unset, :5710) and Py_False (the run-only sentinel get_backend returns for a False callback). Both are effectively unreachable on this path — the None case needs a live entry whose backend is None, and CacheEntry::invalidate (cache_entry.cpp:40-50) sets backend = py::none() and the deleted guard manager together, which get_guard_fail_reason:5810 short-circuits; and create_cache_entry cannot run under a Py_False callback. So this is wording, not a bug: keying on isinstance(backend, str), or saying "cached backend is not a callable" rather than naming the attribute, would stop a future non-callable from being mislabeled.

Minor — carried forward

  • _has_precompile_entries (extra_state.cpp:1403-1432) is still the one region-taking binding with no >= -1 range check. It has the PyCode_Check at :1406 but no TORCH_CHECK_VALUE, while the six siblings do (:1088/:1112, :1239, :1279, :1333, plus init.cpp:518/:535). The FAQ's argument holds — an out-of-range id just fails the entry.isolate_recompiles_id == compare at :1427 and returns false, with no indexing behind it — so this is the consistency nit it is filed as, tracked in #196394.
  • _get_cache_entry_count_for_region still has no caller anywhere. Re-grepped every .py/.pyi/.cpp/.h: exactly four references, all definitional — declaration (extra_state.h:460), definition (extra_state.cpp:1085), binding (init.cpp:626), stub (eval_frame.pyi:101). Worth a grep at the stack head; delete the four lines if [dynamo] Give CompilePackage an explicit capture/serve mode #195913 does not consume it.
  • test/dynamo/test_trace_rules.py:67 still lists "torch._dynamo.eval_frame.reset_code" under ignored_c_binding_in_graph_function_names, whose premise is now doubly false — it was already a Python function on base, and this round made it a compile_lock wrapper. test_torch_name_rule_map_updated is @unittest.skipped twice (:364-367) so nothing breaks, but the entry is stale and the name is the one you just changed.
  • fullgraph_compiled_frame_count is a process-global int (eval_frame.c) consulted for a per-frame callback decision (eval_frame_cpp.cpp:447), so a fullgraph compile on thread A changes the marker's behaviour for thread B's frames. is_skip_guard_eval_unsafe got an explicit "knowingly still global" note; this read deserves the same one-liner.
  • torch/_dynamo/CLAUDE.md:273-274 has two stale claims against this PR: ExtraState "Contains a cache_entry_list" (replaced by cache_entry_map) and frame_state "(dynamic shapes detection)", which extra_state.h:112-115 correctly fixes. Deferred for the IMPORT_LINTER reason I retracted my objection to.
  • CacheCandidate is defined twice, identically, as a function-local struct (extra_state.cpp:712, :872), which is why drop_pending_invalidated_candidates (:657) has to be a template over a duck-typed Candidates. Hoisting one definition to file scope drops the template.
  • Three readers skip the parked-invalidation filter without saying why — it is applied at exactly two of five (:775, :908), while extract_cache_entry (:417), _get_cache_entries_for_region (:1052) and has_relevant_entries (:105) are silent. Cosmetic: those feed recompile-reason reporting, cache-size accounting and the guard-collective gate, not serving.
  • apply_pending_evictions' twelve-site preamble as a tracked RAII follow-up. Its new append-rather-than-swap comment (:281-283) still justifies itself with a caller that reuses the out-param across two drains in one scope; I checked all twelve sites and none does, so that clause describes a future caller rather than a live path.
  • pr_time number for the lost run-only empty-cache fast path. The FAQ's ~88 ns/frame measurement addresses magnitude; the correctness argument I accept in full.
  • Coverage in this commit's test/ delta is docstring-only (7 lines), with the suite one commit up in [dynamo] Concurrency and contract tests for the ExtraState lock #196120. Accepted per the reslice — I read test_region_clear_from_inside_a_lookup_is_parked in this branch's own history several rounds ago and it deterministically pins the park-then-drain and drain-before-read invariants.

Verified good this pass

Re-read rather than carried on trust; no action needed.

  • Both lock-free windows remain structurally identical and correct: reaped_* declared before python_depth (:743/:753, :866-870) so they destruct after depth drops and the lock releases; depth raised at depth 0 under the lock (:888 in the fast path) so any thread that later takes cache_mutex observes it and parks; the lock re-taken only for move_to_front on a hit (:953-956). All park sites consult the depth (:175, :207, :308, :348, :1128).
  • The flattened fast-path loop (:929-948) preserves base's resolution: own-region then -1, first backend match decides, and a guarded entry returns false to fall back to the full lookup rather than skipping past it.
  • invalidate_locked's guard-manager-identity search with its recycled-node rationale (:135-139), the TORCH_CHECK_TYPE stale-caller guard (:295-297) that catches the old argument order — which guards.py:5484 matches — and CachePythonDepth around live_entry->invalidate (:156-161).
  • clear_in_place's park branch keeps pending_invalidations parked with the discard confined to the depth-0 else (:383-387), and the justification at :376-382 correctly says discarding would leave the filter nothing to work with and the entry would stay servable.
  • The CACHE_REGION apply arm's deferred region-strategy reset (:252-260) nests strategy_mutex under cache_mutex and notes that strategy_mutex holds only FrameExecStrategy, so nothing under it runs Python; CHECK rather than TORCH_CHECK at :246 with the C-frame-unwind reason and the note that the pybind twin at :1140 stays TORCH_CHECK.
  • get_backend's falsy-cache-key filter (cache_entry.cpp:124-133) with its explicit note that operator bool is a NULL test, and that both None and the run-only False sentinel must be treated as absent.
  • create_cache_entry returning void and copying code_out / trace_annotation_out under the lock (:1007-1015); set_trace_annotation into SmallVector<char, 64> with the (1, '\0') initial state that keeps .data() a valid C string; the exec-strategy atomic with its fresh-generation reset and the explanation of why zero would be wrong (:408-412); extract_frame_state's build-the-dict-before-the-lock treatment (:456-462).

Recommendation

Approve. Both standing asks landed and both are accurate: the caveat now points at the compiling thread's own prologue rather than a hypothetical third thread, and the NULL-intern branch clears the error it was leaking. The new work this round is a genuine diagnostic fix — with cache keys in CacheEntry::backend, the BACKEND_MATCH reason was calling a str a callable and suggesting functools.partial for it; rendering the cached side as its key and switching the noun is correct, and the stub's backend: object now matches what the header says callers must assume. The decorators.py change collapses two same-named symbols with different locking down to the locked one. My one nit is that the non-callable branch attributes non-callability to a cache key unconditionally, which is right today but will mislabel the next non-callable that reaches it. Remaining items are the standing minors. My standing ask that the stack land together still applies, since this commit's park/drain coverage lives one commit up in #196120.

This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions.
• branch gh/bobrenjc93/1095/head

[ghstack-poisoned]
Comment thread torch/csrc/dynamo/extra_state.cpp Resolved
Comment thread torch/csrc/dynamo/extra_state.cpp Resolved
Comment thread torch/csrc/dynamo/extra_state.cpp Resolved
Comment thread torch/csrc/dynamo/eval_frame.c 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 12m 4s —— View job


Re-reviewed at 786d9e01. The one code change this round is the fail_on_recompile region filter, and it only fixes half the message — the precompile-entry half is now region-filtered, but the guard-failure half still comes from _debug_get_cache_entry_list, which returns every region's entries. Since the stated intent was that the message "no longer blames guards the region-exact lookup never evaluated", the guard-failure reasons are precisely the unfiltered half. The signed-overflow fix on the TSS round trip is correct. Approving, with that asymmetry as the ask.

Full review — PR #195355

PR Review: #195355

Summary

Adds a recursive cache_mutex to dynamo's ExtraState plus an eviction/invalidation parking protocol so the frame cache survives concurrent install, lookup, eviction and reset, and moves the default exec strategy into a lock-free std::atomic with a generation token. git diff base...HEAD is 1745 insertions / 255 deletions across 13 files. Restricted to this PR's files, git diff 0ef7730e..HEAD is eval_frame.c | 4, extra_state.cpp | 19, extra_state.h | 44, eval_frame.py (the region filter only) — the aot_compile.py / package.py / guards.py-pickler / emits_native_code deltas in that range arrive via the base update and are not in this PR's diff.

The three changes — verified

1. Unsigned arithmetic on the TSS round trip (eval_frame.c:53, :60) — correct. The write is now (void*)(uintptr_t)((uint64_t)id + 2) and the read (int64_t)((uint64_t)(uintptr_t)value - 2), so INT64_MAX + 2 is well-defined modular arithmetic instead of signed-overflow UB. I checked the round trip is exact across the range: id = -1 stores pointer value 1 and reads back (uint64_t)1 - 2 → -1; id = 0 stores 2; id = INT64_MAX stores 2^63 + 1 and reads back INT64_MAX. The -1 case does rely on the implementation-defined unsigned→signed narrowing, but that is not UB (so UBSan/-fno-sanitize-recover will not fire on it) and every compiler PyTorch targets defines it modularly, with C++20 mandating it. The fix is complete for its purpose.

2. reset_code named in the lock-ordering block (extra_state.h:94) — accurate. reset_code does now take compile_lock (eval_frame.py:697-706), so listing it alongside reset() and remove_from_cache makes the header's claim true for all three public doors.

3. The lookup() exception-set note (extra_state.cpp:703-704) — accurate. "On the guard-error returns below that Python runs with e.restore()'s exception set" matches the code: e.restore() at :786 / :823 precedes the destruction of reaped_precompile / reaped_cache / reaped_evictions, whose ~CacheEntry / ~PrecompileEntry drop py::objects. Recording it at the declarations with the #196394 reference is the right placement.

The rest of the C++ delta is comment condensation for the size gate. Spot-checked each: the drop_pending_invalidated_candidates block still states the same invariant (only invalidations parked before the snapshot are covered), the _load_precompile_entry block still names install-defeats-its-own-install and keeps the #196394 pointer, _has_precompile_entries still says no Python under the lock with the reaped nodes dying after, and the region_frame_state_map note still names the frame_compile_id cap going per-region with #196495.

Code Quality

  • The fail_on_recompile message filters precompile entries by region but not cache entries, so it still prints guard failures the region-exact lookup never evaluated. _callback_from_stance's fail_callback now does:

    cache_entries = _debug_get_cache_entry_list(frame.f_code)      # :324 — ALL regions
    ...
    reasons = get_and_maybe_log_recompilation_reasons(cache_entries, ...)   # :326
    precompile_entries = [                                          # :338-342 — filtered
        e for e in _debug_get_precompile_entries(frame.f_code)
        if e.isolate_recompiles_id == get_eval_frame_isolate_recompiles_id()
    ]

    _debug_get_cache_entry_list iterates every bucket in cache_entry_map (extra_state.cpp:1039-1047), while lookup() searches the frame's own region plus the -1 fallback only (:739-740, :764-772). So with two isolate_recompiles=True regions on one code object, a miss in region A prints BACKEND_MATCH / guard-failure reasons for region B's entries — exactly the class of misattribution the precompile filter just closed, and the guard-failure text is the part the message calls "the following guard failure(s)".

    The correct filter already exists one caller over: ConvertFrameAssert.__call__ builds cache_entries_for_reasons as _get_cache_entries_for_region(code, id) plus _get_cache_entries_for_region(code, -1) when id >= 0 (convert_frame.py:648-657), with a comment explaining the -1 fallback is included precisely so reasons are not dropped. fail_callback should use the same two-call shape rather than _debug_get_cache_entry_list; the wrapper is already exported as torch._dynamo.eval_frame._get_cache_entries_for_region (:440-461). Fix this →

  • reset_extra_state's doc comment lost the two-line Ownership contract / args split (extra_state.h:341): the condensation left // pytorch/pytorch#196394. Ownership contract args, where all ten other sites in this header use // Ownership contract then // args on separate lines (:244, :256, :267, :305, :350, :367, :404, :421, …). Cosmetic fallout from trimming for the size gate, but the header's ownership blocks are read structurally.

Minor — carried forward

  • _has_precompile_entries (extra_state.cpp:1402-1405) is still the one region-taking binding with no >= -1 range check. It has the PyCode_Check but no TORCH_CHECK_VALUE, while the siblings do (:1058, :1089, plus the _reset_* / _load_* paths and init.cpp:519/:536). The FAQ's argument holds — an out-of-range id just fails the entry.isolate_recompiles_id == compare at :1426 and returns false, with no indexing behind it — so this stays the consistency nit it is filed as under #196394.
  • _get_cache_entry_count_for_region still has no caller anywhere. Re-grepped every .py in the tree excluding the stub: zero hits. Its only four references are the declaration (extra_state.h), definition (extra_state.cpp:1085), binding (init.cpp) and stub (eval_frame.pyi:101). Worth a grep at the stack head; delete the four lines if [dynamo] Give CompilePackage an explicit capture/serve mode #195913 does not consume it.
  • CacheCandidate is defined twice, identically, as a function-local struct (extra_state.cpp:730-733, :872-875), which is why drop_pending_invalidated_candidates has to be a template over a duck-typed Candidates. Hoisting one definition to file scope drops the template.
  • Three readers skip the parked-invalidation filter without saying why — it is applied at exactly two of five (:773, and the fast path's twin), while extract_cache_entry, _get_cache_entries_for_region (:1072 drains but does not filter) and has_relevant_entries are silent. Cosmetic: those feed recompile-reason reporting, cache-size accounting and the guard-collective gate, not serving.
  • torch/_dynamo/CLAUDE.md:273-274 has two stale claims against this PR: ExtraState "Contains a cache_entry_list" (this PR replaced it with cache_entry_map, and extra_state.h:88 even notes "there is no separate default list") and frame_state "(dynamic shapes detection)", which extra_state.h:112-115 correctly fixes. Deferred for the IMPORT_LINTER reason I retracted my objection to.
  • apply_pending_evictions' twelve-site preamble as a tracked RAII follow-up.
  • pr_time number for the lost run-only empty-cache fast path. The FAQ's ~88 ns/frame measurement addresses magnitude; the correctness argument I accept in full.
  • Coverage in this commit's test/ delta is docstring-only (7 lines), with the suite one commit up in [dynamo] Concurrency and contract tests for the ExtraState lock #196120. Accepted per the reslice — I read test_region_clear_from_inside_a_lookup_is_parked in this branch's own history several rounds ago and it deterministically pins the park-then-drain and drain-before-read invariants.

Verified good this pass

Re-read rather than carried on trust; no action needed.

  • Both lock-free windows remain structurally identical and correct: reaped_* declared before python_depth (:705-707/:728, :866-868/:870) so they destruct after depth drops and the lock releases; depth raised at depth 0 under the lock (:749) so any thread that later takes cache_mutex observes it and parks; the lock re-taken only for move_to_front on a hit (:837-840).
  • lookup()'s comment block (:709-727) stays accurate and honestly bounded — it names the ABBA it avoids, scopes the guarantee to node lifetime and address stability, and explicitly excludes field mutability, naming update_diff_guard_root_manager plus its skip_guard_eval_unsafe precondition and that the race predates this change.
  • The precompile guard try/catch (:783-789) mirrors the cache-entry loop's load-bearing half and correctly omits the guard_error_hook call a PrecompileEntry cannot feed.
  • clear_in_place's park branch keeps pending_invalidations parked with the discard confined to the depth-0 else (:372-387), and the justification correctly says discarding would leave the filter nothing to work with and the entry would stay servable.
  • get_backend's falsy-cache-key filter (cache_entry.cpp:124-133) with its note that operator bool is a NULL test, and lookup_optional's NULL-name branch now clearing the MemoryError to keep the stated no-raise contract (:90-96).
  • describe_backend's non-callable branch and the "cache keys" noun (guards.py:5636-5642, :5738), plus _CacheEntry.backend: object in the stub (eval_frame.pyi:44) matching the header's "must not assume callable".
  • decorators.py:65-70 skipping reset_code in the dir() re-export loop, so torch._dynamo.reset_code is the one Python spelling and it takes compile_lock.
  • CachePythonDepth's fetch_add/fetch_sub(acq_rel); the exec-strategy atomic with its fresh-generation reset; create_cache_entry returning void; set_trace_annotation into SmallVector<char, 64>; CHECK (not TORCH_CHECK) in the CACHE_REGION apply arm with its C-frame-unwind reason; reset()'s docstring NB about the asynchronous clear.

Recommendation

Approve. The unsigned round trip closes the signed-overflow UB cleanly and I verified it is exact across [-1, INT64_MAX], the reset_code addition makes the header's lock-ordering claim true for all three public doors, and the new exception-set note at lookup()'s reaped declarations is accurate and correctly placed.

The one ask is that the region filter be finished. The stated goal was that the fail_on_recompile message stop blaming guards the region-exact lookup never evaluated, but only the precompile half was filtered — cache_entries at eval_frame.py:324 still comes from _debug_get_cache_entry_list, which walks every bucket, so the guard-failure reasons (the part the message labels "the following guard failure(s)") still include other regions' entries. The correct shape is already in ConvertFrameAssert.__call__ (own region plus the -1 fallback, convert_frame.py:648-657), and the Python wrapper is already exported. Also worth restoring the two-line Ownership contract / args split on reset_extra_state, which the size-gate condensation collapsed. Everything else is the standing minors. My standing ask that the stack land together still applies, since this commit's park/drain coverage lives one commit up in #196120.

This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions.
• branch gh/bobrenjc93/1095/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 finished @bobrenjc93's task in 24m 38s —— View job


Re-reviewed at 5ce3c04b. The region filter I asked for last round landed, and it landed correctly — fail_callback now reads the same two buckets the lookup consulted, and I verified the region id it uses is the same TSS value eval_frame_cpp.cpp reads, the buckets are disjoint, and the ordering the golden test pins is preserved. The kind = callable(cache_entry_backend or backend) fix, the remove_from_cache revert, the restored ownership-block split and the three comment corrections all check out too. Approving, with three minor notes.

Full review — PR #195355

PR Review: #195355

Summary

Adds a recursive cache_mutex to dynamo's ExtraState plus an eviction/invalidation parking protocol so the frame cache survives concurrent install, lookup, eviction and reset, and moves the default exec strategy into a lock-free std::atomic with a generation token. git diff base...HEAD is 1740 insertions / 254 deletions across 13 files. Restricted to this PR's files, git diff 786d9e01..HEAD is eval_frame.py | 40, guards.py | 7, eval_frame_cpp.cpp | 4, extra_state.cpp | 8, extra_state.h | 4 — the __builtins__ snapshot change in guards.py in that range arrives via the base update (git diff base...HEAD -- torch/_dynamo/guards.py is still only the invalidate signature, describe_backend and kind changes).

The seven changes — verified

1. fail_on_recompile reads the buckets the lookup consulted (eval_frame.py:321-326) — this was my ask and it is correct. Four things I checked rather than assumed:

  • The region id matches the lookup's. fail_callback reads get_eval_frame_isolate_recompiles_id(), which is the TSS value set_eval_frame_isolate_recompiles_id installed at eval_frame.py:1247 before the call; the frame evaluator reads the identical TSS via get_current_isolate_recompiles_id() (eval_frame_cpp.cpp:527) and passes it to lookup(). Same value, including for nested frames under the region.
  • The two-bucket shape mirrors lookup() exactly. lookup() sets num_ids = (isolate_recompiles_id >= 0) ? 2 : 1 over {own, -1} (extra_state.cpp:741-742), and the new code gates the -1 append on the same region_id >= 0. So a non-isolated frame no longer sees isolated regions' reasons — which is the misattribution this closes — and an isolated frame still gets the fallback bucket it can actually hit.
  • No duplicates. Own and -1 are distinct keys in cache_entry_map, so the concatenation cannot double-report.
  • The golden test still holds. test_fail_on_recompile_shows_guard_details (test_decorators.py:2008-2030) expects 0/0 then 0/1. Those live in the -1 bucket, region_id is -1, and _get_cache_entries_for_region(-1) returns that bucket in LRU order — the same order _debug_get_cache_entry_list produced for a single bucket. The f(ones(4)) hit at :2020 does move_to_front, which is what puts 0/0 first in both the old and new spelling.

Reusing region_id for the precompile filter at :343 instead of a second TSS read is also right — one read, one region, both halves consistent.

2. kind = "callables" if callable(cache_entry_backend or backend) else "cache keys" (guards.py:5739) — correct, and it fixes the case that was actually wrong. The or only changes behaviour when cache_entry_backend is falsy, and the reachable falsy values are None (no guard_manager.cache_entry, :5703-5705) and the run-only Py_False sentinel. Previously both said "cache keys" for something that was never a key; now the label follows the new backend. The callable-cached and str-key-cached cases are unchanged.

3. remove_from_cache reverted to its base shape (eval_frame.py:715-728) — verified byte-identical. git show base:torch/_dynamo/eval_frame.py gives the same body, so the function's diff against main is now empty while its behaviour still takes the lock: line 61 imports the raw binding as _reset_code, and the reset_code this function calls is the wrapper at :699-712. That is the right shape — the lock lives in one place, per call.

4. reset_extra_state's ownership block split restored (extra_state.h:342-344). Matches the ten other // Ownership contract / // args pairs in the header (:244, :256, :305, :352, :369, :406, :423, …).

5. _load_precompile_entry's comment (extra_state.cpp:1357-1365) — accurate on both halves. It now says the drain protects the install only at depth 0, names the raw _reset_precompile_entries + push sequence as still losing, and credits #195911's owner-token keying for closing it for CompilePackage, with #196394 for the raw case. Verified the mechanism: apply_pending_evictions early-returns at :207 while any thread holds depth raised, and the PRECOMPILE_ALL arm at :233-235 splices the whole list, so a pushed entry does go with it.

6. clear_in_place's in-place-erase note (extra_state.cpp:364-368) — the invariant it states is true. It now names all the in-place erases (_clear_cache_entries_for_region, the _reset_precompile_entries* bindings) rather than just one, and justifies them by commutation. I checked each pairing: in-place region erase + parked CLEAR_ALL is safe because CLEAR_ALL assigns total_cache_entry_count = 0 (:230) rather than subtracting; in-place region erase + parked CACHE_REGION(R) is safe because the apply arm's decrement and CHECK sit inside if (it != end()) (:238-251), so the second removal is a no-op; the precompile variants touch a different container. And "a depth-zero insert drains before it pushes" holds for both inserters (create_cache_entry:982, _load_precompile_entry:1366).

7. The stale extract_cache_entry NB in eval_frame_cpp.cpp is deleted. Correct — it described a borrowed-reference workaround that stopped existing when create_cache_entry became void with code_out / trace_annotation_out.

Minor — non-blocking

  • The region-filter fix propagates the two-drains-with-a-live-snapshot shape into fail_callback. In the region_id >= 0 branch, cache_entries from the first _get_cache_entries_for_region is still live when the second call's apply_pending_evictions runs at depth 0 (extra_state.cpp:1072), and get_and_maybe_log_recompilation_reasons then dereferences cache_entry.guard_manager / .code / .compile_id / .backend (guards.py:5839-5847) through non-owning py::cast(e, reference) wrappers (:1080). That is the same latent class the header caveat already names, and the caveat enumerates handout functions rather than call sites (extra_state.h:337-341), so the documentation still covers it — but this is now a second in-tree site with the shape, alongside ConvertFrameAssert.__call__'s prologue. Worth naming on the #196394 issue so the owning-reference fix covers both.

  • describe_backend and kind can now disagree. With cache_entry_backend falsy, kind consults the new backend and can say "callables" while cached_desc renders _torchdynamo_cache_key False (id=...) — because describe_backend labels any non-callable as a cache key (guards.py:5640-5643), including False and None-adjacent values. Vanishingly narrow (a live entry with backend = Py_False needs create_cache_entry under a Py_False callback, which cannot happen), and the None path short-circuits at :5638. Keying describe_backend on isinstance(backend, str) rather than not callable(backend) would make the two agree by construction, which is the same nit I raised last round.

  • _get_cache_entries_for_region uses plain TORCH_CHECK for its type check (extra_state.cpp:1057-1059, RuntimeError) where _debug_get_cache_entry_list uses TORCH_CHECK_TYPE (:1021, TypeError). Pre-existing on base, but fail_callback now routes through the TORCH_CHECK spelling, so a non-code argument would raise a different exception type than before. Unreachable in practice (frame.f_code), and this PR already converted the two checks it added to PyCode_Check with a comment saying the pre-existing ones keep the import form — so this is consistency only.

Carried forward — unchanged

  • _has_precompile_entries (extra_state.cpp:1404-1407) is still the one region-taking binding with no >= -1 range check, while the six siblings have TORCH_CHECK_VALUE (:1091, :1114, :1242, :1289, plus init.cpp). Benign per the FAQ — an out-of-range id just fails the entry.isolate_recompiles_id == compare at :1428 and returns false, with no indexing behind it — and tracked in #196394.
  • _get_cache_entry_count_for_region still has no caller anywhere. Re-grepped every .py/.pyi/.cpp/.h: exactly four references, all definitional — declaration (extra_state.h:458), definition (extra_state.cpp:1087), binding (init.cpp:626), stub (eval_frame.pyi:101). Worth a grep at the stack head; delete the four lines if [dynamo] Give CompilePackage an explicit capture/serve mode #195913 does not consume it.
  • test/dynamo/test_trace_rules.py:67 lists "torch._dynamo.eval_frame.reset_code" under ignored_c_binding_in_graph_function_names, whose premise is now false twice over — it was already a Python function on base, and this PR made it a compile_lock wrapper. The owning test is @unittest.skipped, so nothing breaks. Note test_decorators.py:1239/:1261 call torch._dynamo.eval_frame.reset_code(...), which now correctly resolves to the locked wrapper.
  • fullgraph_compiled_frame_count is a process-global int (eval_frame.c:791) consulted for a per-frame callback decision, so a fullgraph compile on thread A changes the marker's behaviour for thread B's frames. is_skip_guard_eval_unsafe got an explicit "knowingly still process-global" note right above it (:784-787); this one deserves the same line.
  • CacheCandidate is defined twice, identically, as a function-local struct (extra_state.cpp:732, :874), which is why drop_pending_invalidated_candidates has to be a template over a duck-typed Candidates. Hoisting one definition to file scope drops the template.
  • torch/_dynamo/CLAUDE.md:273-274 has two stale claims against this PR: ExtraState "Contains a cache_entry_list" (replaced by cache_entry_map) and frame_state "(dynamic shapes detection)". Deferred for the IMPORT_LINTER reason I retracted my objection to.
  • apply_pending_evictions' twelve-site preamble as a tracked RAII follow-up, and the pr_time number for the lost run-only empty-cache fast path (the FAQ's ~88 ns/frame addresses magnitude; the correctness argument I accept in full).
  • Coverage in this commit's test/ delta is docstring-only, with the suite one commit up in [dynamo] Concurrency and contract tests for the ExtraState lock #196120. Accepted per the reslice — I read test_region_clear_from_inside_a_lookup_is_parked in this branch's own history and it deterministically pins the park-then-drain and drain-before-read invariants.

Verified good this pass

Re-read rather than carried on trust; no action needed.

  • Both lock-free windows remain structurally identical and correct: reaped_* declared before python_depth (:707-709/:730) so they destruct after depth drops and the lock releases; depth raised at depth 0 under the lock (:751) so any thread that later takes cache_mutex observes it and parks; the lock re-taken only for move_to_front on a hit. All five park sites consult the depth (:175, :207, :1130, :1227, :1253, plus invalidate's try-lock at :1301).
  • lookup()'s comment block (:711-729) stays accurate and honestly bounded — names the ABBA it avoids, scopes the guarantee to node lifetime and address stability, and explicitly excludes field mutability, naming update_diff_guard_root_manager plus its skip_guard_eval_unsafe precondition and that the race predates this change.
  • The precompile guard try/catch (:785-791) mirrors the cache-entry loop's load-bearing half and correctly omits the guard_error_hook call a PrecompileEntry cannot feed; the exception-set note at :705-706 is accurate (e.restore() precedes the reaped containers' destruction).
  • clear_in_place's park branch keeps pending_invalidations parked with the discard confined to the depth-0 else (:385-389), and builds the fresh dict before both locks so PyDict_New's gen-0 collection cannot run a finalizer under a plain mutex (:392-403).
  • get_backend's falsy-cache-key filter (cache_entry.cpp:124-133) with its note that operator bool is a NULL test; lookup_optional's NULL-intern branch clearing the MemoryError to keep the stated no-raise contract (:90-96).
  • The unsigned TSS round trip (eval_frame.c:53, :60) — exact across [-1, INT64_MAX] with no signed-overflow UB.
  • _reset_precompile_entries_for_owner's never-block park with PyCode_Check and the non-None owner guard (:1277-1312); the CACHE_REGION apply arm's deferred region-strategy reset nesting strategy_mutex under cache_mutex with CHECK (not TORCH_CHECK) and the C-frame-unwind reason (:240-260); create_cache_entry returning void and copying code_out / trace_annotation_out under the lock (:1009-1017); reset()'s docstring NB about the asynchronous clear (__init__.py:145-148); decorators.py skipping reset_code in the dir() re-export loop.

Recommendation

Approve. The region filter is the right fix and it mirrors lookup() precisely rather than approximating it — same TSS id, same two buckets under the same >= 0 gate, and one region_id shared by both halves of the message so the guard-failure and precompile sections can't disagree about scope. The kind change targets exactly the falsy-cached case that was mislabeled, remove_from_cache is back to a zero-diff function that inherits the lock from the wrapper, and the three comment corrections (in-place erases and their commutation, the install-park race with both its raw and CompilePackage forms, the restored ownership-block split) are each accurate against the code.

Three minor notes, none blocking: the fix adds a second in-tree instance of the two-drains-with-a-live-snapshot shape (in the region_id >= 0 branch), which the header caveat already covers by function but which is worth naming on #196394; describe_backend and kind can now disagree in the unreachable falsy-cached case, which keying describe_backend on isinstance(backend, str) would fix by construction; and fail_callback now routes through the one region binding that still uses plain TORCH_CHECK rather than TORCH_CHECK_TYPE. Standing minors otherwise unchanged. My standing ask that the stack land together still applies, since this commit's park/drain coverage lives one commit up in #196120.

This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions.
• branch gh/bobrenjc93/1095/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 finished @bobrenjc93's task in 6m 41s —— View job


Re-reviewed at 7fdf47de. Round-40's PR-owned delta is exactly one line — removing "torch._dynamo.eval_frame.reset_code" from ignored_c_binding_in_graph_function_names — and it is correct: the entry's premise ("this name is a C builtin") was true on base and this PR made it a Python wrapper, so keeping it would have made used and generated disagree if the skipped test were ever re-enabled. The FAQ also picked up five of my standing minors, and one of its answers corrects an error of mine (cache keys are object() instances, not str, so the isinstance(str) key I suggested would have been wrong). Approving, with one small precision note on a different FAQ answer.

Full review — PR #195355

PR Review: #195355

Summary

Adds a recursive cache_mutex to dynamo's ExtraState plus an eviction/invalidation parking protocol so the frame cache survives concurrent install, lookup, eviction and reset, and moves the default exec strategy into a lock-free std::atomic with a generation token. git diff base...HEAD is 1740 insertions / 255 deletions across 14 files. Restricted to this PR's files, git diff 5ce3c04b..HEAD is test_trace_rules.py | 1 - and guards.py | 3 +- — and the guards.py line is not this PR's: git diff base...HEAD -- torch/_dynamo/guards.py still shows only the invalidate signature, describe_backend and kind changes, so the if "__builtins__" in f_globals guard arrived via the base update. So the round-40 change is a single deletion.

The one change — verified

test_trace_rules.py:67 entry removed — correct, and correct in both directions. I traced the mechanism rather than the diff:

  • gen_allowed_objs_and_ids(c_binding_only=True) adds a walked name to c_binding_in_graph_functions only when not hasattr(obj, "__code__") (test_trace_rules.py:165-167).
  • test_torch_name_rule_map_updated builds used from torch_c_binding_in_graph_functions.keys() | ignored_c_binding_in_graph_function_names, loads each name, and set-compares against generated (:369-385).
  • On base, torch._dynamo.eval_frame.reset_code was the re-exported C binding (base:eval_frame.py:61, a bare reset_code, import) — no __code__, so it landed in generated and the ignore entry was correct.
  • At HEAD it is a Python def (eval_frame.py:699-711, wrapping _reset_code under compile_lock), so it has __code__ and can no longer appear in generated — while the ignore entry would still put it in used. That is precisely the asymmetry _check_set_equality fails on.

The owning test is @unittest.skipped twice (:363-366), so nothing was red either way; removing the entry keeps the reconciliation table honest for whenever it is re-enabled. Also confirmed reset_code has no trace_rules.py manual rule that the removal would orphan (zero hits), and that test_decorators.py:1239/:1261 call torch._dynamo.eval_frame.reset_code, which now correctly resolves to the locked wrapper.

FAQ answers added this round — checked

Five of my standing minors now have FAQ answers rather than code changes. Four hold up; one is imprecise.

describe_backend / kind disagreement — my suggestion was wrong, and the FAQ is right to reject it. I proposed keying describe_backend on isinstance(backend, str). The FAQ points out cache keys are object() instances, not strings, so that test would misdescribe every real key as a callable — strictly worse than the current not callable(backend). And the trichotomy it argues holds: get_backend's filter at cache_entry.cpp:131 (key && !key.is_none() && !Py_IsFalse(key.ptr())) treats None and False keys as absent and falls through to the orig-backend chain, so a stored backend is a callable, a real key, or None — and None short-circuits to "None" at guards.py:5639-5640 before either branch is reached, so the two cannot actually disagree. My str framing in earlier rounds was an assumption about a producer that does not exist at this commit; the author landing _PrecompileBackend in #195917 is the authority there. Withdrawn.

_get_cache_entries_for_region's plain TORCH_CHECK — pre-existing, confirmed byte for byte. base:extra_state.cpp:434-436 is the same TORCH_CHECK(py::isinstance(code_obj, ...CodeType), "expected a code object!"); this commit only added the TORCH_CHECK_VALUE range check above it (:1060-1062). Correctly filed as a one-line tidy-up on #196394.

fullgraph_compiled_frame_count — half of this answer is imprecise. The FAQ says "the counter is the base's eval_frame.c", which is true (base:eval_frame.c:769, an unchanged int). But my point was about the read, and that is new: base has exactly two references in eval_frame_cpp.cpp, both inside eval_custom (base:432-433), while HEAD adds a third at :562-564 where the counter now gates a per-frame callback decision (|| fullgraph_compiled_frame_count >= 0 in the force-marker demotion test). So this commit does make a process-global newly load-bearing for a per-frame branch — which is exactly the shape is_skip_guard_eval_unsafe got an explicit "knowingly still process-global" note for two lines above its definition (eval_frame.c:784-787). The cross-thread argument is the same and I accept deferring it; the FAQ answer should just not imply the read pre-exists.

CacheCandidate duplicate — confirmed and correctly deferred. Two identical function-local definitions (extra_state.cpp:732-735, :874-878), which is why drop_pending_invalidated_candidates is a template over a duck-typed Candidates. Mechanical hoist, no behaviour change, rightly parked on #196394 since C++ cannot be built here.

Three readers skipping the parked-invalidation filter — the reasoning is sound. _get_cache_entries_for_region, _get_total_cache_entry_count and _debug_get_cache_entry_list feed recompile reporting, accounting and the collective gate, never serving, so a parked invalidation cannot cause a wrong graph to run. The filter stays on the two paths that serve (:773, :914).

Minor — carried forward

  • _has_precompile_entries (extra_state.cpp:1404-1433) is still the one region-taking binding with no >= -1 range check. It has TORCH_CHECK_TYPE(PyCode_Check(...)) at :1407 but no TORCH_CHECK_VALUE, while the siblings do (:1060, :1091, and the _reset_* / _load_* paths, plus init.cpp). The FAQ's argument holds — an out-of-range id just fails the entry.isolate_recompiles_id == compare at :1428 and returns false, with no indexing behind it — and it is tracked on #196394.
  • _get_cache_entry_count_for_region still has no caller anywhere. Re-grepped every .py/.pyi/.cpp/.h: exactly four references, all definitional — declaration (extra_state.h:458), definition (extra_state.cpp:1087), binding (init.cpp:626), stub (eval_frame.pyi:101). Worth a grep at the stack head; delete the four lines if [dynamo] Give CompilePackage an explicit capture/serve mode #195913 does not consume it after all.
  • torch/_dynamo/CLAUDE.md:273-274 has two stale claims against this PR: ExtraState "Contains a cache_entry_list" (this PR replaced it with cache_entry_map) and frame_state "(dynamic shapes detection)", which extra_state.h correctly fixes. Deferred for the IMPORT_LINTER reason I retracted my objection to; the load-bearing description in the header is right.
  • apply_pending_evictions' twelve-site preamble as a tracked RAII follow-up, and the pr_time number for the lost run-only empty-cache fast path (the FAQ's ~88 ns/frame addresses magnitude; the correctness argument — never free a mutex a waiter is parked on — I accept in full).
  • Coverage in this commit's test/ delta is docstring-only, with the suite one commit up in [dynamo] Concurrency and contract tests for the ExtraState lock #196120. Accepted per the reslice — I read test_region_clear_from_inside_a_lookup_is_parked in this branch's own history and it deterministically pins the park-then-drain and drain-before-read invariants.

Verified good this pass

Re-read rather than carried on trust; no action needed.

  • describe_backend's non-callable branch (guards.py:5641-5644) and the kind selection (:5740) — the or only changes behaviour for a falsy cached backend, which is where the old label was wrong; the callable-cached and key-cached cases are unchanged.
  • fail_callback's region filter (eval_frame.py:321-326) still mirrors lookup() exactly: one region_id from the same TSS the frame evaluator reads, own bucket then the -1 fallback under the same >= 0 gate, and the same id reused for the precompile filter at :343 so both halves of the message agree about scope.
  • get_backend's falsy-cache-key filter with its note that operator bool is a NULL test rather than a truthiness test; lookup_optional's NULL-intern branch clearing the MemoryError to keep the stated no-raise contract (cache_entry.cpp:90-96), with the comment correctly saying "on its first call" rather than at module init.
  • extra_state.h:386-392's contract that get_backend may return a non-callable cache key, matching _CacheEntry.backend: object in the stub.
  • Both lock-free windows remain structurally identical and correct; clear_in_place's park branch keeps pending_invalidations parked with the discard confined to the depth-0 else; CachePythonDepth's fetch_add/fetch_sub(acq_rel); the exec-strategy atomic with its fresh-generation reset; create_cache_entry returning void; set_trace_annotation into SmallVector<char, 64>; the unsigned TSS round trip; CHECK (not TORCH_CHECK) in the CACHE_REGION apply arm with its C-frame-unwind reason; reset()'s docstring NB about the asynchronous clear; decorators.py skipping reset_code in the dir() re-export loop so the locked wrapper is the one Python spelling.

Recommendation

Approve. Round-40 is a one-line bookkeeping fix and it is right for the right reason: the entry asserted "C binding", which this PR falsified by wrapping reset_code in Python, and leaving it would have desynced used from generated in the reconciliation table. The FAQ additions are all reasonable, and one of them corrects me — cache keys are object() instances, so the isinstance(str) key I proposed for describe_backend would have mislabeled every real key; withdrawn, and the current not callable(backend) test is correct given get_backend already filters None/False keys out.

One precision note: the FAQ says fullgraph_compiled_frame_count "is the base's eval_frame.c", which is true of the variable, but the read I flagged is new — base has two references in eval_frame_cpp.cpp, both inside eval_custom, while HEAD adds a third at :562-564 where the counter gates a per-frame callback decision. Deferring the thread-locality question is fine (same argument as the isolate id); the answer just shouldn't imply the read pre-exists. Everything else is the standing minors: _has_precompile_entries' missing range check, the unconsumed _get_cache_entry_count_for_region, the two-line CLAUDE.md drift, the RAII preamble follow-up, and the pr_time number. My standing ask that the stack land together still applies, since this commit's park/drain coverage lives one commit up in #196120.

This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions.
• branch gh/bobrenjc93/1095/head

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

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant