Repository navigation
[dynamo] Lock ExtraState and make the exec strategy atomic - #195355
bobrenjc93 wants to merge 65 commits into
Conversation
[ghstack-poisoned]
🔗 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]
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]
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
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
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]
|
@claude /pr-review |
Re-reviewing at current HEAD
|
[ghstack-poisoned]
|
@claude /pr-review |
|
Claude finished @bobrenjc93's task in 21m 20s —— View job Re-reviewed at Full review — PR #195355PR Review: #195355SummaryAdds a recursive The seven changes — verified1. 2. The deferred-drain caveat drops "third thread" ( 3. 4. 5. 6. 7. Also verified: the Code Quality — one nit
Minor — carried forward
Verified good this passRe-read rather than carried on trust; no action needed.
RecommendationApprove. 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 This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions. |
[ghstack-poisoned]
|
@claude /pr-review |
|
Claude finished @bobrenjc93's task in 12m 4s —— View job Re-reviewed at Full review — PR #195355PR Review: #195355SummaryAdds a recursive The three changes — verified1. Unsigned arithmetic on the TSS round trip ( 2. 3. The The rest of the C++ delta is comment condensation for the size gate. Spot-checked each: the Code Quality
Minor — carried forward
Verified good this passRe-read rather than carried on trust; no action needed.
RecommendationApprove. The unsigned round trip closes the signed-overflow UB cleanly and I verified it is exact across The one ask is that the region filter be finished. The stated goal was that the This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions. |
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]
|
@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description). |
|
Claude finished @bobrenjc93's task in 24m 38s —— View job Re-reviewed at Full review — PR #195355PR Review: #195355SummaryAdds a recursive The seven changes — verified1.
Reusing 2. 3. 4. 5. 6. 7. The stale Minor — non-blocking
Carried forward — unchanged
Verified good this passRe-read rather than carried on trust; no action needed.
RecommendationApprove. The region filter is the right fix and it mirrors Three minor notes, none blocking: the fix adds a second in-tree instance of the two-drains-with-a-live-snapshot shape (in the This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions. |
[ghstack-poisoned]
|
@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 finished @bobrenjc93's task in 6m 41s —— View job Re-reviewed at Full review — PR #195355PR Review: #195355SummaryAdds a recursive The one change — verified
The owning test is FAQ answers added this round — checkedFive of my standing minors now have FAQ answers rather than code changes. Four hold up; one is imprecise.
Three readers skipping the parked-invalidation filter — the reasoning is sound. Minor — carried forward
Verified good this passRe-read rather than carried on trust; no action needed.
RecommendationApprove. 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 One precision note: the FAQ says This review was generated by Claude Code and has not been human-reviewed; treat the findings as suggestions to verify rather than conclusions. |

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:
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_evictionshas a thirteen-fold preamble -- all 13 call sitesrepeat the same four lines declaring
reaped_precompile/reaped_cache/reaped_evictionsbefore takingCacheLock, andlookup()now layers a fourthordering constraint (
reaped_*beforepython_depth) enforced only bydeclaration 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:274still describesExtraStateas holding"
frame_state(dynamic shapes detection)", the same stale claim fixed inextra_state.h. Why leave the doc twin stale?A: Out of scope for this commit for a mechanical reason: a
.mdfile undertorch/_dynamo/cannot be included in a commit here without crashing theIMPORT_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.his 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 >= -1TORCH_CHECK_VALUE, while every sibling got one -- and it runs onevery 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, thesame 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 "atracked follow-up" with no link, and it reproduces: under a concurrent lookup a
raw
_reset_precompile_entries+_load_precompile_entrysequence parks aPRECOMPILE_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 ownertoken and mints a fresh token per install, so the parked owner eviction cannot eat
the reinstall (
test_reinstall_survives_an_eviction_parked_by_uninstallin#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 Pythonrun by a guard (
test_reset_code_from_python_run_by_lookup_is_safe, plus theskipped 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 aparked reset (
test_reinstall_survives_an_eviction_parked_by_uninstall); thethread-local id (
test_isolate_recompiles_id_is_thread_local); and the CAS'sstale generation across reset_code
(
test_exec_strategy_token_and_compare_and_set). They live in the next PR so thisone stays a reviewable C++ change under the size gate.
Q:
torch._dynamo.reset()now returns with a code object's cache entries stillpresent 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 docstringcarries 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_statemakes theframe_compile_id >= accumulated_recompile_limitfallback per-region, removing the only backstop fornon-growing recompiles (invalidated guard managers), and grows
FRAME_COUNTER/FRAME_COMPILE_COUNTERper (code object, region) -- measured +20/+20 for 20isolate_recompiles=Truewrappers 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 exactlyregion-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_keyand_enable_precompile_cache_keyshave no producer at this commit, so the markerlookup, 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_missis set by
eval_frame.py's fail_callback under the serving stance (#195915);_enable_precompile_cache_keys()and_torchdynamo_cache_keyare set byprecompile_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++ landsfirst so each consumer is a Python-only change.
Q: The
compile_lockrequirement is enforced on one of three spellings ofreset_code: the rawtorch._C._dynamo.eval_frame.reset_codeandtorch._dynamo.decorators.reset_code(re-exported by thedir()loop) bypass it.A: Fixed for the trap that mattered:
decorators.pyno longer re-exports the rawbinding (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 onePython-level spelling. Renaming the C binding to
_reset_code_unlockedis thestructural 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_ownerusesPyCode_Check"matching the siblingbindings added in this commit", but
_clear_cache_entries_for_regionand_reset_precompile_entries_for_region, added in the same commit, use thepy::module::import("types")form.A: Fixed: both now use
PyCode_Check, and the comment says the pre-existingbindings keep the import form (converting them would add lines for no behavior).
Q: The
drop_pending_invalidated_candidatescomment reads as if it closes thewrong-graph hazard, but an
invalidate()that arrives afterlookup()releasescache_mutexparks 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 withoutPyErr_Clear()although afailed
PyUnicode_InternFromStringleaves a MemoryError set, breaking the "WITHOUTraising" 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:
CacheCandidateis defined twice (lookupandtry_lookup_without_guard_eval);fullgraph_compiled_frame_countis consulted per frame with no comment on itsprocess-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 recompilereporting, 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_Checkconversion above, while absorbing thereset() 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 cachekey, so
CacheEntry::backendholds the key while Python'sinnermost_backendonlyfollows
_torchdynamo_orig_backend;get_guard_fail_reason_helperthen 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_matchcompares key-to-key, so no wronggraph is served. Fixed here at the site named:
describe_backendrenders anon-callable cached side as its
_torchdynamo_cache_key, the reason says"backend cache keys" instead of "callables", and
_CacheEntry.backendis typedobjectin the .pyi to match the header's "must not assume callable". Renderingthe NEW side as a key needs the un-unwrapped callback chain (a Python twin of
get_backend), which lands with the only producer,_PrecompileBackendin#195917, together with a recompiles-log test; it has no producer at this commit.
Q: The
_has_precompile_entriescomment says no Python runs and the CacheLockwait is the only place the GIL can drop, but the drained nodes' destructors
(
~CacheEntrysetsguard_manager.cache_entry,~PrecompileEntrydrops threepy::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_invalidationsdestroys its drained py::objects undercache_mutex(a parked entry's old guard_manager can be the last reference, soarbitrary user
__del__runs under the lock), unlike its two siblings that handtheir 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_invalidationsout-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
CachePythonDepthspanningpendingwould not fix the ABBA (Python still runs under the lock); it only turnsa 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 thereaped_*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_stateare plain instance attributes ofGuardManagerWrapper, not pybind setters, so nothing terminates; the risk is thata generic setattr's
_PyType_Lookupcan clear the pending exception on amethod-cache miss, so
lookup()returns NULL without an exception set and theframe 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 + 2inint64_tis signed-overflow UB forINT64_MAX, reachable throughthe 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 + 2on the write,(uint64_t)(uintptr_t)value - 2on the read);cast-only C99, unreachable from torch.compile.
Q: The extra_state.cpp comment calls
_clear_cache_entries_for_region"the onedepth-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_entryreturns a borrowed reference describes code that nolonger exists.
A: Deleted.
Q:
remove_from_cachere-implements the lock around_reset_codewhile the newreset_codewrapper already takescompile_lock.A: Reverted to its base shape: it calls
reset_code, which locks per call, so thefunction's diff against main is empty.
Q:
fail_on_recompile's message filters precompile entries by region but readscache entries with
_debug_get_cache_entry_list, so it prints guard failures theregion-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 theregion is isolated -- and both filters share one
region_id.Q: In
get_and_maybe_log_recompilation_reasons,kindis None when the cacheentry'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 theOwnership contract/argssplit the other blocks in the header use.
A: Restored.
Q:
_get_cache_entry_count_for_regionhas 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 theregion API.
Q: The region filter puts two drain-on-read calls in
fail_callbackwith thefirst result live, the same shape as
ConvertFrameAssert.__call__'s prologue.A: Yes, and it is the same latent class, not a new one:
fail_callbackrunsfrom the frame evaluator with no
compile_lock, so a concurrent in-place clearfrees the
py::castwrappers whether or not a second drain sits between thecalls; the base's
_debug_get_cache_entry_listread 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_callbackis now named there.Q:
describe_backendandkindcan disagree whencache_entry_backendisfalsy; key
describe_backendonisinstance(backend, str).A: Unreachable, and the proposed key would be wrong.
get_backendtreatsNone/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()), notstrings, so an
isinstance(str)test would misdescribe every real key as acallable.
Q:
test/dynamo/test_trace_rules.pyliststorch._dynamo.eval_frame.reset_codeunder
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_updatedif that skipped test were re-enabled.Q:
_get_cache_entries_for_regionuses plainTORCH_CHECKfor its type checkwhere
_debug_get_cache_entry_listusesTORCH_CHECK_TYPE; andfullgraph_compiled_frame_countis a process-global int consulted for aper-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 captureargument 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]