Skip to content

[aot_compile] Pin the raise-tolerant module dispatch's exits and binding - #197219

Closed
bobrenjc93 wants to merge 21 commits into
gh/bobrenjc93/1209/basefrom
gh/bobrenjc93/1209/head
Closed

bobrenjc93 wants to merge 21 commits into
gh/bobrenjc93/1209/basefrom
gh/bobrenjc93/1209/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. #196826 made AOTCompiledModel dispatch record a guard tree that raises and either serve over it (with a warning) or fold it into the no-match report, but three exits that leave __call__ with a raise on record and nothing logged -- a bare SystemExit out of a later tree, a later result whose signature cannot take the call, a call the one signature cannot take -- were unpinned, as was the promise that a call binds once per result across both dispatch passes and the report.

Fix. Three tests and one two-signature helper pin those exits, and two assertions are folded into the landed per-result binding test. No source change.

Summary. Test-only, 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 this commit does not touch. The three tests here were three of the twelve of [aot_compile] Pin the raise-tolerant module dispatch's warning: its paths, text and dedup (#197195), directly below; this commit adds them without touching the eight that stayed there, and folds a fourth's two assertions into the landed test whose setup it repeated. They pin the exits of AOTCompiledModel.__call__ that record a raise nowhere -- a SystemExit out of a later tree, a later result whose signature cannot take the call, a call the one signature cannot take -- and that a call binds once per result across both dispatch passes and the report. One module-level helper, compile_two_signatures, builds the two-signature model the landed binding test and the cannot-bind test assemble, and the stub guard manager both raise tests need is the file's own module-level RaisingTree(text), adopted at the two sites where each had an inline copy. The two negative pins each fail a mutant of their own and the two raise tests each error against #196826's parent, measured as the Test Plan records.

Where they sit

The two about binding join the landed test_module_dispatch_* tests on how a call binds, directly after test_module_dispatch_binds_per_result_when_signatures_differ, under that prefix, and, like that cluster, without _hide_leaked_dynamo_globals; test_aot_compile_module_system_exit_out_of_a_later_tree_propagates stays among #197195's dedup tests, because its last call is a dedup pin, and calls it as they all do.

The helper and the stub

def compile_two_signatures(x, second_forward, *second_call):
    # One module, two results: [0] is ScaleModule's own forward compiled for `x`,
    # [1] is `second_forward` compiled for `second_call`. They bind alike iff
    # `second_forward`'s parameters (names, kinds, defaults) and closure cells
    # match forward's, so a caller wanting a non-shared binding varies one.
    mod = ScaleModule()
    doubled = aot_compile_forward(mod, ScaleModule.forward, x)
    second = aot_compile_forward(mod, second_forward, *second_call)
    return AOTCompiledModel(mod, [doubled, second])

One module-level helper beside compile_mode_defaults serves them: compile_two_signatures, the two-signature model that landed test and the cannot-bind test assemble, built from the same aot_compile_forward. Its comment states when the two results bind alike -- iff second_forward's parameters and closure cells match forward's, measured: a (self, x) second forward binds alike, one named (self, y) or given a default does not -- rather than promising they never do. The stub guard manager both tests need for the result whose tree raises is the file's own module-level RaisingTree(text), adopted at the two sites where each had an inline copy; neither reads its checks counter, so this commit adds no second always-raising class beside it (FAQ below).

The exits that record nothing

Every path in #196826 that RETURNS a graph with a raise on record logs one, every path that builds a report chains one, and a call that ends in neither leaves as the exception that ended it; its FAQ says why nothing is logged on the way out.

A bare SystemExit out of a later tree

class Exits:
    def check(self, f_locals):
        raise SystemExit("inside the tree")

results[0]._artifacts.guard_manager = RaisingTree("zero is unhappy")
results[1]._artifacts.guard_manager = Exits()
with self.assertNoLogs(logger, level="WARNING"):
    with self.assertRaisesRegex(SystemExit, "inside the tree"):
        model(x)                                  # leaves __call__ as the SystemExit, nothing logged
results[1]._artifacts.guard_manager = real
with self.assertLogs(logger, level="WARNING") as logs:
    self.assertEqual(model(x), x * 2)             # serves [1]
# exactly one line: "[0]'s guard check raised RuntimeError: zero is unhappy" ... "dispatch served [1]"

test_aot_compile_module_system_exit_out_of_a_later_tree_propagates: two results, [0]'s tree raising RuntimeError and [1]'s raising SystemExit; that call leaves __call__ as the SystemExit with nothing logged, and the next call, with [1]'s real tree back, serves [1] and logs [0]'s guard check raised RuntimeError: zero is unhappy. That last call pins WHERE the dedup is judged (FAQ below). SystemExit and not KeyboardInterrupt, which the landed test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates already drives out of this same handler behind a raiser: what no other test in the file has is a BARE SystemExit, where accepts()' except Exception decides on its own -- the SystemExit cases of the landed test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates arrive wrapped in the pybind boundary's SystemError, which the handler does catch and _meant_an_exception then re-raises -- and the AOTCompiledModel docstring promises both propagate.

A later result that cannot bind

def needs_z(self, y, z):
    return y * z

combined = compile_two_signatures(x, needs_z, x, x)
results[0]._artifacts.guard_manager = RaisingTree("zero is unhappy")
self.assertFalse(combined._binds_alike(tuple(results)))        # premise: [1] binds inside its own accepts()
with self.assertRaisesRegex(RuntimeError, "zero is unhappy"):
    results[0].guard_check(combined.model, x)                  # premise: [0] does raise
with self.assertNoLogs("torch._dynamo.aot_compile", level="WARNING"):
    with self.assertRaisesRegex(TypeError, "missing a required argument: 'z'"):
        combined(x)

test_module_dispatch_later_result_that_cannot_bind_raises_type_error: two results that cannot share a binding, [0]'s tree raising and [1]'s signature needing an argument the call lacks; TypeError: missing a required argument: 'z' leaves __call__ with nothing logged. It pins its premises before the call -- _binds_alike is False, so [1] binds inside its own accepts(), and [0]'s guard_check raises RuntimeError: zero is unhappy -- so a stub that stopped raising fails it with RuntimeError not raised (measured below) instead of leaving the case it names unexercised. Both keep assertNoLogs outermost (FAQ below).

A call the one signature cannot take

model = torch.compile(ScaleModule(), fullgraph=True, backend="eager")
model._aot_compile([ModelInput(args=(torch.randn(3, 3),), kwargs={}, contexts=[])])
with self.assertRaisesRegex(TypeError, "too many positional arguments"):
    model(x, x)
with self.assertRaisesRegex(TypeError, "missing a required argument: 'x'"):
    model()

test_module_dispatch_wrong_arity_raises_type_error is the one-result form of the same exit, and the source before #196826 already had it right: a call the signature cannot bind is the TypeError a plain module call raises, with no report folded around it -- prepare_f_locals stays outside accepts()' try. The type is the whole pin: the report is raised as a RuntimeError, so assertRaisesRegex(TypeError, ...) excludes it and nothing else about the exception needs reading.

One bind per result, across both passes and the report

# folded into test_module_dispatch_binds_per_result_when_signatures_differ
binds = []
def counted(result, *args, **kwargs):
    binds.append(result)
    return bind(result, *args, **kwargs)

with patch.object(AOTCompiledFunction, "prepare_f_locals", counted):
    with checks[0] as check0, checks[1] as check1, no_match:
        combined(x.half())                        # no result matches: the no-match report
self.assertEqual((check0.call_count, check1.call_count), (2, 2))   # both passes checked both results
self.assertEqual(len(binds), len(results))                          # bound once per result
for i, (bind_of, result) in enumerate(zip(binds, results)):
    self.assertIs(bind_of, result, f"bind {i} is not of result [{i}]")   # in index order, the same objects

One more thing the source before #196826 already did, kept, pinned in the landed test_module_dispatch_binds_per_result_when_signatures_differ, which already builds the two-signature model and shows each result binding on its own: a third call, x.half(), that no result matches ends in the no-match report (assertRaisesRegex(RuntimeError, "No AOT compiled graph matched")) having bound once per result -- in index order, the same objects, asserted per position so a wrong-order failure names the position -- while both passes checked each result (check wrapped and counted: two per result); that source's per-result list already satisfied it, and #196826's bound dict keeps it. The report's entry count is not asserted here: the report reads bound[i], so it adds nothing to the bind count, and seven other tests count those lines.

What each test pins, by mutation

mutation of #196826's aot_compile.py fails
bind moved inside accepts()' try test_module_dispatch_wrong_arity_raises_type_error, test_module_dispatch_later_result_that_cannot_bind_raises_type_error, nothing else: the TypeError is read as a raise and each call ends in a no-match report
rebind on every pass (f_locals = None for bound.get(i)) test_module_dispatch_binds_per_result_when_signatures_differ on len(binds): Expected 2 but got 4, nothing else
second pass deleted the same test on its check counts, (2, 2) read as (2, 1), plus 23 other re-check tests
handler AND _meant_an_exception widened to admit SystemExit test_aot_compile_module_system_exit_out_of_a_later_tree_propagates (a no-match report where the exit was asked for); widening the handler alone changes nothing
dedup pair decided in accepts()' handler, not warn_swallowed the same test on its last call's assertLogs, test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning, and six others
dispatch handlers re-raise the system-exit and cannot-bind tests on [0]'s RuntimeError escaping
warning's raiser read off the served index the system-exit test's last call, whose log then names [1] (#197195's mutant)
[0]'s RaisingTree replaced by a stub returning False the cannot-bind test on its premise, RuntimeError not raised

The Test Plan gives each measurement in full, including the parent run: the system-exit and cannot-bind tests both error on [0]'s RuntimeError: zero is unhappy escaping the call before the exit they pin is reached, and the two that pin what that source already did pass, as they should.

Test Plan:

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_system_exit_out_of_a_later_tree_propagates
python test/dynamo/test_aot_compile.py -k test_module_dispatch_later_result_that_cannot_bind_raises_type_error
python test/dynamo/test_aot_compile.py -k test_module_dispatch_wrong_arity_raises_type_error
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_per_result_when_signatures_differ
python test/dynamo/test_aot_compile.py

The whole file is green, OK (skipped=6). lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py is clean. The four were also run against
the torch/_dynamo/aot_compile.py of #196826's parent under this test file:
the system-exit and cannot-bind tests both error on [0]'s RuntimeError: zero is unhappy escaping the call before the exit they pin is reached, and the
two that pin what that source already did pass, as they should.

Each of the two negative pins fails a mutant of its own, each run against the
whole file at this commit. Moving the bind inside accepts()' try fails
test_module_dispatch_wrong_arity_raises_type_error and
test_module_dispatch_later_result_that_cannot_bind_raises_type_error, and
nothing else: the TypeError is read as a raise and each call ends in a
no-match report (No AOT compiled graph matched this call. Tried 1 compiled input(s) with [0] <guard check raised TypeError: too many positional arguments>, and Tried 2) where the TypeError was expected. Rebinding on
every pass (f_locals = None in place of bound.get(i)) fails
test_module_dispatch_binds_per_result_when_signatures_differ, and nothing
else, on len(binds): Expected 2 but got 4. Deleting the second pass fails
it on its check counts, (2, 2) read as (2, 1) -- its bind count alone
reads the same with one pass as with two -- along with 23 other tests of the
file that pin the re-check.

Each fix in #196826 that the other two cover was then reverted on its own
against the same file. A bare SystemExit reaches the record only if BOTH
accepts()' handler and _meant_an_exception are widened to admit it:
widening the handler alone, to BaseException or to (Exception, SystemExit), changes nothing, because the gate re-raises whatever a tree
meant that is not an Exception (measured: this test and the file's five
other interrupt tests stay green). Widened in both places,
test_aot_compile_module_system_exit_out_of_a_later_tree_propagates gets
RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled input(s) where it asked for the exit, with only the three SystemExit
cases of the wrapped-interrupt test above failing beside it. Deciding the
dedup's (index, exception type) pair in accepts()' handler, as the raise
is recorded, rather than in warn_swallowed fails the same test on its last
call's assertLogs (no logs of level WARNING or higher triggered),
#196826's
test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning the
same way, and six others that read the record or the one-shot (FAQ below).
Making the dispatch handlers re-raise fails the system-exit and cannot-bind
tests on [0]'s RuntimeError escaping, the two pins of the older behaviour
passing. Reading the warning's raiser off the served index fails the
system-exit test's last call, whose log then names [1]; that mutant is
#197195's, whose message lists the tests it fails there. Replacing [0]'s
RaisingTree in
test_module_dispatch_later_result_that_cannot_bind_raises_type_error with
a stub that returns False fails it on its premise assertion, RuntimeError not raised.

FAQ:
test_aot_compile_module_system_exit_out_of_a_later_tree_propagates
and test_module_dispatch_later_result_that_cannot_bind_raises_type_error
nest assertNoLogs outside assertRaisesRegex, so a spurious warning on a
call that also fails the raise assertion is reported as the raise failure.
Swap them so assertRaisesRegex is outermost?

Declined, because the swap makes the log pin vacuous, measured here.
unittest's _AssertLogsContext.__exit__ returns False without reading its
records whenever an exception is passing through it ("let unexpected
exceptions pass through"), and on these two tests' expected path the call
ALWAYS raises, so an assertNoLogs nested inside the raise assertion exits
by exception every time and checks nothing. With log.warning("spurious warning on record") added where both tests' aborted call records [0]'s
raise -- the inline handler, not accepts(), which neither aborted call
reaches: as written, both tests fail with AssertionError: Unexpected logs found: ['WARNING:torch._dynamo.aot_compile:spurious warning on record'];
with assertRaisesRegex outermost, the cannot-bind test PASSES and the
system-exit test fails only on its last call, on len(logs.output) reading
2 where 1 is expected -- the swapped blocks let the warning through on the
aborted call. The masking the finding describes happens only on a call that
has already failed the raise assertion, where the test fails either way.
The order as written is the one on which the silence is checked at all, and
a one-line comment at each site says so; that line is the one note about
the test framework the two tests keep, because it is what stops the swap.

FAQ: the system-exit test's last call -- [1]'s real tree restored, the
next call serving [1] and warning about [0] -- asserts the two substrings
test_aot_compile_module_warns_again_about_a_replaced_index (#197195)
already asserts, and a regression that populated _warned while logging
already fails the aborted call's assertNoLogs. Is the exit the test is
named for not the test?

The exit is, and the last call pins WHERE the dedup is judged, which the
aborted call cannot. Measured by moving it: deciding the (index, exception type) pair in accepts()' handler as the raise is recorded, and leaving
warn_swallowed to log the pairs so collected, passes the aborted call
(nothing is logged; the exit still escapes), #197195's pop and every-input
tests and #196826's single-result and once-per-model tests alike, and fails
this last call, with no logs of level WARNING or higher triggered, because
the aborted call had already consumed (0, "RuntimeError"); #196826's
test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning,
whose first call ends in a no-match report rather than an exit and whose
second call is silent for the same reason; and six more that read the
record the mutant drops or the one-shot it spends. That is a restructuring
a later reader could plausibly make -- the handler is where the pair is
first known -- and it would make every aborted call a silent one for the
raise on its record. The test's comment names both tests the move fails.

FAQ: the file's inline raiser stubs -- four class Raises, two
class RaisingGuardManager, and the Interrupts of
test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates -- all
duplicate the module-level RaisingTree these two tests adopt. Why not
convert them too?

git blame puts every one of them in a test of #197188, #197220, #197390
or #197391 below, and #197188, #197220 and #197390 are already approved,
so the conversion cannot be folded into the commits that own the stubs
either; doing it here would put edits to four other PRs' tests in a commit
whose diff is otherwise three tests and one helper, and would shift the
hunks #197050 and #197257 apply above. RaisingTree is module level and
already adopted at 21 sites, so those owners can adopt it in one line each.

Authored with the assistance of Claude Code.

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

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit 5c5f3d9 with merge base 51d4378 (image):

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

  • Scope
    • Test-only: the whole diff is test/dynamo/test_aot_compile.py (three new tests, one module-level compile_two_signatures helper); no source, workflow, or docs file is touched
    • The PR's own body says it does not touch torch/_dynamo/aot_compile.py, and the diff confirms it
  • Correctness against the source
    • prepare_f_locals sits outside the try both inline (aot_compile.py:2010 vs 2012) and in accepts() (2050 vs 2053), so the two TypeError pins match the code, and bind_locals at 189-194 is where inspect.Signature.bind produces those messages
    • accepts() catches Exception (aot_compile.py:2055), so the bare SystemExit from the new class Exits is never recorded and never reaches _meant_an_exception (142-144) — the exit the test asserts
    • The (2, 2) check count in test_module_dispatch_binds_per_result_when_signatures_differ matches dispatch: inline check on [0], accepts(1), then both again in the second loop (2068-2092), with _no_match_report reading the cached bound dict via check_verbose (2212), adding no check or bind
  • Preservation
    • The rewrite of test_module_dispatch_binds_per_result_when_signatures_differ keeps all three original assertions (_binds_alike is False, combined(x.double()) and combined(x)) and only swaps the hand-rolled setup for compile_two_signatures, which builds the same two results in the same order via the pre-existing aot_compile_forward (933-939)
    • Every symbol the new tests use already exists in the file at this commit: RaisingTree (688), ScaleModule (505), AOTCompiledFunction/AOTCompiledModel imports (46-47), patch (29)
  • Safety
    • No secrets, no eval/exec, no shell or deserialization of external input, and no CI gate or security check edited anywhere in the diff

reason: clean
Reviewed commit: 5c5f3d9

Inference job

🐛 Report a wrong verdict

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

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

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

This was referenced Sep 16, 2026
@bobrenjc93 bobrenjc93 added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 16, 2026
@bobrenjc93 bobrenjc93 changed the title [aot_compile] Pin the raise-tolerant module dispatch's exits and binding [no-ci] [aot_compile] Pin the raise-tolerant module dispatch's exits and binding Sep 16, 2026
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
Test-only, 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` this commit does not touch. The four tests
here were four of the twelve of `[aot_compile] Pin the raise-tolerant module
dispatch's warning: its paths, text and dedup` (#197195), directly below;
this commit adds them around #197195's without touching those, and the test
file at this tip is byte-identical to that PR's previous revision, so
#197050 and everything above apply on it unchanged.
They pin the exits of `AOTCompiledModel.__call__` that record a raise
nowhere -- an interrupt out of a later tree, a later result whose signature
cannot take the call, a call the one signature cannot take -- and that a
call binds once per result across both dispatch passes and the report. The
fixtures are `ScaleModule` and stub guard managers defined inline; the
commit adds no class or helper of its own.

The exits that record nothing. Every path in #196826 that RETURNS a graph
with a raise on record logs one, every path that builds a report chains one,
and a call that ends in neither leaves as the exception that ended it; its
FAQ says why nothing is logged on the way out.
`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`: two
results, [0]'s tree raising `RuntimeError` and [1]'s raising
`KeyboardInterrupt`; the interrupt leaves `__call__` as itself with nothing
logged, and the next call, with [1]'s real tree back, serves [1] and logs
`[0]'s guard check raised RuntimeError: zero is unhappy`. That second phase
pins WHERE the dedup is judged (FAQ below).
`test_aot_compile_module_later_result_that_cannot_bind_raises_type_error`:
two results that cannot share a binding, [0]'s tree raising and [1]'s
signature needing an argument the call lacks; `TypeError: missing a required
argument: 'z'` leaves `__call__` with nothing logged. It pins its premises
before the call -- `_binds_alike` is False, so [1] binds inside the second
`accepts()`, and [0]'s `guard_check` raises `RuntimeError: zero is unhappy`
-- so a stub that stopped raising fails it with `RuntimeError not raised`
(measured below) instead of leaving the case it names unexercised. Both keep
`assertNoLogs` outermost (FAQ below).
`test_aot_compile_module_wrong_arity_raises_type_error` is the one-result
form of the same exit, and the parent already had it right: a call the
signature cannot bind is the `TypeError` a plain module call raises, with no
report folded around it -- `prepare_f_locals` stays outside `accepts()`'
`try`, and only the report's absence tells the two apart.

One more thing the parent already did, kept.
`test_aot_compile_module_binds_a_call_once_per_result`: results whose
signatures differ each bind once -- one bind per result, in index order, the
same objects, asserted per position so a wrong-order failure names the
position -- across both passes and the report; the parent's per-result list
already satisfied it, and #196826's `bound` dict keeps it.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_out_of_a_later_tree_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_later_result_that_cannot_bind_raises_type_error
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_wrong_arity_raises_type_error
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_binds_a_call_once_per_result
python test/dynamo/test_aot_compile.py
```

The whole file runs 283 tests, `OK (skipped=6)`; #197195 runs 4 fewer.
`lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean. The
four were also run against the `torch/_dynamo/aot_compile.py` of #196826's
parent under this test file: the interrupt and cannot-bind tests both error
on [0]'s `RuntimeError: zero is unhappy` escaping the call before the exit
they pin is reached, and the two that pin what the parent already did pass,
as they should.

Each of the two negative pins fails a mutant of its own, run against the
whole 283-test file at this commit; the tests named are the only ones that
failed. Moving the bind inside `accepts()`' `try` fails
`test_aot_compile_module_wrong_arity_raises_type_error` and
`test_aot_compile_module_later_result_that_cannot_bind_raises_type_error`:
the `TypeError` is read as a raise and each call ends in a no-match report
(`No AOT compiled graph matched this call. Tried 1 compiled input(s)` and
`Tried 2`) where the `TypeError` was expected. Rebinding on every pass
(`f_locals = None` in place of `bound.get(i)`) fails
`test_aot_compile_module_binds_a_call_once_per_result` with `Expected 2 but
got 4` binds (and the landed
`test_module_dispatch_decides_a_shared_binding_past_the_first_result`, on
`_binds_alike` being called).

Each fix in #196826 that the other two cover was then reverted on its own
against the same file. Widening `accepts()`' handler to `BaseException`
fails only `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`,
which gets a `RuntimeError: No AOT compiled graph matched` report where it
asked for the `KeyboardInterrupt`. Deciding the dedup's `(index, exception
type)` pair in `accepts()`' handler, as the raise is recorded, rather than in
`warn_swallowed` fails the same test on its second call's `assertLogs` (`no
logs of level WARNING or higher triggered`), and one other test in the file,
#196826's
`test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`,
the same way (FAQ below). Making the dispatch handler re-raise fails the
interrupt and cannot-bind tests on [0]'s `RuntimeError` escaping, the two
negative pins passing. Reading the warning's raiser off the served index
fails the interrupt test's second phase, whose log then names `[1]`; that
mutant is #197195's, whose message lists the four tests it fails there.
Making [0]'s stub in
`test_aot_compile_module_later_result_that_cannot_bind_raises_type_error`
return False instead of raising fails it on its premise assertion,
`RuntimeError not raised`. #197195's other reverts -- the warning keyed on
the `SystemError`, the dedup never or conditionally reset, the dedup
deleted, a warning per rejection, `init=True` on `_warned` -- fail nothing
here; each fails a named test there.

> **FAQ: `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`
> and `test_aot_compile_module_later_result_that_cannot_bind_raises_type_error`
> nest `assertNoLogs` outside `assertRaisesRegex`, so a spurious warning on a
> call that also fails the raise assertion is reported as the raise failure.
> Swap them so `assertRaisesRegex` is outermost?**
>
> Declined, because the swap makes the log pin vacuous, measured here.
> `unittest`'s `_AssertLogsContext.__exit__` returns False without reading its
> records whenever an exception is passing through it ("let unexpected
> exceptions pass through"), and on these two tests' expected path the call
> ALWAYS raises, so an `assertNoLogs` nested inside the raise assertion exits
> by exception every time and checks nothing. With
> `log.warning("spurious warning on record")` added to `accepts()`' handler:
> as written, both tests fail with `AssertionError: Unexpected logs found:
> ['WARNING:torch._dynamo.aot_compile:spurious warning on record']`; with
> `assertRaisesRegex` outermost, the cannot-bind test passes and the
> interrupt test fails only in its second phase, on `len(logs.output)`
> reading 2 where 1 is expected -- the swapped block let the warning through
> in both. The masking the finding describes happens only on a call that has
> already failed the raise assertion, where the test fails either way. The
> order as written is the one on which the silence is checked at all, and a
> comment at the first site says so.

> **FAQ: the interrupt test's second phase -- [1]'s real tree restored, the
> next call serving [1] and warning about [0] -- asserts the two substrings
> `test_aot_compile_module_warns_again_about_a_replaced_index` (#197195)
> already asserts, and a regression that populated `_warned` while logging
> already fails the first phase's `assertNoLogs`. Is the first phase not the
> test?**
>
> The second phase pins WHERE the dedup is judged, for an exit that is an
> interrupt. Measured by moving it: deciding the `(index, exception type)`
> pair in `accepts()`' handler as the raise is recorded, and leaving
> `warn_swallowed` to log the pairs so collected, passes the first phase
> (nothing is logged; the interrupt still escapes), #197195's pop and
> every-input tests and #196826's single-result and once-per-model tests
> alike, and fails exactly two of the file's 283 tests: this second phase,
> with `no logs of level WARNING or higher triggered`, because the aborted
> call had already consumed `(0, "RuntimeError")`, and #196826's
> `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`,
> whose first call ends in a no-match report rather than an interrupt and
> whose second call is silent for the same reason. The test's comment says
> the mutant `fails only here`, which is true of this PR's four tests and
> not of the file; that is a restructuring a later reader could plausibly
> make -- the handler is where the pair is first known -- and it would make
> every aborted call a silent one for the raise on its record. The comment
> says that is what the phase is for.

Authored with the assistance of Claude Code.

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

Copy link
Copy Markdown
Contributor Author

@claude

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

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


This round fixes everything from my last review — compile_two_signatures is shared, AlwaysRaises replaces the two inline stubs, the helper comment now states a precondition rather than a guarantee, and the interrupt test's comment names the second test the dedup mutant kills; what's left is that the new AlwaysRaises duplicates a module-level raiser the file has had all along, and one of the two interrupt-test iterations re-runs a scenario 1000 lines above it.

Full review

PR Review: #197219

Summary

Test-only: adds three tests to test/dynamo/test_aot_compile.py pinning AOTCompiledModel.__call__ exits that record no raise (a BaseException out of a later guard tree, a later result whose signature cannot bind, wrong arity), folds two bind assertions into the landed test_module_dispatch_binds_per_result_when_signatures_differ, and adds two module-level helpers. I verified the exits against torch/_dynamo/aot_compile.py:2008-2126 and the coverage is real. Every finding from my previous two rounds is fixed: the triplicated fixture is now compile_two_signatures (952), the "fails only here" comment now names test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning (5372-5373), the unreachable assertNotIns are gone from the arity test (3163-3176), SystemExit is covered (5392), and the helper comment at 953-956 now states the iff-condition instead of promising a verdict. Three things remain.

Code Quality

AlwaysRaises (963-971) duplicates the module-level RaisingTree (688-697), which this PR does not add. Both subclass NeverReChecked, both store a constructor string, both have a check() that raises RuntimeError with it. The only difference is the parameter name (message vs text) and RaisingTree's self.checks counter. Neither new call site reads .checks, so RaisingTree("zero is unhappy") is a drop-in at both 3191 and 5389 — a two-line change entirely inside this PR's own new tests, touching no other PR's hunks, so the description's ghstack argument for not converting the twelve inline stubs does not reach this.

The description's justification is that AlwaysRaises is module level "so those owners can adopt it in one line each." But RaisingTree is already module level and already adopted at 21 sites in this file (3022, 4332-4333, 4386, 4739, 4770-4772, 4975, 5002, 5071, 5089, 5106, 5123, 5194-5195, 5226, 5234, 5253, 5277, 5334, 5355) — it is exactly the class those owners would adopt. The result is a third module-level always-raising stub beside RaisingTree and RaisesPerPass (700), and a future reader picking one now has to diff three classes to learn there is no difference.

The strongest case for keeping it is NeverReChecked's own docstring at 681-682, which distinguishes a stub "on a serving path [that] meets no report and needs neither" — and AlwaysRaises's comment at 964-966 claims exactly that role. But that argument undercuts the class rather than supporting it: if it genuinely never reaches a report, it should not inherit NeverReChecked, whose whole purpose is the check_verbose tripwire for a report that re-checks. As written it takes the base class and claims the role the base class says does not need it. Either reuse RaisingTree (simplest — the unread .checks costs nothing) or, if the distinct role is the point, drop the NeverReChecked base and say so. Fix this →

Two classes in the file are now named Interrupts, and the new one is a strict generalization of the old. 5381-5386 takes the exception type as a constructor argument; the pre-existing 4376-4378 hardcodes KeyboardInterrupt("ctrl-c inside the tree"). The older one is Interrupts(KeyboardInterrupt) under the new definition. Two same-named inline classes 1000 lines apart, one of which subsumes the other, is the situation compile_two_signatures was extracted to avoid one level up; promote the parameterized one to module level beside RaisingTree and have both tests use it.

Testing

The KeyboardInterrupt iteration of test_aot_compile_module_interrupt_out_of_a_later_tree_propagates (5392) re-runs a scenario the file already has. The pre-existing test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates's second assertion (4385-4386) is _model_with_stub_trees(RaisingTree("unhappy"), Interrupts())(x) asserting KeyboardInterrupt propagates — index [0] raising RuntimeError, index [1] raising KeyboardInterrupt, interrupt expected out of __call__. That is the new test's KeyboardInterrupt iteration exactly, down to which handler is reached with what on record; its own comment at 4384 says "Behind a raiser, the interrupt reaches accepts() with a raise on record." The differences are the message text, a fresh model instead of the helper's, and the assertNoLogs wrapper.

That wrapper is the only new coverage in that iteration, and per this PR's own FAQ it is vacuous on a path where the call always raises — _AssertLogsContext.__exit__ returns without reading its records when an exception passes through, and the outer-nesting that makes it non-vacuous only helps when the inner assertion passes, which is the same expected path the older test already pins. So the KeyboardInterrupt iteration adds a message string. The SystemExit iteration is the load-bearing one — nothing else in the file raises SystemExit, and it is the regression pin against widening aot_compile.py:2055's except Exception, which the description's mutation run confirms. Consider dropping to SystemExit alone and adding the assertNoLogs to 4385-4386 if the silence is worth pinning there, or state in the comment that the first iteration is deliberate overlap with 4369 and why.

assertNoLogs is not paired with a positive log assertion on the aborted calls, by design, but the test's own last call shows the cost. 5400 asserts len(logs.output) == 1 after restoring [1]'s real tree — good. On the two aborted calls (5394) there is no way to distinguish "warned about nothing because the interrupt left first" from "warned about nothing because _warned was already populated"; the last call is what separates them, and the comment at 5370-5373 says so. Worth noting only because it makes the last call, not the loop, the test's actual subject — the name says otherwise.

Recommendation

Needs Discussion

Nothing here is behaviourally wrong, the exits are worth pinning, and this revision cleared every defect from the prior two rounds. What's left is duplication pointing the wrong way: a new module-level stub that reimplements one the file has had for a while, a second Interrupts that subsumes the first, and one test iteration that re-runs a scenario 1000 lines above it. The AlwaysRaises/RaisingTree collapse is two lines and entirely local to this PR.

I could not execute anything. The [no-ci] title prefix disables CI on this PR, and this sandbox cannot build PyTorch, so the three tests and the claimed 283-test file run are unverified here; the review is static, reading the tests against torch/_dynamo/aot_compile.py. Claims I confirmed by reading rather than running: the arity test's two messages come from inspect.Signature.bind via bind_locals called from prepare_f_locals (704-716) outside accepts()' try; the (2, 2) check count at 3158 is right (inline check on [0], accepts(1) in the first loop, both again in the second, with _no_match_report using check_verbose and the cached bound dict, so it adds nothing to either count); and compile_two_signatures leaving mod.forward bound to second_forward does not affect any of its three callers, since none calls combined.model.forward directly.

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

@bobrenjc93 bobrenjc93 changed the title [aot_compile] Pin the raise-tolerant module dispatch's exits and binding [no-ci] [aot_compile] Pin the raise-tolerant module dispatch's exits and binding Sep 18, 2026
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
…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
…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
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…aths, text and dedup (#197195)

**Problem.** #197391's swallowed-raise warning had its main path covered but not the rest: which other serving paths log it, what it names behind a pybind `SystemError`, when it stays silent, and that its dedup resets when the results change.

**Fix.** Five tests pin those, plus two assertions added to an existing test. No source change.

**Summary.** Test-only, split for review budget from `[aot_compile] Warn once per defect when module dispatch serves a graph over a raise` (#197391), three commits below, whose `torch/_dynamo/aot_compile.py` this commit does not touch. The five tests here are the rest of the swallowed-raise warning's coverage: which serving paths log it and about which index (the second pass and the last resort), what it names (the exception behind a pybind `SystemError`, keyed into the dedup), when it is silent (an ordinary dispatch that walks past a non-matching input), and that it is logged once per defect and starts over when `compiled_results` changes. They are written on what the stack already has -- the `RaisingTree`, `Rejects` and `Accepts` stubs and the `_model_with_stub_trees` helper, as #197391's warning tests are -- except `ordinary_dispatch` and the unwrap test, which need the real trees, and the second-pass test's stub `RefusesThenAccepts`, the one with no twin. Two assertions land in #197391's `warns_once_per_model_not_per_process` (`dispatch served [0]`, and `_warned` absent from `AOTCompiledModel`'s constructor signature, the one pin `init=True` on that field fails), and #196826's `RaisesOnCompare` gains an `exc` parameter defaulting to the `ValueError` it raised before; those are this commit's only changes to existing tests and fixtures. Each fix in #197391 or #196826 that these tests cover was reverted on its own and the file run against it, and the Test Plan records which test each mutation fails and on what reading.

## Where this sits in the stack

The tests about the exits that record a raise nowhere and the one bind per result are `[aot_compile] Pin the raise-tolerant module dispatch's exits and binding` (#197219), above. `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), five below, pins what a caller sees change; #197390 the records, serves and exits on stub trees; #197391 the warning's dedup on a one-result model and which index each serving site names; #197188 the raise line and the raised-then-answered report; #197179, directly below, the no-match report's other lines once a raise is on record.

Only a pybind boundary produces the `SystemError` the unwrap test is about, so it takes the file's `_aot_compile_dict_branches` model, the one #196826's `raise_from_an_opted_out_result_withholds_nothing` calls, and extends that call with the warning half; that test stays where it is, being #196826's own reading of the change that stops the raise reaching the caller.

Placement: two of the five tests sit among #197391's warning tests; the second-pass and last-resort tests sit just above #197390's `serves_a_tree_that_raised_and_then_accepted`, after #197049's function-side TorchFunction-restore test; the unwrap test sits directly after #197391's parametrized `warns_before_the_served_graph_runs`, last of that block.

## The second pass logs one line about the raiser

```python
class RefusesThenAccepts:
    # RaisesThenAccepts with a rejection where its scan raise is.
    def check(self, f_locals):
        self.checks += 1
        return self.checks > 1

stub = RefusesThenAccepts()
model = self._model_with_stub_trees(RaisingTree("both passes are unhappy"), stub)
with self.assertLogs("torch._dynamo.aot_compile", level="WARNING") as logs:
    model(x)                      # == x * 2, served by [1] on the second pass
stub.checks                       # 2: rejected in the scan, accepted on the second pass
len(logs.output)                  # 1: "[0]'s guard check raised RuntimeError: both passes are unhappy" ... "dispatch served [1]"
```

`test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise`: nothing matched in the scan and the second pass found a match in a result other than the one that raised, so that call site's warning is the one that records the raise, and the stub's `checks` count says the serve was the second pass's. #197391's `second_pass_warning_names_the_index_served` has the same second pass serve [1] over [0]'s raise, with [1] raising in the scan as well and two warnings logged; here [1] rejected there instead. That a rejection logs nothing is already pinned by #197391 -- its scan and last-resort site tests each put a `Rejects()` beside the raiser and count one line -- so what this test adds is the SECOND-PASS site logging one line when the result it serves rejected in the scan rather than raised there. That is why it fails both `accepts()` mutations below, on its warning count and on `stub.checks`, where its named twin passes.

## The last resort names the raiser, not the served index

```python
unhappy = RaisingTree("the second tree is unhappy")
model = self._model_with_stub_trees(Rejects(), unhappy, opt_out=True)   # both results opted out
with self.assertLogs("torch._dynamo.aot_compile", level="WARNING") as logs:
    model(x)                      # == x * 2, the last resort serves the FIRST opted-out result, [0]
unhappy.checks                    # 2: raised in the scan and again on the second pass
len(logs.output)                  # 1: "[1]'s guard check raised RuntimeError: the second tree is unhappy" ... "dispatch served [0]"
"[0]'s guard check raised" in warned   # False: no warning made up for the served index
```

`test_aot_compile_module_last_resort_warns_about_another_index`: the last resort serves the FIRST opted-out result, which need not be the one that raised, so the warning reads the raiser off `raised` and the served index off the loop, and `[0]'s guard check raised` appears nowhere. `opt_out=True` opts out BOTH results, so [1]'s raise vetoes nothing; with [1] enabled that raise would veto the last resort and the call would raise the no-match report instead of reaching a serve. #197391's two-raisers test pins the same reading with both of its results raising; here [0] never raised, so that last assertion -- no warning made up for the served index -- is the one that test cannot make, and why this one stands on its own. [1] raises in the scan and again on the second pass -- `unhappy.checks == 2`, as the second-pass test reads its stub -- and `len(logs.output) == 1` is one line about those two raises.

## The warning unwraps the pybind boundary's `SystemError`

```python
class RaisesOnCompare:
    def __init__(self, message="boom from __eq__", exc=ValueError):   # parent: no exc; always ValueError
        ...
    def __eq__(self, other):
        raise self.exc(self.message)

model, x = self._aot_compile_dict_branches({}, None)
model.forward.compiled_results[0].disable_guard_check()
with self.assertLogs("torch._dynamo.aot_compile", level="WARNING") as logs:
    model(x, {RaisesOnCompare(): 1})                 # x * 2
    model(x, {RaisesOnCompare(exc=TypeError): 1})    # x * 2
# two lines: "[0]'s guard check raised ValueError: boom from __eq__" and "... TypeError: boom from __eq__"
"SystemError" in warned           # False
```

`test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise`: the warning names the exception behind the `SystemError` and keys its dedup on it, so a `ValueError` and a `TypeError` from two colliding keys at one index log twice and `SystemError` appears in neither line. The model and setup are `raise_from_an_opted_out_result_withholds_nothing`'s -- [0] raises through its `DICT_NOT_CONTAINS` leaf, [1] rejects the dict without probing it, so opting [0] out arms the last resort and its own raise vetoes nothing. The `TypeError` is `RaisesOnCompare(exc=TypeError)`: the class gains an `exc` parameter defaulting to the `ValueError` it raised before, so its seven existing callers are unchanged and the collision trick and its comment stay in one place.

## Once per defect, and again after `compiled_results` changes

```python
zero, one = RaisingTree("zero is unhappy"), RaisingTree("one is unhappy")
model = self._model_with_stub_trees(zero, one, Accepts())
results = model.forward.compiled_results
model(x)                          # two warnings, each naming its raiser, both "dispatch served [2]"
model(x)                          # silent: once per defect, not once per call
results.pop(0)                    # compiled_results is public; the artifact at [0] is now `one`
model(x)                          # one warning: "[0]'s guard check raised RuntimeError: one is unhappy" ... "dispatch served [1]"
model(x)                          # silent again
```

`test_aot_compile_module_warns_again_about_a_replaced_index`: the model is `_model_with_stub_trees(zero, one, Accepts())`, two broken artifacts, so the first call is two warnings, each naming its raiser and `dispatch served [2]`, and the next call is silent -- once per defect, not once per call. Then `compiled_results` is public, so after a `pop(0)` the artifact at a warned-about index is a different one: the `(0, "RuntimeError", True)` on record described `zero`'s raise, not `one`'s, and it warns again, naming `one is unhappy` at [0] and `dispatch served [1]`; the call after that is silent. Its one-result twin in #197391 is what tells a reset judged at the warning from one tied to the binding verdict (two results are left after the pop, so a reset hung off the binding verdict would fire here too); this test is the many-result reading of the same reset. An earlier revision pinned the first two calls in a test of their own, `warns_about_every_input_that_raised`; it walked this test's first two blocks step for step under other stub texts, so its three text assertions moved here and it is gone.

## Ordinary dispatch is silent

```python
model._aot_compile([ModelInput(args=(torch.randn(3, 3, dtype=torch.float64),), ...),
                    ModelInput(args=(torch.randn(3, 3),), ...)])
first, later = (r._artifacts.guard_manager for r in model.forward.compiled_results)
with (patch.object(first, "check", wraps=first.check) as first_check,
      patch.object(later, "check", wraps=later.check) as later_check,
      self.assertNoLogs("torch._dynamo.aot_compile", level="WARNING")):
    served = model(torch.randn(3, 3))          # x * 2
first_check.call_count, later_check.call_count   # 1, 1: [0]'s float64 tree rejected, [1]'s accepted
```

One thing the parent already did, kept, and made observable. `test_aot_compile_module_ordinary_dispatch_warns_about_nothing`: the warning is about a raise, so walking past a non-matching input to a matching one logs nothing. Both captures compute `x * 2`, so the served value cannot say which result served; the two real guard managers' `check` is patched with `wraps=`, as the file's other check counters are, and the test asserts one call on each -- [0]'s float64 tree rejected the float32 call and [1]'s accepted it -- so a dispatch that served [0] outright would fail it rather than pass on the value.

## Two assertions added to #197391's `warns_once_per_model_not_per_process`

```python
self.assertNotIn("_warned", inspect.signature(AOTCompiledModel).parameters)   # the field is init=False
...
self.assertIn("dispatch served [0]", logs.output[0])   # the opted-out result itself is what the last resort serves
```

That test's model is the one-result opted-out raiser from `_model_with_stub_trees(unhappy, opt_out=True)`. `dispatch served [0]`: an earlier revision's `last_resort_warns_that_its_own_tree_raised` rebuilt that model by hand and re-asserted its raise line, its last-resort advice and the absence of `Fix or drop input`, adding only this reading, which now sits where the rest already was. `_warned` not in `inspect.signature(AOTCompiledModel).parameters`: the dedup set is a field on the model for the reason that test's comment gives, and for the same reason it is not the caller's to hand in -- a set shared across models would silence the second model the way `warning_once`'s cache silences every later one -- so the field is `init=False`. An earlier revision pinned that with a `dataclasses.fields` walk and CPython's `takes 3 positional arguments but 4` text in a test of its own; the previous revision of this commit pinned it nowhere, and `init=True` on the field ran the whole file green. It is now one assertion in the test whose comment already says why, and the one test `init=True` fails.

> **FAQ: Why does a split-off, tests-only PR edit a test that #197391 owns and a fixture that #196826 owns?**
> Because the review asked for the duplicates to be folded rather than kept
> side by side, and the test they duplicate lives in #197391. The edits are
> two added assertions and their comments in `warns_once_per_model`, and an
> `exc=ValueError` parameter on `RaisesOnCompare`, with a comment clause,
> whose default keeps its callers below unchanged; `git diff` of this commit
> against its parent changes no line outside the five tests, that test and
> that fixture. Both are unapproved drafts; folding into them instead would
> move the change three or five PRs down and re-review it there.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_last_resort_warns_about_another_index
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_about_a_replaced_index
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_ordinary_dispatch_warns_about_nothing
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
```

The whole file passes in a venv without triton. `lintrunner --take RUFF,PYFMT
test/dynamo/test_aot_compile.py` is clean. The five tests and
`warns_once_per_model` were also run against the `torch/_dynamo/aot_compile.py`
of #197391's parent under this test file: the four warning tests here and
`warns_once_per_model` fail with `no logs of level WARNING or higher triggered
on torch._dynamo.aot_compile`, and `ordinary_dispatch` passes, as it should.
Against #196826's parent's `aot_compile.py` the same five error on the tree's
own raise escaping the call -- a stub's `RuntimeError` (`both passes are
unhappy`, `the second tree is unhappy`, `zero is unhappy`, `guard tree is
unhappy`) or, for the unwrap test, the pybind boundary's `SystemError` over
`ValueError: boom from __eq__` -- and `ordinary_dispatch` passes.

Each fix in #197391 or #196826 that these tests cover was then reverted on its
own in this commit's `aot_compile.py`, and the whole file run against it.
Reading the warning's raiser off the served index fails
`test_aot_compile_module_last_resort_warns_about_another_index` on the log
reading `input [0]'s guard check raised RuntimeError: the second tree is
unhappy`, and with it the second-pass test on the same reading and the
replaced-index test on its warning count (`Expected 2 but got 1`), every one a
test whose served index differs from the raiser (and warning tests of #196826,
#197390 and #197391 below, for the same reason). Keying the warning on the
`SystemError` rather than the unwrapped raise fails
`test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise` with the log
reading `raised SystemError: <built-in method check of pybind11_builtins...`,
and the two tests below that #197391 gave the same reading,
`raise_from_an_opted_out_result_withholds_nothing` and
`serves_a_later_match_over_a_raising_leaf`. Never starting the dedup over
(forcing the `_same_results` test in `_warn_swallowed` true) fails
`test_aot_compile_module_warns_again_about_a_replaced_index` with `no logs of
level WARNING or higher triggered` on the call after the `pop`, and the
one-result twin in #197391, and nothing else; gating the reset on two or more
results fails only the twin, this test passing. Deleting the dedup -- the `(i,
kind, enabled) in warned` test and the `warned.add` that ends the loop body --
fails `test_aot_compile_module_warns_again_about_a_replaced_index` on the
repeat call that has to be silent, with `Unexpected logs found` quoting both of
the warnings that call re-emitted, and #197391's dedup tests below. Logging a
warning for a result `accepts()` rejected fails
`test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise` and
`test_aot_compile_module_last_resort_warns_about_another_index` on their
warning count, `Expected 1 but got 2` -- [1] and, on the second pass, [0]
rejected -- and the unwrap test on its, `Expected 2 but got 6` (and tests of
#197391, #196826's `raise_from_an_opted_out_result_withholds_nothing` and the
landed #197048's
`test_no_match_report_survives_a_forward_resolve_that_raises`). The last-resort
test's `len(logs.output) == 1` is what catches this mutation -- an earlier
revision of that test had no count assertion; dropping it here and re-running
leaves the test passing. Logged for the inline check of [0] as well, it also
fails `test_aot_compile_module_ordinary_dispatch_warns_about_nothing` with
`Unexpected logs found: [... input [0] rejected this call]` (the same tests the
inline log alone fails: [0] rejects inline on far more calls than a later
result does in `accepts()`); [0] is checked inline and never reaches
`accepts()`, so the first mutation alone does not reach that test. `init=True`
on `_warned` fails
`test_aot_compile_module_warns_once_per_model_not_per_process` with `'_warned'
unexpectedly found in mappingproxy(OrderedDict({'model': ... '_warned':
<Parameter "_warned: ...` and nothing else. Making both dispatch handlers
re-raise fails the four warning tests here and the raise tests below,
`ordinary_dispatch` being the negative pin. Serving the first result whatever
its tree answered (the inline `if answer:` made unconditional) fails
`ordinary_dispatch` on [1]'s check count, 0 against 1, among many tests below.
Making `accepts()` answer true whatever the tree said fails the last-resort
test on `unhappy.checks` and the second-pass test on `stub.checks`, both
`Expected 2 but got 1` -- the served result's own accept now settles the second
pass before the later stub is reached again, under the same one warning line --
which without the last-resort assertion that test passes.

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: #197195
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
Test-only, 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` this commit does not touch. The three tests
here were three of the twelve of `[aot_compile] Pin the raise-tolerant module
dispatch's warning: its paths, text and dedup` (#197195), directly below;
this commit adds them without touching the eight that stayed there, and
folds a fourth's two assertions into the landed test whose setup it
repeated. They pin the exits of `AOTCompiledModel.__call__` that record a
raise nowhere -- a `KeyboardInterrupt` or `SystemExit` out of a later tree, a
later result whose signature cannot take the call, a call the one signature
cannot take -- and that a call binds once per result across both dispatch
passes and the report.

Where they sit. The two about binding join the landed
`test_module_dispatch_*` tests on how a call binds, directly after
`test_module_dispatch_binds_per_result_when_signatures_differ`, under that
prefix, and, like that cluster, without `_hide_leaked_dynamo_globals`;
`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates` stays
among #197195's dedup tests, because its last call is a dedup pin, and calls
it as they all do. Two module-level helpers beside `compile_mode_defaults`
serve them: `compile_two_signatures`, the two-signature model that landed
test and the cannot-bind test assemble, built from the same
`aot_compile_forward` (its comment states when the two results bind alike --
iff `second_forward`'s parameters and closure cells match forward's,
measured: a `(self, x)` second forward binds alike, one named `(self, y)` or
given a default does not -- rather than promising they never do), and
`AlwaysRaises(message)`, the stub guard manager whose every `check()` raises,
subclassing `NeverReChecked` so a regression that re-checks it in a report
fails on that class's message; the interrupt and cannot-bind tests use it
where each had its own copy.

The exits that record nothing. Every path in #196826 that RETURNS a graph
with a raise on record logs one, every path that builds a report chains one,
and a call that ends in neither leaves as the exception that ended it; its
FAQ says why nothing is logged on the way out.
`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`: two
results, [0]'s tree raising `RuntimeError` and [1]'s raising, on one call
each, `KeyboardInterrupt` and then `SystemExit`; each leaves `__call__` as
itself with nothing logged, and the next call, with [1]'s real tree back,
serves [1] and logs `[0]'s guard check raised RuntimeError: zero is unhappy`.
That last call pins WHERE the dedup is judged (FAQ below). `SystemExit`
travels the same path as `KeyboardInterrupt` today -- one `except Exception`
in `accepts()` is the only handler between the tree and the caller, and the
comment says so -- and is there because the `AOTCompiledModel` docstring
promises both propagate: without it an `except (Exception, SystemExit)`
added later would pass every test in the file (measured below). The order of
the two iterations is not load-bearing (FAQ below).
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error`: two
results that cannot share a binding, [0]'s tree raising and [1]'s signature
needing an argument the call lacks; `TypeError: missing a required argument:
'z'` leaves `__call__` with nothing logged. It pins its premises before the
call -- `_binds_alike` is False, so [1] binds inside its own `accepts()`, and
[0]'s `guard_check` raises `RuntimeError: zero is unhappy` -- so a stub that
stopped raising fails it with `RuntimeError not raised` (measured below)
instead of leaving the case it names unexercised. Both keep `assertNoLogs`
outermost (FAQ below).
`test_module_dispatch_wrong_arity_raises_type_error` is the one-result form
of the same exit, and the source before #196826 already had it right: a call
the signature cannot bind is the `TypeError` a plain module call raises, with
no report folded around it -- `prepare_f_locals` stays outside `accepts()`'
`try`. The type is the whole pin: the report is raised as a `RuntimeError`,
so `assertRaisesRegex(TypeError, ...)` excludes it and nothing else about
the exception needs reading.

One more thing the source before #196826 already did, kept, pinned in the
landed `test_module_dispatch_binds_per_result_when_signatures_differ`, which
already builds the two-signature model and shows each result binding on its
own: a third call, `x.half()`, that no result matches ends in the no-match
report (`assertRaisesRegex(RuntimeError, "No AOT compiled graph matched")`)
having bound once per result -- in index order, the same objects, asserted
per position so a wrong-order failure names the position -- while both
passes checked each result (`check` wrapped and counted: two per result);
that source's per-result list already satisfied it, and #196826's `bound`
dict keeps it. The report's entry count is not asserted here: the report
reads `bound[i]`, so it adds nothing to the bind count, and seven other
tests count those lines.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_out_of_a_later_tree_propagates
python test/dynamo/test_aot_compile.py -k test_module_dispatch_later_result_that_cannot_bind_raises_type_error
python test/dynamo/test_aot_compile.py -k test_module_dispatch_wrong_arity_raises_type_error
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_per_result_when_signatures_differ
python test/dynamo/test_aot_compile.py
```

The whole file runs 283 tests, `OK (skipped=6)`, three more than #197195's
file loads. `lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py`
is clean. The four were also run against the `torch/_dynamo/aot_compile.py`
of #196826's parent under this test file: the interrupt and cannot-bind
tests both error on [0]'s `RuntimeError: zero is unhappy` escaping the call
before the exit they pin is reached, and the two that pin what that source
already did pass, as they should.

Each of the two negative pins fails a mutant of its own, run against the
whole 283-test file at this commit; the tests named are the only ones that
failed. Moving the bind inside `accepts()`' `try` fails
`test_module_dispatch_wrong_arity_raises_type_error` and
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error`: the
`TypeError` is read as a raise and each call ends in a no-match report
(`No AOT compiled graph matched this call. Tried 1 compiled input(s)` and
`Tried 2`) where the `TypeError` was expected. Rebinding on every pass
(`f_locals = None` in place of `bound.get(i)`) fails
`test_module_dispatch_binds_per_result_when_signatures_differ` with
`Expected 2 but got 4` binds (and the landed
`test_module_dispatch_decides_a_shared_binding_past_the_first_result`, on
`_binds_alike` being called). Deleting the second pass fails it on its
`check` counts, `Expected 2 but got 1` -- its bind count alone reads the
same with one pass as with two -- along with 14 tests of the file that pin
the re-check.

Each fix in #196826 that the other two cover was then reverted on its own
against the same file. Widening `accepts()`' handler to `BaseException`
fails only `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`,
whose `KeyboardInterrupt` call gets a `RuntimeError: No AOT compiled graph
matched this call. Tried 2 compiled input(s)` report where it asked for the
interrupt; widening it to `(Exception, SystemExit)` fails only the same
test, on its `SystemExit` call, the same way. Deciding the dedup's `(index,
exception type)` pair in `accepts()`' handler, as the raise is recorded,
rather than in `warn_swallowed` fails the same test on its last call's
`assertLogs` (`no logs of level WARNING or higher triggered`), and one other
test in the file, #196826's
`test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`,
the same way (FAQ below). Making the dispatch handler re-raise fails the
interrupt and cannot-bind tests on [0]'s `RuntimeError` escaping, the two
pins of the older behaviour passing. Reading the warning's raiser off the
served index fails the interrupt test's last call, whose log then names
`[1]`; that mutant is #197195's, whose message lists the four tests it
fails there. Replacing [0]'s `AlwaysRaises` in
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error` with
a stub that returns False fails it on its premise assertion, `RuntimeError
not raised`.

> **FAQ: `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`
> and `test_module_dispatch_later_result_that_cannot_bind_raises_type_error`
> nest `assertNoLogs` outside `assertRaisesRegex`, so a spurious warning on a
> call that also fails the raise assertion is reported as the raise failure.
> Swap them so `assertRaisesRegex` is outermost?**
>
> Declined, because the swap makes the log pin vacuous, measured here.
> `unittest`'s `_AssertLogsContext.__exit__` returns False without reading its
> records whenever an exception is passing through it ("let unexpected
> exceptions pass through"), and on these two tests' expected path the call
> ALWAYS raises, so an `assertNoLogs` nested inside the raise assertion exits
> by exception every time and checks nothing. With
> `log.warning("spurious warning on record")` added to `accepts()`' handler:
> as written, both tests fail with `AssertionError: Unexpected logs found:
> ['WARNING:torch._dynamo.aot_compile:spurious warning on record']`; with
> `assertRaisesRegex` outermost, the cannot-bind test passes and the
> interrupt test fails only on its last call, on `len(logs.output)` reading
> 2 where 1 is expected -- the swapped blocks let the warning through on all
> three aborted calls. The masking the finding describes happens only on a
> call that has already failed the raise assertion, where the test fails
> either way. The order as written is the one on which the silence is
> checked at all, and a one-line comment at each site says so; that line is
> the one note about the test framework the two tests keep, because it is
> what stops the swap.

> **FAQ: the interrupt test's last call -- [1]'s real tree restored, the
> next call serving [1] and warning about [0] -- asserts the two substrings
> `test_aot_compile_module_warns_again_about_a_replaced_index` (#197195)
> already asserts, and a regression that populated `_warned` while logging
> already fails the aborted calls' `assertNoLogs`. Are the aborted calls not
> the test?**
>
> The last call pins WHERE the dedup is judged. Measured by moving it:
> deciding the `(index, exception type)` pair in `accepts()`' handler as the
> raise is recorded, and leaving `warn_swallowed` to log the pairs so
> collected, passes the aborted calls (nothing is logged; the interrupts
> still escape), #197195's pop and every-input tests and #196826's
> single-result and once-per-model tests alike, and fails exactly two of the
> file's 283 tests: this last call, with `no logs of level WARNING or higher
> triggered`, because the aborted calls had already consumed `(0,
> "RuntimeError")`, and #196826's
> `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`,
> whose first call ends in a no-match report rather than an interrupt and
> whose second call is silent for the same reason. That is a restructuring a
> later reader could plausibly make -- the handler is where the pair is first
> known -- and it would make every aborted call a silent one for the raise on
> its record. The test's comment names both tests the move fails.

> **FAQ: `unittest`'s `testPartExecutor` re-raises `KeyboardInterrupt` but
> catches `SystemExit`, so does the interrupt test's iteration order --
> `KeyboardInterrupt` first -- decide whether a regression aborts the whole
> run or is reported as one failure?**
>
> No, measured. The only `KeyboardInterrupt` the test raises is the stub's,
> inside `assertRaisesRegex(KeyboardInterrupt, ...)`, which catches it on the
> expected path and turns a wrong message into an `AssertionError`; a
> regression that swallows it hands the test the no-match report, a
> `RuntimeError`, which `assertRaisesRegex` lets through as this test's
> error. With `accepts()`' handler widened to `BaseException`, the whole
> file ran to completion in either order: 283 tests, `FAILED (errors=1)`,
> the one error this test's `KeyboardInterrupt` iteration getting
> `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled
> input(s)`, both as written and with the tuple reversed to `(SystemExit,
> KeyboardInterrupt)`. No `KeyboardInterrupt` reaches `testPartExecutor` on
> any path this test has, so the order says nothing and the comment claims
> nothing about it.

> **FAQ: `AlwaysRaises` replaces this commit's two inline `Raises` stubs;
> the file's twelve other inline raisers (eight `Raises`, four
> `RaisingGuardManager`, two of them already taking the message as a
> constructor argument) are left in place. Why not convert them too?**
>
> `git blame` puts every one of them in a test of #196826, #197179, #197188
> or #197195 below, and this commit's one claim about #197195's eight tests
> is that it does not touch them; converting their stubs here would put
> edits to four other PRs' tests in a commit whose diff is otherwise three
> tests and two helpers, and would shift the hunks #197220, #197050 and
> #197257 apply above. `AlwaysRaises` is module level so those owners can
> adopt it in one line each; the two message-taking copies are drop-ins for
> it already.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 4b8ef1f
Pull-Request: #197219
@bobrenjc93 bobrenjc93 changed the title [no-ci] [aot_compile] Pin the raise-tolerant module dispatch's exits and binding [aot_compile] Pin the raise-tolerant module dispatch's exits and binding Sep 18, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
Test-only, 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` this commit does not touch. The three tests
here were three of the twelve of `[aot_compile] Pin the raise-tolerant module
dispatch's warning: its paths, text and dedup` (#197195), directly below;
this commit adds them without touching the eight that stayed there, and
folds a fourth's two assertions into the landed test whose setup it
repeated. They pin the exits of `AOTCompiledModel.__call__` that record a
raise nowhere -- a `KeyboardInterrupt` or `SystemExit` out of a later tree, a
later result whose signature cannot take the call, a call the one signature
cannot take -- and that a call binds once per result across both dispatch
passes and the report.

Where they sit. The two about binding join the landed
`test_module_dispatch_*` tests on how a call binds, directly after
`test_module_dispatch_binds_per_result_when_signatures_differ`, under that
prefix, and, like that cluster, without `_hide_leaked_dynamo_globals`;
`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates` stays
among #197195's dedup tests, because its last call is a dedup pin, and calls
it as they all do. Two module-level helpers beside `compile_mode_defaults`
serve them: `compile_two_signatures`, the two-signature model that landed
test and the cannot-bind test assemble, built from the same
`aot_compile_forward` (its comment states when the two results bind alike --
iff `second_forward`'s parameters and closure cells match forward's,
measured: a `(self, x)` second forward binds alike, one named `(self, y)` or
given a default does not -- rather than promising they never do), and
`AlwaysRaises(message)`, the stub guard manager whose every `check()` raises,
subclassing `NeverReChecked` so a regression that re-checks it in a report
fails on that class's message; the interrupt and cannot-bind tests use it
where each had its own copy.

The exits that record nothing. Every path in #196826 that RETURNS a graph
with a raise on record logs one, every path that builds a report chains one,
and a call that ends in neither leaves as the exception that ended it; its
FAQ says why nothing is logged on the way out.
`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`: two
results, [0]'s tree raising `RuntimeError` and [1]'s raising, on one call
each, `KeyboardInterrupt` and then `SystemExit`; each leaves `__call__` as
itself with nothing logged, and the next call, with [1]'s real tree back,
serves [1] and logs `[0]'s guard check raised RuntimeError: zero is unhappy`.
That last call pins WHERE the dedup is judged (FAQ below). `SystemExit`
travels the same path as `KeyboardInterrupt` today -- one `except Exception`
in `accepts()` is the only handler between the tree and the caller, and the
comment says so -- and is there because the `AOTCompiledModel` docstring
promises both propagate: without it an `except (Exception, SystemExit)`
added later would pass every test in the file (measured below). The order of
the two iterations is not load-bearing (FAQ below).
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error`: two
results that cannot share a binding, [0]'s tree raising and [1]'s signature
needing an argument the call lacks; `TypeError: missing a required argument:
'z'` leaves `__call__` with nothing logged. It pins its premises before the
call -- `_binds_alike` is False, so [1] binds inside its own `accepts()`, and
[0]'s `guard_check` raises `RuntimeError: zero is unhappy` -- so a stub that
stopped raising fails it with `RuntimeError not raised` (measured below)
instead of leaving the case it names unexercised. Both keep `assertNoLogs`
outermost (FAQ below).
`test_module_dispatch_wrong_arity_raises_type_error` is the one-result form
of the same exit, and the source before #196826 already had it right: a call
the signature cannot bind is the `TypeError` a plain module call raises, with
no report folded around it -- `prepare_f_locals` stays outside `accepts()`'
`try`. The type is the whole pin: the report is raised as a `RuntimeError`,
so `assertRaisesRegex(TypeError, ...)` excludes it and nothing else about
the exception needs reading.

One more thing the source before #196826 already did, kept, pinned in the
landed `test_module_dispatch_binds_per_result_when_signatures_differ`, which
already builds the two-signature model and shows each result binding on its
own: a third call, `x.half()`, that no result matches ends in the no-match
report (`assertRaisesRegex(RuntimeError, "No AOT compiled graph matched")`)
having bound once per result -- in index order, the same objects, asserted
per position so a wrong-order failure names the position -- while both
passes checked each result (`check` wrapped and counted: two per result);
that source's per-result list already satisfied it, and #196826's `bound`
dict keeps it. The report's entry count is not asserted here: the report
reads `bound[i]`, so it adds nothing to the bind count, and seven other
tests count those lines.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_out_of_a_later_tree_propagates
python test/dynamo/test_aot_compile.py -k test_module_dispatch_later_result_that_cannot_bind_raises_type_error
python test/dynamo/test_aot_compile.py -k test_module_dispatch_wrong_arity_raises_type_error
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_per_result_when_signatures_differ
python test/dynamo/test_aot_compile.py
```

The whole file runs 283 tests, `OK (skipped=6)`, three more than #197195's
file loads. `lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py`
is clean. The four were also run against the `torch/_dynamo/aot_compile.py`
of #196826's parent under this test file: the interrupt and cannot-bind
tests both error on [0]'s `RuntimeError: zero is unhappy` escaping the call
before the exit they pin is reached, and the two that pin what that source
already did pass, as they should.

Each of the two negative pins fails a mutant of its own, run against the
whole 283-test file at this commit; the tests named are the only ones that
failed. Moving the bind inside `accepts()`' `try` fails
`test_module_dispatch_wrong_arity_raises_type_error` and
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error`: the
`TypeError` is read as a raise and each call ends in a no-match report
(`No AOT compiled graph matched this call. Tried 1 compiled input(s)` and
`Tried 2`) where the `TypeError` was expected. Rebinding on every pass
(`f_locals = None` in place of `bound.get(i)`) fails
`test_module_dispatch_binds_per_result_when_signatures_differ` with
`Expected 2 but got 4` binds (and the landed
`test_module_dispatch_decides_a_shared_binding_past_the_first_result`, on
`_binds_alike` being called). Deleting the second pass fails it on its
`check` counts, `Expected 2 but got 1` -- its bind count alone reads the
same with one pass as with two -- along with 14 tests of the file that pin
the re-check.

Each fix in #196826 that the other two cover was then reverted on its own
against the same file. Widening `accepts()`' handler to `BaseException`
fails only `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`,
whose `KeyboardInterrupt` call gets a `RuntimeError: No AOT compiled graph
matched this call. Tried 2 compiled input(s)` report where it asked for the
interrupt; widening it to `(Exception, SystemExit)` fails only the same
test, on its `SystemExit` call, the same way. Deciding the dedup's `(index,
exception type)` pair in `accepts()`' handler, as the raise is recorded,
rather than in `warn_swallowed` fails the same test on its last call's
`assertLogs` (`no logs of level WARNING or higher triggered`), and one other
test in the file, #196826's
`test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`,
the same way (FAQ below). Making the dispatch handler re-raise fails the
interrupt and cannot-bind tests on [0]'s `RuntimeError` escaping, the two
pins of the older behaviour passing. Reading the warning's raiser off the
served index fails the interrupt test's last call, whose log then names
`[1]`; that mutant is #197195's, whose message lists the four tests it
fails there. Replacing [0]'s `AlwaysRaises` in
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error` with
a stub that returns False fails it on its premise assertion, `RuntimeError
not raised`.

> **FAQ: `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`
> and `test_module_dispatch_later_result_that_cannot_bind_raises_type_error`
> nest `assertNoLogs` outside `assertRaisesRegex`, so a spurious warning on a
> call that also fails the raise assertion is reported as the raise failure.
> Swap them so `assertRaisesRegex` is outermost?**
>
> Declined, because the swap makes the log pin vacuous, measured here.
> `unittest`'s `_AssertLogsContext.__exit__` returns False without reading its
> records whenever an exception is passing through it ("let unexpected
> exceptions pass through"), and on these two tests' expected path the call
> ALWAYS raises, so an `assertNoLogs` nested inside the raise assertion exits
> by exception every time and checks nothing. With
> `log.warning("spurious warning on record")` added to `accepts()`' handler:
> as written, both tests fail with `AssertionError: Unexpected logs found:
> ['WARNING:torch._dynamo.aot_compile:spurious warning on record']`; with
> `assertRaisesRegex` outermost, the cannot-bind test passes and the
> interrupt test fails only on its last call, on `len(logs.output)` reading
> 2 where 1 is expected -- the swapped blocks let the warning through on all
> three aborted calls. The masking the finding describes happens only on a
> call that has already failed the raise assertion, where the test fails
> either way. The order as written is the one on which the silence is
> checked at all, and a one-line comment at each site says so; that line is
> the one note about the test framework the two tests keep, because it is
> what stops the swap.

> **FAQ: the interrupt test's last call -- [1]'s real tree restored, the
> next call serving [1] and warning about [0] -- asserts the two substrings
> `test_aot_compile_module_warns_again_about_a_replaced_index` (#197195)
> already asserts, and a regression that populated `_warned` while logging
> already fails the aborted calls' `assertNoLogs`. Are the aborted calls not
> the test?**
>
> The last call pins WHERE the dedup is judged. Measured by moving it:
> deciding the `(index, exception type)` pair in `accepts()`' handler as the
> raise is recorded, and leaving `warn_swallowed` to log the pairs so
> collected, passes the aborted calls (nothing is logged; the interrupts
> still escape), #197195's pop and every-input tests and #196826's
> single-result and once-per-model tests alike, and fails exactly two of the
> file's 283 tests: this last call, with `no logs of level WARNING or higher
> triggered`, because the aborted calls had already consumed `(0,
> "RuntimeError")`, and #196826's
> `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`,
> whose first call ends in a no-match report rather than an interrupt and
> whose second call is silent for the same reason. That is a restructuring a
> later reader could plausibly make -- the handler is where the pair is first
> known -- and it would make every aborted call a silent one for the raise on
> its record. The test's comment names both tests the move fails.

> **FAQ: `unittest`'s `testPartExecutor` re-raises `KeyboardInterrupt` but
> catches `SystemExit`, so does the interrupt test's iteration order --
> `KeyboardInterrupt` first -- decide whether a regression aborts the whole
> run or is reported as one failure?**
>
> No, measured. The only `KeyboardInterrupt` the test raises is the stub's,
> inside `assertRaisesRegex(KeyboardInterrupt, ...)`, which catches it on the
> expected path and turns a wrong message into an `AssertionError`; a
> regression that swallows it hands the test the no-match report, a
> `RuntimeError`, which `assertRaisesRegex` lets through as this test's
> error. With `accepts()`' handler widened to `BaseException`, the whole
> file ran to completion in either order: 283 tests, `FAILED (errors=1)`,
> the one error this test's `KeyboardInterrupt` iteration getting
> `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled
> input(s)`, both as written and with the tuple reversed to `(SystemExit,
> KeyboardInterrupt)`. No `KeyboardInterrupt` reaches `testPartExecutor` on
> any path this test has, so the order says nothing and the comment claims
> nothing about it.

> **FAQ: `AlwaysRaises` replaces this commit's two inline `Raises` stubs;
> the file's twelve other inline raisers (eight `Raises`, four
> `RaisingGuardManager`, two of them already taking the message as a
> constructor argument) are left in place. Why not convert them too?**
>
> `git blame` puts every one of them in a test of #196826, #197179, #197188
> or #197195 below, and this commit's one claim about #197195's eight tests
> is that it does not touch them; converting their stubs here would put
> edits to four other PRs' tests in a commit whose diff is otherwise three
> tests and two helpers, and would shift the hunks #197220, #197050 and
> #197257 apply above. `AlwaysRaises` is module level so those owners can
> adopt it in one line each; the two message-taking copies are drop-ins for
> it already.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 02f1b6b
Pull-Request: #197219
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 5c5f3d9fe9be; each item from the last bot pass below, with what changed. All four are fixed by deletion -- the code diff shrank by 12 lines (19 insertions / 31 deletions against the previously published commit).

1. > AlwaysRaises (963-971) duplicates the module-level RaisingTree (688-697), which this PR does not add. [...] Neither new call site reads .checks, so RaisingTree("zero is unhappy") is a drop-in at both 3191 and 5389 -- a two-line change entirely inside this PR's own new tests.

Fixed in 5c5f3d9fe9be: AlwaysRaises is deleted, and both of its call sites -- in test_module_dispatch_later_result_that_cannot_bind_raises_type_error and in the exit test -- now read results[0]._artifacts.guard_manager = RaisingTree("zero is unhappy"), the file's pre-existing module-level stub at 688. Neither site reads .checks, so the swap is behaviour-preserving; the whole file is green. The commit now adds no always-raising class at all.

2. > Two classes in the file are now named Interrupts, and the new one is a strict generalization of the old. [...] promote the parameterized one to module level beside RaisingTree and have both tests use it.

Fixed in 5c5f3d9fe9be, by deletion rather than promotion: the parameterized stub is gone and the surviving test defines a single-purpose inline class Exits that raises SystemExit, so exactly one Interrupts remains in the file (the pre-existing one). Promotion would have meant editing that pre-existing test, which git blame puts in #197390, already approved; deleting the duplicate name removes the two-same-named-classes problem without a cross-PR edit and with a smaller diff.

3. > The KeyboardInterrupt iteration of test_aot_compile_module_interrupt_out_of_a_later_tree_propagates (5392) re-runs a scenario the file already has. [...] Consider dropping to SystemExit alone [...]

Fixed in 5c5f3d9fe9be: the test is no longer a loop -- it runs the SystemExit scenario only and is renamed test_aot_compile_module_system_exit_out_of_a_later_tree_propagates, with the assertNoLogs (outermost) kept on the surviving aborted call. Measured that the dropped iteration pinned nothing: widening accepts()' handler alone, to BaseException or to (Exception, SystemExit), leaves all six of the file's interrupt/exit tests green, because _meant_an_exception re-raises whatever a tree meant that is not an Exception; and the landed test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates still fails on its own under the make-the-dispatch-handlers-re-raise mutant, so interrupt propagation keeps its regression pin after the deletion. The commit's comment now says explicitly that the landed test is what pins the interrupt out of this handler.

4. > assertNoLogs is not paired with a positive log assertion on the aborted calls, by design, but the test's own last call shows the cost. [...] it makes the last call, not the loop, the test's actual subject -- the name says otherwise.

Fixed in 5c5f3d9fe9be: with the loop gone the test is one aborted call plus one serving call, and its name now names the exit it pins. A new FAQ ("Is the exit the test is named for not the test?") states what the trailing dedup assertion adds over the aborted call -- it is what separates "silent because the exit left first" from "silent because _warned was already populated" -- measured by moving the dedup decision into accepts()' handler, which passes the aborted call and fails that last call with no logs of level WARNING or higher triggered.

Separately, every count and mutation in the description was re-run on the whole file at this head, and several claims were wrong and are corrected: "widening accepts()' handler [...] fails only this test" was false (handler-only widening kills nothing; a bare SystemExit reaches the record only when _meant_an_exception widens too, and then four tests fail); the dropped-second-pass mutant fails 23 other tests, not 14; the per-pass-rebind mutant fails one test, not two; a spurious log.warning has to be injected at the inline handler, not accepts(), to fail the two tests; the FAQ's inline-stub counts are four class Raises and two class RaisingGuardManager, and git blame attributes them to #197188, #197220, #197390 and #197391; the dedup mutant is reimplemented faithfully (eight failures); and the stale whole-file test count is gone.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

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


This round addresses every item from my last review — AlwaysRaises is gone in favour of the pre-existing RaisingTree, the duplicate Interrupts is gone, the test is down to the one load-bearing SystemExit scenario and renamed for the exit it pins, and the trailing dedup assertion is now justified; what's left is that the surviving test hand-rolls a model the test class already has a helper for, and one assertion drops the failure message its whole cluster passes.

Full review

PR Review: #197219

Summary

Test-only: adds three tests to test/dynamo/test_aot_compile.py pinning AOTCompiledModel.__call__ exits that record no raise (a bare SystemExit out of a later guard tree, a later result whose signature cannot bind, wrong arity), folds two bind/check assertions into the landed test_module_dispatch_binds_per_result_when_signatures_differ, and adds one module-level helper.

I re-verified the claims against torch/_dynamo/aot_compile.py. They hold: prepare_f_locals is outside the try at both sites — inline at 2010 with the try starting at 2012, and in accepts() at 2044-2051 with the try at 2053 — so the "for every result, not only the first" comment at 3168-3169 is accurate; accepts() catches Exception at 2055, so a bare SystemExit is never caught and _meant_an_exception never sees it, making the bare-vs-wrapped distinction at 5410-5412 real; the dedup key is built and consumed in _warn_swallowed (1942, 1972), not at record time, so the aborted call spends nothing and the trailing call's warning is correctly predicted; and the two substrings at 5443-5444 are producible from the format string at 1961-1962. The (2, 2) check count at 3147 is right — inline check on [0], accepts(1), then both again in the re-check, with the report using check_verbose on the cached bound dict. Every prior-round finding is fixed. Three things remain, all mechanical.

Code Quality

The system-exit test hand-rolls the artifact its own test class has a helper for. 5421-5424 and 5430-5433 build a ScaleModule compiled against two identical ModelInputs and then swap each result's guard_manager — which is exactly self._model_with_stub_trees(*stubs) at 2296-2306 (same torch.compile(ScaleModule(), fullgraph=True, backend="eager"), same ModelInput(args=(torch.randn(3, 3),), kwargs={}, contexts=[]) replicated len(stubs) times, same per-result guard_manager = stub). Every neighbour in this cluster uses it, three of them on the same (RaisingTree(...), Accepts()) pair: 5295, 5376, 5397. The real/restore dance at 5432 and 5438 exists only to get an accepting tree back at [1] for the second call, and Accepts() (712) is what the neighbours substitute for that — I checked that nothing in the test reads the genuine tree, and nothing depends on x matching the capture, since the four assertions need only "[0] raises, [1] accepts". Writing it as

model = self._model_with_stub_trees(RaisingTree("zero is unhappy"), Exits())
...
model.forward.compiled_results[1]._artifacts.guard_manager = Accepts()

drops seven lines and puts the test in the same shape as the cluster it sits in. This is the same reasoning that produced compile_two_signatures one level up in this very PR. Fix this →

The six-line bind counter is duplicated verbatim. 3132-3137 (binds = [], bind = AOTCompiledFunction.prepare_f_locals, def counted(result, *args, **kwargs)) is character-for-character 3071-3076 in test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature. Two call sites in the same class, 60 lines apart, is the same case compile_two_signatures was extracted for.

12 comment lines on a 38-line test. 5408-5419. Two of those lines are not about the code under test: "A KeyboardInterrupt out of this handler is what test_..._propagates pins, so this does not repeat it" argues the test is not redundant, and "judging the pair at the raise instead fails this and test_aot_compile_module_two_raisers_..." names which other test a hypothetical mutant kills. Both are notes about the test suite's composition rather than the dispatch invariant, and both go stale the moment either named test is renamed. CLAUDE.md asks for comments that carry non-obvious global context; the four lines at 5408-5412 do that and the rest can go. The "assertNoLogs outermost" line is duplicated verbatim at 3172, which at least makes it a local convention rather than a one-off.

Testing

5441 drops the failure message every sibling passes. self.assertEqual(len(logs.output), 1) — of the 28 assertEqual(len(logs.output), N) sites in the file, this is the only one in the warning cluster without a third argument; 5252, 5272, 5282, 5298, 5304, 5323, 5361, 5379 and 5402 all pass "\n".join(logs.output), and 5025, 5051, 5136, 5243 pass a precomputed string. When this fails, the unexpected extra warning is the whole diagnosis and this form hides it — the very next line already computes warned = logs.output[0]. Fix this →

Recommendation

Approve

The exits are worth pinning, the coverage is genuinely new (nothing else in the file asserts an arity TypeError out of dispatch, and nothing else raises a bare SystemExit), and this revision cleared every defect from the prior three rounds. What is left is polish: reuse _model_with_stub_trees, restore the assertEqual message, and trim the two meta-commentary comment lines. None of it blocks.

I could not execute anything. The [no-ci] title prefix disables CI on this PR and this sandbox cannot build PyTorch, so the three tests and the claimed whole-file green run are unverified here; the review is static, reading the tests against torch/_dynamo/aot_compile.py. One wording nit on the new comments: 5416-5417 calls the dedup key a "pair", but the source key at 1942/1972 is the triple (index, exception-type-name, opt-out state) — the description carries the same "pair" wording, and the distinction matters because test_aot_compile_module_warns_again_after_the_raiser_opts_out (5288) exists precisely because of the third element.

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

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 18, 2026 19:42
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197050

pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…a missing-global failure (#197580)

**Problem.** `_no_match_report` only resolves `forward` (running `get_traced_fn` over user code that can raise) when a SUPPLIED entry failed on a missing global, but no test pinned that an ordinary guard mismatch skips the resolve; hoisting the gate out of the missing-global branch left the whole file green.

**Fix.** One test builds a SUPPLIED entry whose guard fails on an ordinary `KeyError` mismatch and asserts the report has no hint line and `_resolve_guard_scope` is never called. No source change.

**Summary.** One test, `test_no_match_report_resolves_no_forward_for_an_ordinary_mismatch`, pins the branch `AOTCompiledModel._no_match_report`'s resolve gate sits in. The gate (`result._guard_scope is _GuardScope.SUPPLIED and not tried_forward`) is nested under `if any(map(_names_a_missing_global, parts)):`, so a SUPPLIED entry whose guard failed on an ordinary mismatch never resolves `forward`. That matters because resolving runs `get_traced_fn` over user code that can raise, the same cost the other gate tests in #197301 exist to avoid; those tests all reach a SUPPLIED missing-global entry first, so hoisting the gate out of the missing-global branch left every one of them green. The new test loads the two-input artifact against a caller dict that binds `GLOBAL_POOLING_CONFIG` to a dict without the key its guard reads, so the report fails on a `KeyError` that `_names_a_missing_global` rejects whole, there is no hint sentence, and the resolve is never called. It sits as its own commit rather than in #197301 because the commit between them (#197319) is approved and must not move; it belongs with the gate tests and can fold into #197301 if that stack order changes.

## The gate under test

```python
# AOTCompiledModel._no_match_report
if any(map(_names_a_missing_global, parts)):                        # the missing-global branch
    if result._guard_scope is _GuardScope.SUPPLIED and not tried_forward:   # the resolve gate
        ...  # resolve forward: get_traced_fn over user code
```

A SUPPLIED entry that fails on an ordinary mismatch never reaches the inner `if`, so `forward` is never resolved for it. Hoisting the gate out of the outer branch fails this test alone (`Called 1 times`).

## The test

```python
def test_no_match_report_resolves_no_forward_for_an_ordinary_mismatch(self):
    data = self._two_input_global_guard_artifact(x)
    keyless = {"__builtins__": builtins, "GLOBAL_POOLING_CONFIG": {}}     # bound, but without the key the guard reads
    loaded = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=keyless)
    results = loaded.compiled_results[:1]                                # keep one result
    self.assertIs(results[0]._guard_scope, _GuardScope.SUPPLIED)
    resolve = patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope)
    with resolve as resolves, self.assertRaises(RuntimeError) as ctx:
        AOTCompiledModel(loaded.model, results)(x)
    resolves.assert_not_called()
    lines = str(ctx.exception).splitlines()
    self.assertEqual(lines[1], "  [0] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']")
    self.assertEqual([line for line in lines if line.startswith("For [")], [])
```

The report fails on `  [0] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']`, which `_names_a_missing_global` rejects whole (the global is bound; only its key is missing), so there is no hint sentence and the resolve is never called. The test asserts that entry line, the absence of any `For [` line, and `assert_not_called()`.

Test Plan:

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

The whole file is green, `OK (skipped=6)`. With the gate hoisted out of the
missing-global branch the new test is the file's only failure.

This PR was authored with an AI assistant (Claude).

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

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

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

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

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

## Where this sits in the stack

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

## The report the commit below prints

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

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

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

## Recording `trusted`

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

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

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

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

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

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

The comment at that block gives the same two numbers.

## The caveat

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

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

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

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

## Why the stale-state clause is hedged

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

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

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

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

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

## What the caveat keys on

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

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

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

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

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

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

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

## The one real throw: `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`

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

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

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

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

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

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

## What does not change

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

## Stubs and the golden

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

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

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

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

## Tests

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

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

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

## Order to review

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

Test Plan:

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

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

Authored with the assistance of Claude Code.

## FAQ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Test Plan:

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

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

Authored with the assistance of Claude Code.

> **FAQ: The trailing-separator improvement is exact only for one trailing
> separator: two leave `...abc >` still, since collapsing a text that ends in
> two of them yields a trailing space of its own.**
>
> True, and left as is: the collapse puts a space between the pieces
> `splitlines()` returns, so a text ending in N separators keeps N-1 spaces
> before the bracket. What the format rests on is the entry staying on one
> line, which holds for any N, and no golden reads the residue; stripping it
> would be a rule the report applies to no other quoted text.

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

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

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

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

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

## The bug: bind first, check second

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

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

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

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

## The fix: check before `import_source`

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

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

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

## The other nine `import_source` callers

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

## Behaviour changes against the parent

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

## The test

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

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

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

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

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

Test Plan:

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

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

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

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

Authored with the assistance of Claude Code.

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

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

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

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

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

Test Plan:

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

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

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

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197746
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050, #197257, #197745
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1209/head branch November 22, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants