Skip to content

[aot_compile] Name and quote the raises the no-match report's caveat means - #197257

Closed
bobrenjc93 wants to merge 24 commits into
gh/bobrenjc93/1213/basefrom
gh/bobrenjc93/1213/head
Closed

bobrenjc93 wants to merge 24 commits into
gh/bobrenjc93/1213/basefrom
gh/bobrenjc93/1213/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Split from [aot_compile] Say what the no-match report's advice rests on after a raise (#197050, the commit below) for review budget: that commit
appends a caveat to the report's ModelInput advice when every rejection the
advice rests on followed a raise from its own tree, and this one makes the
caveat name the trees it means and quote their raises.

At the commit below the caveat reads Fix the raise first: every rejection this advice rests on followed a raise from its own tree, and ..., and the
only raise the report names above it is the raiser line's: [i]'s guard check raised while checking this call, where i is the FIRST enabled index in
raised, and the chain carries the first raise recorded of all. The tree the
caveat means is an entry in answered but not in trusted, whose own entry
line quotes its rejection, not its raise. Those coincide on a one-input
report and diverge as soon as another enabled tree raised before it, so
there the raise points at the wrong tree and the raise the caveat means is
printed nowhere -- measured on ScaleModule with two inputs, a tree that
raises on every pass at [0] and RaisesOnceThenRejects("the scan is unhappy") at [1]: the report at the commit below carries [0] <guard check raised RuntimeError: every pass is unhappy>, [1] stub guard rejected,
[0]'s guard check raised while checking this call, and the advice ending
in Fix the raise first: ..., with the scan is unhappy nowhere on it.

Order to review: _raise_text, split out of _raised_line, and the
caveat's caller added to the reachability comment on _quoted; the caveat's
untrusted list, its plural and its join at the end of _no_match_report,
the coverable and trusted_rejection gates it hangs off, and the comment on
the list; the sentence added to the comment on
_STALE_AFTER_THROW; the AOTCompiledModel docstring's clause about the
report's closing lines; then, in the test file, the two placeholders added to
CAVEAT_AFTER_A_RAISE,
test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice,
test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice,
test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary,
test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection,
test_no_match_message_caveat_reads_the_opt_out_snapshot, and
the quoting assertions added to
test_no_match_message_qualifies_a_rejection_that_followed_a_raise,
test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw,
test_no_match_report_reads_the_dispatch_record_after_a_raise and
test_no_match_message_qualifies_the_advice_when_the_re_check_raises, and
the trailing separator and the odd exception kind added to
test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators.

The caveat now names those trees by index and quotes each one's raise --
Fix the raise out of [1] <RuntimeError: the scan is unhappy> first --
because nothing else on the report carries such a raise.
test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice is
the shape above, and pins that [0]'s line, the raiser line and the
__cause__ are all [0]'s while the caveat names [1] and quotes its raise,
the one place on the report that text appears. Building the caveat over
[raiser] instead of the enabled entries of answered fails that test and
test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice,
whose [1] the raiser line never names. The entries are the ENABLED ones: an
opted-out tree that raised and then rejected is in answered too, since
recording never reads the flag, but nobody asked about its guards, its
own line is the withheld one blaming the raiser, and quoting its raise here
would contradict that line and the withheld advice, which both say the
raiser's raise is what withheld it.
test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection puts
RaisesOnceThenRejects on an enabled [0] and on an opted-out [1], where [0]
being an enabled raiser is what keeps the last resort from serving [1], and
pins that the caveat names and quotes only [0], singular, with [1]'s message
nowhere on the report; dropping the enabled[i] filter fails that test, on
Fix the raises out of [0] <RuntimeError: the checked scan is unhappy>; [1] <RuntimeError: the opted-out scan is unhappy> first. Enabled means the
enabled snapshot the entry lines read, not a fresh read of the flag: the
report runs user code between the veto's read and this list -- an entry's
check_verbose, or a disable_guard_check() from another thread, which is a
plain store -- so a fresh read can drop an entry this same report printed as
a rejection, and where it was the only one the sentence loses its subject,
nothing left between Fix the raise out of and first and a doubled space
where the tree should be.
test_no_match_message_caveat_reads_the_opt_out_snapshot is that shape, the
two-input report above with [1]'s check_verbose opting [1] out before it
returns the rejection the advice rests on: the snapshot leaves Fix the raise out of [1] <RuntimeError: the scan is unhappy> first, and this filter made a
fresh read leaves exactly the subjectless sentence and fails that test, the
only test in the file it fails. The coverable and trusted_rejection gates
that decide whether the caveat fires read that same snapshot, so what they
found and what the list keeps cannot disagree: a coverable and not trusted_rejection report has an answered entry enabled in the snapshot and
outside trusted, which is an entry accepts() recorded a raise for, so the
list is never empty and trusted need not be subtracted. Off the flag the
gates were two reads of it, and a store landing between them on the only
answered entry left coverable true, trusted_rejection false and the
subjectless sentence above over an empty list. Dropping the enabled[i]
filter errors test_no_match_message_quotes_a_tree_that_raised_then_answered
with KeyError: 1 as well, its opted-out [1] having rejected with no raise on
record. The
quoted text comes from _raise_text, the part of _raised_line that turns a
recorded raise into Kind: reason, with the same pybind-boundary clause and
the same newline collapse, so an entry line and the caveat cannot describe
one raise differently. The collapse covers the kind as well as the reason,
which is why it wraps Kind: reason rather than the reason alone: kind is
type(reason).__name__, and a class built with type() may hold a separator
in its name, so interpolating it raw splits an entry line and the caveat over
lines -- the failure the collapse exists to prevent, and one the caveat can
multiply, a report carrying a kind per tree it names. An entry line that
quotes a raise reads as before unless that text ends in a separator
splitlines() breaks on: _raised_line collapsed the whole line after
appending the bracket, so ...abc\n> came out ...abc >, while
_raise_text collapses before the boundary clause and the bracket are
appended and emits ...abc>, which is also what keeps the C++-throw golden
below clean.
test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators, from a
commit below, now ends its message in a fifth separator and raises a class
named Odd\nKind, and pins the whole line, [0] <guard check raised Odd Kind: page break rec sep line (through the guard tree's pybind boundary)>:
on the commit below it fails on sep line (through, and with kind
interpolated raw it fails on a report of four lines where it reads three, the
entry split after Odd.

The caveat is one sentence whichever number of trees it names. Each entry
is bracketed as on the entry line, [i] <Kind: reason>, and the entries are
joined with ; : the quoted text is arbitrary user text that may hold
commas, and _raise_text's pybind-boundary clause is a parenthetical of its
own, so parentheses around an entry nest it ([0] (ValueError: boom on compare 1 (through the guard tree's pybind boundary))) and a comma join
puts a user comma where a boundary between entries reads. With two such
trees it reads Fix the raises out of [0] <RuntimeError: a>; [1] <RuntimeError: b> first, and _STALE_AFTER_THROW, unchanged here, is
already phrased for one tree or several -- a C++ throw out of a tree can leave that tree's relational guard state stale, so its next check ... -- so
the clause has an antecedent however many trees precede it; its comment now
says that is one reason for the phrasing.
test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice
installs RaisesOnceThenRejects on both enabled results with different
messages, one holding a comma, and pins the plural, both bracketed entries,
and that each message appears exactly once on the report (the raiser line and
the chain carry only [0]'s, the first recorded). The order the entries come in
is incidental rather than pinned: answered holds small ints, whose set
iteration is value-ordered at these table sizes, so dropping the sorted
leaves the whole file green (Ran 337 tests ... OK (skipped=6)).
Mutating plural to "", the join to untrusted[0] or the joiner to ,
fails that test; parentheses around the entry fail it, the seven other
tests that pin a whole caveat, and
test_no_match_report_reads_the_dispatch_record_after_a_raise, which pins
its one bracketed entry.
test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary
renders the caveat for the other flavour of raise: a RaisesThenHits(raises=1)
key on DictBranchModule raises through pybind on the scan and answers after
it (RaisesOnCompare raises on every compare, so a tree keyed on it never
gives the rejection the caveat rests on), and the test pins [0] <ValueError: boom on compare 1 (through the guard tree's pybind boundary)>
inside the caveat, quoted exactly once on the report. A commit below's
test_no_match_message_quotes_a_tree_that_raised_then_answered has that
shape too and said no line of the report quotes its raise; the caveat now
does, and its comment says so.

test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw, from
the commit below, drives the caveat with a real TORCH_CHECK throw out of
TENSOR_MATCH (NestedTensorImpl doesn't support strides), and now pins
the caveat quoting it as [0] <RuntimeError: ...> with no boundary clause,
since pybind translated a throw with nothing chained. The golden collapses
str(cause) as _raise_text collapses the reason,
" ".join(str(cause).splitlines()): under TORCH_SHOW_CPP_STACKTRACES=1,
which test/run_test.py sets when it retries a failed test, pybind takes
e.what() over e.what_without_backtrace() and the message carries the
C++ backtrace, one frame per line and each line newline-terminated, while
the report is one line per paragraph, so an uncollapsed golden can never be
the advice's suffix and the test would be red on exactly a retry: measured
red with the variable set and the collapse removed from _raise_text, green
with it, and green either way with the variable unset. The collapse is of
str(cause) alone, not of the whole [0] <RuntimeError: ...> entry, because
the last frame's newline sits right before the closing bracket and collapsing
the whole entry leaves ... > where _raise_text, which collapses the
reason before the bracket is appended, emits ...>.

Against the commit below, nothing served or raised changes: the same calls
raise the same RuntimeError with the same __cause__, and the dispatch
passes, the veto, the warning and trusted are untouched, and the gates on
the report's closing lines, the caveat's included, now read the enabled
snapshot rather than the flag: nothing between the veto's read and them runs
user code, so no call of its own accord tells the two apart, and the whole
file is green under either read. Two texts differ: the
caveat's, where Fix the raise first becomes Fix the raise(s) out of [i] <Kind: reason>; ... first, naming and quoting every enabled tree whose
rejection the advice rests on, and a raise entry line whose reason ends in a
separator, which loses the stray space before its closing bracket. The
AOTCompiledModel docstring said the advice says to fix the raise first; it
now says the advice names and quotes those raises, and the two comments that
called the caveat a follow-up change -- that docstring's closing sentences
and the one on the report's raise entry line, both accurate at the commit
below -- say what it does today. The sentence that followed it -- reading a dispatch-recorded raise's entry line
and __cause__ onto the caveat -- is deleted rather than qualified again:
the entry-line shapes, the caveat's gate and the __cause__ rule are each
stated once earlier in the same docstring, and the sentence only restated
them. Both texts state
that gate as trusted keys it, per tree rather than over every raise on the
report -- a tree that rejected and THEN raised is trusted, and its own line
quotes that raise -- and the entry-line comment keeps the commit below's
reading for the shape the gate leaves out, an enabled tree that rejected
before any raise from its own tree switching the caveat off, and then no line
of that report carries the raise.

One tree can put two raises on the report, in two bracketed forms:
test_no_match_message_qualifies_the_advice_when_the_re_check_raises, from
the commit below, has dispatch record the first pass is unhappy and then a
rejection at [0], and the report's check_verbose raise the re-check is unhappy, so [0]'s entry line is <guard check raised RuntimeError: the re-check is unhappy> and the caveat quotes [0] <RuntimeError: the first pass is unhappy>. That is the intended reading, not a side effect: the
caveat quotes the raise the rejection the advice rests on followed, which is
dispatch's, and the re-check's raise is the report's own, already on the
entry line. The test pins the whole caveat and that dispatch's message
appears exactly once on the report, where it asserted only that the caveat
was present.

Five tests are new; five of the commits below's gain an assertion: three the
assertion that the caveat quotes the raise for their case
(test_no_match_message_qualifies_a_rejection_that_followed_a_raise and
test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw
pin the named entry through CAVEAT_AFTER_A_RAISE's placeholders, and
test_no_match_report_reads_the_dispatch_record_after_a_raise, whose [0]
raised on the scan, rejected on the second pass and accepted on the
re-check, pins the caveat's Fix the raise out of [0] <RuntimeError: the first pass is unhappy> first, and that it appears exactly once on the
report, where it asserted that text absent),
test_no_match_message_qualifies_the_advice_when_the_re_check_raises the
whole caveat, and
test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators the
trailing separator and the odd kind; and a commit below's
test_no_match_message_quotes_a_tree_that_raised_then_answered changes only
its comment. Of those eleven, ten fail on the commit below's
aot_compile.py, all but the comment-only one. The caveat's text stays one
golden, CAVEAT_AFTER_A_RAISE, now with two placeholders, the plural of
raise and the bracketed entries it names, that the eight tests pinning the
whole paragraph share.

Test Plan:

python test/dynamo/test_aot_compile.py -k test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice
python test/dynamo/test_aot_compile.py -k test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary
python test/dynamo/test_aot_compile.py -k test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection
python test/dynamo/test_aot_compile.py -k test_no_match_message_caveat_reads_the_opt_out_snapshot
python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw
TORCH_SHOW_CPP_STACKTRACES=1 python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered
python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_the_advice_when_the_re_check_raises
python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py

The eleven were also run against the commit below's
torch/_dynamo/aot_compile.py (ten fail, the comment-only one passes), and
the caveat's construction was then mutated one term at a time -- built over
[raiser] instead of the enabled entries of answered, the enabled[i]
filter dropped, that filter made a fresh results[i]._guard_check_enabled
read, both gates made fresh reads of the flag, plural made "", the join
made untrusted[0], the joiner made , , the entries parenthesized, and
kind interpolated raw in _raise_text -- and the tests that name the caveat
rerun; only the tests named above failed under each, the gates' fresh reads
leaving the whole file green and the filter's fresh read failing
test_no_match_message_caveat_reads_the_opt_out_snapshot alone.

Authored with the assistance of Claude Code.

FAQ: The trailing-separator improvement is exact only for one trailing
separator: two leave ...abc > still, since collapsing a text that ends in
two of them yields a trailing space of its own.

True, and left as is: the collapse puts a space between the pieces
splitlines() returns, so a text ending in N separators keeps N-1 spaces
before the bracket. What the format rests on is the entry staying on one
line, which holds for any N, and no golden reads the residue; stripping it
would be a rule the report applies to no other quoted text.

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 commented Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit 4f1da67 with merge base 51d4378 (image):

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

  • Correctness
    • The caveat's raised[i] read cannot KeyError: answered.add at aot_compile.py:2045/:2088 pairs with trusted.add whenever i not in raised, and the not trusted_rejection gate at :2317 excludes every enabled trusted index
    • untrusted at :2328 cannot be empty: coverable at :2210 is the same predicate over the same set and the same immutable enabled list as the comprehension's filter
    • The _raise_text split at :176-191 changes _raised_line output only for a reason ending in a separator (...abc > becomes ...abc>), and the collapse now wraps kind too, which a type()-built name can break lines in
  • Testing
    • Five new caveat tests in test/dynamo/test_aot_compile.py cover the single-tree, multi-tree plural, pybind-boundary, opted-out-skip and mid-loop enabled-snapshot shapes
    • test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators pins the whole line for type("Odd\nKind", (ValueError,), {}) plus five separators, covering the widened collapse
    • The shared golden CAVEAT_AFTER_A_RAISE at test:​802 gained exactly the two placeholders the new message at :2335 interpolates
  • Scope
    • Confined to _raise_text, _raised_line, the caveat block in _no_match_report, and comments/docstring; no public API, CI, or build file touched
    • The gate switch at :2210-2211 from a fresh _guard_check_enabled read to enabled[i] is behaviour-identical, since nothing between the snapshot at :2133 and those lines runs user code
    • Only the diagnostic text of an internal no-match report changes; the served graphs, __cause__ and trusted bookkeeping are untouched

reason: clean
Reviewed commit: 4f1da67

Inference job

🐛 Report a wrong verdict

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

CRCR (non-blocking) - The following CRCR downstream CI job failed but is non-blocking:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 16, 2026
This was referenced Sep 16, 2026
@bobrenjc93 bobrenjc93 changed the title [aot_compile] Name and quote the raises the no-match report's caveat means [no-ci] [aot_compile] Name and quote the raises the no-match report's caveat means Sep 16, 2026
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…raise (#197050)

**Problem.** After #197220, the no-match report advises "Add a ModelInput covering this call" whenever some guard tree rejected the call, without saying how that rejection came about. When the only rejection came from a tree that had raised on the pass before, the rejection may be about the stale relational state a C++ throw left behind rather than about this call, and the report said nothing about it.

**Fix.** Dispatch records `trusted`, the indices that rejected with no raise of their own on record at that moment. When every rejection the advice rests on followed a raise from its own tree, the advice paragraph gains one more sentence: fix the raise first, since a C++ throw can leave that tree's relational guard state stale.

**Summary.** The commit below, #197220, advises a `ModelInput` whenever some checked tree rejected the call and says nothing about how that rejection came about, so when the only rejection dispatch got out of a tree FOLLOWED a raise from the same tree, the advice stands on the answer the last-resort veto below refuses to act on: a C++ throw skips `_reset_relational_guard_state()`, so that rejection can be about the stale relational state rather than about this call. Dispatch now records one more set, `trusted`, the indices that answered with no raise of their own on record at that moment (`if i not in raised`), written on the rejection-only path of `accepts()` so an accept pays nothing for it, and the report computes `trusted_rejection` over the enabled ones the way it already computes `coverable` over `answered`. When `coverable and not trusted_rejection`, the `ModelInput` paragraph goes on to say so -- fix the raise first, since every rejection this advice rests on followed a raise from its own tree, and a C++ throw can leave that tree's relational guard state stale -- with the stale-state clause hedged (`can leave`) and held in a constant, `_STALE_AFTER_THROW`, because it is emitted for both flavours of raise and is a fact about only the throw that unwinds past the reset. The caveat keys on what dispatch recorded rather than on the lines the report printed, does not yet say WHICH tree's raise it means (#197257, the commit above, makes it name and quote them), and one trusted rejection is enough to leave the advice unqualified. Against the commit below nothing served or raised changes -- same `RuntimeError`, same `__cause__`, same entry lines, same gates -- only the `ModelInput` paragraph differs, and the four new tests plus the existing ones that now assert the caveat fail on the commit below's `aot_compile.py`.

## Where this sits in the stack

Split from `[no-ci] [aot_compile] Advise a ModelInput only when some checked tree answered the no-match report's call` (#197220, the commit below) for review budget: that commit decides whether the report's closing advice applies at all, and this one says what the advice rests on when it does. Split again, for the same budget, from `[aot_compile] Name and quote the raises the no-match report's caveat means` (#197257, the commit above): this commit adds the caveat and the bookkeeping it keys on, and that one makes the caveat name the trees it means and quote their raises.

## The report the commit below prints

Measured on `ScaleModule` with one input and a stub tree that raises on the scan and rejects on the second pass, the report at the commit below reads:

```
  [0] stub guard rejected
[0]'s guard check raised while checking this call; fix or drop that artifact.
Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy -- ...
```

The `ModelInput` advice stands on a rejection that followed the same tree's raise, which the last-resort veto below refuses to act on, and nothing on the report says so.

## Recording `trusted`

```python
# AOTCompiledModel.__call__
answered: set[int] = set()
trusted: set[int] = set()          # new: answered with no raise of their own on record

# inline first result
else:
    answered.add(0)
    trusted.add(0)                 # new

def accepts(i, result):
    ...
    if answer:
        return True                # an accept serves and builds no report
    # Recorded on a rejection only. Measured 0.06us for the four against a 1.3us check().
    unanswered.discard(i)
    answered.add(i)
    if i not in raised:            # new
        trusted.add(i)
    return False
```

Dispatch now records one more thing about a rejection, and records it where the order is known rather than reconstructing it afterwards. `trusted` holds the indices that answered with no raise of their own on record at that moment (`if i not in raised`), so it does not depend on dispatch running exactly two passes: under a third pass an answer-raise-answer tree would still be in it and a raise-answer-raise tree still out of it, where a predicate over `answered`, `raised` and `unanswered` can only tell those two apart by counting passes. Recording `trusted` without the `raised` check -- every answer trusted -- fails `test_no_match_message_qualifies_a_rejection_that_followed_a_raise`, `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`, `test_no_match_message_quotes_a_tree_that_raised_then_answered` and `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, all on the caveat going missing.

The two lines that record it sit on the rejection-only path the commit below made of the answer exit of `accepts()`: an accept returns before them, since dispatch then serves and builds no report, so the result that accepts pays nothing for them, and a rejection pays the four set operations now on that path -- `unanswered.discard(i)`, `answered.add(i)`, `i not in raised`, `trusted.add(i)`:

| operation | cost |
| --- | --- |
| the four set operations on the rejection path | 0.06us (timeit) |
| one `check()` of a one-input `ScaleModule` tree through `GuardManagerWrapper`, the call dispatch makes | 1.3us |

The comment at that block gives the same two numbers.

## The caveat

```python
# _no_match_report
coverable = any(results[i]._guard_check_enabled for i in answered)
trusted_rejection = any(results[i]._guard_check_enabled for i in trusted)   # new
...
if coverable or not results:
    advice = "Add a ModelInput covering this call, or check whether guard_filter_fn kept ..."
    if coverable and not trusted_rejection:
        advice += (" Fix the raise first: every rejection this advice rests on "
                   f"followed a raise from its own tree, and {_STALE_AFTER_THROW}.")
    lines.append(advice)
```

The report says what it knows rather than choosing. The commit below advises a `ModelInput` whenever at least one checked tree reached an answer (`coverable`); when none of those answers came before its own tree raised (`not trusted_rejection`) the same paragraph now goes on to say so: fix the raise first, since every rejection the advice rests on followed a raise from its own tree, and a C++ throw out of a tree can leave that tree's relational guard state stale.

```
Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy -- both belong to the process that compiles the artifacts, which need not be the one that loaded them. Fix the raise first: every rejection this advice rests on followed a raise from its own tree, and a C++ throw out of a tree can leave that tree's relational guard state stale, so its next check can reject a call it fits or accept one it does not.
```

The caveat does not say WHICH tree's raise it means: on the one-input reports here the raiser line above it names that tree, and the commit above makes the caveat name and quote the raises itself, since the two diverge as soon as another enabled tree raised first -- measured on the report of `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, from a commit below, where [0] raises on both passes and [1] raises on the scan and rejects after: the raiser line and the `__cause__` are [0]'s, the advice rests on [1]'s rejection alone, and [1]'s raise appears nowhere on the report (its entry line is its `check_verbose` rejection). That test now also pins that the caveat is emitted there, on a clause the commit above keeps. The two texts that promised a caveat naming those trees -- the last sentence of the `AOTCompiledModel` docstring and the comment on the report's `unanswered` branch -- now say what this caveat does say and leave the naming to that commit.

## Why the stale-state clause is hedged

```python
_STALE_AFTER_THROW = (
    "a C++ throw out of a tree can leave that tree's relational guard state "
    "stale, so its next check can reject a call it fits or accept one it does not"
)
```

The clause is hedged (`can leave`, not `leaves`) because it is emitted for both flavours of raise and is a fact about only one of them: `_reset_relational_guard_state()` runs on every return path of `RootGuardManager::check_nopybind_template` and `check_verbose_nopybind` (`torch/csrc/dynamo/guards.cpp`), so only a throw that unwinds past them skips it, and a tree that returns to pybind with an error merely set -- the `SystemError` whose chained cause `_unwrapped_raise` quotes, which is how `DICT_CONTAINS` raises, its `result == -1` branch being dead -- ran the reset on its way out.

| flavour of raise | how it reaches Python | ran the reset? |
| --- | --- | --- |
| C++ throw (`TORCH_CHECK`) unwinding past the root's exits | pybind translates it into a plain `RuntimeError`, no `__cause__` | no: state can be stale |
| error left set, normal return | `SystemError` at the pybind boundary, cause quoted by `_unwrapped_raise`; `(through the guard tree's pybind boundary)` on the entry line | yes |

The caveat is still emitted after the second flavour, and the veto below still withholds on it, because dispatch does not tell the two apart (`test_no_match_message_quotes_a_tree_that_raised_then_answered`, from a commit below, says so in as many words), and a report that called clean a rejection dispatch refused to act on would contradict the veto it explains; so the clause states what a raise can have cost, and the entry line's `(through the guard tree's pybind boundary)` is where a reader tells which flavour this one was.

The clause is a constant, `_STALE_AFTER_THROW`, so that it sits beside the comment explaining that hedge rather than inside the f-string that appends it, and so that the commit above can rewrite the caveat around it without touching it. Nothing else shares it: the class docstring states the same fact of an actual throw, unhedged, in its own prose, and the warning `_warn_swallowed` logs states the defect in its own words and is untouched here -- a caller on the report path never sees that warning anyway, since it runs only when dispatch served something and a report is built only when nothing was, so the report is the only place such a caller learns this. The constant is phrased `a C++ throw out of a tree can leave that tree's` rather than the docstring's `out of it leaves its relational guard state stale` because the caveat's own sentence names no tree, so `it` would have no antecedent in it.

## What the caveat keys on

The caveat keys on what dispatch recorded, not on the lines the report printed: the re-check is a third evaluation, and where it raises instead of rejecting -- `test_no_match_message_qualifies_the_advice_when_the_re_check_raises` -- or accepts -- the shape of #196826's `test_no_match_report_reads_the_dispatch_record_after_a_raise` -- the report quotes no rejection, but the `ModelInput` line still stands on the one dispatch got, so the caveat is emitted whatever the entry line reads.

```python
# test_no_match_message_qualifies_the_advice_when_the_re_check_raises
class RaisesThenRejectsThenRaises(RaisesOnceThenRejects):
    def check_verbose(self, f_locals):
        raise RuntimeError("the re-check is unhappy")
# report: "  [0] <guard check raised RuntimeError: the re-check is unhappy>"  (the only entry line)
#         "[0]'s guard check raised while checking this call; ..."
#         "Add a ModelInput ... every rejection this advice rests on ..."      (still qualified)
# __cause__: "the first pass is unhappy"
```

It is emitted with an opted-out entry on the report too, and after the error-set flavour of raise: `test_no_match_message_quotes_a_tree_that_raised_then_answered` puts `RaisesThenHits(raises=1)` on a checked [0] beside an opted-out [1], and its withheld line says only why the opt-out was withheld.

One trusted rejection is enough to leave the advice unqualified, even beside a rejection that followed a raise: `trusted_rejection` is an `any`, pinned by `test_no_match_message_trusts_one_rejection_taken_before_a_raise`, where [0] rejected then raised and [1] raised then rejected:

```python
results[0]._artifacts.guard_manager = RejectsOnceThenRaises("the second pass is unhappy")
results[1]._artifacts.guard_manager = RaisesOnceThenRejects("the scan is unhappy")
# "  [0] <guard check raised RuntimeError: the second pass is unhappy>"
# "  [1] stub guard rejected"
# "[1]'s guard check raised while checking this call ..."   (raised is in recording order; [1]'s scan raise came first)
# __cause__: "the scan is unhappy"
# "Add a ModelInput ..." with NO caveat: [0]'s rejection came before its raise
```

Requiring every enabled entry in `answered` to be in `trusted` instead fails only that test. Dropping `trusted_rejection` from the caveat gate fails it, `test_no_match_message_survives_a_raising_guard` and `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` on the caveat appearing. The gate's other term is `coverable`, which is what keeps the caveat off a report about an artifact with no inputs at all, where the advice is printed by the `not results` disjunct beside it and no rejection exists to have followed anything: `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` now also asserts the caveat's absence, and dropping `coverable` from the inner gate fails that test alone.

| mutation | fails |
| --- | --- |
| `trusted` recorded without the `raised` check | the five caveat-present tests above, on the caveat going missing |
| `trusted_rejection` made an `all` over the enabled entries of `answered` | `test_no_match_message_trusts_one_rejection_taken_before_a_raise` only |
| `trusted_rejection` dropped from the caveat gate | `..._trusts_one_rejection_taken_before_a_raise`, `test_no_match_message_survives_a_raising_guard`, `test_no_match_message_advises_an_input_after_an_answer_then_a_raise`, on the caveat appearing |
| `coverable` dropped from the inner gate | `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` only |

## The one real throw: `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`

The one flavour the clause is a fact about has a test on a real tree.

```python
class PairModule(torch.nn.Module):
    def forward(self, x, y):           # two tensors, so Dynamo installs NO_TENSOR_ALIASING over both
        return x + y

model._aot_compile([ModelInput(args=(torch.randn(3, 3), torch.randn(3, 3)), ...)])
nested = torch.nested.nested_tensor([torch.randn(2, 3), torch.randn(3, 3)], layout=torch.strided)
model(x, nested)
# scan:        TENSOR_MATCH on y fires TORCH_CHECK "NestedTensorImpl doesn't support strides";
#              the throw skips the reset, so NO_TENSOR_ALIASING still holds L['x']
# second pass: visits x's manager first, finds the duplicate, rejects there -- before reaching y's leaf;
#              that clean return resets the state
# re-check:    quotes y's dispatch-key mismatch, not a raise
# report:      one entry line naming L['y'], no raise line, the raiser line, the advice ending in the caveat
# __cause__:   the strides error, with nothing chained behind it (pybind translated a throw)

# probed AFTER the dispatch under test, on the same tree:
tree.check(f_locals)                    # raises "doesn't support strides"
tree.check_verbose(f_locals).verbose_code_parts   # ["Duplicate tensor found where not expected!"]
```

`PairModule` (`forward(self, x, y)`, so Dynamo installs `NO_TENSOR_ALIASING` over both) is compiled on two dense tensors and called with a strided nested tensor as `y`. `TENSOR_MATCH` on it fires a `TORCH_CHECK` (`NestedTensorImpl doesn't support strides`), pybind translates the throw into a plain `RuntimeError` with no `__cause__`, and the throw skips the reset, so the scan leaves `x` recorded in the aliasing guard; the second pass visits x's manager first, finds the duplicate and rejects there, before reaching the leaf that threw; that clean return resets the state; and the report's re-check quotes y's dispatch-key mismatch rather than a raise. Measured on that tree directly, which the test also pins: `check()` throws, and the `check_verbose()` right after it answers `Duplicate tensor found where not expected!`. The report carries one entry line naming `L['y']` and no raise line, the raiser line, and the `ModelInput` advice ending in the caveat; the `__cause__` is the strides error with nothing chained behind it.

The two probes of the tree run AFTER the dispatch under test, so that dispatch ran on a tree the test had not touched; the residue they pin is the same on the tree dispatch and the report have been through, since a `check()` after a throw still fails on x as a duplicate. The test's comment names the two orderings the shape rests on besides the skipped reset: root accessors stay in `Guard.sort_key` order, `L['x']` before `L['y']`, because the throw leaves `check_accessors_nopybind` before its fail-count bump and sort; and `TensorCheck::check_verbose` compares dispatch key sets before it reads strides, which is why the re-check names `L['y']` instead of throwing a second time. Every other test that asserts the caveat drives it with a stub whose `check()` raises from Python and touches no relational state, and the only other real throw in the suite (`test_aot_compile_module_restores_torch_function_after_a_throw`, one tensor) raises on every pass, reaches no answer, and so gets no `ModelInput` advice to qualify.

## What does not change

Against the commit below, nothing served or raised changes: the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto, the warning `_warn_swallowed` logs, every entry line and the gates on the report's closing lines are untouched. Only the `ModelInput` paragraph differs: it carries the caveat sentence when every rejection it stands on came after a raise from its own tree.

## Stubs and the golden

```python
class RaisesOnceThenRejects:                     # raises on the first check(), rejects after;
    def check_verbose(self, f_locals):           # check_verbose quotes "stub guard rejected"
        return types.SimpleNamespace(result=False, verbose_code_parts=["stub guard rejected"])

class RejectsOnceThenRaises(NeverReChecked):     # the mirror: rejects first, raises after;
    ...                                          # on NeverReChecked since its last evaluation raised

CAVEAT_AFTER_A_RAISE = "which need not be the one that loaded them. Fix the raise first: every rejection this advice rests on followed a raise from its own tree, and a C++ throw out of a tree can leave that tree's relational guard state stale, so its next check can reject a call it fits or accept one it does not."
```

The stubs that drive the caveat are two module-scope classes next to `NeverReChecked`, each taking its raise message: `RaisesOnceThenRejects` (raises on the first `check()`, rejects after, quotes a rejection in `check_verbose`) and `RejectsOnceThenRaises` (the mirror, on `NeverReChecked` since its last evaluation raised). Each replaces a local copy from the commits below -- `RaisesThenRejects` in `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, whose entry line now reads the shared stub's `stub guard rejected`, and `RejectsThenRaises` in `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` -- and the one local stub of the first shape, `RaisesThenRejectsThenRaises` in the new re-check test, subclasses `RaisesOnceThenRejects` and overrides only `check_verbose`, which is the one thing that differs. The one same-named local stub left, in `test_no_match_report_reads_the_dispatch_record_after_a_raise`, is not collapsible: its `check_verbose` accepts, and the `RaisesTwice` beside it inherits that. Every `checks` count the tests assert is unchanged. The caveat's text is one golden, `CAVEAT_AFTER_A_RAISE`, which starts in the advice's own last clause and runs through the caveat, so the two tests that assert it with `endswith` pin the junction of the two rather than the caveat alone.

## Tests

Four tests are new, and tests of the commits below gain an assertion about the caveat for their case. The ones that assert the caveat is present fail on the commit below's `aot_compile.py`:

- `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`
- `test_no_match_message_qualifies_a_rejection_that_followed_a_raise`
- `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`
- `test_no_match_message_quotes_a_tree_that_raised_then_answered`
- `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`

The rest pass there because the parent's `ModelInput` line has no caveat to find; each is a pin here by a mutation named above.

## Order to review

`_STALE_AFTER_THROW` and the comment on why it is hedged; `trusted` and its update in `accepts()`; the report's `trusted_rejection`; the caveat appended to the `ModelInput` advice at the end of `_no_match_report`; the sentence of the `AOTCompiledModel` docstring that describes the report's closing lines, and the two texts -- its last sentence and the comment on the report's `unanswered` branch -- that said what this caveat would carry; then, in the test file, the two stubs next to `NeverReChecked` and the one that subclasses one of them, `PairModule`, `CAVEAT_AFTER_A_RAISE`, `test_no_match_message_qualifies_a_rejection_that_followed_a_raise`, `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, `test_no_match_message_trusts_one_rejection_taken_before_a_raise` and `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_the_advice_when_the_re_check_raises
python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw
python test/dynamo/test_aot_compile.py -k test_no_match_message_trusts_one_rejection_taken_before_a_raise
TORCH_SHOW_CPP_STACKTRACES=1 python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw
python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raising_guard
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_after_an_answer_then_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_when_one_of_two_raisers_answered
python test/dynamo/test_aot_compile.py -k test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The caveat tests were also run against the commit below's
`torch/_dynamo/aot_compile.py`, and each gate was then mutated on its own --
`trusted_rejection` dropped from the caveat gate, `coverable` dropped from
it, `trusted_rejection` made an `all` over the enabled entries of `answered`,
`trusted_rejection` made a literal `all` over `trusted`, `trusted` recorded
without the `raised` check -- and those tests rerun; only the tests named
above failed under each.

Authored with the assistance of Claude Code.

## FAQ

> **FAQ: `_STALE_AFTER_THROW` asserts the stale relational state as a fact
> about the raise on record, but only a genuine C++ unwind skips the reset;
> for the `SystemError`-with-a-chained-cause flavour the reset ran. Hedge the
> verb, or key the clause on the `boundary` signal `_raised_line` already
> computes (`reason is not e`).**
>
> Hedged, to `can leave`; not keyed. The signal is real -- a `SystemError`
> whose `__cause__` is set is a tree that returned to pybind with an error
> set, and every return path of `check_nopybind_template` and
> `check_verbose_nopybind` resets -- but the caveat qualifies a rejection the
> last-resort veto refused to act on, and that veto withholds on either
> flavour without telling them apart
> (`test_no_match_message_quotes_a_tree_that_raised_then_answered`, from a
> commit below, states that as its premise). A clause keyed on the flavour
> would have the report call a rejection clean where dispatch just refused to
> serve an opt-out on it, and dropping the clause for that flavour would leave
> `fix the raise first` with no stated reason. So the clause says what a raise
> of either flavour can have cost -- true of the throw, vacuous of the
> error-set return -- and the entry line's `(through the guard tree's pybind
> boundary)` tells a reader which this one was. The one case the clause is a
> fact about has a real-tree test,
> `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`,
> which pins both the residue (`Duplicate tensor found where not expected!`
> from the evaluation right after the throw) and the caveat on the report
> that residue's rejection produces.

> **FAQ: The caveat restates what `warn_swallowed` already says, in other
> words, on another channel, and with no action the raiser line does not
> already give; demote it to a `log.warning` beside that text, or fold it into
> the raiser line rather than adding a fourth trailing paragraph.**
>
> Folded, into the `ModelInput` paragraph rather than the raiser line. A
> caller on the report path never sees `warn_swallowed`: it runs only when
> dispatch served something, and a report is built only when nothing was, so a
> warning beside the report would be the second channel, not the report. The
> sentence qualifies the `ModelInput` advice, so it lives in that paragraph;
> the raiser line is the wrong home because an opted-out entry on the report
> replaces it with the withheld line
> (`test_no_match_message_quotes_a_tree_that_raised_then_answered`), which
> would have lost the caveat exactly there. It carries an action of its own --
> fix the raise before adding an input -- and its stale-state clause is one
> named constant, `_STALE_AFTER_THROW`, beside the comment on why that clause
> is hedged.

> **FAQ: A mutation of the `any` in the caveat gate to `all` would pass the
> whole suite.**
>
> Measured, both readings. The literal
> `all(results[i]._guard_check_enabled for i in trusted)` fails four tests
> (`test_no_match_message_qualifies_a_rejection_that_followed_a_raise`,
> `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`,
> `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`,
> `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`) because
> `all` of an empty `trusted` is `True` and the caveat vanishes; it never
> reaches the one-trusted-beside-one-untrusted case the finding is about. That
> case is `all(i in trusted for i in answered if
> results[i]._guard_check_enabled)`, which fails exactly
> `test_no_match_message_trusts_one_rejection_taken_before_a_raise` and
> nothing else. That test passes on the parent for the same reason the other
> two do (no caveat to find), so it is a pin of this commit's `any`, not a
> red-on-parent.

> **FAQ: An entry that raised on one pass and rejected on the other is not in
> `unanswered`, so its line quotes a third evaluation, `check_verbose(bound[i])`,
> which runs under the same stale relational state the caveat warns about; and
> since `trusted_rejection` is an `any`, one clean rejection elsewhere
> suppresses the caveat and that line stands unqualified ([1]'s `stub guard
> rejected` in `test_no_match_message_trusts_one_rejection_taken_before_a_raise`).
> Mark such entries per line -- an index in `raised` and `answered` but not in
> `trusted` -- reusing `_STALE_AFTER_THROW`.**
>
> Declined: the third evaluation is not the stale one, measured.
> `_reset_relational_guard_state()` runs on every return path of
> `RootGuardManager::check_nopybind_template` and `check_verbose_nopybind`
> (`torch/csrc/dynamo/guards.cpp`) and only a throw skips it, so the one
> evaluation that runs on stale state is the first to complete after the throw
> -- dispatch's second-pass `check()`, the rejection the advice rests on -- and
> that evaluation's own return resets the state before the report's
> `check_verbose` runs. On a hand-built tree (`install_no_tensor_aliasing_guard`
> over `x` and `y`, `add_tensor_match_guard` on `y`): `check(x, nested)` throws
> `NestedTensorImpl doesn't support strides` out of the C++ leaf after the
> aliasing guard has recorded `x`; the next `check(x, y)` returns `False` for a
> call the fresh tree accepts (the stale rejection); the `check_verbose(x, y)`
> after it returns `True`; and a `check_verbose(x, y)` made directly after the
> throw instead returns `False` with `Duplicate tensor found where not
> expected!`. The same sequence on Dynamo's own `PairModule` tree is what
> `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`
> pins. So the reason quoted on such a line is the clean verdict on the
> same f_locals, and a marker saying it came out of stale state would be
> false. What the reader needs is on the report already: the raiser line says
> a checked tree raised and to fix or drop it, and the answer that may be
> stale is dispatch's, which is the one the caveat qualifies; where that
> stale rejection was spurious the clean re-check accepts and the entry line
> reports that disagreement in so many words.

> **FAQ: The caveat's `Fix the raise first` names no index, and the nearest
> indexed raise on the report can be the wrong one: with [0] enabled raising
> on both passes and [1] enabled raising on the scan then rejecting, the
> raiser line names [0], the `__cause__` is [0]'s, and [1]'s raise -- the sole
> reason the caveat is emitted -- appears nowhere. Name the indices whose
> raise made the rejection untrusted and quote each one's raise from
> `raised[i]`, and add a test for that two-entry shape.**
>
> Measured, and done in the commit above, `[aot_compile] Name and quote the
> raises the no-match report's caveat means` (#197257). At this commit that
> shape is the report of
> `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`:
> `[0] <guard check raised RuntimeError: the first tree is unhappy>`, `[1]
> stub guard rejected`, `[0]'s guard check raised while checking this call`,
> the advice ending in `Fix the raise first: ...`, `__cause__` =
> `RuntimeError('the first tree is unhappy')`, and `the second tree's first
> pass is unhappy` on the report zero times. The same dispatch under the
> commit above's `aot_compile.py` ends the advice in `Fix the raise out of
> [1] <RuntimeError: the second tree's first pass is unhappy> first: ...`,
> that text once, with the raiser line and the `__cause__` unchanged, and the
> commit above's test for that two-entry shape pins all of it. Not here,
> because naming needs `_raise_text` split out of `_raised_line` and the list
> over the enabled entries of `answered`, which with their tests are what this
> commit was split from for review budget; what this commit owns is WHETHER
> the caveat is emitted, and the two-raiser test now pins that it is in this
> shape too, on the clause `followed a raise from its own tree` that the named
> caveat keeps. That assertion fails on the commit below, and fails here with
> `trusted` recorded without the `raised` check or with the gate's `any` made
> a literal `all` over `trusted`.

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

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

Pull Request resolved: #197050
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 18b5461d529b; all four items plus the two nits are fixed.

1. > the final docstring sentence states the caveat's gate as a global chronology and misattaches its last clause. [...] Reword it to say "before any raise from its own tree", matching the advice string at line 2344. (2) The clause "and is the __cause__ when recorded first of all" coordinates with "carries", so its subject is "which" = the entry line.

Fixed in 18b5461d529b: the parenthetical now reads "no rejection it rests on taken before any raise from its own tree", and the last clause is its own sentence with the dispatch raise as subject: "that raise is the __cause__ when recorded first of all".

2. > same misreading of trusted, and this one is contradicted by a test already in the file. [...] The accurate blocking condition is an enabled tree that rejected before any raise from its own tree.

Fixed in 18b5461d529b: the comment now says "rejected before any raise from its own tree, whether or not it raised after", which matches test_no_match_message_trusts_one_rejection_taken_before_a_raise.

3. > _raise_text gains a third caller [...] the reachability comment on _quoted (158-166) was not updated for it.

Fixed in 18b5461d529b: the _quoted comment names the caveat as a caller and states that an interrupt out of __str__ escapes the report there as on the two _raised_line sites. Behaviour unchanged.

4. > test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary inlines torch.compile(DictBranchModule(), ...) [...] Use the helper.

Fixed in 18b5461d529b: it uses self._aot_compile_dict_branches({}).

5. > the enabled[i] filter is defended by ten of the comment's lines and exercised by no test [...] none opts out the only untrusted answered entry under the loop.

Fixed in 18b5461d529b: test_no_match_message_caveat_reads_the_opt_out_snapshot opts the only untrusted answered entry out from inside its check_verbose and asserts the caveat still names it; a fresh _guard_check_enabled read there produces Fix the raise out of first and fails that test alone.

6. > this edit weakened a pin. assertNotIn("the first pass is unhappy", message) guaranteed the text appeared zero times; assertIn(...) only that it appears at least once.

Fixed in 18b5461d529b: the assertIn stays and message.count("the first pass is unhappy") == 1 is asserted beside it, so an entry-line leak is caught again.

@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 30m 38s —— View job


One sentence summary

All six items from the last pass are genuinely fixed and the caveat's construction is provably sound at this head, but the docstring sentence rewritten for item 1 makes an unqualified claim about every dispatch raise a later evaluation answered that this PR's own new opted-out test is the counterexample to.

PR Review: #197257

Summary

Splits _raise_text out of _raised_line and uses it to make the no-match report's post-raise caveat name and quote every enabled tree whose rejection the ModelInput advice rests on. Re-verified at 18b5461d529b:

  • The docstring parenthetical now reads "before any raise from its own tree" (1902-1903) and the __cause__ clause is its own sentence with the raise as subject (1905) — item 1 fixed.
  • The entry-line comment now reads "rejected before any raise from its own tree, whether or not it raised after" (2239-2240), which matches RejectsOnceThenRaises and test_no_match_message_trusts_one_rejection_taken_before_a_raise — item 2 fixed.
  • _quoted's reachability comment names the caveat as a third caller and states the interrupt cost (164-169) — item 3 fixed.
  • test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary uses self._aot_compile_dict_branches({}) (5323) — item 4 fixed.
  • test_no_match_message_caveat_reads_the_opt_out_snapshot (5343) does opt [1] out from inside check_verbose, i.e. under the entry loop at 2246 and after both gates at 2214-2215; traced by hand, the snapshot yields [1] <RuntimeError: the scan is unhappy> and a fresh read yields an empty list — item 5 fixed, and it is the first test that can tell the two reads apart.
  • test:4455-4456 keeps the assertIn and adds count(...) == 1 — item 6 fixed.

I also re-derived the invariant the comment at 2337-2339 asserts: for i in answered with enabled[i], the gate not trusted_rejection forces i not in trusted, and accepts() (2087-2094) only reaches trusted.add(i) when i not in raised — so raised[i] is always present, the list is non-empty under coverable, and - trusted is genuinely unnecessary. The inline first-result path (2048-2050) adds to both sets before anything can be in raised, so it does not break the argument. raised[i] is also always the raise the rejection followed: dispatch evaluates an index at most twice, so an index that rejected last raised first. The trailing-separator residue is correctly declined.

One problem, plus two non-blocking items.

API Design

  • torch/_dynamo/aot_compile.py:1901-1905 — the rewritten sentence is unqualified where the code filters: "A dispatch raise a later evaluation answered is quoted by the advice's caveat where it fires -- no rejection it rests on taken before any raise from its own tree -- not on its entry line...". The caveat's entry list filters on enabled[i] (2343), so an opted-out tree that raised and then rejected is in answered, is not in trusted, and is skipped anyway. That shape is not hypothetical — it is the shape this PR adds a test for: test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection (test:5371) puts RaisesOnceThenRejects on an opted-out [1], the caveat fires, and test:5413 asserts [1]'s message appears nowhere on the report. So for [1] the sentence's subject holds, its stated gate holds (no trusted rejection), the caveat fires, and the raise is still not quoted. The docstring does say elsewhere (1881-1883) that an opted-out result gets the withheld line, but this sentence overrides that by naming no exception to itself. Qualify it to a tree nobody opted out, and say the opted-out one's raise is carried by its withheld line instead.

    Same omission, weaker case, at :2237-2241: "the caveat below is the only line that can carry that raise ... it does not fire where another enabled tree rejected before any raise from its own tree" reads as if that were the only way the raise goes uncarried, where an opted-out tree's is dropped by the filter and a report with no enabled answered entry has no advice at all (coverable, 2314). The can and the enabled-only branch it sits in blunt this one; the docstring's is the one worth fixing.
    Fix this →

Code Quality

  • torch/_dynamo/aot_compile.py:2322-2344 — non-blocking: 18 comment lines over 5 lines of code, and the four that defend the snapshot read ("check_verbose ran user code under the loop above, so a fresh read could drop an entry this report printed as a rejection -- naming no tree at all when it was the only one") now restate what test_no_match_message_caveat_reads_the_opt_out_snapshot and its own six-line comment say. One sentence naming the snapshot and pointing at the agreement invariant already stated at 2205-2210 would carry it. The one clause I would keep verbatim is the non-emptiness argument at 2337-2339, since that is what licenses the unguarded raised[i] and the missing - trusted. Also: untrusted (2340) holds formatted strings, and being untrusted is the property the comment has to prove rather than something the list carries — named or entries would not ask the reader to take the name on faith.

Testing

  • test/dynamo/test_aot_compile.py:5343 — non-blocking: the new snapshot test pins the caveat but not that the rest of the report agrees with it. The same snapshot decides withheld (2216) and [1]'s entry line, so with the mid-loop opt-out the report prints [1]'s rejection and no withheld line even though results[1]._guard_check_enabled is False by the time the test reads it (asserted at 5365). That is exactly the "the entries, the raiser they name and the veto must agree" invariant at 2205-2210, and one assertNotIn("opted out of guard checks", message) would pin it — otherwise a regression that moved only the entry-line/footer reads to a fresh flag read would leave this test green.
    Fix this →

Recommendation

Request Changes — for the docstring sentence only; the other two are take-or-leave.

Everything else holds up: the caveat's construction and its non-emptiness proof, both gates on the snapshot, the dropped - trusted, kind inside the collapse with a golden that is byte-exact for type("Odd\nKind", ...) plus five separators (splitlines() breaks on all six and drops the trailing empty field), the semicolon join over a comma, the str(cause)-only collapse in the C++-throw golden, and the five new tests.

I could not run the Test Plan — there is no .venv in the repo or its parent and no built torch in this checkout, so the twelve commands are unverified here. CI on 18b5461d529b: Lint, BC Lint and the ghstack mergeability check green; pull, inductor, docs-build and torchtitan-test still running, so test/dynamo/test_aot_compile.py has not reported yet on this head.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 40a5dd967c26; the blocker is resolved by deletion, one take-or-leave item is taken, one declined.

1. > the rewritten sentence is unqualified where the code filters [...] Qualify it to a tree nobody opted out, and say the opted-out one's raise is carried by its withheld line instead.

Fixed in 40a5dd967c26 by deleting the sentence rather than qualifying it a fifth time: the docstring already states each of its parts once -- the entry-line shapes, the caveat's own gate, the opted-out withheld line, and the __cause__ rule -- so the sentence only restated them and every restatement drifted. The check_verbose-only sentence before it stays; the comment at the raise entry line already carries "can" and sits in the enabled-only branch, as you noted.

2. > the new snapshot test pins the caveat but not that the rest of the report agrees with it. [...] one assertNotIn("opted out of guard checks", message) would pin it.

Fixed in 40a5dd967c26: test_no_match_message_caveat_reads_the_opt_out_snapshot now asserts that line is absent, so a regression that moved only the entry-line or footer reads to a fresh flag read fails it.

3. > 18 comment lines over 5 lines of code [...] untrusted (2340) holds formatted strings [...] named or entries would not ask the reader to take the name on faith.

Declined: the comment keeps the non-emptiness argument you asked to keep verbatim and the snapshot sentence the mid-loop test now backs; trimming it further and renaming the local are churn on a settled diff.

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

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


One sentence summary

The caveat's construction is provably correct at this head and every prior-round item is fixed, but the 18-line comment this PR adds above it states two things the code does not do — one of them contradicted by the file's own docstring and by a test two hundred lines away, the other self-contradicted two lines up.

PR Review: #197257

Summary

Splits _raise_text out of _raised_line and uses it to make the no-match report's post-raise caveat name and quote every enabled tree whose rejection the ModelInput advice rests on. I re-derived the construction from scratch at 40a5dd94 and it holds unconditionally:

  • No KeyError on raised[i]. answered/trusted are written only at 2045/2046 (inline) and 2088/2090 (accepts), never removed from; dispatch evaluates each index at most twice (inline-or-first-loop plus second loop, both of which return on an accept). So i in answered and i not in trusted forces the 2088 path with i in raised already true. Under not trusted_rejection every kept i is outside trusted, hence in raised.
  • untrusted is never empty. coverable (2210) is the identical predicate to the comprehension's filter over the identical set, so any witness to the gate is kept — the doubled-space Fix the raise out of first is now unreachable.
  • Entry-line agreement. A kept i raised first and rejected second, and that rejection ran unanswered.discard(i) (2087), so it never takes the _raised_line branch. The reverse order leaves i in trusted and closes the gate.

Also verified by hand: the odd-separators golden at test:2668 is byte-exact (splitlines() breaks on all five of \x0c \r \x1e 
 
, and the trailing 
 yields an empty field it drops), and it catches both the raw-kind mutation and reverting the collapse to the base's after-the-boundary placement. Prior rounds' items — both gates on the snapshot, - trusted dropped, kind inside the collapse, the helper at test:5323, the mid-loop snapshot test, the restored count == 1 at test:4456, and the deleted self-contradictory docstring sentence — are all genuinely in. The trailing-separator residue is correctly declined.

Three problems, all in the comment added at 2318-2335.

Code Quality

  • torch/_dynamo/aot_compile.py:2321 — "the entry line quotes the rejection" is false for the entries the caveat names, and line 2319 says the opposite. As established above, every named index falls through to the re-check, whose line is one of four shapes and only one of which is a quoted rejection. Two of the others are pinned by this PR's own edits: test_no_match_report_reads_the_dispatch_record_after_a_raise (test:4447) has [0]'s line be _ACCEPTED_IN_THE_REPORT while only the caveat carries its raise, and test_no_match_message_qualifies_the_advice_when_the_re_check_raises (test:3716) has it be <guard check raised RuntimeError: the re-check is unhappy>. The fourth is <guard check failed without naming a guard> (2265), which quotes nothing at all. Two lines up, 2319 already says "the re-check may have printed a raise or an accept instead" — so the comment asserts and denies the same thing within one sentence of itself. The accurate claim is the one the conclusion needs: the entry line carries only the re-check's own verdict, never the raise dispatch recorded.
    Fix this →

  • torch/_dynamo/aot_compile.py:2323 — "the chain carries the first raise of all" is false, and the file says so twice elsewhere. The chain is raise RuntimeError(report) from next(iter(raised.values())) (2158); raised is keyed in first-raise order but each value is overwritten by that index's later raise, so the chain carries the last raise of the first index that raised. The class docstring at 1800 states it correctly ("the last raise of the first input that raased in dispatch"), the chain's own comment at 2154-2157 says "the index that raised first" rather than the raise, and test_no_match_message_quotes_the_last_raise_at_one_index (test:4478) pins __cause__ as "pass 2 unhappy" when the first raise of all was "pass 1 unhappy". This matters inside the caveat's own reach, not just in the abstract: in test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice (test:5228) [0] raises on both passes and the caveat fires, so the chain there is [0]'s second raise.
    Fix this →

Testing

  • torch/_dynamo/aot_compile.py:2337 — the collapse is the reason _raise_text exists rather than an inline f-string, but no test exercises it in the caveat position on a normal run. Every caveat golden quotes single-line text; the only separator-bearing text in the file reaches _raised_line (test:2643). The one caveat test that appears to cover it, test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw, computes collapsed = " ".join(str(cause).splitlines()) at test:5178 — a no-op unless TORCH_SHOW_CPP_STACKTRACES=1, which only a run_test.py retry sets, so on a normal run that golden is byte-identical to the uncollapsed string. A caveat-local regression that rebuilt the quote inline without the collapse would leave the whole file green and split the advice paragraph across lines, which is exactly the failure mode _raise_text's comment says the collapse prevents. Give one caveat test a message holding a separator — test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice (test:5228) is a one-entry caveat and already asserts the whole paragraph, so putting "the scan\ris unhappy" in RaisesOnceThenRejects and the collapsed form in the golden covers it without a new test.
    Fix this →

  • torch/_dynamo/aot_compile.py:2338 — low confidence, mutation coverage only: you noted sorted is incidental and the description now says so, which resolves the over-claim. Worth recording why no test can catch it: the only multi-entry caveat test uses indices 0 and 1, and a CPython small-int set iterates ascending for elements below the table size, so divergence needs an index colliding modulo that size (answered == {1, 8} with 8 inserted first iterates 8, 1) — nine-plus compiled inputs, which no test in this family has. Either leave it as documented-incidental or make the golden order-insensitive; asserting a fixed order that nothing can violate is the one thing worth avoiding.

Recommendation

Request Changes — for the two false clauses at 2321 and 2323, which are one edit each.

The caveat's semantics and non-emptiness proof, the enabled-only filter, the semicolon join over a comma, kind inside the collapse, the str(cause)-only collapse in the C++-throw golden, and all five new tests hold up. The missing collapse coverage in the caveat position is a real gap but a small one.

I could not run the Test Plan — there is no .venv in the repo or its parent and no built torch in this checkout, so the twelve commands are unverified here. CI on 40a5dd94: Lint, BC Lint and the ghstack mergeability check green; pull, inductor, docs-build and torchtitan-test still in progress, so test/dynamo/test_aot_compile.py has not reported on this head yet.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 4f1da674d258; both items are fixed, by cutting the comment down rather than rewording it again.

1. > "the entry line quotes the rejection" is false for the entries the caveat names, and line 2319 says the opposite.

Fixed in 4f1da674d258: the comment now says an entry line carries only the re-check's own verdict, and the sentence that contradicted line 2319 is gone.

2. > "the chain carries the first raise of all" is false, and the file says so twice elsewhere. [...] Reword line 2323 to "the chain carries the last raise of the first index that raised".

Fixed in 4f1da674d258: it reads "the chain carries the last raise of the first index that raised", matching the class docstring and the chain's own comment. The block is ten lines now: what the caveat is keyed on and why nothing else quotes these raises, the bracket-and-semicolon format, and the snapshot argument that makes the list agree with the entry lines and never be empty.

@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 19m 6s —— View job


One sentence summary

Both items from the last pass are fixed and I re-derived the caveat's construction from scratch at this head — it is sound and the comment is now proportionate; the only things left are one clause in that comment that lists the __cause__ chain among places which do not carry these raises (a test in this PR shows it can carry exactly one of them), and the still-unpinned collapse in the caveat position.

PR Review: #197257

Summary

Splits _raise_text out of _raised_line and uses it to make the no-match report's post-raise caveat name and quote every enabled tree whose rejection the ModelInput advice rests on.

Re-verified at 4f1da674d258:

  • Item 1 fixed. aot_compile.py:2318-2319 now reads "an entry line carries only the re-check's own verdict", and the sentence that contradicted it is gone. This is the accurate claim, and it is the one the conclusion needs: for every index the caveat names, accepts() ran unanswered.discard(i) (2087), so the entry loop takes the check_verbose branch and prints the re-check's rejection, the accepted-here line (2252), the no-guard-named line (2265), or the re-check's own raise (2248) — never raised[i].
  • Item 2 fixed. :2320-2321 reads "the chain carries the last raise of the first index that raised", matching the class docstring at 1800, the chain comment at 2154-2157, and test_no_match_message_quotes_the_last_raise_at_one_index.
  • The comment is 10 lines over 5 lines of code now, down from 18, and keeps the non-emptiness argument that licenses the unguarded raised[i] and the absent - trusted.

Construction re-derived independently:

  • No KeyError on raised[i]. answered is written only at 2045 and 2088, and each write is paired with trusted.add(i) when i not in raised, so answered \ trusted ⊆ raised. Nothing is ever removed from any of the three sets. Under not trusted_rejection every kept index is outside trusted, hence in raised.
  • untrusted is never empty. coverable (2210) is the identical predicate over the identical set as the comprehension's filter, both off the same immutable enabled list, so any witness to the gate is kept.
  • raised[i] is the raise that rejection actually followed. Dispatch evaluates each index at most twice (inline-or-scan plus the second loop, both of which return on an accept), so an index that rejected raised on exactly one prior evaluation — the one raised[i] holds.
  • Odd-separators golden is byte-exact. "Odd\nKind: page\x0cbreak\rrec\x1esep
line
" splits on all six separators with the trailing empty field dropped, giving Odd Kind: page break rec sep line and no stray space before (through ...). It catches both the raw-kind mutation and reverting the collapse to the base's after-the-bracket placement.
  • test_no_match_message_caveat_reads_the_opt_out_snapshot (test:5343) genuinely distinguishes the snapshot from a fresh read: the snapshot is taken at 2133, both gates run at 2210-2211 before any user code, and check_verbose at 2242 is the first user code — so [1], the only untrusted answered entry, is dropped by a fresh read and the sentence loses its subject.

Two small items, both non-blocking.

Code Quality

  • torch/_dynamo/aot_compile.py:2320-2322 — the chain does not belong in this enumeration. The clause reads "the raiser line names the first enabled raiser, and the chain carries the last raise of the first index that raised, so nothing else on the report quotes these raises". The chain is not on the report — it is __cause__ (2158) — and it can carry exactly one of the raises the caveat quotes: in test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice (test:5265) both trees raise on the scan and reject on pass 2, so raised's first value is [0]'s, which is both str(ctx.exception.__cause__) (test:5303) and the first entry of the caveat (test:5306). The conclusion survives only because of the "on the report" scoping, which the chain sits outside of; as written the clause reads as though the chain carried a different raise. The entry-line and raiser-line clauses are the two that actually establish the conclusion — drop the chain from the list, or say separately that the chain may repeat the first named entry's raise off the report.
    Fix this →

Testing

  • torch/_dynamo/aot_compile.py:2329 — carried over from the last pass and not addressed in your reply: the newline collapse is the reason _raise_text exists rather than an inline f-string, but nothing exercises it in the caveat position on a normal run. Every caveat golden quotes single-line text; the only separator-bearing text in the file reaches _raised_line (test:2647); and the one caveat test that looks like it covers this, test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw, computes collapsed = " ".join(str(cause).splitlines()) (test:5178), which is the identity unless TORCH_SHOW_CPP_STACKTRACES=1 — set only on a run_test.py retry. So a caveat-local regression that rebuilt the quote without the collapse would split the advice paragraph across lines and leave the whole file green. test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice (test:5228) is a one-entry caveat that already pins the whole paragraph, so putting a separator in RaisesOnceThenRejects's message and the collapsed form in the golden closes it without a new test.
    Fix this →

Recommendation

LGTM — neither item blocks. The chain clause is one deletion inside a comment; the collapse coverage is a three-character change to an existing test's stub message plus its golden, and is worth doing while the goldens are open.

Everything else holds up: the caveat's semantics and non-emptiness proof, both gates on the snapshot, the absent - trusted, the enabled-only filter with its mid-loop test, kind inside the collapse with a byte-exact golden, the semicolon join over a comma, the str(cause)-only collapse in the C++-throw golden, the six new tests, and the reworded _quoted reachability comment. The trailing-separator residue is correctly declined. No non-ASCII in added comments; no added line over the column limit.

I could not run the Test Plan — there is no .venv in the repo or its parent and no built torch in this checkout, so the twelve commands are unverified here. CI on 4f1da674d258: BC Lint and the ghstack mergeability check green; pull, Lint, inductor, docs-build and torchtitan-test in progress, so test/dynamo/test_aot_compile.py has not reported on this head yet.

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

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 19, 2026 03:50
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 19, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: This PR needs a release notes: label
If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Details for Dev Infra team Raised by workflow job

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197746

pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…as (#197745)

**Problem.** `IMPORT_NAME` checked that `__import__`'s result was a module only after `import_source` had already bound the result into the traced globals and a process-wide cache, so a non-module `sys.modules` entry was left behind in both, and a later trace with a real module in the entry crashed with an `InternalTorchDynamoError` instead of compiling.

**Fix.** Move the module-type check ahead of the `import_source` call, so a non-module never reaches the traced globals or the cache and the graph break happens first; the replay arm needs no check and pushes as-is.

**Summary.** `IMPORT_NAME` tested `__import__`'s result with `isinstance(value, (types.ModuleType, DummyModule))` at push time, after `import_source` had already minted `__import_<mangled>` for the name and written that result into `self.output.global_scope` -- the root frame's real globals, a live module `__dict__` that nothing unwinds -- and into `_import_module`'s process-wide cache. `sys.modules` accepts any object and `__import__` hands it back verbatim, so a non-module entry was bound under the alias and only then graph-broken on (`Bad import result`), and a later trace, after a real module had replaced the entry, passed the push-time check on the module `__import__` returned while `import_source` served the cached non-module: the alias kept the non-module, the pushed variable held the module, and the guards built on the alias read `VALUE` off an `object()`, an `InternalTorchDynamoError` on a trace that should have compiled. Hoisting the check ahead of the `import_source` call keeps the non-module out of the traced globals and out of the cache, since the call that filled it no longer runs, so a later trace with a real module in the entry binds the alias to that module and compiles. The hoisted test is `isinstance(value, types.ModuleType)` alone and sits on the import arm only, because a replayed value is a `DummyModule`, a plain dataclass that is not a `ModuleType`, which `add_local_mod` already rejected non-modules for when the record was written, so the replay arm pushes with no type test and the `DummyModule` import goes away. Two behaviours change against the parent, both pinned or explained below: `IMPORT_NAME` of a non-module entry no longer writes the alias before breaking, and with `replay_record_enabled` on such an entry reaches the graph break instead of `add_local_mod`'s `AssertionError`.

## The bug: bind first, check second

```python
# parent, IMPORT_NAME
value = __import__(module_name, ...)                    # sys.modules[name] handed back verbatim
source = self.import_source(module_name)                # mints __import_<mangled>, writes value into
                                                        # self.output.global_scope AND _import_module's cache
if isinstance(value, (types.ModuleType, DummyModule)):  # checked only now
    self.push(PythonModuleVariable(value, source=source))
else:
    unimplemented(gb_type="Bad import result", ...)     # too late: the alias is already bound
```

`self.output.global_scope` is the root frame's real globals, a live module `__dict__` that nothing unwinds, so the non-module stayed bound under the alias for good. The second failure follows from the cache:

```python
sys.modules[name] = object()
torch.compile(fn)(x)        # parent: Unsupported: Bad import result -- but fn.__globals__["__import_..."] is the object()
torch._dynamo.reset()
sys.modules[name] = module  # a real module now
torch.compile(fn)(x)        # parent: InternalTorchDynamoError -- the guards read VALUE off the cached object()
                            # now:    compiles, agrees with eager, alias bound to `module`
```

On the parent's second trace, `__import__` returned the module, so the push-time check passed, but `import_source` served the cached non-module: the alias kept the non-module, the pushed variable held the module, and the guards built on the alias read `VALUE` off an `object()`.

## The fix: check before `import_source`

```python
# now, IMPORT_NAME, import arm
value = __import__(module_name, ...)
if not isinstance(value, types.ModuleType):
    unimplemented(gb_type="Bad import result", context=typestr(value),
                  explanation="Import result is not a Python module.", hints=[])
...
source = self.import_source(module_name)                # never reached with a non-module
...
self.push(PythonModuleVariable(value, source=source))   # no type test on either arm
```

Hoisting the check ahead of the `import_source` call keeps the non-module out of the traced globals and out of the cache, since the call that filled it no longer runs: a later trace with a real module in the entry binds the alias to that module and compiles.

**Why `ModuleType` alone, on the import arm only.** A replayed value is a `DummyModule`, a plain dataclass that is not a `ModuleType`, so a check on that arm would refuse every replay -- and needs none, `add_local_mod` having rejected non-modules when the record was written. That is why the replay arm now pushes with no type test at all, and why the `DummyModule` half of the old condition, which existed only for it, goes away with the import from `replay_record`.

## The other nine `import_source` callers

The check guards this one call site. The other nine `import_source` callers reach it with no module-type test, and a non-module entry under one of their names is still bound verbatim there, unchanged here -- though `get_globals_source_and_value` already brings its own test, since `_registered_module_for_globals` returns a name only for a `types.ModuleType` whose `__dict__` is the frame's globals. Those names are torch's own and stdlib ones, or a class's `__module__`; a non-module under one of them is a broken process, not a trace to save. `IMPORT_NAME` is the one caller resolving a name the traced bytecode chose, which is what makes its result worth checking.

## Behaviour changes against the parent

- **`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` pins it by planting a non-module, requiring the `Bad import result` graph break and an unbound alias, and then, with a real module in the entry, a compile that agrees with eager and an alias bound to that module.
- **With `replay_record_enabled` on (off by default), such an entry now reaches that graph break** instead of the `AssertionError` `add_local_mod` raised first when it ran ahead of the check. That one is untested, since the path is the parent's `add_local_mod` and the config is off by default.

## The test

```python
name = "torch_test_package_import_alias_non_module"
alias = f"__import_{name}"

def fn(x):
    import torch_test_package_import_alias_non_module as taken
    return x + taken.VALUE

sys.modules[name] = object()
with self.assertRaisesRegex(Unsupported, "Bad import result"):
    torch.compile(fn, backend="eager", fullgraph=True)(*args)
self.assertNotIn(alias, fn.__globals__)              # parent: the alias is bound to the object()
torch._dynamo.reset()
sys.modules[name] = module                           # types.ModuleType(name) with VALUE = 1
compiled = torch.compile(fn, backend="eager", fullgraph=True)
self.assertEqual(fn(*args), compiled(*args))         # parent: InternalTorchDynamoError from the guard build
self.assertIs(fn.__globals__[alias], module)
```

The cleanup clears `_import_module`'s cache as well as `sys.modules` and the alias, since the memo outlives the `sys.modules` entry and a same-process rerun would otherwise resolve this run's module from it.

The test lives in `test_package.py` rather than `test_misc.py` because the alias binding this is about is the one `CompilePackage` records and `install()` rebinds, and that file already owns the rest of the `import_sources` coverage.

Test Plan:

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

The new test is red on the parent's `torch/_dynamo/symbolic_convert.py`, on the
alias the parent wrote before breaking, and its second half fails there too,
with the guard-build `AttributeError` on the cached `object()`; restoring the
push-time `isinstance` in place of the hoisted one reproduces the first failure. The whole file is green at
this commit.

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

The `Bad import result` registry entry is unchanged: the call moves, its
strings do not.

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197745
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050, #197257
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…197746)

A refactor with no behaviour change, to make room for the commit directly
above, which gives `import_source` a second argument: `graph_break_ok`, the
flag that decides whether an alias slot already holding something else is a
graph break or a hard error.

`cache_method` keys on the whole argument tuple, so that flag would silently
become part of the key, and a module name that two callers on one translator
both resolve would run the body once per distinct flag value instead of once.
Nothing about the second run would be wrong -- `f_globals[alias] is value`
holds by then, so the check is skipped, and the package record and
`update_co_names` are idempotent -- but the memo exists to make resolution
happen once, and the flag cannot change the answer a memo hit returns: it is
read only when the slot is taken, which a hit rules out, because the memo is
written only past that check. First-caller-wins is therefore the same source
any caller would have got. Keying on `module_name` alone also lets the new
argument be passed by keyword at the call sites, which the decorator forbade.

So the decorator gives way to an explicit `_import_source_memo` dict declared
in `InstructionTranslatorBase.__init__`, read at the top of the method and
written just before the return. Its lifetime is the decorator's: it lives on
the translator and dies with it, which is what made the cache safe in the first
place -- the alias it hands back names a global in the globals of the compile
that minted it. The comment above the method now says why the key is one
argument rather than the signature.

Test Plan:

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

Behaviour-neutrality was also measured directly on this tree, on a frame doing
`from torch.autograd.profiler import profile` with `config.record_runtime_overhead`
on, so that `IMPORT_NAME` and codegen's pregraph marker both resolve
`torch.autograd.profiler`: the sequence of aliases `import_source` resolves
across the compile is identical before and after this commit.

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

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197746
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050, #197257, #197745
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1213/head branch November 22, 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 Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants