Skip to content

[aot_compile] Test a rebuilt runtime-env helper end to end - #196688

Closed
bobrenjc93 wants to merge 9 commits into
gh/bobrenjc93/1154/basefrom
gh/bobrenjc93/1154/head
Closed

bobrenjc93 wants to merge 9 commits into
gh/bobrenjc93/1154/basefrom
gh/bobrenjc93/1154/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Tests only. The previous commits pin the rebuild at the pickler level; these two
drive it through torch.compile(...).aot_compile, save_compiled_function and
load_compiled_function, so the runtime env's own closure path is covered:

def outer():
    scale = None

    def helper(x, y=3, *, k=2):
        if x is None:
            return unset            # a cell that is never assigned: EMPTY
        if scale is None:           # a cell holding None
            x = x + 1
        return x * k + y

    helper.tag = 2.0
    if helper is None:
        unset = 1
    return helper

helper = outer()

def fn(x):
    return helper(x) * 2

After save, torch._dynamo.reset() and reload, the first test reads the helper
back out of runtime_env.closure and checks each piece survived: the empty
cell is still empty, the None cell holds None, __defaults__ == (3,),
__kwdefaults__ == {"k": 2} and helper.tag == 2.0. The old reduce raised on the empty cell and dropped
__kwdefaults__ and __dict__; the None cell is asserted so the empty/None
distinction stays pinned. The second test stashes a lock next to tag and
checks the save succeeds with exactly one warning, naming the dropped lock,
the reload (after torch._dynamo.reset(), under fail_on_recompile) runs,
and the reloaded helper's __dict__ holds exactly the float.

Test Plan:

python test/dynamo/test_aot_compile.py
python test/dynamo/test_aot_compile.py -k test_aot_compile_reloads_a_runtime_env_helper_faithfully -k test_aot_compile_prunes_a_helpers_unpicklable_attribute

Authored with an AI assistant.

🤖 Generated with Claude Code

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit ded277d with merge base 0929b23 (image):

GREEN LIGHT - PR approved to be merged without human review:

  • Scope
    • Diff is additive test-only: two new methods in TestAOTCompile in test/dynamo/test_aot_compile.py, no source, config or CI file touched.
    • Nothing is deleted or weakened; the pre-existing test_aot_compile_prunes_a_lock_behind_functools_wraps_wrapped below the insertion point is untouched.
  • Assertions match the implementation
    • Empty-vs-None cell round trip is real: _reduce_cell returns a bare _unpickle_empty_cell on ValueError and wraps live contents in a 1-tuple via _set_cell_contents (torch/_dynamo/package.py:334-347, :148-156).
    • __defaults__, __kwdefaults__ and __dict__ are restored in _apply_function_state (torch/_dynamo/package.py:249-265), and type_params=None (aot_compile.py:158) skips the extra write, so __dict__ == {"tag": 2.0} is exact.
    • The single dropping ... helper.lock (lock) from the artifact warning follows log.warning at aot_compile.py:187-195, reached once per entry from _pickleable_attributes (:197-214) with the probe early-return at :173-174.
  • Robustness of the new tests
    • The empty cell cannot break tracing: both bind_args derefs are except ValueError-wrapped (variables/functions.py:863-881) and the unwrapped deref at convert_frame.py:1430-1432 reads only fn's own fully-assigned closure.
    • (cell,) = ..._artifacts.runtime_env.closure holds because closure is fn.__closure__ verbatim (convert_frame.py:1439) with the length re-asserted at aot_compile.py:376-380.
    • Warning-text assertions use the version-independent tail, so they pass on both the 3.10 co_name and 3.11+ co_qualname forms of aot_compile.py:189.

reason: clean
Reviewed commit: ded277d

Inference job

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

This was referenced Sep 11, 2026
…e guard, load-bearing tests

[ghstack-poisoned]
… check, root-verdict caching, scope-first reduce tuple, load-bearing tests

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 24m 23s —— View job


This tests-only PR is clean as written, but it lands with zero CI signal and the sibling test it sits next to (added in this same stack) will fail on Python 3.10 — details below.

PR Review: #196688

Summary

Adds two end-to-end tests driving a nested helper through torch.compile(...).aot_compile → save_compiled_function → load_compiled_function, pinning that the helper's empty cell / None cell / __kwdefaults__ / __dict__ survive the runtime-env round trip, and that an unpicklable __dict__ entry is dropped per-entry with one warning. I verified both tests' claims against the implementation and found no defects in the added lines. The problems are (a) neither test has ever executed in CI, and (b) a Python 3.10 incompatibility in the adjacent test from this stack's base commit.

Testing

  • No CI has run these tests. All 22 red jobs on this PR are sits on top of >=10 ghstack entries; refusing to run CI — every one is a build job that refused to start, so there is no test signal at all for either new test on any Python version or platform. The two new tests read as correct against the implementation, but "reads correct" is not "passes." Before landing, please either run python test/dynamo/test_aot_compile.py -k runtime_env_helper -k unpicklable_attribute locally on both 3.10 and 3.13, or shorten the stack so CI will actually execute. This matters specifically because of the next item.

  • test_aot_compile_prunes_a_lock_behind_functools_wraps_wrapped will fail on Python 3.10. This test is not in this diff — it is at test/dynamo/test_aot_compile.py:776 and is already present on origin/gh/bobrenjc93/1154/base:693, i.e. it came from an earlier commit in this stack — but it is the direct sibling of the tests added here and no CI has exercised it either. _warn_dropped formats the function name as getattr(code, "co_qualname", code.co_name) (torch/_dynamo/aot_compile.py:181). co_qualname is 3.11+; PyTorch declares requires-python = ">=3.10" and .github/workflows/pull.yml:117-134 runs a full linux-jammy-py3.10-gcc11 test job over test/dynamo. On 3.10 the message therefore carries the bare co_name, so:

    self.assertTrue(any("build.<locals>.helper.lock (lock)" in l for l in logs.output))  # :811
    self.assertTrue(any("build.<locals>.base.lock (lock)" in l for l in logs.output))    # :814

    both fail — the emitted lines are helper.lock (lock) ... and base.lock (lock) ... with no <locals> path. There is no version skipIf on the test or on TestAOTCompile (line 595-608). Either gate those two assertions on sys.version_info >= (3, 11), or assert the version-independent tail the way the new test at line 769 already does ("helper.lock (lock)" / "base.lock (lock)"), which is a substring of the 3.11+ qualname form too. Note the new test at line 769 is itself 3.10-safe — this finding is purely about the sibling that has to be fixed before the stack lands. Fix this →

  • test_aot_compile_prunes_a_helpers_unpicklable_attribute (line 744) reloads without clearing state. The sibling test at line 730-733 does torch._dynamo.reset() and wraps the load in torch.compiler.set_stance("fail_on_recompile"); this one does neither, so nothing in it proves the reloaded artifact is the thing being exercised rather than live in-process state. The assertions happen to be safe (AOTCompileUnpickler with empty external_data cannot hand back a live object, and AOTCompiledFunction.__call__ bypasses frame eval), so this is a strength gap rather than a false pass — but the two tests should not differ here without a reason.

  • __defaults__ from the same reduce stays untested on this path. AOTCompilePickler.reducer_override passes defaults=obj.__defaults__ alongside kwdefaults= (torch/_dynamo/aot_compile.py:153-154), and _apply_function_state restores both (torch/_dynamo/package.py:245-246). grep -n "__defaults__" test/dynamo/test_aot_compile.py returns nothing — the whole file never pins positional defaults, on the runtime-env path or the direct-pickler path. Given this PR's stated goal is that "everything it holds has to survive," adding a positional default to the existing helper (def helper(x, y=3, *, k=2)) plus one assertEqual(loaded.__defaults__, (3,)) covers it at essentially no cost. Same for the _pickleable_doc drop path (aot_compile.py:207-216), which is pinned only at the direct-pickler level (line 2051) and never through runtime_env.

Code Quality

  • The comment at line 698-700 parenthetically notes that "the compiled function itself cannot have an empty cell: capture reads all of its cells up front." That is accurate — _get_frame at torch/_dynamo/convert_frame.py:1431 does cell.cell_contents for every cell — but the consequence is that a user who compiles a function with a genuinely unassigned freevar gets a bare ValueError: Cell is empty out of a zip comprehension rather than a Dynamo-level diagnostic. Pre-existing and out of scope for a tests-only PR, so not a change request; flagging it since the new comment is the first place in the tree that documents the constraint, and it would be a reasonable follow-up.

Verified, no findings

For the record, these were checked and are correct, so no action is needed:

  • The empty-vs-None cell distinction the test pins is real: _reduce_cell returns a bare (_unpickle_empty_cell, ()) on ValueError and wraps live contents in a 1-tuple so None is not mistaken for empty (torch/_dynamo/package.py:301-314, 152-156).
  • assertEqual(len(logs.output), 1) is deterministic, not flaky: _warn_dropped returns early while probing (aot_compile.py:172-173), _pickleable_attributes memoizes per id(obj) for the real dump only (:195-204), and aot_compile.py has exactly one log.warning call site.
  • (cell,) = ..._artifacts.runtime_env.closure is not brittle: the closure is the original fn.__closure__ in co_freevars order (convert_frame.py:1423-1442), and Dynamo does not synthesize extra freevars.
  • The substring "helper.lock (lock) from the artifact" matches the format string at aot_compile.py:180-183; type(threading.Lock()).__name__ is lock on CPython.
  • Both fixes under test (_unpickle_empty_cell, _pickleable_attributes) are absent from origin/main and present on this stack's base, so these are genuine regression tests for the stack rather than coverage of already-landed code.

Recommendation

Approve the diff as written — I found no defect in the 83 added lines, and the assertions are all backed by the implementation.

Two things should be resolved before the stack lands, neither of which is a change to this diff: fix the Python 3.10 breakage in the sibling test at line 811/814, and get actual CI (or a local 3.10 + 3.13 run) on this file, since right now nothing has executed it. The __defaults__/__doc__ gaps and the missing reset() in the second test are worth folding in while you are here.

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

…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196693

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…196691)

`types.FunctionType(code, ...)` leaves `__annotations__` empty, so a reloaded
helper lost them. Carrying them verbatim fails the save in ordinary shapes:

```python
def outer():
    class Cfg:                      # a local class: resolves, but pickle
        pass                        # cannot reference it by name

    def inner(x: Cfg, y: int) -> int:
        return y

    return inner
```

and on 3.14, where annotations are evaluated lazily (PEP 649), a name that only
exists under `TYPE_CHECKING` reads back as a `ForwardRef` proxy even nested in
`list[Bar]`, which must not be carried: it holds its owner and may drag the
owner's globals along.

The runtime must SERIALIZE these, so `_pickleable_annotations` reads them
differently from the guard pickler: the shared `_read_raw_annotations` takes an
`evaluate=` flag, and this caller passes it, so on 3.14 the read hands back
evaluated VALUEs rather than the FORWARDREF proxies the guard pickler reads. A
proxy must not be carried (it holds its owner and may drag the owner's globals
along). Evaluating runs the function's `__annotate__` and caches the result on
it, the same thing `inspect.signature` does. When that read raises, a
TYPE_CHECKING-only name being the common case, the whole set is dropped, since
`__annotate__` is one function returning the whole dict and there is nothing
finer to keep (a FORWARDREF retry that kept the proxy-free siblings would
salvage more; not done). That drop is a debug line where the per-value drop
below warns, because a set that does not evaluate was not readable at runtime
in this process either (`typing.get_type_hints` raises the same), so nothing
the body does can depend on it, while a value that resolved but does not pickle
is a live object the body may read. Below 3.14 the read hands back the live
`__annotations__` dict, whose items are snapshotted since a probe runs user
`__reduce__` code that may write back onto the function, and the kept values go
into a fresh dict. Each value is probed with `_dumps_cleanly` and kept only if
it dumps, with the same warning a dropped `__dict__` entry gets
(`__annotations__['x']`), so the example above reloads with
`{"y": int, "return": int}` and runs. A failing key is dropped rather than kept
with a sentinel as the guard pickler does: this function is CALLED after load,
and a sentinel where the body expects a type is a wrong object, while a missing
key is the `KeyError` the warning predicts. The kept set is memoized for the
real dump like the attributes. Two `<locals>` functions annotated with each
other form an annotation cycle, which the probe's in-flight guard handles.

Test Plan:

```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_aot_compile.py -k annotation
```

The write-back test has an annotation value whose `__reduce__` adds a key to
the function's `__annotations__` mid-walk and checks the dump succeeds; a live
iteration raises "dictionary changed size during iteration", a hazard that is
pre-3.14 only since the 3.14 read returns a copy, and there the test checks no
more than that the write-back is harmless. The end-to-end test saves and
reloads a compiled function whose helper is annotated with a `<locals>` class
and an `int`, and checks the reloaded helper carries the `int` annotations. The
dropped-annotation test also checks the warning names
`inner.__annotations__['x']`. The ForwardRef test is 3.14-only and pins the
resolve path through its debug log, since an empty annotation set alone is what
the previous commit produced too. A last test pins the limitation this does not
fix: the compiled function's OWN annotations ride on
`CompileArtifacts.signature`, which `serialize()` dumps whole, so a `<locals>`
class there still fails the save and the nested-helper prune does not reach it.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196691
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688
pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…196692)

`types.FunctionType(code, ...)` leaves `__type_params__` empty, so a helper
that was handed type params reloads without them. Carrying the tuple verbatim
is not an option for the common source of one:

```python
def outer():
    def inner[T](x: T) -> T:        # PEP 695: T is a function-scoped TypeVar
        return x
    return inner

>>> T = outer().__type_params__[0]
>>> T.__module__, T.__reduce__()
('typing', 'T')
>>> pickle.dumps(T)
PicklingError: Can't pickle T: it's not the same object as typing.T
```

A PEP 695 TypeVar pickles by name as `typing.<name>` and fails pickle's
identity check against it (or the lookup, for a name `typing` lacks). So the
tuple is carried when its elements pickle, and one element that will not dump
drops the whole tuple, since a generic cannot be rebuilt around a missing
parameter, with the same warning the other pruned slots get (a reloaded
generic is no longer generic, so the drop must be visible). The scan stops at
the first element that fails: every probe serializes the reachable graph into a
throwaway buffer, and only the one element the warning names is used. Ordinary functions
carry `()`, which dumps and is kept. A TypeVar the body itself references sits
in a closure cell, which is never pruned, so that shape still fails the dump
(the comment says so). Nothing aborted before this commit; the previous commits
passed `type_params=None`, so the tuple was simply not carried. In practice a generic's params survive only
when the user hands the TypeVar over in `external_data` (the probe pickler
shares it, so the element is written by reference) or assigns a module-level
TypeVar by hand; the drop itself is silent, as `()` is what `FunctionType`
gives anyway.

Test Plan:

```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_aot_compile.py -k test_pickler_keeps_picklable_type_params -k test_pickler_keeps_pep695_type_params_given_as_external_data -k test_pickler_drops_unpicklable_type_params -k test_pickler_warns_once_for_a_generic_reduced_twice
```

The drop is memoized for the real dump like the other slots, so a generic
that closes over itself warns once, and it stays quiet below 3.12 where the
tuple lives in `__dict__` and the attributes pass has already reported it; the
warning names the element that failed, so an unmarked `nn.Module` among the
params gets the external-data reason. The external-data test is the realistic kept case: a PEP 695 generic (defined
via exec so the file still parses below 3.12) whose `T` is passed in
`external_data` reloads with its type params and annotations intact; the
previous commit gives `()`. The manual test assigns a module-level `TypeVar`
and checks the same object comes back; it is not version-gated, since below
3.12 the slot lives in `__dict__` and the reducer's write has to win over the
carried dict, and on 3.12+ it asserts the slot does not leak into `__dict__`.
The dropped test checks the generic without external data reloads with `()`
and runs, and that the drop is warned about, where a verbatim tuple fails the
dump. The warns-once test pins the memo itself: a generic whose body
references itself is reduced twice (the closure is a reduce ARGUMENT, so the
second pass finds it not yet memoized), and exactly one warning must name
`__type_params__`; with the memo deleted it warns twice and the single-line
unpack raises. That shape also pins where `T` lands, since the self-reference
is the only closure cell -- PEP 695 compiles `T` into the hidden type-params
scope, so it is not a freevar of the body, which is what a `T` the body reads
would change. The exec-built generic is a module-level helper the tests share,
taking the body text so each can pick its own.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196692
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691
pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…ickle a value (#196693)

A value the artifact carries unpruned fails the dump with pickle's own error
and nothing pointing at the fix:

```python
def outer():
    lock = threading.Lock()

    def fn(x):
        def unused():
            return lock             # makes `lock` a closure cell of fn
        return x + 1

    return fn

compiled = torch.compile(outer(), fullgraph=True).aot_compile(((x,), {}))
compiled.save_compiled_function(path)
# TypeError: cannot pickle '_thread.lock' object
```

`serialize()` now catches that, appends guidance naming the common sources and
the escape hatch, and re-raises the SAME exception object:

```
TypeError: cannot pickle '_thread.lock' object
Some value reached by the artifact is not picklable (a closure cell, a
default/kwdefault, or the top-level function's own signature annotations,
which ride unpruned, are the common sources). Mark it as external data by
using `external_data={'key': ...}`.
```

The same instance is re-raised because callers and tests match on the original
text, and a TypeError subclass from a user `__reduce__` may take a non-message
constructor, so rebuilding `type(e)(msg)` could swap the real error for a
constructor failure (a subclass whose `__str__` ignores `args` still renders
without the guidance; `add_note()` would cover it but is 3.11+). `e.args[0]`
becomes the combined string and the tail is kept for a consumer that reads it.
The prefix is `str(e.args[0])`, not `str(e)`: for a two-argument exception
`str(e)` is `repr(args)`, which would embed the tail twice. `str()` of the
result is still a tuple repr in that case, the price of keeping the tail;
`.name` and `.obj` on an AttributeError are untouched. Unmarked `nn.Module`s
recorded before the failure are named in the same message by class name (a
Module repr renders the whole child tree and runs user code inside the
handler), so the user does not fix the lock only to hit the module error on
the next attempt; the external-data hint is one shared constant for both
paths, and a re-raised singleton that already carries it is not decorated
twice. `AttributeError` is in the tuple
because the C `_pickle` accelerator raises a bare `AttributeError: Can't get
local object ...` for a `<locals>` class (the pure-Python pickler and 3.14+
raise PicklingError). `RecursionError` is in it because a deep-but-finite
value in an unpruned slot overflows the C pickler, and external data is its
fix too. The backend's own pickling of `compiled_fn` stays OUTSIDE the handler,
which a comment now records: `external_data` cannot fix an unpicklable graph
module, so dressing that failure up with this guidance would misdirect. One
gap the guidance cannot close is noted where it lives: nothing threads
`external_data` through `AOTCompiledModel.serialize` or
`_save_aot_compiled_module`, so on a module save the advice is only actionable
by saving the offending function on its own. Threading a parameter through both
is a follow-up, not this commit.

Test Plan:

```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_aot_compile.py -k test_save_guidance -k test_save_fails_loudly_on_a_helpers_unpicklable_kwdefault
```

All five drive `save_compiled_function`. The lock, `<locals>`-class-default
(asserting the offender `Cfg` is named, not pickle's per-version wording) and
kwdefault tests assert the original message plus the guidance. The lock test
matches the join with a regex over a REAL newline, which is what a
single-argument exception renders and what a reintroduced `str(e)` prefix would
break (the tuple repr escapes it). The kwdefault test overlaps two pins that
predate this commit and its comment now says so, keeping it for the one axis
neither covers: the unprunable slot belongs to a nested helper reached through
the runtime env rather than to the compiled function itself. The
identity test raises a `TypeError` subclass with a two-argument constructor
from a `__reduce__` and checks the SAME instance comes out, guidance appended,
second argument intact and embedded once. The recorded-modules test closes
over an unmarked `Linear` and a lock, asserts the freevar order that makes the
module dump first, and checks the raised message names both the lock and the
module's class. The overflow test puts a value whose `__reduce__` returns a
fresh instance in a default, so the C pickler recurses without bound on every
version (3.14's no longer overflows on a merely deep list), and checks the
`RecursionError` carries the guidance and the handler itself does not overflow.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196693
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692
pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…196756)

Follow-up to #196505, from its review. A resume frame whose backend artifact
is missing when the package is saved is written with `bypassed=True` by
`PrecompileCacheEntry.from_cache_entry`, and `install()` skips it, so the
next process traces that frame fresh:

```python
def fn(x):
    y = x.sin()
    torch._dynamo.graph_break()          # a resume frame with its own backend
    return x.sin() + y

torch.compile(fn)(x)
del PrecompileContext._backend_artifacts_by_key[resume_backend_id]
save()                                   # resume entry written bypassed
# next process
torch.compile(fn)(x)                     # resume frame traced fresh
save()
```

That fresh compile appended its guarded code to the stale one the reload had
deserialized, cleared the flag, and re-registered a backend id next to the
missing one still listed first. The next save found the missing id again,
re-poisoned the entry and wrote the bigger one back over the same path, so the
entry never became installable and never stopped growing:

```
base:    guarded_codes 1 -> 1  backend_ids 1 -> 7   (33 KB -> 34 KB over six cycles)
#196505: guarded_codes 1 -> 7  backend_ids 1 -> 7   (33 KB -> 64 KB)
```

(Byte sizes from the reviewer's environment; the counts reproduce exactly.)

The backend-id half predates #196505 (`OutputGraph` registers the id whether
or not the entry is bypassed); the guarded-code half is new there, since
`add_guarded_code` now appends and clears the flag on such an entry.

`CompilePackage.initialize` now loads a bypassed entry without its guarded
codes and backend ids: the package's own map gets a `dataclasses.replace` copy,
and the caller's entry is untouched, since a store may hand out the object it
holds (`InMemoryDynamoStore` does); the containers the fresh compile writes to
(`import_sources`, `function_names`) are detached in the copy as well, since
`dataclasses.replace` is shallow. `install()` skips such an entry entirely,
so nothing on it was installable, every variant of that code object included
(`from_cache_entry` flags the whole entry on the first missing artifact); the
fresh compile's record is the whole entry and the next save writes an
installable one, so the third process hits without compiling anything. The reset lives on the load side rather than in the save-time writer
because for an entry already on disk in the stale state the writer cannot tell
the missing id from the fresh compile's id listed beside it, so a writer-side
clear would discard the fresh code too and converge one save later. The
better endpoint, not taken here, is a per-guarded-code prune at write time
(drop only the guarded codes whose bytecode names the missing backend), which
would keep a multi-variant entry installable and never write the stale bytes;
tracked in #196773.
The entry docstring says what the writer and the loader each do.

Two test cleanups from the same review: `ConfigThatCannotPickle` says why it
raises AttributeError specifically (the one exception the bypass mapped before
#196470 widened it), and the earlier-variant test pins that only the bypassed
inputs compiled after the reload. It counts `counters["frames"]["total"]`
rather than the `FRAME_COUNTER` bracket the file's other caching_precompile
tests use: `reset()` zeroes `FRAME_COUNTER` and installing a precompiled entry
consumes a compile id, so a `+ 1` there holds only by cancellation.

Test Plan:

```
python test/dynamo/test_package.py
python test/dynamo/test_package.py -k test_a_poisoned_entry_is_reset_on_load_instead_of_growing -k test_bypassed_guards_keep_the_frames_earlier_variant
```

The new test runs the cycle above through `PrecompileContext` and
`DynamoCache`: after the second save the resume entry has one guarded code and
one backend id and is not bypassed (on the previous commit it has two of each
and is bypassed again), and a third load serves both frames with
`counters["frames"]["total"]` unchanged under `fail_on_recompile`. It also
builds a `CompilePackage` from a loaded entry and checks the entry it was
given still holds its guarded code while the package's `cache_entry()` does
not.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196756
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693
pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…y, pin the dict-served case (#196764)

Follow-up to the reviews of #196473 and #196474.

`_reduce_bound_method` read `func.__name__` before its `try`. `getattr` with a
default swallows only AttributeError, and `__func__` is an arbitrary callable
by the reducer's own premise, so a proxy that raises anything else escaped the
reducer while the receiver-side probe two lines down was already guarded:

```python
class ProxyFunc:
    def __getattr__(self, name):
        raise RuntimeError(f"proxy has no {name}")

pickler._reduce_bound_method(types.MethodType(ProxyFunc(), Plain()))
# before: RuntimeError: proxy has no __name__
# now:    (_unpickle_bound_method, (ProxyFunc(), Plain()))
```

The read moves inside the `try`, after the `__getattr__` gate (which takes the
pair without probing `func` at all), where `explicit` is already built for the
`except` to return.

The `__dict__` half of the per-instance condition had no test: `SlottedByName`
has no instance dict, so the slot test lands on the `getattr_static` half, and
ablating the `__dict__` clause left the suite green while the shape it exists
for broke at load:

```python
obj = Plain()
obj.global_add = types.MethodType(global_add, obj)
# with the clause:    loads back as MethodType(global_add, Plain)
# without the clause: AttributeError: 'Plain' object has no attribute 'global_add'
```

Pinned now, and the comment says which receivers reach that clause: one that
HAS an instance dict, which a pure-slots receiver does not (a slotted subclass
of a non-slotted base has both, and either clause gives the same answer), and a
class defining `__getattr__` (every nn.Module) takes the pair before it either
way.

Two tests from #196474 were not pinning what they said. The shared-closure-cell
test used a `<locals>` pair, whose branch returns before the `guard_tree_values`
gate, so the dict it built was inert and the test passed on the parent; it now
uses two module-level `functools.wraps` wrappers sharing one cell, which only
the gate carries. The module-method test's comment described the `<locals>`
rebuild bug from the commit that fixed it; the comment is gone and the test
asserts the rebuilt function's `__name__` is `forward`, which is a record of
what the rebuild carries rather than a regression guard (the name path is
pinned by `test_rebuilt_locals_function_keeps_its_name`), so the comment now
points at the call as the assertion that catches the placeholder.

Type nits from the same reviews: `object` instead of `Any` for the resolution
walk and both rebuilt scopes; the bound-method reducer returns its real shape,
`tuple[Callable[..., Any], tuple[Any, ...]] | None`; the state tuple stays
`Any`, since its elements are assigned to typed function slots and the checker
rejects `object` there.

One #196474 comment is not a code change here: at that commit the by-value
payload carried every closure cell and default unconditionally, so a `wraps`
wrapper capturing a lock no guard read failed the dump. #196476, two commits
above it, prunes each cell and default through the same `guard_tree_values`
test, and that is where the prune lives in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k bound_method -k shared_closure_cell
python test/dynamo/test_aot_compile.py -k Pickler
```

The proxy test fails on the previous commit with the RuntimeError above. Its
second case pins the ORDERING rather than the `try`: the receiver is a proxy
whose class defines `__getattr__`, so the gate takes the pair and the name is
never asked for, which the fixture records; moving the read back above the gate
fails that assertion while the rest of the test stays green. The
monkeypatched-method test fails against the `__dict__` clause ablated. The
shared-cell test fails when the fqn-mismatched pair is not in
`guard_tree_values` (both prune to `_Missing`), which the old `<locals>` pair
could not show.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196764
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693, #196756
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1154/head branch November 18, 2026 01:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants