Repository navigation
[dynamo] Graph-break instead of asserting when an import alias is already bound - #197255
bobrenjc93 wants to merge 33 commits into
Conversation
[ghstack-poisoned]
🔗 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 FailuresAs of commit 578eb70 with merge base 51d4378 ( 🟢 GREEN LIGHT - PR approved to be merged without human review:
reason: 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. |
…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
|
Re-reviewed against the current head 1. > Hint 3's "Without fullgraph=True" names one of the two modes that re-raise; Fixed in 2. > The memo comment explains why Fixed in 3. > Fixed in 4. > Fixed in 5. > No test covers the graph break under 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 |
PR Review: #197255No defects found this round — the four claimed fixes hold up under independent verification, and so do the memo rewrite and the Full reviewPR Review: #197255SummaryAdds 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:
Code Quality1. The memo comment's perf rationale describes a cost the design already pays per inlined frame, not one the flag would newly introduce.
The safety half is now correct (the memo is written only past the check, so a hit proves the slot passed for this exact 2. The repo's own rule (
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. I traced the inlined arm because the other two hints are explicitly about the root frame's globals. An Testing4. Nothing covers the memo rewrite — the invariant its own comment names as load-bearing is unpinned. The memo's correctness rests on one ordering: the write at
So the decision the seven-line comment exists to justify is untested, and the author's stated mutation-testing methodology ( 5. The replay arm lost its only type guard and has no coverage under The hoisted 6.
RecommendationApprove 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
View job run | branch |
PR Review: #197255The 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 Full reviewPR Review: #197255SummaryAdds 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).
I also verified the Code Quality1. Hint 3's
The mode-agnostic conditional is now right, and right for a reason worth stating: But the two outcomes the sentence enumerates do not share the consequence it attributes to both:
So the hint tells a user whose frame was partially compiled — the outcome the PR's own 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 Two smaller points on the same string: 2. On the hard-error arm, The comment at The The PR's own test shows the gap: 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. The description enumerates (a), (b), (c). There is a fourth, visible only under Separately, 4. On base, Testing5. Nothing pins the partially-compiled outcome's cache behavior, which is why finding 1 survived a suite measured by mutation. 6. The RecommendationRequest 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
View job run | branch |
[ghstack-poisoned]
|
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 |
|
Claude finished @bobrenjc93's task in 54m 18s —— View job PR Review: #197255The round-7 split checks out — the tree is byte-identical to Full reviewPR Review: #197255SummaryAfter the split, the live diff is the Code Quality1. Hint 3 asserts the
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: The partially-compiled arm does not behave that way. With a checkpoint present,
2. The codegen arm — the one the comment defends on diagnosability grounds — is the arm whose The justification reads: the codegen callers keep the hard error "because an
Two things make that worth an edit rather than a shrug. Testing3. The comment says "the trace restarts and the frame is compiled up to it," and 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 4. Smaller test points.
RecommendationRequest 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
|
[ghstack-poisoned]
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > Hint 3 asserts the Fixed in 2. > The codegen arm -- the one the comment defends on diagnosability grounds -- is the arm whose Fixed in 3. > Declined, and recorded as a FAQ: the test pins the package record, which is what its name says, and its backend must stay 4. > Smaller test points. [...] Fixed in |
|
Claude finished @bobrenjc93's task in 58m 13s —— View job PR Review: #197255The round-8 fixes hold up under verification, but Full reviewPR Review: #197255SummaryAdds I verified the round-8 claims by reading code rather than taking the reply's word, and all four folded items are correct:
Code Quality1.
That is user code executed mid-trace, on the way to reporting a graph break — and on the The in-repo precedent is four lines of the same file: 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.
The mechanism is real and I confirmed it: It does not apply to the other three codegen-phase callers:
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 Testing3. for entry in package._codes.values():
self.assertNotIn(alias, entry.import_sources)
This file already has the idiom for it ( 4. Two smaller test points.
5. The
RecommendationRequest 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
|
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > Fixed in 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 3. > Fixed in 4. > Two smaller test points. [...]
5. > The Fixed in |
|
Claude finished @bobrenjc93's task in 21m 2s —— View job PR Review: #197255The five round-9 fixes hold up, but the Full reviewPR Review: #197255SummaryAdds I verified the round-9 items by reading code rather than taking the reply's word, and all five folded items are correct:
Code Quality1. The appended constant expands to:
It also contradicts the hint two lines above it. "Remove or rename the global The previous round asked for a constant on the grounds that 2. The name = object.__getattribute__(bound, "__dict__").get("__name__")
if name is not None:
offender = f"{offender} named {name}"
Reachability is not exotic; the PR's own fixture demonstrates the technique two lines apart: The remedy is the one already applied to 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.
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 Testing4. The test asserts 5.
RecommendationRequest 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 The On the registry: I traced |
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > Fixed in 2. > The Fixed in 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 4. > Moot with item 1: three hints, three pins. 5. > Fixed in |
PR Review: #197255
|
|
Claude finished @bobrenjc93's task in 58m 50s —— View job PR Review: #197255The five round-10 fixes all hold up under independent verification and I found no behavioral defect — but the Full reviewPR Review: #197255SummaryAfter the round-7 split, the live diff is the I verified all five round-10 claims by reading code rather than taking the reply's word, and all five are correct:
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 Code Quality1. The block now guards both of its other reads of user-controlled data:
This is the same exoticness class as the Testing2. The The three That matters more than a typical coverage gap because the author's stated methodology is mutation testing ( 3. Hint 2 — the only hint whose text is specific to a case the suite exercises — is the one hint never asserted. The test pins 4.
RecommendationApprove 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 The
|

Stack from ghstack (oldest at bottom):
Summary.
import_sourcemints an__import_<mangled>alias for everymodule 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
AssertionErrorthat restated the conditionand named nothing, with no eager fallback because
AssertionErroris in_compile's pass-through tuple. An occupied alias slot is a state of theuser'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. Twomoves go with it: the alias is recorded for the
CompilePackageentry onlyonce 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; andIMPORT_NAME'smodule-type check now runs before
import_source, so a non-modulesys.modulesentry is never written into the traced globals. The check itselfis 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
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.installbinds each recorded alias toimportlib.import_module(module_name)in the traced module's globals, andAOTCompiledFunction._seed_guard_scopedoes the same into a scope its owncomment describes as possibly a user module's live namespace.
A graph break that names the offender
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 moduleso 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 dictthrough
object.__getattribute__(bound, "__dict__"): a module's PEP 562__getattr__and a class-level__getattribute__(importlib.util._LazyModule'simports the module on any attribute read,
__dict__included) are user codethat must not run inside a trace on the way to a graph break.
IMPORT_NAMEhas nobreak_graph_if_unsupported, so theUnsupportedlandsin
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.banda_dot_bboth alias as__import_a_dot_b).Record the alias only after the check passes
The check can now fail recoverably, and the package entry is entered outside
the trace that fails (
code_contextwraps the whole compile, and a frame thatskips or restarts leaves its entry in
_codes), so a record written before thecheck would ship in the saved entry, and
install()would then bind the aliasto
importlib.import_module(module_name)over the very global the checkrefused to touch:
_install_globalwrites unconditionally,record_only_if_newgates only the uninstall bookkeeping.With the old
AssertionErrorthis was unreachable, since the compile diedbefore anything was serialized.
Hoist
IMPORT_NAME's module-type check ahead ofimport_sourceOn that path, the one caller resolving a name the traced bytecode chose, a
non-module
sys.modulesentry is never written into the traced globals. Thehoisted check is
isinstance(value, types.ModuleType)alone:DummyModuleonly ever arrives on the replay arm, where
add_local_modrejected non-moduleswhen the record was written, so that import goes, and the
DummyModuleimportwith it. The other eight callers (
nn_modules_globals_vt,codegen.py's threesites,
torch_function.py,ctx_manager.py,misc.py,functions.py) reachimport_sourcewith no module-type test and pass torch's own and stdlib namesor a class's
__module__; a non-module entry under one of those is still boundverbatim there, unchanged by this commit, and
get_globals_source_and_valuealready has one, since
_registered_module_for_globalsreturns a name only fora
types.ModuleTypewhose__dict__is the frame's globals.Behaviour changes against the parent
Each is pinned by a test below.
Unsupportedgraph break where it was anAssertionError, skipped orcompiled 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).(
test_import_alias_the_trace_refused_is_not_recorded_for_install).IMPORT_NAMEof a non-modulesys.modulesentry no longer writesthe 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
CleanupHookhere, unlikeinstall_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 saysso.
graph_break_registry.jsongains theImport alias already boundentrywith one hint per case.
Order to review:
import_sourceintorch/_dynamo/symbolic_convert.py(thecheck, the
unimplementedcall, the record after it), thenIMPORT_NAME'shoisted check in the same file, then the three tests and the
_import_alias_getattr_boomhelper intest/dynamo/test_package.py, then theregistry entry.
Test Plan:
Three tests, all red on the parent's
torch/_dynamo/symbolic_convert.pyunder this commit's test file (
Ran 3 tests,FAILED (failures=5): the threesubtests of the first and the second on the old
AssertionError, the third onthe alias the parent wrote). One plants a
str, a module namedother.nameand a nameless module (with a PEP 562
__getattr__that raises) in the aliasslot in turn and pins the graph break's wording for each, then, with a
CompileCounterand nofullgraph, thatframe_countstays 0 across therefused 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 aCompilePackagewhile astrholds the alias -- two ops before the import, sothe trace restarts and compiles up to that checkpoint rather than skipping,
pinned by
len(guarded_codes) == 1-- saves, loads and installs, and pins thatno entry recorded the alias and the
stris still there. One plants twosuccessive non-module
sys.modulesentries and pins that neither is bound andthat both graph-break as
Bad import result.Each is load-bearing, measured on this tree by mutation (
-k test_import_aliasafter each): recording the alias above the check fails the refused case on
assertNotIn(alias, entry.import_sources); reading the bound object's namewith
getattr(bound, "__name__", None)errors the nameless-module subtest withRuntimeError: module __getattr__ ran inside a trace for __name__, the PEP562 hook the fixture installs; dropping the
named {bound_name}half of themessage fails the
other.namesubtest on itsassertRaisesRegex; raisingAssertionErrorin place ofunimplementedfails all three subtests and therefused case on the exception type; un-hoisting the module check (the parent's
push-time
isinstancerestored) failstest_import_alias_is_not_bound_to_a_non_module_importon the alias it wrote.The two tests that plant a module under a fixed
sys.modulesname and resolveit through
import_sourcecall_import_module.cache_clear()infinally,next to the
sys.modulespop: the memo outlives the entry, and on asame-process re-execution (the default
--reruns=2ofrun_test.py) thesecond run would resolve the first run's object; #196896's message carries the
measurement over all thirteen
test_import_aliasinstances of the threecommits. The non-module case needs none, since the hoisted check graph-breaks
before
import_sourceruns and the memo never sees its name. The whole fileat this commit: 81 tests, OK (skipped=40, expected failures=1).
They live in
test_package.pyrather thantest_misc.pybecause the writerthat empirically reaches the collision path is
CompilePackage.install, andthat file already owns the
DiskDynamoStoresave/load/install idiom and therest of the
import_sourcescoverage.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