Skip to content

[dynamo] Graph-break instead of asserting when an import alias is already bound - #197255

Closed
bobrenjc93 wants to merge 33 commits into
gh/bobrenjc93/1211/basefrom
gh/bobrenjc93/1211/head
Closed

bobrenjc93 wants to merge 33 commits into
gh/bobrenjc93/1211/basefrom
gh/bobrenjc93/1211/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. import_source mints an __import_<mangled> alias for every
module a trace reads through and writes it into the traced frame's real
globals, and when that slot already held something other than the object just
resolved, the parent raised a bare AssertionError that restated the condition
and named nothing, with no eager fallback because AssertionError is in
_compile's pass-through tuple. An occupied alias slot is a state of the
user's globals, not an invariant of the tracer, so it is now a graph break
(Import alias already bound, GB3718) that names the offender by type and,
for a module, by its __name__, read out of the instance dict so no PEP 562
__getattr__ or lazy-module __getattribute__ runs inside the trace. Two
moves go with it: the alias is recorded for the CompilePackage entry only
once the check has passed, because a graph break no longer kills the compile
and a record written first would ship in the saved entry and be bound by
install() over the very global the check refused; and IMPORT_NAME's
module-type check now runs before import_source, so a non-module
sys.modules entry is never written into the traced globals. The check itself
is still the parent's identity test, so a same-named module object in the slot
is still refused here; accepting it is #196896, directly above, and deciding
which module stays in the slot is #197046 above that. This is the bottom of
that three-commit split of #196896, made for the review budget.

What the parent did

# parent, in import_source
value = _import_module(module_name)
alias = f"__import_{module_name.replace('.', '_dot_')}"
if self.package is not None:
    self.package.add_import_source(alias, module_name)      # recorded BEFORE the check
self.output.import_sources[alias] = module_name
if not (alias not in f_globals or f_globals[alias] is value):
    raise AssertionError("expected alias not in f_globals or f_globals[alias] is value to be true")
f_globals[alias] = value

Nothing removes that binding, so it outlives the compile that minted it, and
any later compile of any function in the same module re-enters with the alias
already bound. A writer other than this method can have bound it, too:
CompilePackage.install binds each recorded alias to
importlib.import_module(module_name) in the traced module's globals, and
AOTCompiledFunction._seed_guard_scope does the same into a scope its own
comment describes as possibly a user module's live namespace.

def fn(x):
    import mypkg.helper as h
    return x + h.VALUE

fn.__globals__["__import_mypkg_dot_helper"] = "not a module"      # a user global in the alias slot
torch.compile(fn, backend="eager")(x)
# parent: AssertionError: expected alias not in f_globals or f_globals[alias] is value to be true
#         -- restates the condition, names nothing, and kills the call with no eager fallback

A graph break that names the offender

if alias in f_globals and f_globals[alias] is not value:          # the parent's identity test, unchanged
    bound = f_globals[alias]
    bound_name = (object.__getattribute__(bound, "__dict__").get("__name__")
                  if isinstance(bound, types.ModuleType) else None)
    offender = type(bound).__name__ + (f" named {bound_name}" if bound_name is not None else "")
    unimplemented(gb_type="Import alias already bound",
                  context=f"{alias} for {module_name}: {offender}", ...)
fn.__globals__[alias] = "not a module"
# Unsupported: ... alias __import_mypkg_dot_helper for mypkg.helper ... already bound to a str ...
fn.__globals__[alias] = types.ModuleType("other.name")
# Unsupported: ... bound to a module named other.name ...        <- two module names mangling onto one alias
fn.__globals__[alias] = <module with no __name__ and a raising PEP 562 __getattr__>
# Unsupported: ... already bound to a module in the globals ...  <- __getattr__ never ran

A slot that is empty or already holds the resolved object passes, and anything
else (a non-module, a module of another name, and on this commit still a
module object of the right name) is refused; accepting the same-named module is
#196896. The offender is named by type, plus its __name__ when it is a module
so that the message names the colliding module, and never repr'd, since
__repr__ is user code too. That __name__ is read out of the instance dict
through object.__getattribute__(bound, "__dict__"): a module's PEP 562
__getattr__ and a class-level __getattribute__ (importlib.util._LazyModule's
imports the module on any attribute read, __dict__ included) are user code
that must not run inside a trace on the way to a graph break.

IMPORT_NAME has no break_graph_if_unsupported, so the Unsupported lands
in step(): the frame is skipped outright unless an empty-stack checkpoint
(two or more ops) precedes the import, and compiled up to that checkpoint
otherwise. Either outcome is cached on the code object and nothing guards the
alias, so fixing the global afterwards does not retrace the frame until
torch._dynamo.reset():

cnt = CompileCounter(); skipped = torch.compile(fn, backend=cnt)   # no fullgraph: the import is the frame's first work
skipped(x); cnt.frame_count            # 0: frame skipped, alias left alone
del fn.__globals__[alias]
skipped(x); cnt.frame_count            # still 0: the outcome is cached and nothing guards the global
torch._dynamo.reset()
skipped(x); cnt.frame_count            # 1, and fn.__globals__[alias] is the module

The registry entry's third hint says so, and its second names the case a
module of another name in the slot is: two module names mangling onto one
alias (a.b and a_dot_b both alias as __import_a_dot_b).

Record the alias only after the check passes

# now
if alias in f_globals and f_globals[alias] is not value:
    unimplemented(...)                                              # may graph-break here
if self.package is not None:
    self.package.add_import_source(alias, module_name)              # recorded only past the check
self.output.import_sources[alias] = module_name
f_globals[alias] = value

The check can now fail recoverably, and the package entry is entered outside
the trace that fails (code_context wraps the whole compile, and a frame that
skips or restarts leaves its entry in _codes), so a record written before the
check would ship in the saved entry, and install() would then bind the alias
to importlib.import_module(module_name) over the very global the check
refused to touch: _install_global writes unconditionally,
record_only_if_new gates only the uninstall bookkeeping.

def fn(x):
    y = x + 1; y = y * 2                    # two ops before the import: a checkpoint to compile up to
    import mypkg.helper as h
    return y + h.VALUE

fn.__globals__[alias] = "not a module"
package = CompilePackage(fn); torch._dynamo.optimize(backend="eager", package=package)(fn)(x)
len(package._codes[fn.__code__].guarded_codes) == 1     # compiled up to the checkpoint, entry kept
store.save_package(package, path); pkg, backends = store.load_package(fn, path); pkg.install(backends)
fn.__globals__[alias]
# recorded before the check: the module, bound by install() over the str the trace refused
# now:                       still "not a module"; no entry names the alias

With the old AssertionError this was unreachable, since the compile died
before anything was serialized.

Hoist IMPORT_NAME's module-type check ahead of import_source

# IMPORT_NAME, now: before import_source binds the result into the traced frame's globals
if not isinstance(value, types.ModuleType):
    unimplemented(gb_type="Bad import result", context=typestr(value), ...)
...
source = self.import_source(module_name)
self.push(PythonModuleVariable(value, source=source))
sys.modules["mypkg.weird"] = object()           # sys.modules accepts anything; __import__ hands it back verbatim
torch.compile(fn, fullgraph=True)(x)            # Unsupported: Bad import result
alias in fn.__globals__                         # parent: True (bound BEFORE the push-time check broke)
                                                # now:    False
sys.modules["mypkg.weird"] = object()           # swap for another non-module and trace again
torch.compile(fn, fullgraph=True)(x)            # now: Bad import result again
                                                # parent: tripped the alias check on two nameless objects

On that path, the one caller resolving a name the traced bytecode chose, a
non-module sys.modules entry is never written into the traced globals. The
hoisted check is isinstance(value, types.ModuleType) alone: DummyModule
only ever arrives on the replay arm, where add_local_mod rejected non-modules
when the record was written, so that import goes, and the DummyModule import
with it. The other eight callers (nn_modules_globals_vt, codegen.py's three
sites, torch_function.py, ctx_manager.py, misc.py, functions.py) reach
import_source with no module-type test and pass torch's own and stdlib names
or a class's __module__; a non-module entry under one of those is still bound
verbatim there, unchanged by this commit, and get_globals_source_and_value
already has one, since _registered_module_for_globals returns a name only for
a types.ModuleType whose __dict__ is the frame's globals.

Behaviour changes against the parent

Each is pinned by a test below.

  • (a) An occupied alias slot that does not hold the resolved object is an
    Unsupported graph break where it was an AssertionError, skipped or
    compiled up to the checkpoint as above and cached until
    torch._dynamo.reset() (test_import_alias_taken_by_a_non_module_graph_breaks,
    test_import_alias_the_trace_refused_is_not_recorded_for_install).
  • (b) No package record is made for an alias the trace refused to bind
    (test_import_alias_the_trace_refused_is_not_recorded_for_install).
  • (c) IMPORT_NAME of a non-module sys.modules entry no longer writes
    the alias before breaking (test_import_alias_is_not_bound_to_a_non_module_import).

An empty slot is written as before, and the write is still into a live
namespace that nothing unwinds (there is no CleanupHook here, unlike
install_global_unsafe), so it outlives a trace that graph-breaks or restarts,
as does the write install() makes to this name; the comment at the write says
so. graph_break_registry.json gains the Import alias already bound entry
with one hint per case.

Order to review: import_source in torch/_dynamo/symbolic_convert.py (the
check, the unimplemented call, the record after it), then IMPORT_NAME's
hoisted check in the same file, then the three tests and the
_import_alias_getattr_boom helper in test/dynamo/test_package.py, then the
registry entry.

Test Plan:

python test/dynamo/test_package.py -k test_import_alias
python test/dynamo/test_package.py

Three tests, all red on the parent's torch/_dynamo/symbolic_convert.py
under this commit's test file (Ran 3 tests, FAILED (failures=5): the three
subtests of the first and the second on the old AssertionError, the third on
the alias the parent wrote). One plants a str, a module named other.name
and a nameless module (with a PEP 562 __getattr__ that raises) in the alias
slot in turn and pins the graph break's wording for each, then, with a
CompileCounter and no fullgraph, that frame_count stays 0 across the
refused call and a second call after the global is removed, and goes to 1 with
the alias bound only after torch._dynamo.reset(). One traces with a
CompilePackage while a str holds the alias -- two ops before the import, so
the trace restarts and compiles up to that checkpoint rather than skipping,
pinned by len(guarded_codes) == 1 -- saves, loads and installs, and pins that
no entry recorded the alias and the str is still there. One plants two
successive non-module sys.modules entries and pins that neither is bound and
that both graph-break as Bad import result.

python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks
python test/dynamo/test_package.py -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_is_not_bound_to_a_non_module_import

Each is load-bearing, measured on this tree by mutation (-k test_import_alias
after each): recording the alias above the check fails the refused case on
assertNotIn(alias, entry.import_sources); reading the bound object's name
with getattr(bound, "__name__", None) errors the nameless-module subtest with
RuntimeError: module __getattr__ ran inside a trace for __name__, the PEP
562 hook the fixture installs; dropping the named {bound_name} half of the
message fails the other.name subtest on its assertRaisesRegex; raising
AssertionError in place of unimplemented fails all three subtests and the
refused case on the exception type; un-hoisting the module check (the parent's
push-time isinstance restored) fails
test_import_alias_is_not_bound_to_a_non_module_import on the alias it wrote.
The two tests that plant a module under a fixed sys.modules name and resolve
it through import_source call _import_module.cache_clear() in finally,
next to the sys.modules pop: the memo outlives the entry, and on a
same-process re-execution (the default --reruns=2 of run_test.py) the
second run would resolve the first run's object; #196896's message carries the
measurement over all thirteen test_import_alias instances of the three
commits. The non-module case needs none, since the hoisted check graph-breaks
before import_source runs and the memo never sees its name. The whole file
at this commit: 81 tests, OK (skipped=40, expected failures=1).

They live in test_package.py rather than test_misc.py because the writer
that empirically reaches the collision path is CompilePackage.install, and
that file already owns the DiskDynamoStore save/load/install idiom and the
rest of the import_sources coverage.

lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py torch/_dynamo/graph_break_registry.json

FAQ: the hoisted Bad import result check guards one of the ten import_source call sites, but the description states its consequence for all of them.

Narrowed: the message scopes that sentence to IMPORT_NAME, the one caller resolving a name the traced bytecode chose, and says outright that the other eight bind a non-module entry under their names verbatim, as before this commit, while get_globals_source_and_value brings its own module-type test. Those names are torch's own and stdlib ones (codegen.py's three sites, functions.py, torch_function.py, nn_modules_globals_vt) or a class's __module__ (ctx_manager.py, misc.py); a non-module under one of those is a broken process, not a trace to save.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 [email protected]

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 added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 16, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 11 Pending, 3 Unrelated Failures

As of commit 578eb70 with merge base 51d4378 (image):

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

  • Correctness
    • The new alias in f_globals and f_globals[alias] is not value at symbolic_convert.py:2443 is the De Morgan equivalent of the parent's not (alias not in f_globals or f_globals[alias] is value) it replaces
    • graph_break_ok defaults to False, and only IMPORT_NAME passes True (:2588, :2590), so the nine other callers I grepped (codegen.py:781/792/848, ctx_manager.py:118, misc.py:1311, torch_function.py:220, functions.py:3005, symbolic_convert.py:2384/6515) keep an AssertionError
    • Moving the add_import_source/import_sources writes below the check (:2484-2488) is unobservable when the check passes, and on failure it stops install() binding an alias the trace refused
  • Preservation
    • The object.__getattribute__(bound, "__dict__").get("__name__") read plus the type(name) is str / type(owner) is str guards (:2452-2458) keep PEP 562 __getattr__ and non-string __name__ values out of the message path
  • Testing
    • Six new tests in test/dynamo/test_package.py:1081-1333 cover the IMPORT_NAME graph break, its caching until torch._dynamo.reset(), and the hard error at the codegen, torch_package, and inlined-callee arms
    • test_import_alias_the_trace_refused_is_not_recorded_for_install pins the record ordering through save_package/load_package/install, asserting the planted global survives
  • Scope
    • Three files: symbolic_convert.py, the new unique GB3718 entry in graph_break_registry.json:1158-1169 whose strings match the unimplemented() call verbatim, and the tests; no public API, workflow, or policy-doc change

reason: clean
Reviewed commit: 578eb70

Inference job

🐛 Report a wrong verdict

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

UNSTABLE - The following jobs are 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 16, 2026
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…eady bound

Split from `[dynamo] Rebind a stale module alias instead of failing the trace`
(#196896) for the review budget, as the bottom of three: this commit turns the
alias collision into a graph break, records the alias only once the check has
passed, and hoists `IMPORT_NAME`'s module-type check ahead of `import_source`;
#196896, directly above, then accepts a same-named module in the slot, and
`[dynamo] Replace a same-named import alias binding only when the resolved
module is live` (#<sibling>) above that decides which module stays in it.

`import_source` mints `__import_<mangled>`, resolves the module it names and
writes it into `self.output.global_scope`, which is the traced frame's real
globals -- a live module `__dict__`. Nothing removes that binding, so it
outlives the compile that minted it, and any later compile of any function in
the same module re-enters with the alias already bound -- and a writer other
than this method can have bound it: `CompilePackage.install` binds each
recorded alias to `importlib.import_module(module_name)` in the traced module's
globals, and `AOTCompiledFunction._seed_guard_scope` does the same into a scope
its own comment describes as possibly a user module's live namespace. When the
slot held something other than the object this method resolved, the parent
raised a hard `AssertionError` that restated the condition and named nothing,
and `AssertionError` is in `_compile`'s pass-through tuple, so the call had no
eager fallback.

An alias name holding something else is a state of the user's globals, not an
invariant of the tracer, so it is now reported through the graph break
registry with `unimplemented` (gb_type `Import alias already bound`, GB3718).
The check itself is the parent's identity test: a slot that is empty or already
holds the resolved object passes, and anything else -- a non-module, a module
of another name, and on this commit still a module object of the right name --
is refused; accepting the same-named module is #196896. The offender is named
by type, plus its `__name__` when it is a module so that the message names the
colliding module, and never repr'd, since `__repr__` is user code too. That
`__name__` is read out of the instance dict through
`object.__getattribute__(bound, "__dict__")`: a module's PEP 562 `__getattr__`
and a class-level `__getattribute__` (`importlib.util._LazyModule`'s imports
the module on any attribute read, `__dict__` included) are user code that must
not run inside a trace on the way to a graph break. `IMPORT_NAME` has no
`break_graph_if_unsupported`, so the `Unsupported` lands in `step()`: the
frame is skipped outright unless an empty-stack checkpoint (two or more ops)
precedes the import, and compiled up to that checkpoint otherwise. Either
outcome is cached on the code object and nothing guards the alias, so fixing
the global afterwards does not retrace the frame until `torch._dynamo.reset()`;
the registry entry's third hint says so, and its second names the case a
module of another name in the slot is: two module names mangling onto one
alias (`a.b` and `a_dot_b` both alias as `__import_a_dot_b`).

Two moves go with the graph break, both about what happens before a refusal.
The alias is recorded for the `CompilePackage` entry and
`output.import_sources` only once the check has passed. The check can now fail
recoverably, and the package entry is entered outside the trace that fails --
`code_context` wraps the whole compile, and a frame that skips or restarts
leaves its entry in `_codes` -- so a record written before the check would ship
in the saved entry, and `install()` would then bind the alias to
`importlib.import_module(module_name)` over the very global the check refused
to touch: `_install_global` writes unconditionally, `record_only_if_new` gates
only the uninstall bookkeeping. With the old `AssertionError` this was
unreachable, since the compile died before anything was serialized. And the
module-type check that `IMPORT_NAME` ran on `__import__`'s result at push time
now runs before its `import_source` call, so on that path -- the one caller
resolving a name the traced bytecode chose -- a non-module `sys.modules` entry
is never written into the traced globals, and a second trace after the entry
is swapped for another non-module graph-breaks the same way (`Bad import
result`) instead of tripping the alias check on two nameless objects. The
hoisted check is `isinstance(value, types.ModuleType)` alone: `DummyModule`
only ever arrives on the replay arm, where `add_local_mod` rejected
non-modules when the record was written, so that import goes, and the
`DummyModule` import with it. The other eight callers (`nn_modules_globals_vt`,
`codegen.py`'s three sites, `torch_function.py`, `ctx_manager.py`, `misc.py`,
`functions.py`) reach `import_source` with no module-type test and pass
torch's own and stdlib names or a class's `__module__`; a non-module entry
under one of those is still bound verbatim there, unchanged by this commit,
and `get_globals_source_and_value` already has one, since
`_registered_module_for_globals` returns a name only for a `types.ModuleType`
whose `__dict__` is the frame's globals.

Behaviour changes against the parent, each pinned by a test below. (a) An
occupied alias slot that does not hold the resolved object is an `Unsupported`
graph break where it was an `AssertionError`, skipped or compiled up to the
checkpoint as above and cached until `torch._dynamo.reset()`
(`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`). (b) No
package record is made for an alias the trace refused to bind
(`test_import_alias_the_trace_refused_is_not_recorded_for_install`). (c)
`IMPORT_NAME` of a non-module `sys.modules` entry no longer writes the alias
before breaking (`test_import_alias_is_not_bound_to_a_non_module_import`). An
empty slot is written as before, and the write is still into a live namespace
that nothing unwinds -- there is no `CleanupHook` here, unlike
`install_global_unsafe` -- so it outlives a trace that graph-breaks or
restarts, as does the write `install()` makes to this name; the comment at the
write says so. `graph_break_registry.json` gains the `Import alias already
bound` entry with one hint per case.

Order to review: `import_source` in `torch/_dynamo/symbolic_convert.py` (the
check, the `unimplemented` call, the record after it), then `IMPORT_NAME`'s
hoisted check in the same file, then the three tests and the
`_import_alias_getattr_boom` helper in `test/dynamo/test_package.py`, then the
registry entry.

Test Plan:

```
python test/dynamo/test_package.py -k test_import_alias
python test/dynamo/test_package.py
```

Three tests, all red on the parent's `torch/_dynamo/symbolic_convert.py`
under this commit's test file (`Ran 3 tests`, `FAILED (failures=5)`: the three
subtests of the first and the second on the old `AssertionError`, the third on
the alias the parent wrote). One plants a `str`, a module named `other.name`
and a nameless module (with a PEP 562 `__getattr__` that raises) in the alias
slot in turn and pins the graph break's wording for each, then, with a
`CompileCounter` and no `fullgraph`, that `frame_count` stays 0 across the
refused call and a second call after the global is removed, and goes to 1 with
the alias bound only after `torch._dynamo.reset()`. One traces with a
`CompilePackage` while a `str` holds the alias -- two ops before the import, so
the trace restarts and compiles up to that checkpoint rather than skipping,
pinned by `len(guarded_codes) == 1` -- saves, loads and installs, and pins that
no entry recorded the alias and the `str` is still there. One plants two
successive non-module `sys.modules` entries and pins that neither is bound and
that both graph-break as `Bad import result`.

```
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks
python test/dynamo/test_package.py -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_is_not_bound_to_a_non_module_import
```

Each is load-bearing, measured on this tree by mutation (`-k test_import_alias`
after each): recording the alias above the check fails the refused case on
`assertNotIn(alias, entry.import_sources)`; reading the bound object's name
with `getattr(bound, "__name__", None)` errors the nameless-module subtest with
`RuntimeError: module __getattr__ ran inside a trace for __name__`, the PEP
562 hook the fixture installs; dropping the `named {bound_name}` half of the
message fails the `other.name` subtest on its `assertRaisesRegex`; raising
`AssertionError` in place of `unimplemented` fails all three subtests and the
refused case on the exception type; un-hoisting the module check (the parent's
push-time `isinstance` restored) fails
`test_import_alias_is_not_bound_to_a_non_module_import` on the alias it wrote.
The two tests that plant a module under a fixed `sys.modules` name and resolve
it through `import_source` call `_import_module.cache_clear()` in `finally`,
next to the `sys.modules` pop: the memo outlives the entry, and on a
same-process re-execution (the default `--reruns=2` of `run_test.py`) the
second run would resolve the first run's object; #196896's message carries the
measurement over all thirteen `test_import_alias` instances of the three
commits. The non-module case needs none, since the hoisted check graph-breaks
before `import_source` runs and the memo never sees its name. The whole file
at this commit: 81 tests, OK (skipped=40, expected failures=1).

They live in `test_package.py` rather than `test_misc.py` because the writer
that empirically reaches the collision path is `CompilePackage.install`, and
that file already owns the `DiskDynamoStore` save/load/install idiom and the
rest of the `import_sources` coverage.

```
lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py torch/_dynamo/graph_break_registry.json
```

> **FAQ: the hoisted `Bad import result` check guards one of the ten `import_source` call sites, but the description states its consequence for all of them.**
>
> Narrowed: the message scopes that sentence to `IMPORT_NAME`, the one caller resolving a name the traced bytecode chose, and says outright that the other eight bind a non-module entry under their names verbatim, as before this commit, while `get_globals_source_and_value` brings its own module-type test. Those names are torch's own and stdlib ones (`codegen.py`'s three sites, `functions.py`, `torch_function.py`, `nn_modules_globals_vt`) or a class's `__module__` (`ctx_manager.py`, `misc.py`); a non-module under one of those is a broken process, not a trace to save.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: f84a202
Pull-Request: #197255
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 8b3e78f2e708; items 1 to 4 are folded, item 5 is declined.

1. > Hint 3's "Without fullgraph=True" names one of the two modes that re-raise; error_on_graph_break=True without fullgraph also re-raises with nothing cached. [...] Change the qualifier to name both [...]

Fixed in 8b3e78f2e708 by naming neither: the hint now opens "When this graph break is not raised as an error, Dynamo caches this frame's outcome ...", which is the condition itself rather than the two flags that produce it, in the source and the GB3718 entry; the test's anchor on the hint follows the new wording and the commit message names both modes.

2. > The memo comment explains why graph_break_ok is excluded from the key with a reason that is one step short of the load-bearing one. [...] Say that the memo is written only past the check, since that is the invariant the exclusion rests on.

Fixed in 8b3e78f2e708: the comment now says a memo hit rules the taken slot out "because the memo is written only past that check (a refusal memoizes nothing)".

3. > import_source's docstring says "hard error" without naming which exception, and the two arms differ in more than severity. [...]

Fixed in 8b3e78f2e708: the docstring says "is an AssertionError unless graph_break_ok says the caller can graph break there".

4. > test_import_alias_taken_at_codegen_is_a_hard_error omits the _import_module.cache_clear() its four siblings all do. [...]

Fixed in 8b3e78f2e708: the finally clears it like the others.

5. > No test covers the graph break under error_on_graph_break=True, fullgraph=False. Follows from finding 1. [...]

Declined: with item 1 fixed the hint no longer names a mode, so there is no third-mode wording left to pin. The re-raise path is pinned under fullgraph=True (test_import_alias_taken_by_a_non_module_graph_breaks) and the caching under the default (test_import_alias_graph_break_is_cached_until_reset); an error_on_graph_break=True case would add a third arm to the matrix for a claim the text no longer makes.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

PR Review: #197255

No defects found this round — the four claimed fixes hold up under independent verification, and so do the memo rewrite and the DummyModule removal; what is left is that the memo mechanism this revision introduced is itself untested, and the comment block around it has grown to outweigh the code it annotates.

Full review

PR Review: #197255

Summary

Adds graph_break_ok to import_source, making an occupied alias slot a graph break for IMPORT_NAME and a hard AssertionError for the other nine callers; replaces @cache_method with an explicit per-translator memo keyed on the module name alone; defers the CompilePackage/import_sources record until past the check; and hoists IMPORT_NAME's module-type check ahead of import_source.

I verified the previous round's four fixes and the two structural rewrites by reading code rather than taking the reply's word, and all of them hold:

  • Hint 3 (item 1). The re-raise paths are as described: step() re-raises at symbolic_convert.py:1786 on self.one_graph or self.error_on_graph_break (:1768-1773), and ConvertFrame.__call__ re-raises at convert_frame.py:2415 gated on _box.error_on_graph_break — above soft_fail (:2434) and above the ConvertFrameReturn(skip_reason=...) at :2502 whose default FrameExecStrategy(SKIP, DEFAULT) with apply_to_code=True (types.py:80-84) is what persists the skip onto the code object's ExtraState until reset_code_caches. I also checked the qualifier for faithfulness in the other direction: config.suppress_errors cannot produce a third outcome (an Unsupported is always soft_fail, so :2476 never fires), and the only other re-raise path, is_tracing_resume_prologue -> ResumePrologueTracingError (:2101, re-raised unconditionally at convert_frame.py:2401), is also "raised as an error" and unreachable here. So "not raised as an error" picks out exactly the set of modes that cache, including error_on_graph_break=True without fullgraph. The GB3718 Hints entry matches the source verbatim.
  • The memo, checked harder than last round. _import_source_memo is initialized at symbolic_convert.py:5561, before _register_cells() at :5579, and nothing InstructionTranslatorBase.__init__ does before that line can reach import_source. OutputGraph is built as a caller-side argument expression (:5692), so it completes first; its one real reach-back into the not-yet-initialized root_tx — maybe_install_saved_tensors_hooks_subgraphs -> register_attr_or_module -> VariableTracker.build(self.current_tx, ...) (output_graph.py:990, :1629) — lands in SourcelessBuilder's GraphModule branch (builder.py:5434) and never resolves an import source. All 13 PyCodegen(...) sites pass an InstructionTranslatorBase. GlobalSource defines no __bool__/__len__ on itself, Source, or dataclass_with_cached_hash, so dict.get(...) is not None is equivalent to the dropped _cache_sentinel. And the re-run an inlining translator's empty memo causes is idempotent: _import_module is functools.cached so f_globals[alias] is value short-circuits the check, add_import_source is a dict assignment (package.py:1244), update_co_names guards on membership (output_graph.py:1572-1575), and f_globals[alias] = value is a direct write that bypasses install_global_unsafe's duplicate guard and its CleanupHook. Nothing in the tree pops or rebinds an __import_* alias mid-trace, and SpeculationRestartAnalysis rebuilds translator and OutputGraph together (convert_frame.py:1634-1668, symbolic_convert.py:5692), so memo and import_sources are discarded as a unit while the write into the user's live module dict persists — which is what the comment at :2482-2483 exists to handle.
  • The DummyModule removal. ___local_mod_* keys are written only through ExecutionRecorder.add_local_mod (replay_record.py:101-104), which type-checks, and get_record's _resolve_modules (:114-143) converts every ModuleRecord to a DummyModule. PythonModuleVariable touches only .__name__ (a DummyModule property, :49-51) and .__dict__ (a dataclass instance dict). convert_frame.replay() sets replay_record_enabled = False, so self.exec_recorder is None during replay and the unconditional add_local_mod at :2594-2596 never sees a DummyModule — the comment at :2565-2567 is accurate. Under replay_record_enabled a non-module sys.modules entry previously bound the alias and then died in add_local_mod's raise; it now reaches Bad import result with the alias unbound, which the commit message records as behaviour change (d).

Code Quality

1. The memo comment's perf rationale describes a cost the design already pays per inlined frame, not one the flag would newly introduce. torch/_dynamo/symbolic_convert.py:2415-2421

"... so keying on it would only run the body a second time for a name two callers both resolve."

The safety half is now correct (the memo is written only past the check, so a hit proves the slot passed for this exact value). The perf half reads as though excluding the flag keeps the body to one run per module. It does not: _import_source_memo is per-translator — InliningInstructionTranslator.__init__ takes output=parent.output (:6425) and package=parent.package (:6441) but reaches InstructionTranslatorBase.__init__ and so gets its own empty dict at :5561. So in a frame that inlines N functions each reading a global from the same module, the body runs up to N+1 times for that name regardless of the key. The flag would add at most one more. That is fine — I verified the re-run is idempotent — but the sentence is the only place a reader learns what the memo's scope is, and it implies a tighter scope than the code has. One clause ("per-translator, as the @cache_method cache also was") makes it checkable. Same note applies to :2416's "for the duration of this InstructionTranslator", which is true but reads as "per compile."

2. import_source is now ~26 lines of comment around ~35 lines of code, and two of the seven blocks restate the message they sit above. torch/_dynamo/symbolic_convert.py:2415-2491

The repo's own rule (CLAUDE.md: "Minimize comments; be concise; code should be self-explanatory... Comments should be useful, for example, comments that remind the reader about some global context that is non-obvious and can't be inferred locally") is the standard here, and three of the blocks clear it easily — the __dict__ note at :2450-2453 names a hazard invisible at the line it guards, the graph_break_ok rationale at :2460-2465 records a deferred design decision and the order-dependence it leaves, and the record-ordering note at :2482-2483 names an invariant spanning install(). Two do not:

  • :2457-2458 ("f_globals is the root frame's: an inlined callee's own module is not where the alias lives, so the message names the module whose it is") annotates a single .get("__name__") with a restatement of what the hint text three lines below already says in user-facing prose ("Remove or rename the global {alias} from the globals of {scope}").
  • :2447 ("Named by type, never repr'd: __repr__ is user code too") is the right length, but it sits above offender = type(bound).__name__, and the claim it makes is the same one the :2450-2453 block makes more precisely four lines later. Fold them.

Trimming those two brings the method back under a comment-per-two-lines-of-code ratio without losing anything a future reader needs.

3. Hint 3's "compiled up to the last checkpoint before the import" reads as an empty-stack checkpoint, which is not the shape the inlined case takes. torch/_dynamo/symbolic_convert.py:2479

I traced the inlined arm because the other two hints are explicitly about the root frame's globals. An IMPORT_NAME inside an inlined callee gets should_compile_partial_graph() == False (:6483, the default nested_graph_breaks=False), so step() takes the current_speculation is None branch and sets skip_frame = True (:1803); inline_call_ then clears it (:6340-6344) and the parent's decorated CALL catches the Unsupported at :1110, passing :1131/:1134 to restart. The end state matches the hint — root frame compiled and cached, callee separately skip-cached on re-entry, nothing guarding the alias — but the checkpoint it compiled to is the speculate() that break_graph_if_unsupported takes unconditionally at :1100 on the CALL, not an empty-stack checkpoint reached by step(). The hint's two alternatives ("skipped, or compiled up to the last checkpoint") do cover it, so this is a precision note rather than an inaccuracy; if the wording is touched again, "compiled up to the last resumable point" would cover both shapes without implying the empty-stack one.

Testing

4. Nothing covers the memo rewrite — the invariant its own comment names as load-bearing is unpinned. torch/_dynamo/symbolic_convert.py:2430-2431, :2490

The memo's correctness rests on one ordering: the write at :2490 is below the check at :2445, so a hit implies the check passed. I mutated both halves against the six new tests and neither is caught:

  • Move self._import_source_memo[module_name] = source above the check: every test still passes, because each refusal raises on its first resolution and no test resolves the same module twice in one translator after a refusal.
  • Re-add graph_break_ok to the key: every test still passes, since the only consequence is an extra idempotent body run.

So the decision the seven-line comment exists to justify is untested, and the author's stated mutation-testing methodology (-k test_import_alias after each mutation) would not flag either. This is the one gap I would want closed before landing: a test that resolves the same module through two callers in one compile — e.g. a frame that both imports module B and calls a function inlined from B — and asserts on len(tx._import_source_memo) or on the body running once, would pin the scope and the ordering together. It is also the case the :2460-2465 comment describes as order-dependent, so one fixture serves both.

5. The replay arm lost its only type guard and has no coverage under replay_record_enabled. torch/_dynamo/symbolic_convert.py:2544-2546, :2598-2599

The hoisted isinstance sits inside the else branch, so the replay arm's value now reaches self.push(PythonModuleVariable(value, source=source)) unchecked where the base's end-of-method check covered both arms. I confirmed this is not reachable from the recorder — add_local_mod type-checks on the way in and _resolve_modules converts to DummyModule — so the only way in is a user hand-planting a global literally named ___local_mod__{level}_{fromlist}_{name}, and the failure mode changes from Unsupported: Bad import result to an AttributeError: __name__ out of PythonModuleVariable.__init__ (variables/misc.py:2009), rewrapped as InternalTorchDynamoError at convert_frame.py:2243. Contrived, and I would not ask for a guard back. But there is no test in test/dynamo/ exercising the replay arm at all, which is why removing its guard is invisible to CI; the commit message's behaviour change (d) is likewise unpinned. Worth one line in the message saying the arm is uncovered, so the next person to touch it knows the check's absence is deliberate rather than tested.

6. test_import_alias_the_trace_refused_is_not_recorded_for_install couples its central assertion to restart internals. test/dynamo/test_package.py:1291-1310

assertEqual(len(package._codes[fn.__code__].guarded_codes), 1) is the test's proof that the frame compiled up to the checkpoint rather than skipping, which is what makes the package entry exist for the save/load/install half to be meaningful. That is the right thing to assert, but it reads as a fact about the PR when it is a fact about step()'s current_speculation/fail_and_restart_analysis path (symbolic_convert.py:1787-1817). A comment at that line naming what it is standing in for — "the frame restarted and compiled to the checkpoint; if this becomes 0 the rest of this test is vacuous" — keeps a future change to the restart bound from silently hollowing the test out rather than failing it.

Recommendation

Approve

No defects. Finding 4 is the one I would act on before landing — the memo rewrite is new implementation with no test, and both plausible mutations of its load-bearing ordering pass the current suite. Findings 1-3 and 6 are comment and annotation edits; 5 is a note for the commit message. The behaviour split, the deferred package record, the hoisted module-type check, the DummyModule removal, and hint 3's mode-free rewording all check out under independent verification.

GB3718 is unique in graph_break_registry.json and its Context/Explanation/Hints match the unimplemented() call verbatim, so GB_REGISTRY should be satisfied; gb_registry_linter.py compares sorted(hints) against the entry (:175, :330), and dynamic {} placeholders plus a fully custom hints list with no graph_break_hints.* constant are both conventional here. No non-ASCII was introduced in added lines (checked the diff). I could not run the test suite or lintrunner — there is no built torch and no .venv in this checkout — so this review is static analysis only.

View job run | branch gh/bobrenjc93/1211/head

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

PR Review: #197255

The four fixes from the last round hold up, but hint 3 still over-claims on the half of its own sentence that the last round's rewrite added: "compiled up to the last checkpoint" produces a guarded cache entry, not a skip, so an ordinary recompile retraces it and picks up the fix with no torch._dynamo.reset() at all.

Full review

PR Review: #197255

Summary

Adds graph_break_ok to import_source, making an occupied alias slot a graph break for IMPORT_NAME and a hard AssertionError for the other nine callers; replaces @cache_method with an explicit per-translator memo keyed on the module name alone; defers the CompilePackage/import_sources record until past the check; and hoists IMPORT_NAME's module-type check ahead of import_source.

I verified the last round's four claimed fixes and its one decline. The decline and three of the four fixes are correct; the fourth is still partly wrong (finding 1).

  • Memo (item 2). cache_method keyed on the whole positional args tuple, stored under _cache_method_<name> on the instance (torch/utils/_functools.py:87-98), and raises on kwargs (:91-92) — which is why the keyword call sites could not have kept the decorator. The new self._import_source_memo (symbolic_convert.py:5561) has identical lifetime and identical hit/miss: the sentinel cache_method used to distinguish absent-from-falsy is unnecessary because GlobalSource is a frozen dataclass with no __bool__/__len__ and the only stored value is a fresh GlobalSource. Excluding graph_break_ok from the key is unobservable — a hit implies the memo was written, which happens only below f_globals[alias] = value (:2487-2490), so the slot provably holds value; all four side effects are idempotent (update_co_names is membership-guarded at output_graph.py:1572). No rollback skew: import_sources appears in no copy_graphstate/restore_graphstate, and RestartAnalysis rebuilds translator and OutputGraph together (convert_frame.py:1639, symbolic_convert.py:5692).
  • Docstring (item 3) names graph_break_ok and its exception type; test anchor (item 4) is scoped to ...in the globals of {scope}.
  • Decline of item 5. Correct. scope is computed once at :2459, above the if not graph_break_ok split, so the fallback cannot differ between arms.

I also verified the DummyModule removal, the riskiest part of the hoist: DummyModule is constructed in exactly one place (replay_record.py:136), from a ModuleRecord that add_local_mod type-checked on the way in (:101-104), and ___local_mod_* keys are only ever written by the replay path. It is a plain dataclass, not a ModuleType subclass (:43-44), with __name__ as a property (:49-51) and a dataclass __dict__ that _resolve_modules populates — so the now-unconditional PythonModuleVariable push is safe (variables/misc.py:2006-2009, :2023-2039 need only __name__ and __dict__, neither type-checked).

Code Quality

1. Hint 3's reset() claim is true of the skipped outcome and false of the partially-compiled one — and the partially-compiled clause is the half this hint's own rewrite introduced. torch/_dynamo/symbolic_convert.py:2479

"When this graph break is not raised as an error, Dynamo caches this frame's outcome -- skipped, or compiled up to the last checkpoint before the import -- and nothing guards this global, so fixing it later does not retrace the frame until torch._dynamo.reset()."

The mode-agnostic conditional is now right, and right for a reason worth stating: step()'s re-raise condition is self.one_graph or self.error_on_graph_break or self.is_tracing_resume_prologue or getattr(e, "skip_frame", False) (:1768-1773) — four disjuncts — and ConvertFrame.__call__ gates on _box.error_on_graph_break alone (convert_frame.py:2409), which _optimize sets independently of fullgraph (eval_frame.py:1230-1234). Naming the condition rather than any flag is the only phrasing that covers all four. That part is settled.

But the two outcomes the sentence enumerates do not share the consequence it attributes to both:

  • Skipped (current_speculation is None at :1787, or no checkpoint): suppression returns ConvertFrameReturn(skip_reason=...) (convert_frame.py:2502), whose default is FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) with apply_to_code=True (types.py:74-86). Sticky on the code object, cleared only by reset()/reset_code_caches(). The hint is correct here, and this is what test_import_alias_graph_break_is_cached_until_reset pins.
  • Compiled up to the checkpoint (fail_and_restart_analysis at :1817 → step_graph_break at :1882): this path returns wrap_guarded_code(guarded_code) (convert_frame.py:1999), which is FrameExecStrategy(FrameAction.DEFAULT, FrameAction.DEFAULT) plus a guarded cache entry (types.py:89-93) — not a skip. Any ordinary guard failure (a new dtype, a new shape, anything already guarded) recompiles that frame, retraces from the top, re-runs import_source against a fresh _import_source_memo, and picks up the corrected global. No reset() involved.

So the hint tells a user whose frame was partially compiled — the outcome the PR's own test_import_alias_the_trace_refused_is_not_recorded_for_install constructs, with two ops before the import precisely to reach it — that only reset() will help, when in practice the next recompile will. That is the failure mode of the two prior rewrites of this hint repeating in a third place: the conditional got fixed, the consequence clause did not.

The adjacent clause "nothing guards this global" is accurate, and I checked it rather than assuming: nothing on the failing path installs a guard (the guard-installing writes at :2485-2490 are all past the check), and global guards are per-name DictGetItemGuardAccessors under GlobalsGuardAccessor (guards.py:1722, guards.cpp:5737, :6501) — a dict-tag mismatch only forces re-checking children, it never fails, so deleting or renaming the alias fails no guard. The reset() tail is what needs narrowing: scope it to the skipped case, or drop the enumeration and say the outcome is cached without asserting which remedy applies. Same edit in the GB3718 Hints entry.

Two smaller points on the same string: torch._dynamo.reset_code_caches() suffices, reset() is broader than needed; and the biconditional the conditional implies has one exotic counterexample — variables/functions.py:1465-1470 calls skip_code(self.get_code()) and sets e.skip_frame = True before re-raising, unconditionally of one_graph/error_on_graph_break, so an import collision inside an inlined generator's next() is raised as an error and leaves a sticky skip. Not worth wording around; noted so it is a known edge rather than a surprise.

Fix this →

2. On the hard-error arm, scope names the root frame's module, but the tracing-phase caller that reaches that arm is reached from another module — and unlike the graph break, that message has no user stack to fall back on. torch/_dynamo/symbolic_convert.py:2459, :2466-2470

The comment at :2457-2458 gets the mechanism right. For the graph-break arm it is sufficient: hint 1 turns scope into an instruction, and the Unsupported carries a real_stack — Unsupported.__init__ calls TracingContext.extract_stack() when none is passed (exc.py:311-316), and augment_exc_message appends "from user code:" from it (:818-821). The user gets both halves: which global, and which line.

The AssertionError arm gets only the first. A bare AssertionError has no real_stack, so get_real_stack returns None (exc.py:918-920), nothing is appended, and get_exc_message reports filename=None, lineno=None (:873-876). The previous round settled — correctly — that the type must stay AssertionError, because soft_fail at convert_frame.py:2434 excludes it and that is what keeps the codegen callers loud. But the consequence is that on get_globals_source_and_value (:6517) the user is told to edit a global in module A while the import that resolved module B lives in B, with nothing naming B beyond {module_name} — the module being resolved, not the one resolving it.

The PR's own test shows the gap: test_import_alias_taken_for_an_inlined_callees_module_is_a_hard_error (test/dynamo/test_package.py:1247-1279) asserts exactly ...in the globals of {fn.__globals__['__name__']} — the root module — for a collision triggered by a LOAD_GLOBAL inside helper, which lives in the planted module. In the test both are findable because the test wrote them. In a real tree, "remove __import_pkg_b from pkg_a" with no line number leaves the user hunting for which of pkg_a's inlined callees resolved pkg_b. self.f_globals.get("__name__") is available at the call site and is that module; adding it to the AssertionError only costs one f-string.

3. The hoist has a fourth behavior change the description does not list, on the one path where the old code hard-errored instead of graph-breaking. torch/_dynamo/symbolic_convert.py:2563-2576

The description enumerates (a), (b), (c). There is a fourth, visible only under config.replay_record_enabled (TORCH_COMPILE_REPLAY_RECORD=1, symbolic_convert.py:5582-5589): the check now runs above self.exec_recorder.add_local_mod(recorded_name, value) (:2594-2596), and add_local_mod raises on a non-module (replay_record.py:101-104). On base the order was import_source → add_local_mod → type check, so a non-module sys.modules entry hit that AssertionError before reaching Bad import result; now it graph-breaks cleanly. That is an improvement, it is the only one of the four no test can catch (the suite does not run with replay recording on), and it is the case the PR's rationale most directly covers.

Separately, resolve_name can raise ImportError("attempted relative import beyond top-level package") (:2501) outside the except ImportError at :2555, and calc_package can log.warning (:2524); both are now skipped for a non-module value where base reached them. Neither mutates state, so not a defect — but if the description enumerates what the hoist changes, the skipped hard ImportError belongs in the same sentence.

4. pyrefly: ignore [bad-argument-type] on the final push is probably stale. torch/_dynamo/symbolic_convert.py:2598

On base, value was narrowed to ModuleType | DummyModule by the deleted isinstance, so the DummyModule arm genuinely violated PythonModuleVariable.__init__(value: types.ModuleType). Now the narrowing is gone: pyrefly sees Any from self.f_globals: dict[str, Any] joined with typeshed's __import__ -> ModuleType, and DummyModule is not visible at that line. unbound-name is still needed. pyrefly.toml:138 sets permissive-ignores = true and the PYREFLY lintrunner entry does not pass --remove-unused-ignores, so a leftover will not fail CI — worth one lintrunner -a --take PYREFLY before dropping it rather than leaving a suppression that suppresses nothing.

Testing

5. Nothing pins the partially-compiled outcome's cache behavior, which is why finding 1 survived a suite measured by mutation. test_import_alias_graph_break_is_cached_until_reset (test/dynamo/test_package.py:1131-1168) covers the skipped arm and asserts the reset() requirement directly. test_import_alias_the_trace_refused_is_not_recorded_for_install (:1281) constructs the partially-compiled arm — two ops before the import, len(guarded_codes) == 1 — but asserts only the package record, never what a subsequent call does. Since hint 3 makes a claim about both arms, the one test that reaches the second arm should assert it: after the refused compile, fix the global and trigger an ordinary recompile (e.g. a differently-shaped input), then assert the frame retraces and binds the alias without reset(). That is the assertion that would have caught finding 1.

6. test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error cleans up the registry entry but not the module keeping it alive. test/dynamo/test_package.py:1216-1245

The finally pops the mangled name from _package_imported_modules (:1244), which addresses the last round's finding. But that dict is a WeakValueDictionary (package_importer.py:731) and packaged is captured by the closure fn, itself referenced from the test frame — so the explicit pop is doing all the work. That matters more than a normal leak: GuardBuilder.__init__ iterates the whole registry and writes every mangled name into both self.scope and self.scope["__builtins__"] for every guard build in the process (guards.py:1378-1386), and _registered_module_for_globals consults the same dict (symbolic_convert.py:276-279). import_module also raises on a duplicate name (package_importer.py:390-393). Adding del packaged beside the pop makes the lifetime explicit rather than leaving it to closure liveness.

Recommendation

Request Changes

Finding 1 is a two-line fix (source plus registry, plus the test's anchor string) but it is user-facing text that is false for the partially-compiled outcome — and that outcome is the one the PR deliberately constructs a test for. It is also the third round on this same hint, which argues for finding 5: assert the behavior rather than re-reading the sentence. Finding 2 is one f-string on a message that lost its user stack to a type choice that is otherwise correct. Findings 3, 4 and 6 are small.

The behavior split, the memo rewrite, the deferred package record, the hoisted module-type check, and the DummyModule removal all check out under independent verification, and the previous round's decline plus three of its four fixes are correct.

GB3718 is unique in graph_break_registry.json (as is the Bad import result gb_type it reuses) and its Context/Explanation/Hints match the unimplemented() call verbatim. A fully custom hints list with no graph_break_hints.* constant is conventional in this file. No non-ASCII in added lines (checked). I could not run the test suite, lintrunner, or the GB_REGISTRY adapter — no built torch in this checkout and no execution permission — so this review is static analysis only.

View job run | branch gh/bobrenjc93/1211/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

The round-7 review of this PR timed out twice at the 60-minute ceiling (the diff had not changed in size since the six passes that finished), so per the review protocol it is split: the hoisted IMPORT_NAME module-type check is now #197745 and the explicit _import_source_memo dict is #197746, both directly below; this PR keeps the graph_break_ok split, the record-after-check ordering, the GB3718 registry entry and their tests. The combined tree is byte-identical to the previous head 8b3e78f2e708, and the round-6 dispositions above still describe it. Current head 475308d36913.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 54m 18s —— View job


PR Review: #197255

The round-7 split checks out — the tree is byte-identical to 8b3e78f2e708 — but hint 3's reset() claim is false for the second of the two outcomes it enumerates, and that outcome is the one the PR's own ..._is_not_recorded_for_install test deliberately constructs.

Full review

PR Review: #197255

Summary

After the split, the live diff is the graph_break_ok parameter on import_source (graph break for IMPORT_NAME, AssertionError for the other nine callers), the deferred CompilePackage/import_sources record, the GB3718 registry entry, and six tests. I confirmed the split claim rather than taking the comment's word: git diff 8b3e78f2e708 HEAD is empty, and the hoisted module-type check plus _import_source_memo now appear as base context in git diff origin/gh/bobrenjc93/1211/base...HEAD, so the round-6 dispositions do describe this tree. The memo and DummyModule verifications from rounds 6-7 therefore still stand and I did not redo them.

Code Quality

1. Hint 3 asserts the reset() requirement for both outcomes it enumerates; it holds for only one — and the other is the arm the PR tests. torch/_dynamo/symbolic_convert.py:2479

"... Dynamo caches this frame's outcome -- skipped, or compiled up to the last checkpoint before the import -- and nothing guards this global, so fixing it later does not retrace the frame until torch._dynamo.reset()."

The mode-agnostic opener ("When this graph break is not raised as an error") is right, and for the skipped arm the rest is right too: step() sets e.skip_frame = True only on the empty-checkpoint branch (:1803), and suppression returns ConvertFrameReturn(skip_reason=...) whose default is FrameExecStrategy(SKIP, DEFAULT) with apply_to_code=True (types.py:80-84) — sticky on the code object, cleared only by reset()/reset_code_caches(). That is what test_import_alias_graph_break_is_cached_until_reset pins.

The partially-compiled arm does not behave that way. With a checkpoint present, step() falls through to fail_and_restart_analysis (:1817) without setting skip_frame; the restarted pass reaches step_graph_break, and for a root frame the rest of the function is emitted inline into the same output code object (:2077-2083, create_jump_absolute(continue_inst), *self.instructions) — skip_code is called only on the nested leaf resume (:1939). _compile then returns wrap_guarded_code(guarded_code) (convert_frame.py:1999) = FrameExecStrategy(DEFAULT, DEFAULT) plus an ordinary guarded cache entry (types.py:89-93). No skip is recorded anywhere. So any later guard failure on that frame — a new shape, a new dtype, anything already guarded — retraces from the top against a fresh SpeculationLog (convert_frame.py:1602), re-runs import_source, and binds a corrected alias with no reset() at all. The only thing that defeats this is the recompile limit's RUN_ONLY transition (:2100-2104).

test_import_alias_the_trace_refused_is_not_recorded_for_install puts two ops before the import precisely to reach this arm, so the PR constructs the case its own hint misdescribes. The accurate statement is narrower: nothing proactively retraces the frame, because the global is unguarded — which is true of both arms — while only the skipped arm actually requires reset(). Scope the reset() tail to the skipped case, or drop the enumeration and stop at the unguarded-global fact. Same edit in the GB3718 Hints entry and in the cached anchor at test/dynamo/test_package.py:1110.

Fix this →

2. The codegen arm — the one the comment defends on diagnosability grounds — is the arm whose AssertionError carries no user stack at all. torch/_dynamo/symbolic_convert.py:2460-2470

The justification reads: the codegen callers keep the hard error "because an Unsupported there is not a graph break but a frame skipped after the backend ran, silent at default log levels." That mechanism is correct. But the replacement is not located either, and for a structural reason specific to those callers:

  • Tracing-phase callers do get a stack. run_ctx_mgr wraps the whole trace (:2085-2089, inliner at :6456-6457) and TracingContext.current_frame attaches real_stack to any exception lacking one (_guards.py:1269-1271); AssertionError is in _compile's pass-through tuple (convert_frame.py:2227) so it is not rewrapped, and augment_exc_message appends "from user code:" (exc.py:818-821).
  • The two codegen.py callers do not. codegen.py:781/:792 run inside make_call_generated_code, called at output_graph.py:3174 — inside the with torch._guards.TracingContext.clear_frame(): that opens compile_and_call_fx_graph at :2826. clear_frame sets e.real_stack = None on the way out (_guards.py:1248-1249), so get_real_stack returns None (exc.py:918-920) and nothing is appended. The user gets alias, module and {scope} — and no line.

Two things make that worth an edit rather than a shrug. {scope} is the root frame's __name__, which for codegen.py's torch.* names is the only locator in the message; and the codegen set is not uniformly Dynamo-named — ctx_manager.py:118 resolves self.module_name(), and GenericContextWrappingVariable.module_name (ctx_manager.py:196) returns self.cm_obj.__module__, a user module for a user-written context manager. Either attach a stack on that arm (the translator has frame_summary() at :5266), or say in the comment that the codegen arm trades the silent skip for a loud-but-unlocated error, so the tradeoff is recorded rather than implied. Worth noting alongside: under the non-default config.suppress_errors=True, if not config.suppress_errors and not soft_fail: (convert_frame.py:2476) does not fire, so this arm degrades to log.warning (:2490) plus the same whole-frame skip — the escape hatch works, as the round-6 reply said, but it lands in the state the comment argues against.

Fix this →

Testing

3. test_import_alias_the_trace_refused_is_not_recorded_for_install asserts neither half of what its comment claims about the compile, which is how finding 1 survived a suite measured by mutation. test/dynamo/test_package.py:1281-1321

The comment says "the trace restarts and the frame is compiled up to it," and assertEqual(len(package._codes[fn.__code__].guarded_codes), 1) (:1312) is presented as the proof. It is not: a whole-frame compile also produces exactly one guarded code entry, so a mutation that stopped breaking at the import would still pass. Pin the shape instead — a CompileCounter or EagerAndRecordGraphs asserting op_count == 2 (the x + 1 and y * 2 only, with taken.VALUE's add outside the graph) says what len == 1 cannot.

And nothing in the test asserts what a subsequent call or recompile does. This is the one test that reaches the partially-compiled arm, and hint 3 makes a claim about that arm; asserting it — fix the global, force an ordinary recompile with a differently-shaped input, then check the frame retraced and bound the alias without reset() — is the assertion that would have caught finding 1. Separately, assertNotIn(alias, entry.import_sources) (:1313-1314) is vacuous if import_sources is empty; one assertTrue(package._codes[fn.__code__].import_sources) beside it makes the loop known to be checking something, and repeating the assertNotIn on the loaded package before install() closes the save/load half.

4. Smaller test points.

  • test_import_alias_taken_by_a_non_module_graph_breaks (:1118-1119) never pins gb_type. format_graph_break_message (exc.py:680-685) puts it on the first line, and it must stay in sync with graph_break_registry.json, so renaming it goes undetected — add assertIn("Import alias already bound", str(cm.exception)).
  • test_import_alias_taken_at_codegen_is_a_hard_error (:1194-1197) interpolates torch.autograd.profiler into a regex unescaped, so the dots match any character; use re.escape. The nameless-scope half (:1205-1211) also omits the counterpart of :1201 — assertEqual(nameless[alias], "not a module") — so only the named case is shown to leave the slot alone.
  • The three-case loop at :1102-1124 uses a hand-rolled tuple plus subTest where CLAUDE.md asks for @parametrize ("For tests over multiple inputs, use the @parametrize decorator"); the class is already @instantiate_parametrized_tests (:141), so the three cases would get independent test IDs for free.

Recommendation

Request Changes

Finding 1 is a two-line fix plus a test anchor, but it is user-facing text that is false for one of the two outcomes it names, and that outcome is the one the PR builds a test for — the fourth round in which this same hint has been wrong about caching, which is the argument for finding 3: assert the behavior instead of re-reading the sentence. Finding 2 is either one comment sentence or one frame summary. Finding 4 is small.

The graph_break_ok split itself, the deferred package record, and the split's byte-identity with 8b3e78f2e708 all check out, as do the round-6/7 verifications of the memo and the DummyModule removal (unchanged here, now base context).

GB3718 is unique in graph_break_registry.json and its Context/Explanation/Hints match the unimplemented() call verbatim, so GB_REGISTRY should be satisfied; a fully custom hints list with no graph_break_hints.* constant is conventional in this file. No non-ASCII in added comments. I could not run the test suite or lintrunner — there is no built torch and no .venv in this checkout — so this review is static analysis only.

| branch `gh/bobrenjc93/1211/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head dbe9ff33c832; items 1, 2 and the three one-line parts of 4 are folded, item 3 and the @parametrize rewrite are declined.

1. > Hint 3 asserts the reset() requirement for both outcomes it enumerates; it holds for only one [...] Scope the reset() tail to the skipped case, or drop the enumeration and stop at the unguarded-global fact.

Fixed in dbe9ff33c832, both ways: the hint now reads "When this graph break is not raised as an error, nothing guards this global, so fixing it later does not by itself retrace the frame; a frame skipped here stays skipped until torch._dynamo.reset()." -- the enumeration is gone and reset() is scoped to the skipped arm -- in the source, the GB3718 entry and the test anchor. The commit message says the compiled-to-checkpoint arm retraces on its next guard failure and binds the alias then.

2. > The codegen arm -- the one the comment defends on diagnosability grounds -- is the arm whose AssertionError carries no user stack at all. [...] Either attach a stack on that arm [...] or say in the comment that the codegen arm trades the silent skip for a loud-but-unlocated error [...]

Fixed in dbe9ff33c832 with the comment: the codegen arm's error is "loud but unlocated, codegen running under TracingContext.clear_frame, which attaches no user stack". No stack is attached here; the message names alias, module and scope, and locating it is a change to how codegen reports errors rather than to this split.

3. > test_import_alias_the_trace_refused_is_not_recorded_for_install asserts neither half of what its comment claims about the compile [...]

Declined, and recorded as a FAQ: the test pins the package record, which is what its name says, and its backend must stay eager for the DiskDynamoStore save path, so an op-count pin is a new fixture; the graph-break shape is pinned where the message is, and with item 1 fixed the hint no longer claims anything about the partially-compiled arm's caching for a recompile assertion to catch.

4. > Smaller test points. [...]

Fixed in dbe9ff33c832: test_import_alias_taken_by_a_non_module_graph_breaks asserts the Import alias already bound gb_type, the profiler regex uses re.escape, and the nameless-scope half asserts the slot is left alone. The subTest loop stays: three cases sharing one fixture read more clearly in one method than as three instantiated tests, and the class already uses both styles.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 58m 13s —— View job


PR Review: #197255

The round-8 fixes hold up under verification, but scope = f_globals.get("__name__") or ... runs user __bool__/__format__ mid-trace in the one method that deliberately avoids user code, and the codegen justification's clear_frame ground covers only two of the five codegen call sites.

Full review

PR Review: #197255

Summary

Adds graph_break_ok to import_source (graph break for IMPORT_NAME, AssertionError for the other nine callers), defers the CompilePackage/import_sources record until past the collision check, and adds the GB3718 registry entry plus six tests.

I verified the round-8 claims by reading code rather than taking the reply's word, and all four folded items are correct:

  • Hint 3. The new wording is accurate in every reachable mode. step()'s re-raise set is one_graph or error_on_graph_break or is_tracing_resume_prologue or skip_frame (symbolic_convert.py:1768-1786), and every raise on that path bypasses the returns at convert_frame.py:2497/:2502, so "not raised as an error" does pick out exactly the modes where something is cached — I found no mode that is neither raised nor cached. "Nothing guards this global" holds: the failing branch returns before any install_guard, and even on success IMPORT_NAME pushes PythonModuleVariable(value, source=source) directly (:2596), bypassing VariableBuilder. The globals root is a GUARD_MANAGER, explicitly not a DictGuardManager (guards.py:1722-1728), so there is no key-set or version guard over f_globals and rebinding an unguarded name fails nothing. Dropping the enumeration also leaves no gap in the other direction: in the partial-compile outcome the resume frame re-hits the same break with no checkpoint, so it takes the :1787-1804 arm and becomes SKIP-cached itself. (reset_code_caches() is strictly narrower than reset() — __init__.py:198-218 — but it is not in __all__ and is self-described as test-only, so naming reset() is right.)
  • Test points. gb_type is asserted (test_package.py:1120), the profiler name is re.escaped (:1194), and the nameless-scope half asserts the slot (:1211) and frame_count == 2 (:1210).

Code Quality

1. scope = f_globals.get("__name__") or ... runs user code inside the trace — the exact hazard the two lines above it refuse to take. torch/_dynamo/symbolic_convert.py:2458

f_globals is a real dict (Scope = dict[str, object], output_graph.py:406/:450, fed the root frame's f_globals at symbolic_convert.py:5697), so the in/[]/get operations themselves are safe. But __name__ is only a str by convention. For a frame whose globals came from exec(src, {...}) — a shape Dynamo explicitly supports, see the no-__name__ / ___unnamed_scope arm at :6520-6524, and which this PR's own test_import_alias_taken_at_codegen_is_a_hard_error constructs — it can be an arbitrary object. Then:

  • or invokes its __bool__, and
  • the three {scope} interpolations (:2470, :2476, :2478) invoke its __format__/__str__.

That is user code executed mid-trace, on the way to reporting a graph break — and on the AssertionError arm inside codegen it can replace the intended failure with an unrelated exception from __format__, or an InternalTorchDynamoError wrapper. The contrast with :2446-2447 is the point: that line refuses to repr(bound) for precisely this reason, and the test file builds a booby-trapped PEP 562 module to prove the care at :2453 is load-bearing. The same care is missing one line later.

The in-repo precedent is four lines of the same file: _registered_module_for_globals opens with if not isinstance(module_name, str) (:273) on a value read the same way. Mirroring it here — name = f_globals.get("__name__"); scope = name if type(name) is str else "<a scope with no __name__>" — costs one line and closes it. (Weaker version of the same argument for type(bound).__name__ at :2447, which a metaclass __name__ property could hijack; not worth guarding.)

Fix this →

2. The codegen arm's justification is true of two of its five call sites; for the other three the error is pre-backend and located, which is the opposite of what the comment says. torch/_dynamo/symbolic_convert.py:2459-2466

"The codegen callers keep the hard error because an Unsupported there is not a graph break but a frame skipped after the backend ran, silent at default log levels; the error is loud but unlocated, codegen running under TracingContext.clear_frame, which attaches no user stack."

The mechanism is real and I confirmed it: clear_frame blanks frame_summary_stack/loc_in_frame and sets e.real_stack = None (_guards.py:1221-1250), so get_real_stack returns None (exc.py:918-920) and augment_exc_message emits no "from user code" block (:818-821). And it does apply to codegen.py:781/:792 — make_call_generated_code is called at output_graph.py:3174, inside the with clear_frame() that opens at :2826, and after call_user_compiler at :3020. So far so good.

It does not apply to the other three codegen-phase callers:

  • codegen.py:848 (load_import_from) is reached mostly from outside that block — codegen_suffix pass1/pass2 (output_graph.py:2240, :2263 → :2523/:2536/:2551) and resume-function codegen (symbolic_convert.py:1184, :1919, :2061, :3786). Both codegen_suffix calls precede compile_and_call_fx_graph at :2336, so they are pre-backend, and they run while run_ctx_mgr's TracingContext.current_frame is still active (symbolic_convert.py:2089-2092), so _guards.py:1269-1270 does attach a real_stack from loc_in_frame — the error is located.
  • ctx_manager.py:118 and torch_function.py:220 (reconstruct_type) are on the same footing.

The decision is unaffected — those callers should still hard-error. What is wrong is the stated ground, and it is wrong in the direction that matters: three of the five sites produce a located, pre-backend error, i.e. the diagnosability cost the comment records as the price of the choice is not actually paid there. Since the comment exists to let a future reader re-derive the split, scope its two claims to codegen.py:781/792 (plus output_graph.py:3149) rather than to "the codegen callers".

Fix this →

Testing

3. test_import_alias_the_trace_refused_is_not_recorded_for_install's central assertion goes vacuous if a config default drifts, and the drift it depends on is one the sibling test explicitly guards against. test/dynamo/test_package.py:1315-1316

for entry in package._codes.values():
    self.assertNotIn(alias, entry.import_sources)

import_sources is a dict[str, str] (package.py:595), so the membership test is right. But the loop only means something if some entry has a non-empty import_sources, and today that holds only because the partial compile's codegen resolves torch.autograd.profiler and torch._dynamo.utils (codegen.py:781, :792) — both gated on config.record_runtime_overhead. This test does not patch it. Its sibling test_import_alias_taken_at_codegen_is_a_hard_error does, with a comment saying exactly why ("patched so this keeps driving that site if the default moves", :1173-1175). So one test hard-guards the default and the other silently depends on it. If it flips, every entry.import_sources plausibly becomes {} and this assertion passes forever — and the vacuity mode is already live inside the same loop, since the extra _DynamoCodeCacheEntry in package._codes contributes an empty dict today.

This file already has the idiom for it (:817-821): add the positive control, self.assertTrue(any(entry.import_sources for entry in package._codes.values())), or patch record_runtime_overhead=True here as the sibling does. Worth also repeating the assertNotIn against the loaded package before install() — right now nothing checks the serialized side, which is the half the save/load exists to cover.

Fix this →

4. Two smaller test points.

  • test_import_alias_taken_for_an_inlined_callees_module_is_a_hard_error:1270-1272 interpolates alias, name and fn.__globals__['__name__'] into an assertRaisesRegex pattern with no re.escape, where :1194, :1240 and :1115 all escape. Benign today (the dots match anything) but the escaping fix from the last round stopped one test short.
  • :1230 builds a PackageImporter and never closes it, so its PyTorchFileReader holds alias.pt open for as long as packaged lives — and packaged is captured by the closure fn, itself referenced from the test frame. fresh_cache's rmtree at tearDown can fail on that on Windows. The finally already pops the _package_imported_modules entry; closing the importer (or del packaged) beside it makes the lifetime explicit.

5. The hints list uses no graph_break_hints.* constant, where the condition is squarely user error. torch/_dynamo/symbolic_convert.py:2477-2481

torch/_dynamo/CLAUDE.md directs hints at the constants in graph_break_hints.py, and USER_ERROR is what an occupied user-globals slot is — the PR's own premise ("a state of the user's globals, not an invariant of the tracer"). IMPORT_NAME's sibling break at :2561 uses a constant. A fully custom list is not unprecedented in this file, but three bespoke hints and no constant is the one combination the module's own guidance argues against; appending *graph_break_hints.USER_ERROR keeps all three and satisfies it.

Recommendation

Request Changes

Finding 1 is a one-line type check with in-file precedent four lines away, and it is a latent user-code-in-trace escape in the one method that otherwise goes to unusual lengths to avoid exactly that. Finding 3 is a test whose central assertion can degrade to a tautology without failing. Finding 2 is a comment whose stated grounds are wrong for three of the five sites they claim to cover. Findings 4-5 are small.

The graph_break_ok split itself, the deferred package record, and hint 3's rewording all check out, as does the ordering change: import_sources is read only at convert_frame.py:1077/:1082, package.py:1334 and aot_compile.py:771/:908, never during tracing, so a graph break taken between the check and the writes cannot be observed by an in-flight compile — the CompilePackage consequence the PR describes is the only one.

GB3718 is unique, in range, and its mid-file placement is what gb_registry_linter.py:194-208's random insert produces. I traced find_unimplemented_calls/extract_info_from_value (tools/dynamo/gb_id_mapping.py:106-148, :283-301) against the call: the two implicitly concatenated explanation f-strings parse as one ast.JoinedStr so the extracted string matches including all four placeholders, and the re.findall(r'"([^"]*)"', ...) hint extraction returns all three verbatim since none contains an embedded quote. Gb_type is unique in torch/_dynamo. No non-ASCII in added lines. I could not run the test suite or lintrunner — no built torch and no .venv in this checkout — so this review is static analysis only.

| branch `gh/bobrenjc93/1211/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 48f000867752; items 1, 2, 3, 5 and the re.escape half of 4 are folded, the importer-close half of 4 is declined.

1. > scope = f_globals.get("__name__") or ... runs user code inside the trace -- the exact hazard the two lines above it refuse to take. [...]

Fixed in 48f000867752: owner = f_globals.get("__name__") and scope = owner if type(owner) is str else "<a scope with no __name__>", mirroring _registered_module_for_globals; a non-str __name__ is reported by the fallback and never formatted.

2. > The codegen arm's justification is true of two of its five call sites; for the other three the error is pre-backend and located [...]

Fixed in 48f000867752: the comment scopes both grounds to make_call_generated_code's two pregraph-marker imports; the other callers keep the hard error under the deferral, as before.

3. > test_import_alias_the_trace_refused_is_not_recorded_for_install's central assertion goes vacuous if a config default drifts [...]

Fixed in 48f000867752: a positive control asserts some entry has a non-empty import_sources, and the assertNotIn loop is repeated on the loaded package before install().

4. > Two smaller test points. [...]

re.escape fixed in 48f000867752 for the inlined-callee test's three interpolations. The importer close is declined: PackageImporter has no close API, and a del would not release the module the closure holds; the finally already pops the registry entry, and the file lives under the test's temporary directory on the Linux runners this file targets.

5. > The hints list uses no graph_break_hints.* constant, where the condition is squarely user error. [...]

Fixed in 48f000867752: *graph_break_hints.USER_ERROR follows the three specific hints, in the source and in the GB3718 entry; GB_REGISTRY is clean.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 21m 2s —— View job


PR Review: #197255

The five round-9 fixes hold up, but the *graph_break_hints.USER_ERROR this round appended tells the user to reproduce the condition uncompiled — and nothing outside a Dynamo compile ever reads an __import_ alias, so the advice cannot be followed and contradicts the entry's own first hint.

Full review

PR Review: #197255

Summary

Adds graph_break_ok to import_source (graph break for IMPORT_NAME, AssertionError for the other nine callers), defers the CompilePackage/import_sources record until past the collision check, and adds the GB3718 registry entry plus six tests.

I verified the round-9 items by reading code rather than taking the reply's word, and all five folded items are correct:

  • scope type check (item 1). owner = f_globals.get("__name__") / scope = owner if type(owner) is str else "<a scope with no __name__>" (:2458-2459) does close the __bool__/__format__ hole, and it mirrors _registered_module_for_globals's own isinstance(module_name, str) (:273).
  • Codegen comment scoping (item 2). All four claims in the narrowed comment (:2460-2468) check out. make_call_generated_code is called at output_graph.py:3174, lexically inside the with torch._guards.TracingContext.clear_frame(): opened at :2826 and after call_user_compiler at :3020; clear_frame sets e.real_stack = None at _guards.py:1248-1249, so augment_exc_message emits no "from user code" block; and the order-dependence sentence is right, since the memo is written only at :2494, below both raises, and InliningInstructionTranslator gets its own dict from :5561.
  • Positive control (item 3) at test_package.py:1317 plus the assertNotIn repeat on the loaded package at :1323-1324; re.escape at :1271-1272; _import_module.cache_clear() at :1215.

Code Quality

1. *graph_break_hints.USER_ERROR is false advice here: no eager execution reads an __import_ alias, so the reproduction it prescribes cannot show anything. torch/_dynamo/symbolic_convert.py:2483

The appended constant expands to:

"Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the torch.compile call, or by using torch.compiler.set_stance("force_eager")."

__import_<mangled> is a name Dynamo mints. I traced every reader and writer in the tree: import_source writes it (:2491), GlobalSource(alias).reconstruct() emits a LOAD_GLOBAL for it in generated bytecode, the guard tree reads it through GlobalsGuardAccessor, CompilePackage.install binds it (package.py:1334-1338), and AOTCompiledFunction._seed_guard_scope seeds it. Every one is compile-time or compiled-runtime. Nothing in the user's source refers to it, so removing the torch.compile call makes the condition unobservable rather than reproducible. force_eager is worse than unhelpful: it sets the eval-frame callback to None (eval_frame.py:188-196), so import_source never runs and the break never fires — the user follows the hint, sees a clean run, and concludes the message was wrong.

It also contradicts the hint two lines above it. "Remove or rename the global {alias} from the globals of {scope}" is actionable because the condition is a compile-time collision on a Dynamo-owned name; "check whether eager errors too" is only sensible for a condition eager shares. The two cannot both be right.

The previous round asked for a constant on the grounds that torch/_dynamo/CLAUDE.md directs hints at graph_break_hints.py and that the condition is user-caused. The first half is real guidance; the second was my inference and it does not survive contact with what the alias is. Sampling the constant's other uses in this file supports the narrower reading — Import failure (:2564), Attempted to read undefined local variable (:2229), Variadic function call with bad args/kwargs type (:3344) all name conditions that do fail uncompiled. Drop the starred element and keep the three specific hints; hints=[]-style lists with no constant are not unprecedented here (nine of the 39 unimplemented calls in this file pass hints=[], including Bad import result three lines away at :2575), and three accurate hints beat four with one that misdirects. Same edit in the GB3718 entry. I withdraw the previous round's finding 5.

Fix this →

2. The __name__ read that the defensive comment sits on has the exact hole that was just closed four lines below it. torch/_dynamo/symbolic_convert.py:2453-2455

name = object.__getattribute__(bound, "__dict__").get("__name__")
if name is not None:
    offender = f"{offender} named {name}"

object.__getattribute__ stops a __getattribute__ override and a PEP 562 __getattr__ from running, which is what the comment above it claims and what the test's booby-trapped module proves is load-bearing. But name itself is an arbitrary object out of an arbitrary dict, and the f-string at :2455 invokes its __format__/__str__ — user code, run inside the trace, on the way to reporting a graph break. Nothing between :2444 and :2455 type-checks it.

Reachability is not exotic; the PR's own fixture demonstrates the technique two lines apart: test_package.py:1093-1094 does del nameless.__dict__["__name__"] and nameless.__dict__["__getattr__"] = ..., i.e. direct instance-dict writes, and types.ModuleType validates nothing on that path. A __format__ that raises escapes import_source as neither Unsupported nor AssertionError: step() catches only (Unsupported, UserError, StepUnsupported) (:1760), break_graph_if_unsupported only (Unsupported, UserError) (:1108-1110), so convert_frame.py:2243 rewraps it as InternalTorchDynamoError — replacing the intended diagnostic with a Dynamo-bug report.

The remedy is the one already applied to scope one line later, and the same one _registered_module_for_globals uses at :273: if type(name) is str: in place of if name is not None:.

Fix this →

3. The memo comment now runs three sentences above a two-line memo lookup, and its middle clause describes a case the method does not have. torch/_dynamo/symbolic_convert.py:2415-2420

"graph_break_ok stays out of the key: a memo hit means this translator bound the alias, an inlined translator's miss finds f_globals[alias] is value, and a taken slot is decided by each caller's own flag."

The first and third clauses are the load-bearing ones and both are right. The middle clause is not a property of the memo at all — an inlined translator's miss re-runs the body and finds the slot holding value because the parent's successful run wrote it, which is true whether or not graph_break_ok is in the key, so it argues for nothing. Six lines of comment for one dict.get is already at the limit of what CLAUDE.md asks for ("Minimize comments; be concise"); the clause that does not support the conclusion is the one to cut.

Testing

4. test_import_alias_taken_by_a_non_module_graph_breaks pins three of the four hints, and the one it does not pin is the one this round added. test/dynamo/test_package.py:1109-1124

The test asserts gb_type, hint 1 (hint), hint 3 (cached), and the explanation's tail via the regex. Hint 4 — the newly appended USER_ERROR text — is unasserted, so finding 1 is invisible to the suite in both directions: neither its presence nor its removal changes a test outcome. If the hint stays after finding 1 is considered, it should be pinned like its three siblings; if it goes, nothing needs to change, which is itself the argument that it is not carrying weight.

5. test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error does its PackageExporter/PackageImporter setup outside the try, so a failure between them leaks the registry entry the finally exists to pop. test/dynamo/test_package.py:1226-1247

packaged = torch.package.PackageImporter(path).import_module(name) at :1230 registers mangled in torch.package.package_importer._package_imported_modules (package_importer.py:389-394), and the finally at :1246 pops it. But the try opens at :1238, eight lines later — so if anything between :1230 and :1238 raises (or the test is interrupted), the entry survives the test. That is worse than an ordinary leak here: GuardBuilder.__init__ iterates the whole registry and writes every mangled name into both self.scope and self.scope["__builtins__"] on every guard build in the process (guards.py:1378-1386), and import_module raises on a duplicate name (package_importer.py:390-393). Move the import_module call inside the try, or take the registry pop into an addCleanup registered immediately after it.

Recommendation

Request Changes

Finding 1 is a one-element deletion in two files, but it is user-facing text prescribing a reproduction that cannot exist, added on my own previous advice — the accuracy argument beats the style guidance here, and I withdraw that advice. Finding 2 is a one-line type check with the matching fix already sitting one line below it and a raise path that turns a diagnostic into an InternalTorchDynamoError. Findings 3-5 are a comment clause, an unasserted hint, and a test-scope tightening.

The graph_break_ok split, the deferred package record, the scope guard, the narrowed codegen rationale, and the positive control all check out under independent verification.

On the registry: I traced extract_hint_list (tools/dynamo/gb_id_mapping.py:151-182) against the new starred element. ast.Starred is expanded in place via expand_hints, the comparison is sorted(...)-based so order does not matter, the four JSON strings match the source including USER_ERROR's trailing space, and the implicitly-concatenated explanation= f-strings parse as one ast.JoinedStr so all four placeholders survive — GB_REGISTRY should pass as written, and removing the starred element per finding 1 requires deleting the fourth Hints string to keep it passing. GB3718 is unique and its mid-file position is what the linter's random insert produces. No non-ASCII in added lines. I could not run the test suite or lintrunner — there is no built torch and no .venv in this checkout — so this review is static analysis only.

| branch `gh/bobrenjc93/1211/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 578eb7044a5d; all five items are folded (item 4 by way of item 1).

1. > *graph_break_hints.USER_ERROR is false advice here: no eager execution reads an __import_ alias [...] Drop the starred element and keep the three specific hints [...]

Fixed in 578eb7044a5d: removed from the source and the GB3718 entry; the three specific hints stay. Recorded as a FAQ with the reason.

2. > The __name__ read that the defensive comment sits on has the exact hole that was just closed four lines below it. [...]

Fixed in 578eb7044a5d: if type(name) is str: in place of if name is not None:.

3. > The memo comment now runs three sentences above a two-line memo lookup, and its middle clause describes a case the method does not have. [...]

Fixed in 578eb7044a5d: the middle clause is cut; the sentence keeps the memo-hit and taken-slot halves.

4. > test_import_alias_taken_by_a_non_module_graph_breaks pins three of the four hints, and the one it does not pin is the one this round added. [...]

Moot with item 1: three hints, three pins.

5. > test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error does its PackageExporter/PackageImporter setup outside the try, so a failure between them leaks the registry entry [...]

Fixed in 578eb7044a5d: the pop is an addCleanup registered right after import_module.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

PR Review: #197255

  • Gather context (diff vs origin/gh/bobrenjc93/1211/base, prior rounds)
  • Run /pr-review skill per repo CLAUDE.md
  • Verify the five round-10 fixes claimed in 578eb7044a5d
  • Post review

View job run | branch gh/bobrenjc93/1211/head

@claude

claude Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 58m 50s —— View job


PR Review: #197255

The five round-10 fixes all hold up under independent verification and I found no behavioral defect — but the type(name) is str guard added this round is indistinguishable from the code it replaced under the current suite, so the one thing I'd close before landing is a fourth case in the existing cases tuple.

Full review

PR Review: #197255

Summary

After the round-7 split, the live diff is the graph_break_ok parameter on import_source (graph break for IMPORT_NAME, AssertionError for the other nine callers), the deferred CompilePackage/import_sources record, the GB3718 registry entry, and six tests.

I verified all five round-10 claims by reading code rather than taking the reply's word, and all five are correct:

  • USER_ERROR removal (item 1). Three hints in the source (symbolic_convert.py:2479-2481), three in GB3718 (graph_break_registry.json:1164-1166), matching string-for-string. I also confirmed the removal cannot break the lint: find_unimplemented_calls's inline-hints path (tools/dynamo/gb_id_mapping.py:290-300) clean_strings the list source and re.findall(r'"([^"]*)"')s it, so three f-string literals with no " inside yield exactly three strings, the if "*graph_break_hints." in hints branch at :297 is simply skipped, and the comparison is sorted(hints) == sorted(Hints) (gb_registry_linter.py:345).
  • type(name) is str (item 2) at :2453, now matching the owner guard at :2458. type(...) is rather than isinstance is the right choice here, since a str subclass's __format__ is itself user code.
  • Memo comment (item 3). The surviving text is accurate: the memo write at :2492 sits below both the raise at :2469 and the unimplemented() at :2473 and below the bind at :2489, so a hit does imply this translator completed the bind, and the cut clause was genuinely not load-bearing.
  • addCleanup (item 4) at test_package.py:1233, registered immediately after import_module at :1230. unittest runs cleanups after tearDown regardless of outcome, so it is strictly more reliable than the old finally, and WeakValueDictionary.pop(key, default) returns the default both for an absent key and for a dead referent. The only pre-try setup left is the exporter file, which lands under the per-test fresh_cache() directory.

I also re-verified the parts the split moved into base context and the two claims most likely to have rotted. The record-ordering change is unobservable on the success path: the pre-check is False there, so add_import_source (:2487) and import_sources[alias] (:2488) run exactly as before, and every reader of those dicts is post-compile (convert_frame.py:1130, package.py:1334, aot_compile.py:908). The codegen-phase comment at :2459-2467 is accurate as narrowed — make_call_generated_code is called at output_graph.py:3174, inside the clear_frame() opened at :2826 and after call_user_compiler at :3020, and the trailing "The other callers keep it too, for now" correctly covers load_import_from and the rest rather than claiming they share that reasoning.

Code Quality

1. type(bound).__name__ is the one read in this block still unguarded, and it is interpolated into four f-strings. torch/_dynamo/symbolic_convert.py:2446 (low confidence — I could not run a probe in this checkout)

The block now guards both of its other reads of user-controlled data: type(name) is str at :2453 and type(owner) is str at :2458. offender gets no such guard, and it is the value the message is built around — interpolated at :2454, :2471, :2475 and :2477.

type(bound).__name__ is an attribute lookup on type(bound), resolved through its metaclass. A metaclass that defines __name__ as a property (or a __getattribute__) shadows type.__name__'s getset descriptor and runs user code here; it can raise, or return a non-str whose __format__/__str__ then runs at the interpolation. Either way the exception is neither Unsupported nor AssertionError, so step() (:1760, catching Unsupported/UserError/StepUnsupported) and break_graph_if_unsupported (:1108-1110) both let it through and convert_frame.py:2243 rewraps it as InternalTorchDynamoError — on the one path this PR deliberately made soft, an intended graph break becomes a Dynamo-bug report.

This is the same exoticness class as the __dict__-as-property case declined in round 9, and I would not argue for it on its own merits. I raise it because the round-10 fix established the guard-then-interpolate pattern two lines below, and offender is now the outlier: offender = type(bound).__name__ → name = type(bound).__name__; offender = name if type(name) is str else "object" costs one line and makes the block uniform. If it is declined, the reason worth recording is that the type's __name__ is a narrower attack surface than the instance's, which is the distinction the current asymmetry implies but does not state.

Fix this →

Testing

2. The type(name) is str guard added this round is untested — reverting it to if name is not None: passes the whole suite. test/dynamo/test_package.py:1102-1106

The three cases exercise a str in the slot, a module named other.name, and a module with __name__ deleted. For the third, .get("__name__") returns None, so name is not None and type(name) is str agree — every case is insensitive to which predicate is used. The failure mode the guard exists for, a module whose __dict__["__name__"] is a non-string, is not among them.

That matters more than a typical coverage gap because the author's stated methodology is mutation testing (-k test_import_alias after each mutation), and this mutation is invisible to it. The fix is one tuple entry beside the three already there — plant types.ModuleType("m") with mod.__dict__["__name__"] = 42 and expect the plain already bound to a module in the globals of {scope} wording, which pins both that the non-string is not interpolated and that no __format__ ran. The sibling type(owner) is str guard at :2458 has the same shape of gap: test_import_alias_taken_at_codegen_is_a_hard_error:1206 covers a missing __name__ key, never a non-string one.

Fix this →

3. Hint 2 — the only hint whose text is specific to a case the suite exercises — is the one hint never asserted. test/dynamo/test_package.py:1122-1124

The test pins gb_type, hint 1 (hint) and hint 3 (cached). Hint 2 ("two module names mangle onto this __import_ alias...") is unpinned, even though cases[1], the other.name module, is precisely the state it describes — the assertRaisesRegex there matches only bound to a module named other.name, which comes from the explanation, not the hint. Since that hint's scoping to the __import_ arm was itself the subject of a prior round, one assertIn on its first clause inside the second subtest would keep it from drifting silently.

4. package.install(backends) writes into the shared test-module globals and is never undone. test/dynamo/test_package.py:1326

install() resolves module = sys.modules[entry.python_module] (package.py:1326) — the test module — and binds every recorded alias there via _install_global, which writes unconditionally. The finally pops only the planted alias and resets Dynamo. What gets left behind is benign (the codegen aliases bound to their real modules, which any later collision check accepts by identity), so this is a convention gap rather than a leak: the file's two other tests that exercise the alias-install path call package.uninstall() afterwards (:831, :846). Adding it here, or an addCleanup(package.uninstall), keeps the test from being the one that leaves state for a future install()-related test to trip over.

Recommendation

Approve

No behavioral defects. Finding 2 is the one I would close before landing, and it is one tuple entry: the guard added this round is the fourth consecutive round in which a defensive read was hardened, and it is the first of them with no test that distinguishes it from the code it replaced. Finding 1 is a one-line consistency edit on a low-confidence hazard; findings 3 and 4 are one assertIn and one uninstall().

The graph_break_ok split, the deferred package record, the narrowed codegen rationale, the scope/name guards, and the addCleanup all check out under independent verification.

GB3718 is unique in graph_break_registry.json and its Gb_type/Context/Explanation/Hints match the unimplemented() call verbatim after the USER_ERROR removal, so GB_REGISTRY should be satisfied; the two implicitly-concatenated explanation= f-strings parse as one ast.JoinedStr, so all four placeholders survive extraction. No non-ASCII in added comments. I could not run the test suite or lintrunner — there is no built torch and no .venv in this checkout — so this review is static analysis only.

| branch `gh/bobrenjc93/1211/head`

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 20, 2026 02:00
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 20, 2026
@bobrenjc93 bobrenjc93 closed this Sep 20, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1211/head branch November 24, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant