Skip to content

[aot_compile] Say when a no-match report entry's guards accepted the call the dispatch refused - #197150

Closed
bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1204/basefrom
gh/bobrenjc93/1204/head
Closed

bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1204/basefrom
gh/bobrenjc93/1204/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This commit and [aot_compile] Raise a report naming every input when no compiled graph matches (#196823, two commits below) were one commit, split for
review budget: that commit raises the report, and this one owns what an
entry's line says when check_verbose answers that the tree ACCEPTS the call.

An entry's line quotes the guards check_verbose named for that input, and
one of its answers names none while meaning the opposite of a failure: a tree
that accepts the call. Both dispatch passes ran that tree and rejected the
call, and the report's check_verbose accepts it, so a guard in that tree
does not answer consistently between evaluations. Below this commit such an
entry prints nothing after [i], since an accept carries no verbose parts,
and the call is refused all the same: the report is raised whatever its
entries say. Quoting the guards the tree just passed as a reason the call
failed would name the wrong thing, so GuardDebugInfo.result decides and the
entry now reads <guards rejected this call twice and then accepted it here: a guard that does not answer consistently>, and the loop moves on so that line
is all the entry contributes. That is not a match to serve: an accept that
arrives only on the third evaluation is not a certified match. The class
docstring's description of the report now lists this line kind beside the
guard-quoting line and the For [i, j]: hint.

This changes what the entry says and nothing about which calls are served.
Refusing this call is #196823's: before it, the fall-through's
AOTCompiledFunction.__call__ gave [0] alone, by its position, a third
evaluation and served the graph when that one accepted (SERVED equal_to_x*3= True compares= 3), and from #196823 on the report's
check_verbose is that third evaluation and the call raises (RAISED compares= 3). test_no_match_message_when_a_guard_answers_inconsistently
pins the raise, the three evaluations, the entry's full text and the report's
entry count together: the evaluation count says the report's check_verbose
is the third evaluation of that tree and nothing evaluates it a fourth time to
serve it, and the entry count, two [ lines for two results, says the
explanation is the whole of [1]'s entry. The test builds its model
through _aot_compile_mode_branches(), the helper its siblings on this path
use, whose first line, _hide_leaked_dynamo_globals(), strips the synthetic
globals a capture mints into this test module's dict for the test's duration.
_install_global_probe now returns the CountedKey it installed along with
the saved value so the test can read probe.compares; its other caller
unpacks the pair.

Order to review: the if reason.result: branch in
AOTCompiledModel._no_match_report and the class docstring's report
paragraph; then _install_global_probe and the test.

FAQ: The dispatch comment above _no_match_report names a check() exit
that refuses without running the tree -- a tag-safe root's dict-tag fast path
in GuardManager::check_nopybind. Why does the entry not name it as a
second cause?
Because it cannot be the cause in a default build.
find_tag_safe_roots() runs only when config.use_recursive_dict_tags_for_guards
(default False) and its justknob are both on (guards.py, GuardBuilder
setup), so no node is ever marked a tag-safe root and the
check_dict_pointer_tags branch is unreachable; an entry naming it would
hand a reader debugging on defaults a hypothesis their build cannot take.
With the config on the case is still narrow: a root's fast-path refusal
disarms it (_disable_dict_tag_matching = true), so the second dispatch
pass runs the tree that root skipped, and reaching this entry from the fast
path needs a second, still-armed root the first pass never got to refusing
in the second. An earlier draft of this commit named both causes; the
clause was dropped rather than made conditional on the config so the entry
says one thing that is true of every build. The fast path stays documented
where it is acted on, in the dispatch comment.

FAQ: AOTCompiledFunction.__call__ has the same shape -- guard_check()
is one check(), and when it rejects and the following check_verbose
accepts, the message interpolates the whole GuardDebugInfo, whose
to_string renders result=1 and verbose_code_parts=[] under
GuardManager check failed, reason:. Why is that path left as it is?

It is the same defect, and the function path reaches it after one
evaluation rather than two, so a single inconsistent answer is enough. It is
out of this commit's scope, which is what the MODULE report's entry says
(the piece split from #196823); the function path's message is a separate,
pre-existing string with its own missing-global plumbing, and it is left for
a follow-up commit that can pin it with its own test rather than folded in
here.

FAQ: test_no_match_message_when_a_guard_answers_inconsistently asserts
exactly 3 evaluations. Isn't that count a property of the guard tree's shape
rather than of the dispatch?
The count is the pin: it says the report's
check_verbose is the third evaluation of that tree and nothing evaluates it
a fourth time to serve it, which is the behaviour the entry above describes.
It does rest on the tree's shape -- one DictGetItemGuardAccessor rooted at
the global, so one lookup per evaluation -- and on the dict-tag fast path not
firing, which it cannot here: use_recursive_dict_tags_for_guards is off
(the default), and even on, the probe's pop/insert bumped this module dict's
version past the one the last accepting evaluation recorded (_dict_tag is
stored only on an accept). A second accessor rooted at the same global would
change the count and the misses=2 premise together, and the test's comment
names both dependencies, so a reader who changes the tree knows what to
re-derive; loosening the assertion to >= 3 would stop pinning that the
report evaluates it once.

FAQ: The closing advice lands directly under the "rejected this call twice
and then accepted it here" entry, where it reads as a diagnosis of it. Why
leave it there?
The line is deliberately the report's footer, not per-entry
commentary, and that is why #196823 emits it after the loop rather than
inside it. Adding a ModelInput is a real mitigation for that entry too --
an input captured for this call gets a tree that matches it on the first
evaluation, so the inconsistent entry stops being consulted. Moving the
advice above the entries, or suppressing it when any entry took that branch,
would make the only actionable line in the report depend on which branch some
unrelated entry hit, the same masking #196823's message argues against for
the missing-global hint. The entry's own text already says what happened in
its own words, so the reader is not being told the footer explains it.

Test Plan:

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_module_dispatch_never_pairs_old_contents_with_a_new_verdict
python test/dynamo/test_aot_compile.py

The whole file runs 210 tests, OK (skipped=6); the parent runs one
fewer. With the parent's aot_compile.py under this test file the new test
fails on the entry's text, ' [1] <guards rejected this call twice and then accepted it here: a guard that does not answer consistently>' not found in "... [1] \nAdd a ModelInput ...", after its evaluation-count assertion
passed. The assertion is the entry's whole text: cutting the clause after it here or replacing it with the dropped tag-safe wording fails it the same way.
Deleting the continue after the accept branch (the mutant that lets the
accept's empty verbose parts add a blank [1] line under the explanation)
passes the text assertion and fails the entry-count pin, Expected 2 but got 3. With the aot_compile.py below #196823 the test fails earlier, on the
evaluation count, Expected 3 but got 2, since the fall-through's third
evaluation is of [0], which fails on L['mode'] before it reads the global.

Authored with the assistance of Claude Code.

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

🤖 Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 10 New Failures, 1 Unclassified Failure

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

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • TSan / get-label-type / runner-determinator (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    ##[error]CI is disabled by the [no-ci] PR title prefix. Remove the prefix and push a new commit to run CI.

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 15, 2026
This was referenced Sep 15, 2026
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 15, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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


Reviewed: the new report branch is correct and the behavior claim holds, but the test duplicates an existing helper and drops its global-leak cleanup, and its assertion only pins the first half of the new message.

Full review

PR Review: #197150

Summary

Adds a branch to AOTCompiledModel._no_match_report so that a report entry whose check_verbose accepts the call prints an explanatory line instead of a bare [i], plus a test pinning the raise, the three tree evaluations, and the entry text. The branch logic and the "nothing about which calls are served" claim check out; the problems are in the test's setup and the strength of its assertion, plus one unreachable-by-default clause in the message.

Code Quality

  • test/dynamo/test_aot_compile.py:2644-2657 reimplements _aot_compile_mode_branches() (test/dynamo/test_aot_compile.py:2370-2386) line for line — same ModeBranchGlobalModule, same guard_filter_fn=keep_global_guards, same two ModelInputs for mode 0 and 1, and the helper already returns exactly the (model, x) pair this test builds. The one difference is that the copy omits the helper's first line, self._hide_leaked_dynamo_globals(), and that omission is the part that bites: the helper's cleanup is what strips the synthetic globals (__compiled_fn_*, __import_*, ...) that torch.compile + _aot_compile mint into this test module's globals(), so without it this test leaks them into the other 208 tests in the file. Every sibling test on this path calls it — 2371, 2495, 2528, 2730, and 38 more — and _install_global_probe's own docstring at test/dynamo/test_aot_compile.py:2121-2122 mandates the ordering ("Call _hide_leaked_dynamo_globals before this, never after"). Replace the eleven-line block with model, x = self._aot_compile_mode_branches(), which restores the call and removes the duplication in one edit. Fix this →

  • torch/_dynamo/aot_compile.py:1601-1603 names two causes, and the second one — "a tag-safe fast path that refused without running the tree" — cannot fire in a default build. find_tag_safe_roots() is gated on config.use_recursive_dict_tags_for_guards (torch/_dynamo/guards.py:396-400), which defaults to False (torch/_dynamo/config.py:497), so no node is ever marked a tag-safe root and the check_dict_pointer_tags branch of GuardManager::check_nopybind (torch/csrc/dynamo/guards.cpp:3796-3816) is unreachable. A reader debugging on defaults is handed two hypotheses when only the first is possible for them. Worth either dropping the clause or conditioning it on the config, so the message does not send someone chasing a path their build cannot take.

  • torch/_dynamo/aot_compile.py:893-907 has the same latent defect this PR fixes for the module path, and stays unfixed. When guard_check() (a single check()) rejects and the following check_verbose(f_locals) accepts, the message interpolates the whole GuardDebugInfo, whose to_string (torch/csrc/dynamo/guards.cpp:1750-1758) renders result=1, verbose_code_parts=[] under the header GuardManager check failed, reason: — a message that asserts a failure while displaying a pass and naming no guard, which is exactly the wrong-thing-named problem the new branch exists to avoid. The function path is if anything more exposed than the module path: it evaluates the tree once before reporting rather than twice, so a single fast-path refusal is enough to reach it. Out of this PR's stated scope, but it should not be left to be rediscovered from a confusing bug report.

Testing

  • test/dynamo/test_aot_compile.py:2667 asserts only the message's prefix, "[1] <guards rejected this call twice and then accepted", and stops there. The clause the PR's entire rationale rests on — naming the two causes, "a guard that does not answer consistently, or a tag-safe fast path that refused without running the tree" — is unpinned, so that half of torch/_dynamo/aot_compile.py:1601-1603 could be deleted or reworded to something untrue and this test would still pass. Assert the full entry text (or at least a fragment of the causes clause) so the test covers what the commit is actually about.

Recommendation

Request Changes

Nothing here affects which calls get served, and the three-evaluation count the description defends does hold up: results is snapshotted once at torch/_dynamo/aot_compile.py:1547, both passes check every reported result, [0] fails on L['mode'] == 0 before reaching the global, and DictGetItemGuardAccessor::check_nopybind (torch/csrc/dynamo/guards.cpp:5765) makes exactly one PyDict_GetItem per evaluation — so probe.compares == 3 is well-determined rather than brittle. What blocks approval is small and mechanical: reuse _aot_compile_mode_branches() so the test stops leaking Dynamo's synthetic globals into the rest of the file, and widen the message assertion to cover the causes clause.

· branch `gh/bobrenjc93/1204/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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


The new report branch and its test check out on the code side; what needs fixing is text — the PR description still quotes a message the code no longer emits, the class docstring wasn't updated for the new line kind, and the test would still pass if the continue were dropped.

Full review

PR Review: #197150

Summary

Adds a branch to AOTCompiledModel._no_match_report so a report entry whose check_verbose accepts the call prints an explanatory line instead of a bare [i], plus a test pinning the raise, the three tree evaluations, and the entry text. Verified sound: the "twice" claim holds on every reachable path, probe.compares == 3 is well-determined rather than brittle, and the branch cannot change which calls are served. The problems are all in text that ships with the change and one gap in what the test pins.

Code Quality

  • The PR description no longer matches the code, and it becomes the commit message. The body quotes the entry as reading <guards rejected this call twice and then accepted it here: a guard that does not answer consistently, or a tag-safe fast path that refused without running the tree> and then spends a paragraph plus an FAQ justifying that second clause. torch/_dynamo/aot_compile.py:1602-1606 emits only ...accepted it here: a guard that does not answer consistently> — the tag-safe clause is gone. So the merged commit message would explain, at length, wording that never appears in any report a user sees, and a future reader grepping for tag-safe fast path from the commit log finds nothing. Trimming the clause was the right call (see below), but the description has to be re-synced before merge. Note the FAQ's other premise is still accurate: misses=2 at test/dynamo/test_aot_compile.py:2687 and assertEqual(probe.compares, 3) at :2695 are unchanged. Fix this →

  • The class docstring wasn't updated for the new line kind. torch/_dynamo/aot_compile.py:1514-1515 enumerates what the report contains: "one line per compiled result quoting the guards that refused it", then the For [i, j]: hints, then the advice. After this change an entry can instead be a <guards rejected this call twice and then accepted it here...> line, which quotes no guards and describes the opposite of a refusal. The docstring is the contract for a report whose exact shape the tests assert line-position by line-position (:2077-2080), so leaving it enumerating only two of the three line kinds is the kind of drift that makes the next reader mistrust the whole paragraph. Fix this →

  • Unrelated to this diff but the same defect this PR fixes, still unfixed one path over: torch/_dynamo/aot_compile.py:894-906 interpolates the whole GuardDebugInfo after a single check() rejection, so a check_verbose that accepts renders result=1, verbose_code_parts=[] under the header GuardManager check failed, reason: — a message asserting a failure while displaying a pass and naming no guard. Worth a follow-up rather than scope creep here.

Testing

  • test/dynamo/test_aot_compile.py:2696-2699 asserts the new line is present but nothing asserts it is the only thing entry [1] contributes, so deleting the continue at torch/_dynamo/aot_compile.py:1607 still passes: control would fall into parts = reason.verbose_code_parts, which is empty for an accepting GuardDebugInfo (torch/csrc/dynamo/guards.cpp:1737-1740), and append a second, blank [1] line right after the explanatory one. That blank-entry line is exactly what test_aot_compile_module_no_match_error (:2077-2080) was strengthened to forbid, yet it would slip through here because this test only uses assertIn. Pin the entry count — e.g. self.assertEqual(sum(line.startswith(" [") for line in message.splitlines()), 2) — so the continue is load-bearing under test. Fix this →

Recommendation

Request Changes

Everything blocking is text-level and mechanical. The three earlier findings are resolved: the test now calls _aot_compile_mode_branches() (:2686), so it regains the _hide_leaked_dynamo_globals() sweep in the order _install_global_probe's docstring requires, and the unreachable tag-safe clause is out of the message.

On dropping that clause — it was the right call, and I checked it rather than assuming. The structure for a double fast-path refusal does exist: find_tag_safe_roots marks sibling roots (suppression is only vertical, torch/_dynamo/guards.py:584-586), _disable_dict_tag_matching is per-node and never reset (guards.cpp:4270), and a root skipped in pass 1 by the accessor-loop break can be reached and refuse in pass 2. But use_recursive_dict_tags_for_guards is off by default (torch/_dynamo/config.py:497), and the refusal itself requires a dead recorded weakref or a duplicate verdict — i.e. a cache-coherence hole, which is the same "the cached answer disagrees with the live one" the message already names. Naming one cause is accurate.

Separately verified and fine: _no_match_report is reachable only after each result was checked exactly twice (every skipping exit at aot_compile.py:1558/:1566/:1576 is a return), _live_guard_manager() returns the same object across all three evaluations, the raise at :1582 is unconditional, probe.compares == 3 is independent of fail-count accessor re-sorting because [0]'s tree has no accessor keyed on that global at all, and the 122-char golden string needs no noqa: B950 (E501 and B950 are both ignored repo-wide; test_aot_compile.py:7253 is a 137-char precedent).

· branch `gh/bobrenjc93/1204/head`

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…fter a raise

Test-only, split for review budget from `[aot_compile] Tolerate a guard tree
that raises during module dispatch` (#196826), two commits below, whose
`torch/_dynamo/aot_compile.py` this commit does not touch. The nine 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. It also adds the one key class only
its own test uses, `HitsThenRaises`, between `RaisesOnCompare` (#196826) and
`RaisesThenHits` (#197188), the comment on `RaisesOnCompare` counts three such
keys again, and one assertion goes into #196826's
`test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`
(below). The warning's other paths, the exits that record nothing and four
more things the parent already did are #197195, directly above, which adds its
tests around these without touching them; #197050 and everything above apply
on it unchanged.

The report, after a raise.
`test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators`: the
raise line is the one report entry whose text is arbitrary user data, so a
message carrying `\x0c`, `\r`, `\x1e` and `\u2028` collapses to the one entry
`  [0] <guard check raised RuntimeError: page break rec sep line>` rather
than splitting across several; the message holds no spaces, so the whole-line
assertion says all four separators arrived and were collapsed. The report's
total line count -- four: header, entry, fix-or-drop advice, `ModelInput`
advice -- is the count a split entry moves; counting the entries that start
with `  [`, as this test did before, reads 1 either way, the first fragment
being the only one that starts so (measured below).
`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, `unhappy on pass 2`, and chains it, and `pass 1` appears nowhere.
The chain carrying the FIRST index that raised while the advice names the
first ENABLED one is #196826'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. A previous
revision had a test of its own for that shape; four of its five assertions
were that test's, so it is folded into it instead (FAQ below).
`test_no_match_message_keeps_the_advice_beside_a_raise` and
`test_no_match_message_keeps_the_advice_beside_a_withheld_opt_out`: a
missing global and a raiser in one report, where the missing global's own
hint, the fix-or-drop line and the `ModelInput` line stand on disjoint
entries; both pin that order, locate each line through the class's
`_line_index` so a dropped advice line reads as a message diff instead of as
a `StopIteration` from inside the test, and then read what the located 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 -- `[0]'s guard check
raised while checking this call` with no opt-out in the list, `[0]'s raise,
not a guard failure, is what withheld` with one -- since `fix or drop that
artifact` ends both sentences. Both hide the leaked Dynamo globals first, as
every other test here that captures a `ScaleModule` does -- the two-input one
is the `_aot_compile_mode_branches` fixture and says so -- and both register
the name's restore before deleting it, as `_install_global_probe` does and
says, so an interrupt in between leaves it in place. The three-input one's
opted-out [2] is made unsatisfiable by its dtype, and has to be: `mode`
traces dynamic on that third compile, after [0] and [1] recompiled on it, so
its else-branch guard is `L['mode'] != 1` and accepts the `mode=2` call (FAQ
below).
`test_no_match_message_after_a_raise_counts_no_second_rejection`:
pass 1 raised, pass 2 rejected, the report accepted -- the case that made
#196826 reword the re-check line -- so the line, asserted whole, counts no
second rejection for a stub checked exactly twice. The raise's TEXT survives
in the chain alone, `the first pass is unhappy` appearing nowhere in the
report; the fact of it does reach the report, as the `[0]'s guard check
raised while checking this call` advice, which the test pins too.
`test_no_match_message_when_only_the_report_raises` and its stub twin
`test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check`: both
dispatch passes got a clean rejection and only the re-check raised, so the
entry carries the raise itself -- only a dispatch raise is chained onto the
report -- and the `ModelInput` advice still applies. Both assert the entry
line whole against `splitlines()`, as every other entry-line assertion here
does. `_raised_line` prints the same line from either handler, so both twins
also pin 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 stub twin pins `stub.checks == 2` besides, both dispatch passes
having answered. Measured on the stub twin with its `check()` raising the same
`RuntimeError` instead of rejecting, so the raise is dispatch's and the entry
line reads the same: it fails on `__cause__` reading `RuntimeError('the
re-check is unhappy')` where None is expected, and with that assertion
removed on `'fix or drop that artifact' unexpectedly found` in the report.
The leaf version pins `key.compares >= 3`, the third evaluation the report
made rather than reusing a dispatch answer; a lower bound, since how often
one evaluation probes a key is codegen's business. `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 the entry line and the compare
count reading the same, which is why the leaf version pins the two readings
above too. Measured, in an earlier revision of this PR, with a wrapper around
the real guard manager that calls `check()` twice: the entry-line,
compare-count and `ModelInput` assertions all pass against it,
`assertIsNone(__cause__)` fails with the pybind `SystemError` as the cause,
and `assertNotIn("fix or drop that artifact")` fails on the report reading
`[0]'s guard check raised while checking this call; fix or drop that
artifact.` above the same entry line.
`test_aot_compile_module_veto_and_report_survive_without_the_dict_leaf`:
the stub twin of #197188's
`test_no_match_message_quotes_a_tree_that_raised_then_answered` -- [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 -- which also counts the report's `  [` entry lines against
one per input: 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. Its
`Rejects` stub defines a `check_verbose` for the reason `NeverReChecked`'s
docstring gives: without one, the report's own handler would dress the
resulting `AttributeError` up as a raise from the guard tree and that
mutation would pass. The `NeverReChecked` convention itself is exercised by
four stubs here (the odd-separators, two advice-order and last-raise tests),
one in #196826 and two in #197188: with `if i in unanswered:` forced to `if
False:`, all seven fail on "the report re-checked a tree that raised in
dispatch" (the four here and #196826's measured against this commit, the two
in #197188 in its message), and with `check_verbose` aliased to `check` under
the same mutation six of the seven pass -- only
`test_no_match_message_quotes_the_last_raise_at_one_index` still fails, on
its exact `stub.checks == 2` reading 3.

One thing the parent already did, kept.
`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_report_keeps_a_raise_on_one_line_past_odd_separators
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_keeps_the_advice_beside_a_withheld_opt_out
python test/dynamo/test_aot_compile.py -k test_no_match_message_after_a_raise_counts_no_second_rejection
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_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_veto_and_report_survive_without_the_dict_leaf
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
```

The whole file runs 270 tests, `OK (skipped=6)`; #197188 runs nine fewer.
`lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean. The
nine were also run against the `torch/_dynamo/aot_compile.py` of #196826's
parent under this test file: eight fail or error -- the leaf test on
`ValueError: boom on compare 3` escaping the call; the odd-separators,
veto-survives, no-second-rejection and last-raise tests on a count (`Scalars
are not equal!`); and three on a report line that is not there, the stub's
`RuntimeError` caught but carrying no report (`'  [0] <guard check raised
RuntimeError: the scanned tree is unhappy>' not found in ['the scanned tree
is unhappy']`) -- and the one that pins what the parent already did passes,
as it should; `raise RuntimeError(report) from None` fails it with `True is
not False` on `__suppress_context__`.

Each fix in #196826 was then reverted on its own against the tests of this
commit, and only the named tests failed (#197195's message lists its own):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_veto_and_report_survive_without_the_dict_leaf
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_after_a_raise_counts_no_second_rejection
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_keeps_the_advice_beside_a_withheld_opt_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_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
```

Dropping the `continue` from the report's withheld branch fails
`test_aot_compile_module_veto_and_report_survive_without_the_dict_leaf` on
3 entry lines where there are 2 inputs (`Expected 2 but got 3`), and
#196826's 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.
Chaining `raised[raiser]` instead of `next(iter(raised.values()))` fails
nothing here and the two-raisers test with `__cause__` reading `checked tree
is unhappy` where `the opted-out tree is unhappy` should be.
`raised.setdefault(i, e)` fails
`test_no_match_message_quotes_the_last_raise_at_one_index` with `unhappy on
pass 1` where `pass 2` is expected. Restoring the old "rejected this call
twice and then accepted" wording fails
`test_no_match_message_after_a_raise_counts_no_second_rejection` on its
whole-line assertion (#197150's
`test_no_match_message_when_a_guard_answers_inconsistently` asserts the same
line whole). Skipping an
index in `raised` on the second pass fails the veto-survives, no-second-
rejection and last-raise tests here on their `stub.checks` reading 1 where 2
is expected, the tree never re-evaluated (and two in #197188). Removing the
veto's `_guard_check_enabled` gate fails the veto-survives test here with
`dispatch served <the opted-out graph's value>, not a raise` and the
withheld-advice test with `RuntimeError not raised` (and one each in #196826
and #197188). Dropping the raise line's separator collapse fails
`test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` alone
here, on `Expected 4 but got 8` lines, the entry arriving as five; under the
same mutant the entry-start count this test used before still reads 1, and
with the whole-line assertion removed that count passes it. Dropping the raise
line's two-space indent fails the six tests here that assert an entry line
whole (odd-separators, last-raise, both advice-order, both re-check-only) and
nothing else here. Hinting entry 0 instead of the entry that named the global
(`hinted.setdefault(hint, []).append(0)`) fails both advice-order tests on
`'For [1]:' not found in 'For [0]: a guarded global is missing ...'` (and
#197149's `hints_only_the_entry_that_named_a_missing_global`). Emitting the
withheld sentence for every raiser (`if withheld:` to `if raiser is not
None:`) fails `test_no_match_message_keeps_the_advice_beside_a_raise` on
`lines[fix]` reading `[0]'s raise, not a guard failure, is what withheld ...`
and `test_no_match_message_after_a_raise_counts_no_second_rejection` on the
advice it pins (and #196826's `survives_a_raising_guard`); dropping the
no-opt-out advice altogether (`elif False:`) fails those two -- the first in
`_line_index`, no line found -- and the odd-separators test on 3 lines where
4 are expected. Making the report's `check_verbose` handler re-raise fails
`test_no_match_message_when_only_the_report_raises` and
`test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check` on the
re-check's raise escaping the call -- the leaf test on `ValueError: boom on
compare 3`, the stub test finding `the re-check is unhappy` alone where the
report line is expected -- (and #196826's describer test); widening that
handler to `BaseException` fails nothing. Making the dispatch handler re-raise
fails six of the nine, the three that pass being the two re-check-only tests
and the negative pin. Forcing `if i in unanswered:` to `if False:` fails the
four `NeverReChecked` stubs here on their re-check message (and the two in
#197188, and #196826's two-raisers test); with `check_verbose`
aliased to `check` under the same mutation, only
`test_no_match_message_quotes_the_last_raise_at_one_index` still fails here,
on `stub.checks` reading 3 (`Expected 2 but got 3`). 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: in `test_no_match_message_keeps_the_advice_beside_a_withheld_opt_out`,
> the third input is traced with `mode=0`, so its `L['mode'] == 0` guard
> already rejects the one call made, `model(x, 2)`; is the float64 dtype
> redundant?**
>
> No, measured: with a float32 third input the test fails with `RuntimeError
> not raised`, the scan serving opted-out [2]. Its guard is not `L['mode'] ==
> 0`: [0] and [1] already recompiled on `mode`, so the third trace takes it
> as dynamic and the else branch guards `L['mode'] != 1`, which `mode=2`
> satisfies (read off `check_verbose` of that result: `result=True` on
> `mode=2`, `L['mode'] != 1` as the failing part on `mode=1`; the same for a
> third input at mode 3). With the float64 input, [2]'s tree rejects the call
> on `tensor 'L['x']' dtype mismatch. expected Double, actual Float`. The
> comment now says why the mode cannot do it.

> **FAQ: why does a test-only commit add a line to a test #196826 owns
> instead of keeping its own test for the chain-versus-advice split?**
>
> Because that test and #196826's two-raisers test were the same
> construction -- two `ScaleModule` inputs, a `Raises(NeverReChecked)` taking
> a message, [0] opted out with `the opted-out tree is unhappy`, [1] raising
> -- and four of its five assertions (the withheld line, the raise line, the
> `not a guard failure` advice, `__cause__`) were 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 #196826 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.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 847f032
Pull-Request: #197179
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 28m 31s —— View job


The code and the description are in sync this round, and every prior finding is fixed and re-verified; the one open question is that the new entry names a single cause for a condition that has a second reachable one — concurrently-changed guarded state, which this file explicitly contemplates.

Full review

PR Review: #197150

Summary

Adds a branch to AOTCompiledModel._no_match_report so a report entry whose check_verbose accepts the call prints an explanatory line instead of a bare [i], plus a test pinning the raise, the three tree evaluations, the entry text, and the entry count. The implementation is correct and all three prior rounds' findings are resolved. One finding remains, and it is about what the message asserts rather than what the code does.

Code Quality

  • The entry names one cause; a second is reachable and in scope for this file. torch/_dynamo/aot_compile.py:1605-1609 diagnoses the report-time accept as a guard that does not answer consistently — i.e. nondeterminism inside the guard. But an accept on the third evaluation also arises when the guard is perfectly deterministic and the guarded state moved between dispatch pass 2 (:1577-1579) and the report's check_verbose (:1604). Nothing is snapshotted at bind time — prepare_f_locals binds only locals and closure cells, while GlobalsGuardAccessor re-descends the live dict each call (torch/csrc/dynamo/guards.cpp:6519-6523) and TENSOR_MATCH re-unpacks dtype/shape per evaluation (:5255-5260) — so a concurrent rebind of a guarded global, or an in-place mutation of a guarded tensor, in that window produces exactly this entry. __call__ holds no lock across the dispatch, and concurrency is not out of scope here: _binding_verdict's own comment says "A hint, not a lock: the last writer wins" (aot_compile.py:1526-1531), and two existing tests interleave a second thread with a live dispatch (test/dynamo/test_aot_compile.py:2316, :2353). A reader hitting that case is told to hunt for a nondeterministic guard when the real story is a race on the guarded value — the same wrong-thing-named failure the branch exists to prevent. The PR's FAQ argues at length for naming only one cause, but it argues it against the tag-safe fast path (unreachable on defaults, correctly dropped); it does not address this cause, which needs no config flag. Widening the tail — e.g. a guard that does not answer consistently, or guarded state that changed in between — costs one clause and keeps the entry true of every build; the golden string at :2683 would follow. Fix this →

Recommendation

Needs Discussion — on the message's tail only. The code is otherwise ready.

All three prior findings are closed, and I re-derived each fix rather than taking it on trust:

  • The description now quotes the shipped single-clause form, and the dropped tag-safe clause was correctly dropped: find_tag_safe_roots() is gated on config.use_recursive_dict_tags_for_guards and justknobs_check(...) in GuardManagerWrapper.finalize (guards.py:396-401), the config defaults False (config.py:497), and mark_tag_safe_root() has no other caller, so check_dict_pointer_tags (guards.cpp:3797-3813) is dead on defaults. The FAQ's disarm premise also holds — the no-tensor-aliasing refusal sets _disable_dict_tag_matching = true (guards.cpp:3810) and the only false in the file is the member initializer (:4270), so it never re-arms. Its Test Plan count is right too: 191 def test_ methods minus the 9 parametrized bases plus their 28 expansions is 210.
  • The class docstring covers the third line kind (aot_compile.py:1513-1521), and its <... accepted it here: ...> ellipsis is why that paragraph will not go stale if the tail changes.
  • The continue at :1610 is load-bearing under test: RootGuardManager::check_verbose_nopybind's sole success return is GuardDebugInfo(true, num_guards_executed) (guards.cpp:4488), whose two-arg ctor (:1737) leaves verbose_code_parts empty, so without the continue a blank second [1] line would appear — which the count at test_aot_compile.py:2688-2689 now forbids.

Also verified and fine:

  • .result is a real bool, not a count. Declared bool result (guards.cpp:1761) beside a separate int num_guards_executed (:1771), def_readonly at :7659, stubbed result: bool in torch/_C/_dynamo/guards.pyi:24; GuardManagerWrapper.check_verbose is a pass-through (guards.py:774-776).
  • "rejected this call twice" holds on every reachable path. bound gets exactly one entry per result unconditionally before that result's check (aot_compile.py:1562, :1567), so the second pass's zip truncates nothing, and every early exit is a return — the raise at :1585 is reachable only after two checks each, single-result case included. _live_guard_manager() returns the stored field (:645-650), so it really is the same tree all three times, and check_verbose_nopybind has no fast path (guards.cpp:4428-4500), so the third evaluation always runs the whole tree.
  • probe.compares == 3 is exact. CountedKey.__eq__ short-circuits on identity without incrementing (test_aot_compile.py:580-600) and __hash__ delegates to the name; ModeBranchGlobalModule reads AOT_BRANCH_SCALE only under mode == 1 (:606-612), so [0]'s tree holds no accessor on it — corroborated empirically by the pre-existing misses=1 sibling, whose check.call_count == 2 (:2418-2428) only holds if [0] consumes zero lookups. GlobalSource maps to one memoized dict_getitem_manager (guards.py:1724-1725, :1770-1779) doing one PyDict_GetItem per evaluation (guards.cpp:5757-5784), and both addCleanups run after the assertion.
  • No existing test regresses. The five other report-line assertions (:2077, :2096, :2136, :2206, :2716) all fail on a genuine dtype mismatch or a genuinely deleted global, so none can reach the new branch.
  • No lint issue. :2683 is 123 chars; E501 is ignored repo-wide (.flake8:10, pyproject.toml:484) and B950 is in .flake8:25, so no # noqa: B950 is needed. Both changed files are ASCII-only.

Not verified empirically: torch is not built in this checkout, so python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently could not be run here. Everything above is source reading plus the sibling-test corroboration noted for the evaluation count.

· branch `gh/bobrenjc93/1204/head`

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

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

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; that catch is unsound below #197049 and
the lines it saved were wrong (FAQ below), so it is gone from here, and the
place a raising tree is read as no answer and reported as one line is #196826,
above the TorchFunction restore #197049 adds.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below. One of those tests,
`test_module_dispatch_no_match_falls_through_to_the_first_result`, was named
and commented for the fall-through its zero-opt-out row now proves gone, so
it is renamed `test_module_dispatch_no_match_raises_unless_a_result_opted_out`
and its comment says what the rows show: a call neither result guards raises
and is handed to no result, and with `[0]` opted out its graph runs. Three
sibling dispatch tests named the same fall-through for the stage before or
after the one they pin --
`test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`,
`test_module_dispatch_serves_an_opted_out_result_from_any_position` and
`test_module_dispatch_rechecks_before_honouring_an_opt_out` -- and their
comments now name the stages the dispatch has: the opt-out last resort, then
this report. Their assertions are unchanged.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches, and counts it apart
from the matched call's: the list is asserted `[results[0]]` and cleared after
the matched call, and asserted `[results[0]]` again after the no-match call,
so each bind is attributed to the call that made it -- a combined
`[results[0], results[0]]` would also accept a dispatch that bound the matched
call nowhere and the no-match call twice. The fall-through fails the second
assertion with `The length of the sequences mismatch: 3 != 1`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list AHEAD of it mid-call, and
asserts the report counts one input and never ran the spliced result's
`check_verbose`, which is wrapped; the splice is `[:] = [later, first]`, so
the re-check pass running the patched `check()` a second time leaves the list
as it is. Counting alone would not pin which result an entry describes: a
report that re-read the list and zipped it against `bound` would describe the
spliced result against `[0]`'s binding under a `Tried 1` header, and the two
results differ only in a closure scale, so their dtype-mismatch lines read
alike. The second call, over the spliced list, reports `Tried 2` and runs the
spliced describer once, so the watch is on the object the report reads.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because below #197049 the catch continues on a thread the
> throw left broken, and the lines it saves are wrong.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. So the catch belongs above the restore, in #196826, and the test that
> pinned it here, `test_no_match_report_describes_the_other_entries_when_one_raises`,
> goes with it.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses. What the reader is told in the
> meantime, measured at this tree against the parent's: with a
> `CountedKey(misses=2)` on the global `[1]`'s tree reads and a `mode=1` call,
> this tree raises `[0] L['mode'] == 0` over a blank `[1]` (`compares= 3`),
> and the parent raised `[0]`'s `L['mode'] == 0` alone (`compares= 2`) -- it
> never evaluated `[1]` a third time and said nothing of it, and with the probe
> on a global `[0]`'s tree reads it served the graph (above); so no `result=1`
> repr was ever printed for this answer. With #197134's fixture -- a
> `SetIterModule` iterating a set, `SEQUENCE_LENGTH` dropped by the filter,
> called with a shorter set -- this tree prints `  [0] ` blank, and the parent
> printed `GuardDebugInfo(result=0, verbose_code_parts=[], num_guards_executed=6,
> user_stack=None)`: no guard named either, but a `result=0` the blank entry
> here does not carry. That one entry is what this commit says less about than
> the fall-through did, for the three commits until #197134, which lands with
> it. Neither blank entry loses a hint: the hint rides on a part that reads
> `KeyError on G[...]`, matched whole by `_names_a_missing_global`, so an
> answer with no parts named no missing global -- an accept has no failure to
> hint, and the short-set failure is not about a global -- and the absent hint
> is the accurate answer there, not a second loss.

> **FAQ: a report whose entries all failed on the same missing global repeats
> the hint on every one of them. Why not one hint per report here?** Because
> where the hint sits is #197149's, the next commit, which gives the report one
> `For [i, j]:` line per distinct sentence naming the entries that share it,
> and pins the count at one in
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
> `test_no_match_message_hints_only_the_entry_that_named_a_missing_global`.
> Here each entry carries its own hint, appended with ` -- ` as the
> fall-through appended it to `[0]`'s message, so the five tests below that
> assert the hint's text keep passing across the split. Measured at this tree,
> the report `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
> produces on its first load is four lines, the two entries 203 characters each
> and identical, with `a guarded global is missing` twice; that test asserts
> the text with `assertIn`, so it sees neither count, and pinning the
> repetition here only to remove it one commit up would assert something no
> user is meant to rely on. The class docstring describes what this commit
> does -- one line per result, carrying the hint when that result's guards
> failed on a missing global -- and #197149 rewrites it for the `For` line.

> **FAQ: `test_no_match_message_keeps_the_advice_for_every_entry` asserts the
> hint with `assertIn` over the whole message rather than on the `[1]` line.
> Why not anchor it here?** Because the hint's line is #197149's, the next
> commit, which replaces that very assertion with `For [1]: a guarded global is
> missing` and `message.count("a guarded global is missing") == 1` -- the
> anchoring, at the placement the report keeps. Here the hint is appended to
> `[1]`'s own line, and an assertion pinning it there would pin a placement the
> next commit removes and be rewritten one commit up. The two substrings the
> test does assert are not one check twice: `a guarded global is missing`
> opens all three scopes' sentences, while `the module the compiled function
> was traced in` is the CAPTURED wording alone -- SUPPLIED reads `the live
> scope this artifact was loaded against` and RECONSTRUCTED `the scope rebuilt
> from the artifact` -- so the second pins that an in-process capture's result
> is hinted for the scope it resolved against.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature
python test/dynamo/test_aot_compile.py -k test_module_dispatch_no_match_raises_unless_a_result_opted_out
python test/dynamo/test_aot_compile.py
```

The whole file runs 208 tests, `OK (skipped=6)`; the parent's file
defines three fewer. Every `-k` above fails with the parent's `aot_compile.py`
under this test file (5/5): the three that assert on report text (`No AOT
compiled graph matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled
input(s)`) find the fall-through's `GuardManager check failed` message instead,
the binding test sees three binds for the no-match call against the one it
expects, `The length of the sequences mismatch: 3 != 1`, and the renamed
test's zero-opt-out row finds `GuardManager check failed` where it expects
`No AOT compiled graph matched` (its two opt-out rows pass on both, as they
should: an opted-out `[0]` is served on the parent and here alike).

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

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report; re-reading it zipped
against `bound`, with the header off `results`, passes the header and entry
counts and fails it with `Expected 'check_verbose' to not have been called.
Called 1 times.` Both mutations were run at this tree.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 93bb35b
Pull-Request: #196823
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…call the dispatch refused

This commit and `[aot_compile] Raise a report naming every input when no
compiled graph matches` (#196823, two commits below) were one commit, split for
review budget: that commit raises the report, and this one owns what an
entry's line says when `check_verbose` answers that the tree ACCEPTS the call.

An entry's line quotes the guards `check_verbose` named for that input, and
one of its answers names none while meaning the opposite of a failure: a tree
that accepts the call. Both dispatch passes ran that tree and rejected the
call, and the report's `check_verbose` accepts it. Two things make a tree do
that. A guard in it does not answer consistently between evaluations; or every
guard answers consistently and the state it guards moved between the second
pass and the report: guards read live state on each evaluation (a global's
dict is re-descended, a tensor's dtype and shape re-read) and `__call__` holds
no lock across the dispatch, so a concurrent rebind of a guarded global, or an
in-place mutation of a guarded tensor, in that window gets the same accept.
Below this commit such an entry prints nothing after `[i]`, since an accept
carries no verbose parts, and the call is refused all the same: the report is
raised whatever its entries say. Quoting the guards the tree just passed as a
reason the call failed would name the wrong thing, and naming only the first
cause would send a reader whose guarded value raced off to hunt for a
nondeterministic guard, so `GuardDebugInfo.result` decides and the entry now
reads `<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>`, and the loop moves on so that line is all the entry
contributes. That is not a match to serve: an accept that arrives only on the
third evaluation is not a certified match. The class docstring's description
of the report now lists this line kind beside the guard-quoting line and the
`For [i, j]:` hint.

This changes what the entry says and nothing about which calls are served.
Refusing this call is #196823's: before it, the fall-through's
`AOTCompiledFunction.__call__` gave `[0]` alone, by its position, a third
evaluation and served the graph when that one accepted (`SERVED
equal_to_x*3= True compares= 3`), and from #196823 on the report's
`check_verbose` is that third evaluation and the call raises (`RAISED
compares= 3`). One test per cause pins the entry, and both assert its full
text through one module constant, `_ACCEPTED_IN_THE_REPORT`.
`test_no_match_message_when_a_guard_answers_inconsistently` is the first
cause: it pins the raise, the three evaluations, the entry's text and the
report's entry count together. The evaluation count says the report's
`check_verbose` is the third evaluation of that tree and nothing evaluates it
a fourth time to serve it, and the entry count, two `  [` lines for two
results, says the explanation is the whole of `[1]`'s entry.
`test_no_match_message_when_guarded_state_changes_before_the_report` is the
second: `AOT_BRANCH_SCALE` is rebound to a wrong value before the call, so
`[1]`'s tree, every guard deterministic, refuses it in both passes
(`check.call_count == 2`), and a wrapper around the report's `check_verbose`
rebinds the right value before calling through, placing the writer in the
window a concurrent one could land in; the call raises with the same entry.
Both tests build their model through `_aot_compile_mode_branches()`, the
helper their siblings on this path use, whose first line,
`_hide_leaked_dynamo_globals()`, strips the synthetic globals a capture mints
into this test module's dict for the test's duration. `_install_global_probe`
now returns the `CountedKey` it installed along with the saved value so the
first test can read `probe.compares`; its other caller unpacks the pair.

Order to review: the `if reason.result:` branch in
`AOTCompiledModel._no_match_report` and the class docstring's report
paragraph; then `_install_global_probe` and the two tests.

> **FAQ: The dispatch comment above `_no_match_report` names a `check()` exit
> that refuses without running the tree -- a tag-safe root's dict-tag fast path
> in `GuardManager::check_nopybind`. Why does the entry not name it as a
> cause?** Because it cannot be the cause in a default build.
> `find_tag_safe_roots()` runs only when `config.use_recursive_dict_tags_for_guards`
> (default `False`) and its justknob are both on (guards.py, `GuardBuilder`
> setup), so no node is ever marked a tag-safe root and the
> `check_dict_pointer_tags` branch is unreachable; an entry naming it would
> hand a reader debugging on defaults a hypothesis their build cannot take.
> With the config on the case is still narrow: a root's fast-path refusal
> disarms it (`_disable_dict_tag_matching = true`), so the second dispatch
> pass runs the tree that root skipped, and reaching this entry from the fast
> path needs a second, still-armed root the first pass never got to refusing
> in the second. An earlier draft of this commit named the fast path too; that
> clause was dropped rather than made conditional on the config so that every
> cause the entry names is reachable in every build. The two it does name need
> no config flag. The fast path stays documented where it is acted on, in the
> dispatch comment.

> **FAQ: The second test plays the concurrent writer from inside the report's
> own `check_verbose` rather than from a second thread. Why?** The window is
> the few microseconds between the second pass's last `check()` and the
> report's `check_verbose`; a thread that has to land a rebind in it would make
> the test flaky or need a synchronisation hook in the dispatch, which is not
> worth adding for a message test. The wrapper puts the rebind at exactly the
> point such a writer could reach and leaves the tree alone: every evaluation
> is the real tree against the real module dict, and the wrapped `check()`
> count says both passes refused the wrong value before anything changed.

> **FAQ: `AOTCompiledFunction.__call__` has the same shape -- `guard_check()`
> is one `check()`, and when it rejects and the following `check_verbose`
> accepts, the message interpolates the whole `GuardDebugInfo`, whose
> `to_string` renders `result=1` and `verbose_code_parts=[]` under
> `GuardManager check failed, reason:`. Why is that path left as it is?**
> It is the same defect, and the function path reaches it after one
> evaluation rather than two, so a single inconsistent answer is enough. It is
> out of this commit's scope, which is what the MODULE report's entry says
> (the piece split from #196823); the function path's message is a separate,
> pre-existing string with its own missing-global plumbing, and it is left for
> a follow-up commit that can pin it with its own test rather than folded in
> here.

> **FAQ: `test_no_match_message_when_a_guard_answers_inconsistently` asserts
> exactly 3 evaluations. Isn't that count a property of the guard tree's shape
> rather than of the dispatch?** The count is the pin: it says the report's
> `check_verbose` is the third evaluation of that tree and nothing evaluates it
> a fourth time to serve it, which is the behaviour the entry above describes.
> It does rest on the tree's shape -- one `DictGetItemGuardAccessor` rooted at
> the global, so one lookup per evaluation -- and on the dict-tag fast path not
> firing, which it cannot here: `use_recursive_dict_tags_for_guards` is off
> (the default), and even on, the probe's pop/insert bumped this module dict's
> version past the one the last accepting evaluation recorded (`_dict_tag` is
> stored only on an accept). A second accessor rooted at the same global would
> change the count and the `misses=2` premise together, and the test's comment
> names both dependencies, so a reader who changes the tree knows what to
> re-derive; loosening the assertion to `>= 3` would stop pinning that the
> report evaluates it once.

> **FAQ: The closing advice lands directly under the "rejected this call twice
> and then accepted it here" entry, where it reads as a diagnosis of it. Why
> leave it there?** The line is deliberately the report's footer, not per-entry
> commentary, and that is why #196823 emits it after the loop rather than
> inside it. Adding a `ModelInput` is a real mitigation for that entry too --
> an input captured for this call gets a tree that matches it on the first
> evaluation, so the inconsistent entry stops being consulted. Moving the
> advice above the entries, or suppressing it when any entry took that branch,
> would make the only actionable line in the report depend on which branch some
> unrelated entry hit, the same masking #196823's message argues against for
> the missing-global hint. The entry's own text already says what happened in
> its own words, so the reader is not being told the footer explains it.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_guarded_state_changes_before_the_report
python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_old_contents_with_a_new_verdict
python test/dynamo/test_aot_compile.py
```

The whole file runs 211 tests, `OK (skipped=6)`; the parent runs two
fewer. With the parent's `aot_compile.py` under this test file both new tests
fail on the entry's text, `'  [1] <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>' not found in "... [1] \nAdd a
ModelInput ..."`, the first after its evaluation-count assertion passed and
the second after its `check()`-count assertion passed, so on the parent too
the call is refused and the entry is blank. The assertion is the entry's whole
text: cutting either clause, or the clause after `it here`, fails it the same
way. Deleting the `continue` after the accept branch (the mutant that lets the
accept's empty verbose parts add a blank `  [1] ` line under the explanation)
passes the text assertion and fails the entry-count pin, `Expected 2 but got
3`. With the `aot_compile.py` below #196823 the first test fails earlier, on
the evaluation count, `Expected 3 but got 2`, since the fall-through's third
evaluation is of `[0]`, which fails on `L['mode']` before it reads the global.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: f3994b4
Pull-Request: #197150
@bobrenjc93 bobrenjc93 changed the title [aot_compile] Say when a no-match report entry's guards accepted the call the dispatch refused [no-ci] [aot_compile] Say when a no-match report entry's guards accepted the call the dispatch refused Sep 16, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Reviewing PR #197150

  • Load repo review guidelines (/pr-review skill + CLAUDE.md)
  • Read the diff vs origin/gh/bobrenjc93/1204/base
  • Verify the new report branch and its claims against source
  • Re-check prior rounds' findings (message tail / description sync)
  • Post review

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

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

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

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; measured without #197049's TorchFunction
restore -- now the bottom of this stack -- that catch continued on a thread the
throw had left broken and the lines it saved were wrong (FAQ below), so it is
gone from here, and the place a raising tree is read as no answer and reported
as one line is #196826, above, with the test that pins it.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below. One of those tests,
`test_module_dispatch_no_match_falls_through_to_the_first_result`, was named
and commented for the fall-through its zero-opt-out row now proves gone, so
it is renamed `test_module_dispatch_no_match_raises_unless_a_result_opted_out`
and its comment says what the rows show: a call neither result guards raises
and is handed to no result, and with `[0]` opted out its graph runs. Three
sibling dispatch tests named the same fall-through for the stage before or
after the one they pin --
`test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`,
`test_module_dispatch_serves_an_opted_out_result_from_any_position` and
`test_module_dispatch_rechecks_before_honouring_an_opt_out` -- and their
comments now name the stages the dispatch has: the opt-out last resort, then
this report. Their assertions are unchanged. A fourth,
`test_module_dispatch_serves_a_call_the_guard_tree_accepts`, said the
fall-through "re-checked compiled_results[0] and raised [0]'s L['mode'] == 0";
nothing is re-checked alone any more, so its comment now says what a call the
re-check did not rescue meets: this report, with `[0]`'s guard one line of it.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches, and counts it apart
from the matched call's: the list is asserted `[results[0]]` and cleared after
the matched call, and asserted `[results[0]]` again after the no-match call,
so each bind is attributed to the call that made it -- a combined
`[results[0], results[0]]` would also accept a dispatch that bound the matched
call nowhere and the no-match call twice. The fall-through fails the second
assertion with `The length of the sequences mismatch: 3 != 1`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list AHEAD of it mid-call, wraps
both results' `check_verbose` under one `Mock` so their call order is
recorded, and asserts the report counts one input and ran the first result's
describer alone; the splice is `[:] = [later, first]`, so the re-check pass
running the patched `check()` a second time leaves the list as it is.
Counting alone would not pin which result an entry describes: a report that
re-read the list and zipped it against `bound` would describe the spliced
result against `[0]`'s binding under a `Tried 1` header, and the two results
differ only in a closure scale, so their dtype-mismatch lines read alike. The
second call, over the spliced list, reports `Tried 2` with entries `[0]` and
`[1]` -- two, not one -- and the recorded order is `first, later, first`: the
spliced result's tree is described first, as the list now orders it, so a
report over `results[:1]` or `reversed(results)` fails here rather than only
in a test elsewhere.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because without #197049's restore the catch continues on
> a thread the throw left broken, and the lines it saves are wrong; #197049 is
> now the bottom of this stack, and the catch is #196826's with its test.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. Above that restore the catch is sound, and it is one change with the
> test that pinned it here,
> `test_no_match_report_describes_the_other_entries_when_one_raises`; both are
> #196826's, split out of this commit for review budget.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses. What the reader is told in the
> meantime, measured at this tree against the parent's: with a
> `CountedKey(misses=2)` on the global `[1]`'s tree reads and a `mode=1` call,
> this tree raises `[0] L['mode'] == 0` over a blank `[1]` (`compares= 3`),
> and the parent raised `[0]`'s `L['mode'] == 0` alone (`compares= 2`) -- it
> never evaluated `[1]` a third time and said nothing of it, and with the probe
> on a global `[0]`'s tree reads it served the graph (above); so no `result=1`
> repr was ever printed for this answer. With #197134's fixture -- a
> `SetIterModule` iterating a set, `SEQUENCE_LENGTH` dropped by the filter,
> called with a shorter set -- this tree prints `  [0] ` blank, and the parent
> printed `GuardDebugInfo(result=0, verbose_code_parts=[], num_guards_executed=6,
> user_stack=None)`: no guard named either, but a `result=0` the blank entry
> here does not carry. That one entry is what this commit says less about than
> the fall-through did, for the three commits until #197134, which lands with
> it. Neither blank entry loses a hint: the hint rides on a part that reads
> `KeyError on G[...]`, matched whole by `_names_a_missing_global`, so an
> answer with no parts named no missing global -- an accept has no failure to
> hint, and the short-set failure is not about a global -- and the absent hint
> is the accurate answer there, not a second loss.

> **FAQ: a report whose entries all failed on the same missing global repeats
> the hint on every one of them. Why not one hint per report here?** Because
> where the hint sits is #197149's, the next commit, which gives the report one
> `For [i, j]:` line per distinct sentence naming the entries that share it,
> and pins the count at one in
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
> `test_no_match_message_hints_only_the_entry_that_named_a_missing_global`.
> Here each entry carries its own hint, appended with ` -- ` as the
> fall-through appended it to `[0]`'s message, so the five tests below that
> assert the hint's text keep passing across the split. Measured at this tree,
> the report `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
> produces on its first load is four lines, the two entries 203 characters each
> and identical, with `a guarded global is missing` twice; that test asserts
> the text with `assertIn`, as do the other tests built on
> `_two_input_global_guard_artifact`, so none sees the count, and pinning the
> repetition here only to remove it one commit up would assert something no
> user is meant to rely on. The class docstring describes what this commit
> does -- one line per result, carrying the hint when that result's guards
> failed on a missing global -- and #197149 rewrites it for the `For` line.

> **FAQ: `test_no_match_message_keeps_the_advice_for_every_entry` asserts the
> hint with `assertIn` over the whole message. Why not assert it is a suffix
> of the `[1]` line?** Because the hint's line is #197149's, the next commit,
> which replaces that very assertion with `For [1]: a guarded global is
> missing` and `message.count("a guarded global is missing") == 1` -- the
> anchoring, at the placement the report keeps. Here the hint is appended to
> `[1]`'s own line, and a suffix assertion would pin a placement the next
> commit removes and be rewritten one commit up. What holds at both placements
> is asserted here: the `[0]` line (`lines[1]`) does not carry the hint, and
> neither does the advice, which is the last line. Measured at this tree, a
> hint hoisted onto the advice, a hint appended to every entry with the
> `_names_a_missing_global` gate dropped, and a hint attached to the previous
> entry's line each fail those assertions, and #197149 cherry-picks clean on
> top of them with its renamed test green. The two substrings the test also
> asserts are not one check twice: `a guarded global is missing` opens all
> three scopes' sentences, while `the module the compiled function was traced
> in` is the CAPTURED wording alone -- SUPPLIED reads `the live scope this
> artifact was loaded against` and RECONSTRUCTED `the scope rebuilt from the
> artifact` -- so the second pins that an in-process capture's result is
> hinted for the scope it resolved against.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature
python test/dynamo/test_aot_compile.py -k test_module_dispatch_no_match_raises_unless_a_result_opted_out
python test/dynamo/test_aot_compile.py
```

The whole file runs 210 tests, `OK (skipped=6)`; the parent's file
defines three fewer. Every `-k` above fails with the parent's `aot_compile.py`
under this test file (5/5): the three that assert on report text (`No AOT
compiled graph matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled
input(s)`) find the fall-through's `GuardManager check failed` message instead,
the binding test sees three binds for the no-match call against the one it
expects, `The length of the sequences mismatch: 3 != 1`, and the renamed
test's zero-opt-out row finds `GuardManager check failed` where it expects
`No AOT compiled graph matched` (its two opt-out rows pass on both, as they
should: an opted-out `[0]` is served on the parent and here alike).

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

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report; re-reading it zipped
against `bound`, with the header off `results`, passes the header and entry
counts and fails it on the describer order. Describing `results[:1]` fails it
on the second call's entries, `'Add a ' != '  [1] '`, and `reversed(results)`
on the order, `'first' != 'later'`. Hoisting the hint onto the advice,
dropping the `_names_a_missing_global` gate, and attaching the hint to the
previous entry's line each fail
`test_no_match_message_keeps_the_advice_for_every_entry` with `'a guarded
global is missing' unexpectedly found in` the advice or the `[0]` line. All
were run at this tree.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 31dd3ef
Pull-Request: #196823
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…call the dispatch refused

This commit and `[aot_compile] Raise a report naming every input when no
compiled graph matches` (#196823, two commits below) were one commit, split for
review budget: that commit raises the report, and this one owns what an
entry's line says when `check_verbose` answers that the tree ACCEPTS the call.
It was then split once more for the same budget: this commit names one cause
of that accept, and `[aot_compile] Name guarded state that changed as a cause
of the no-match report's accept line` (#<sibling>, directly above) adds the
second.

An entry's line quotes the guards `check_verbose` named for that input, and
one of its answers names none while meaning the opposite of a failure: a tree
that accepts the call. Both dispatch passes ran that tree and rejected the
call, and the report's `check_verbose` accepts it, so a guard in that tree
does not answer consistently between evaluations. Below this commit such an
entry prints nothing after `[i]`, since an accept carries no verbose parts,
and the call is refused all the same: the report is raised whatever its
entries say. Quoting the guards the tree just passed as a reason the call
failed would name the wrong thing, so `GuardDebugInfo.result` decides and the
entry now reads `<guards rejected this call twice and then accepted it here: a
guard that does not answer consistently>`, and the loop moves on so that line
is all the entry contributes. That is not a match to serve: an accept that
arrives only on the third evaluation is not a certified match. The class
docstring's description of the report now lists this line kind beside the
guard-quoting line and the `For [i, j]:` hint; it quotes the entry up to
`accepted it here: ...` and describes the condition rather than a cause, so it
holds as the sibling above widens the tail. A tree whose every guard answers
consistently can also accept only at the report, when the state it guards
moved between the second pass and the report; that cause is #<sibling>'s, and
until it lands the entry names the one cause this commit pins.

This changes what the entry says and nothing about which calls are served.
Refusing this call is #196823's: before it, the fall-through's
`AOTCompiledFunction.__call__` gave `[0]` alone, by its position, a third
evaluation and served the graph when that one accepted (`SERVED
equal_to_x*3= True compares= 3`), and from #196823 on the report's
`check_verbose` is that third evaluation and the call raises (`RAISED
compares= 3`). `test_no_match_message_when_a_guard_answers_inconsistently`
pins the raise, the three evaluations, the entry's full text and the report's
entry count together: the evaluation count says the report's `check_verbose`
is the third evaluation of that tree and nothing evaluates it a fourth time to
serve it, and the entry count, two `  [` lines for two results, says the
explanation is the whole of `[1]`'s entry. The test builds its model
through `_aot_compile_mode_branches()`, the helper its siblings on this path
use, whose first line, `_hide_leaked_dynamo_globals()`, strips the synthetic
globals a capture mints into this test module's dict for the test's duration.
`_install_global_probe` now returns the `CountedKey` it installed along with
the saved value so the test can read `probe.compares`; its other caller
unpacks the pair.

Order to review: the `if reason.result:` branch in
`AOTCompiledModel._no_match_report` and the class docstring's report
paragraph; then `_install_global_probe` and the test.

> **FAQ: The dispatch comment above `_no_match_report` names a `check()` exit
> that refuses without running the tree -- a tag-safe root's dict-tag fast path
> in `GuardManager::check_nopybind`. Why does the entry not name it as a
> cause?** Because it cannot be the cause in a default build.
> `find_tag_safe_roots()` runs only when `config.use_recursive_dict_tags_for_guards`
> (default `False`) and its justknob are both on (guards.py, `GuardBuilder`
> setup), so no node is ever marked a tag-safe root and the
> `check_dict_pointer_tags` branch is unreachable; an entry naming it would
> hand a reader debugging on defaults a hypothesis their build cannot take.
> With the config on the case is still narrow: a root's fast-path refusal
> disarms it (`_disable_dict_tag_matching = true`), so the second dispatch
> pass runs the tree that root skipped, and reaching this entry from the fast
> path needs a second, still-armed root the first pass never got to refusing
> in the second. An earlier draft of this commit named the fast path too; that
> clause was dropped rather than made conditional on the config so that every
> cause the entry names is reachable in every build. The cause it does name
> needs no config flag, and neither does the one #<sibling> adds. The fast path
> stays documented where it is acted on, in the dispatch comment.

> **FAQ: `AOTCompiledFunction.__call__` has the same shape -- `guard_check()`
> is one `check()`, and when it rejects and the following `check_verbose`
> accepts, the message interpolates the whole `GuardDebugInfo`, whose
> `to_string` renders `result=1` and `verbose_code_parts=[]` under
> `GuardManager check failed, reason:`. Why is that path left as it is?**
> It is the same defect, and the function path reaches it after one
> evaluation rather than two, so a single inconsistent answer is enough. It is
> out of this commit's scope, which is what the MODULE report's entry says
> (the piece split from #196823); the function path's message is a separate,
> pre-existing string with its own missing-global plumbing, and it is left for
> a follow-up commit that can pin it with its own test rather than folded in
> here.

> **FAQ: `test_no_match_message_when_a_guard_answers_inconsistently` asserts
> exactly 3 evaluations. Isn't that count a property of the guard tree's shape
> rather than of the dispatch?** The count is the pin: it says the report's
> `check_verbose` is the third evaluation of that tree and nothing evaluates it
> a fourth time to serve it, which is the behaviour the entry above describes.
> It does rest on the tree's shape -- one `DictGetItemGuardAccessor` rooted at
> the global, so one lookup per evaluation -- and on the dict-tag fast path not
> firing, which it cannot here: `use_recursive_dict_tags_for_guards` is off
> (the default), and even on, the probe's pop/insert bumped this module dict's
> version past the one the last accepting evaluation recorded (`_dict_tag` is
> stored only on an accept). A second accessor rooted at the same global would
> change the count and the `misses=2` premise together, and the test's comment
> names both dependencies, so a reader who changes the tree knows what to
> re-derive; loosening the assertion to `>= 3` would stop pinning that the
> report evaluates it once.

> **FAQ: The closing advice lands directly under the "rejected this call twice
> and then accepted it here" entry, where it reads as a diagnosis of it. Why
> leave it there?** The line is deliberately the report's footer, not per-entry
> commentary, and that is why #196823 emits it after the loop rather than
> inside it. Adding a `ModelInput` is a real mitigation for that entry too --
> an input captured for this call gets a tree that matches it on the first
> evaluation, so the inconsistent entry stops being consulted. Moving the
> advice above the entries, or suppressing it when any entry took that branch,
> would make the only actionable line in the report depend on which branch some
> unrelated entry hit, the same masking #196823's message argues against for
> the missing-global hint. The entry's own text already says what happened in
> its own words, so the reader is not being told the footer explains it.

Test Plan:

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

The whole file runs 212 tests, `OK (skipped=6)`; the parent runs one
fewer. With the parent's `aot_compile.py` under this test file the new test
fails on the entry's text, `'  [1] <guards rejected this call twice and then
accepted it here: a guard that does not answer consistently>' not found in
"... [1] \nAdd a ModelInput ..."`, after its evaluation-count assertion
passed, so on the parent too the call is refused and the entry is blank. The
assertion is the entry's whole text, so a change to the tail fails it the
same way. Deleting the `continue` after the accept branch (the mutant that
lets the accept's empty verbose parts add a blank `  [1] ` line under the
explanation) passes the text assertion and fails the entry-count pin,
`Expected 2 but got 3`. With the `aot_compile.py` below #196823 the test
fails earlier, on the evaluation count, `Expected 3 but got 2`, since the
fall-through's third evaluation is of `[0]`, which fails on `L['mode']`
before it reads the global.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 412ec4f
Pull-Request: #197150
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…tch report's accept line

This commit and `[aot_compile] Say when a no-match report entry's guards
accepted the call the dispatch refused` (#197150, directly below) were one
commit, split for review budget: that commit gives a no-match report entry
whose tree ACCEPTS the call on the report's evaluation an explanation in place
of any guards, naming one cause; this one adds the second cause to that text.

Below this commit the entry reads `<guards rejected this call twice and then
accepted it here: a guard that does not answer consistently>`. That is one
way a tree the dispatch ran twice and refused twice can accept on the third
evaluation. The other needs no inconsistent guard: every guard answers
consistently and the state it guards moved between the second dispatch pass
and the report. Guards read live state on each evaluation (a global's dict is
re-descended, a tensor's dtype and shape re-read), and `__call__` holds no
lock across the dispatch, so a concurrent rebind of a guarded global, or an
in-place mutation of a guarded tensor, landing in the window between the
second pass's last `check()` and the report's `check_verbose` gets the same
accept; the dispatch already contemplates concurrent calls (the
`_binding_verdict` comment: a hint, not a lock). Naming only the first cause
sends a reader whose guarded value raced off to hunt for a nondeterministic
guard, so the entry now reads `<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>`. The branch, the `continue` after
it, and the class docstring are #197150's and unchanged: the docstring quotes
the entry up to `accepted it here: ...` and describes the condition, so it
holds for both tails.

This changes what the entry says and nothing about which calls are served.
`test_no_match_message_when_guarded_state_changes_before_the_report` pins the
second cause with a deterministic tree: `AOT_BRANCH_SCALE` is rebound to a
wrong value before the call, so `[1]`'s tree refuses it in both passes
(`check.call_count == 2` through `patch.object(manager, "check", wraps=...)`),
and a wrapper around the report's `check_verbose` rebinds the right value
before calling through, placing the writer in the window a concurrent one
could land in; the call raises with the entry, two `  [` lines for two
results, and `[0]`'s real mismatch. The entry's full text now has two
readers, so it moves out of
`test_no_match_message_when_a_guard_answers_inconsistently`'s inline literal
into one module constant, `_ACCEPTED_IN_THE_REPORT`, beside
`AOT_BRANCH_SCALE`, and both tests assert it; that test is otherwise
unchanged. Both build their model through `_aot_compile_mode_branches()`,
the helper their siblings on this path use.

Order to review: the string in `AOTCompiledModel._no_match_report`; then
`_ACCEPTED_IN_THE_REPORT` and the new test; then the first test's swap to the
constant.

> **FAQ: The new test plays the concurrent writer from inside the report's
> own `check_verbose` rather than from a second thread. Why?** The window is
> the few microseconds between the second pass's last `check()` and the
> report's `check_verbose`; a thread that has to land a rebind in it would make
> the test flaky or need a synchronisation hook in the dispatch, which is not
> worth adding for a message test. The wrapper puts the rebind at exactly the
> point such a writer could reach and leaves the tree alone: every evaluation
> is the real tree against the real module dict, and the wrapped `check()`
> count says both passes refused the wrong value before anything changed.

> **FAQ: Why two causes and not a third, the tag-safe dict-tag fast path the
> dispatch comment names?** #197150's FAQ covers it: `find_tag_safe_roots()`
> runs only with `config.use_recursive_dict_tags_for_guards` (default `False`)
> and its justknob on, so that exit is unreachable on defaults, and an entry
> naming it would hand a reader a hypothesis their build cannot take. Both
> causes the entry names now are reachable in every build without a flag.

Test Plan:

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

The whole file runs 213 tests, `OK (skipped=6)`; the parent runs one fewer.
With the parent's `aot_compile.py` under this test file both tests fail on
the entry's text, `'  [1] <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>' not found in "... [1] <guards rejected
this call twice and then accepted it here: a guard that does not answer
consistently>\nAdd a ModelInput ..."`, the new test after its `check()`-count
assertion passed: on the parent too both passes refuse, the report accepts,
the call is refused, and the entry names one cause. The assertion is the
entry's whole text, so the parent's tail is the mutant that cuts the new
clause.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 7617536
Pull-Request: #197300
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
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` is one way in: Dynamo installs a `DICT_NOT_CONTAINS` guard,
whose C++ leaf runs `PyDict_Contains`, a colliding key whose `__eq__` raises
leaves the exception set, and the guard returns normally anyway because
`guards.cpp:2475` collapses its result through C `&&`, which yields 0 or 1
and never the -1 the following check looks for. CPython then reports the
still-set exception as `SystemError` at the boundary of the guard tree. It is
not the only way in: the `SET_CONTAINS` leaf has the identical shape at
`guards.cpp:2505-2506` (`(PySet_Check(value) || PyFrozenSet_Check(value)) &&
PySet_Contains(...)`), and a module branching on `"foo" not in s` -- a
`SET_NOT_CONTAINS` guard -- called with a set holding such a key produces the
same report. Neither `DICT_NOT_CONTAINS` nor `SET_NOT_CONTAINS` is in
`UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, so those guards 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.

Both stages of module dispatch handled a raise badly. In the report, an
exception from `check_verbose` replaced the whole report, hiding every other
input's reason behind an unrelated traceback. In the dispatch passes, it
propagated out of `__call__`, so one artifact's raise killed the call
outright. Treat a raising tree during dispatch 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 -- and record it as one line in
the report like any other non-match, so the no-match report survives a
raising tree, names the raiser, and still carries the reason from every entry
that can explain itself.

Order to review: `_unwrapped_raise` and `_raised_line` at the top of the
file; `_same_results` and the `_warned` field beside `_binding_verdict`;
`accepts()`, `warn_swallowed` -- which judges that field against the results
it is about to log for -- and the three serving paths in
`AOTCompiledModel.__call__`; the veto on the last resort and the chained
raise; then `_no_match_report`, whose new arguments are the dispatch record.
Both dispatch passes now go through the one `accepts(i, result)` closure,
which is where a raise is recorded, and the per-result bindings become a
`dict[int, ...]` it fills on first use, so the second pass and the report
reuse the scan's binding of each result; the list the parent kept for the
same purpose was filled by the scan alone. That count -- one bind per
result, in index order, the same objects -- is pinned by the assertions
#197219, the fourth of four tests-only commits above this one, adds to the
landed `test_module_dispatch_binds_per_result_when_signatures_differ`. This
commit carries the whole source change and the tests that pin what a caller
sees change, all three serving paths that log the warning, the warning's
dedup, its reset and its per-model set, both handlers that read a raise as
no answer, the two records of one raise parting, the raise line's collapse
against the warning's raw quote, the unwrap stopping at `SystemError`, the
serve after a raise being the scan's, and the report reading the opt-outs
once;
#197188, directly above, carries the tests that pin how a raise is quoted
and what the report says when a tree that raised in the scan rejects on the
second pass, with the two fixtures only those tests and the commits above
use; #197179 above it carries the report's remaining lines after a raise;
#197195 above that the warning's other paths, its text and its dedup key;
and #197219 at the top of the four the exits that record nothing and the
binding. All four are named below wherever this message leans on one of
their tests; they were split off for review budget, as the census at the
end says, and the first FAQ at the end maps each decision a review of an
earlier revision found unpinned to the test that pins it.

A tree can raise on one evaluation and answer on the next, so a raise is
remembered as two things, each read by a different line of the report.
`raised` keeps the last exception per index, which the report chains onto
and draws its fix-or-drop advice from -- not always from the same entry,
since the chain carries the first index that raised while the advice skips
an opted-out one, whose report line quotes no exception text at all, leaving
the chain the only place its raise survives. That it is the LAST -- an index
raising in both passes is quoted for the second raise -- is pinned here by
`test_no_match_report_reads_the_dispatch_record_after_a_raise`, whose [1]
raises `pass 1 unhappy` in the scan and `pass 2 unhappy` on the second pass
and is quoted for the second, `pass 1 unhappy` asserted absent from the whole
report; `raised.setdefault(i, e)` quotes the first and fails it (measured
below). Last wins because the report quotes `raised[i]` for exactly the
indices in `unanswered`, which records what the LAST evaluation did, so the
line quotes the evaluation whose outcome put the index there; the second
pass also runs more of the tree than the first need have (`check()` can
reject from the dict-tag fast path without running it), so a pass-2 raise
comes from more of the tree. #197179's
`test_no_match_message_quotes_the_last_raise_at_one_index` pins the same on
a one-input report. `unanswered` holds the indices whose LAST evaluation
reached no answer, which are the only ones with nothing else to quote. Reporting from the raise alone would be wrong, because the
re-check evaluates the tree again: an entry that raised in the scan can go on
to reject this call on a guard the report could name, and quoting its raise
instead loses that reason and re-evaluates nothing. What dispatch does NOT
yet record is which entries answered at least once; the `Add a ModelInput`
line at the end of the report stays unconditional here, exactly as at the
parent, and deciding it from the dispatch record is #197050's, above the
four tests-only commits.

That line reports the exception the `SystemError` was chained from and names
the boundary once (`[0] <guard check raised ValueError: boom from __eq__
(through the guard tree's pybind boundary)>`): 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` the report
becomes, so the line has to carry it. 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 exists to explain why the line quotes a chained
exception rather than the one the tree raised, so with nothing chained there
is nothing to explain. `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`
below asserts such a line whole for a stub's dispatch raise, and
`test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary` in
#197188 does the same for a one-raiser report and asserts the clause absent
from the whole of it. The chain it reads is `__cause__`, which is what
`_PyErr_FormatFromCause` sets when it raises that `SystemError`, 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. Reading
`__context__` would therefore quote the exception the CALLER was handling for
a `SystemError` that reached the tree some other way. Measured on a stub tree
raising a bare `SystemError` from inside an `except Boom:` block, which is
`test_no_match_message_reads_the_cause_not_the_handled_exception` in
#197188: `__context__` puts `[0] <guard check raised Boom: the caller
was handling this (through the guard tree's pybind boundary)>` in the report,
`__cause__` puts `[0] <guard check raised SystemError: stub tree is
unhappy>`, and every entry above that quotes a real pybind boundary reads the
same either way, since that call sets both. That 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. The dispatch-record test's [1] raises `RuntimeError(...) from
ValueError("x")`, and its line is asserted to read the `RuntimeError` with
no `ValueError` anywhere in the report; unwrapping unconditionally quotes
`ValueError: x (through the guard tree's pybind boundary)` and fails it
(measured below). The unwrap lives in one
`_unwrapped_raise` helper, which both this report line and the dispatch
warning below read, so the two records of one raise cannot drift.

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 fix-or-drop advice follows what the dispatch passes did, and stands on
its own entries rather than on which line text an entry ended up with. A
tree that raised in either dispatch pass has to be fixed or dropped whichever
of the two it was, and whether or not its raise also cost the caller an
opted-out graph, so that instruction is emitted whenever any tree whose
guards someone asked about raised in dispatch, naming the first of them.
`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 this entry's
line.

A rejection that follows a raise from the same tree is taken at face value
by the report, and after a C++ throw that is a weaker claim than it looks.
The throw skips the `_reset_relational_guard_state()` call the normal exits
of `RootGuardManager::check_nopybind_template` run, so a tree holding a
relational guard -- `NO_TENSOR_ALIASING`, `OBJECT_ALIASING`,
`STORAGE_OVERLAPPING`, `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`, which installs `NO_TENSOR_ALIASING` over its
three tensors, called with a strided nested tensor in `c` whose
`TENSOR_MATCH` throws out of a `TORCH_CHECK`: `check()` on the SAME call
alternates, attempts 0 and 2 throwing `RuntimeError` and attempts 1 and 3
returning False, and `check_verbose` on a rejecting attempt reads `Duplicate
tensor found where not expected!` about three distinct tensors. Unlike the
TorchFunction TLS, which #197049 below restores, that residue cannot be
cleared from Python: `RelationalGuard::reset_state` (`guards.cpp:2657`) has
no binding, since `RelationalGuard` is exposed only as a `py::class_` with no
methods. So it is documented rather than fixed -- in the veto's comment and
in the warning below, the two places this commit acts on a raise -- and the
report line that qualifies the `ModelInput` advice by it is #197050's, along
with that advice's gate.

`disable_guard_check()` keeps meaning what it means on the function path,
where `AOTCompiledFunction.__call__` short-circuits on
`_guard_check_enabled` before evaluating anything. 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 the
relational residue above. A raise from the opted-out result itself holds back
nothing, and the report decides the opt-out line before the raise so that
entry is described once, as the opt-out it is. That veto is also the only way
`_no_match_report` can run with an opted-out result present, and the report
has to say what happened to it: quoting the guards nobody asked about would
name the wrong thing, and no `ModelInput` covers it, so it is reported as
`[1] <opted out of guard checks; withheld because [0]'s guard check raised>`
and followed by the one instruction that would let it serve again -- fix or
drop the artifact that raised. The report reads `_guard_check_enabled` once,
into `enabled`, before its loop, and both the raiser it names and the
opt-out branch read that list: `check_verbose` runs user code, and a result
opted out from inside it would otherwise reach the loop's opt-out branch
after `raiser` was computed from an earlier read, interpolating `None` into
the withheld line and the footer. Exotic, but the two reads have to be the
same read, and the describer test below pins it by opting [1] out from inside
[0]'s patched `check_verbose`: [1] keeps its own guard's line (measured
below).

#197049 below restores the TorchFunction TLS a C++ throw leaves disabled,
inside `GuardManagerWrapper.check` and `check_verbose`, so by the time a
raise reaches this file the thread is as the caller left it and nothing here
has to put it back. This commit catches `Exception` at two sites --
`accepts()` in the dispatch passes and the re-check in the report -- and
reads it as no answer. A `KeyboardInterrupt` or a `SystemExit` out of a
guard check is not an answer about this call and is not dispatch's to
swallow, and reading one as "did not match" would go on dispatching under an
interrupt, or turn a Ctrl-C into a report line about a guard; neither is an
`Exception`, so neither handler sees them and both travel on as before.
Every `Exception` is read as no answer, `MemoryError` and `RecursionError`
included: a raise is no answer whatever its type, the C++ tree is not a
demonstrated source of either (its accessors `PyErr_Clear()` and answer
False), and the only way one reaches these handlers is a Python-level guard
manager on `_artifacts.guard_manager`, so the line is drawn at `Exception`
and left there. `raised` stays a `dict[int, Exception]`, and it is the
handler's type rather than the annotation that keeps it one.

Against the parent, three things change for a caller, each pinned here:

(a) A raise from one result no longer ends the call when another result's
guards match. The match is served and the raise is logged (below):
`test_aot_compile_module_serves_a_later_match_after_an_earlier_raise`.

(b) A result whose tree raised in the scan and ACCEPTED on the second pass
is served on that accept, with the same warning naming its index and
exception. The accept is the tree's own answer about this call -- the only
answer anyone got -- and vetoing it would not contain the relational residue,
because the evaluation that runs on the residue need not be in the same call
at all: measured on a one-raise stub with two inputs, [0] raises in the scan,
[1]'s real guards match, dispatch serves [1] and warns, and the NEXT call
gets [0]'s post-throw answer with nothing on record -- no raise, so no veto
and no warning. The warning therefore names both directions a stale tree can
bend a later answer ("reject a call it fits or accept one it does not"):
`test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted`.

(c) When nothing matches and some checked tree raised, the caller no longer
sees the tree's own exception. Measured on `DictBranchModule` with a
colliding key at the parent: `__call__` lets the `SystemError` out, with the
`ValueError` from `__eq__` as its `__cause__`. Now the call raises
`RuntimeError(report) from <first raise>`: a caller catching `SystemError`
(or `RuntimeError` for a `TORCH_CHECK` leaf) catches the report instead, and
the tree's exception is one hop down the chain. Every no-match test here
with a raise on record pins the `RuntimeError`;
`test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`
walks the chain to the `ValueError` a plain call surfaces, and pins the veto
with it: [1] opted out, so without the gate the raise would be read as a
plain non-match and `x * 5` served for a call whose correct answer is a
raise. That a tree which raised in the scan and rejected on the second pass
has its rejection quoted, the raise surviving in the chain alone, while the
opt-out stays withheld, is
`test_no_match_message_quotes_a_tree_that_raised_then_answered` in
#197188.

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 rather than for this dispatch -- and are worth fixing
as a follow-up: replacing the two leaves with `int result =
PyDict_Check(value) ? PyDict_Contains(value, _key.ptr()) : 0;` and the
`PySet_Contains` equivalent restores the -1 branch and turns 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.

A match found after a raise is served, and warned about. The raise says
nothing about the artifact that did answer, and refusing would not undo the
relational residue: 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: `SYMBOLIC_SHAPE_GUARD::check_nopybind` (`guards.cpp:2816-2843`)
leaves `_args_seen` partway after a throw, so 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. What a refusal would
buy is only that a raise dispatch served over cannot go unrecorded, and a
warning buys that: every path that RETURNS a graph with a raise on record --
a match in either dispatch pass, and the last resort serving an opted-out
result whose own tree raised -- logs one naming the index that raised, its
exception, the index served and what the raise left stale -- for an enabled
tree; every path that builds a report chains the first raise onto it. All
three serving paths are pinned here. The later-match test above reads
the raiser's index and exception, the served index and the fix-or-drop
advice off the first pass's warning, so a warning that named the served
index as the raiser fails it (measured below); it also counts the raiser's
evaluations, one, so the serve is pinned to the scan -- a dispatch that
withheld the scan's match once a raise was on record and served it on the
second pass would log the same warning and fails only that count (measured
below). The second pass's serve is
`test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted`: a
stub raises in the scan and accepts on the second pass, `stub.checks == 2`
says the serve was the second pass's, and the warning names `[0]'s guard
check raised RuntimeError: the scan is unhappy`, `dispatch served [0]` and
both directions a stale tree can bend a later answer; the next call, with
no raise on record, is served silently. The two dedup tests below reach the
last resort -- a one-result model whose only artifact opted out and whose
tree raises -- and read the raiser's index and type off that path's
warning, and the first of them pins the advice that path logs instead: the
warning says the graph is `reachable only through the last resort` and
carries no `Fix or drop input`, so handing an opted-out raiser the enabled
tree's advice fails it (measured below); #197195 adds to it the reading that
the served index is the raiser's own, `dispatch served [0]`, having folded
the test that repeated the rest of it. The
two-raiser test below reaches the same path with two opted-out raisers, so
one call logs two warnings, and the second names `[0]` as served rather than
the `[1]` it is about. A
call that ends in neither leaves as the exception that ended it and records
nothing. Four exits have that shape: a later result's
tree raising a `BaseException`, a later result's bind raising `TypeError`,
`_binding_key` raising over a malformed artifact -- `_binds_alike` is
outside `accepts()`' `try`, as `prepare_f_locals` is -- and the report
builder itself raising, whose `except Exception` around `check_verbose` lets
a `BaseException` through and whose `_missing_global_hint` call has no
handler (FAQ below). The first two, the ones a guard manager can produce,
are pinned in #197219
(`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`,
`test_module_dispatch_later_result_that_cannot_bind_raises_type_error`);
the other two have no test, since no guard tree is a source of either. An
opted-out tree's rejections are never acted on, so its line asks for no fix
-- the report describes the same entry as the opt-out it is -- and names the
cost it does pay instead: a raising tree never matches in the scan, so its
graph is reachable only through the last resort, which any enabled raise
withholds. Each warning is deduplicated per `(index, exception type)` on the
model, so a hot loop over a broken artifact logs once per defect rather than
once per call. Both the type it names and that dedup key are read off the
UNWRAPPED exception, not off the `SystemError` pybind hands back: otherwise a
`DICT_NOT_CONTAINS` raise -- the case above -- is logged as `SystemError:
<built-in method check of pybind11_builtins... returned a result with an
exception set>` on the one path that records it at all, and every such raise
at one index shares the key `(index, "SystemError")`, so two different
underlying defects collapse into a single warning. With the unwrap the same
raise logs `ValueError: boom from __eq__`, and a `ValueError` and a
`TypeError` at one index log twice
(`test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise`,
#197195). `torch._logging.warning_once` is the wrong tool for that on two
counts, measured when the dedup was designed: its `functools.cache` key
includes every argument, so passing the exception object defeats the dedup
outright, and the cache is process-global, so the first test to log silences
the rest -- running four of this file's warning tests three times in one
process, which is what `--repeat` does, failed 8 of 12 with `no logs of
level WARNING or higher triggered`;
`test_aot_compile_module_warns_once_per_model_not_per_process` pins both
halves: two models with the same defect each log once, and a second call on
the first logs nothing, which is the once-per-defect half over repeated
calls -- with the dedup deleted, that call logs again (measured below). Both dedup tests build their artifact through `_model_whose_tree_raises(text)`, a method beside them: one result, opted out of the re-check, whose stub tree raises `RuntimeError(text)`. The
set is keyed on a bare index, 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 pairs 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. 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.
`test_aot_compiled_model_keeps_its_warning_dedup_out_of_the_constructor`
pins both: `_warned` is absent from the dataclass's `init` field list, and
two models built from one module hold distinct sets, which
`default=((), set())` fails with `unexpectedly identical: set()` (measured
below); #197195 adds the constructor's `inspect.signature` view beside the
field walk. 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)` would silence every artifact later put
at [0]. The cost is one repeat per mutation, not per call, so a hot loop
still logs once per defect.
`test_aot_compile_module_warns_again_about_a_replaced_single_result`
pins it: 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. It is the test that tells the placements
apart: with the reset in `_binds_alike`, as the previous revision had it, or
gated on two or more results, it fails with `no logs of level WARNING or
higher triggered` on the call after the swap (measured), since a one-result
model never re-decides the binding verdict. Its multi-result twin, where a
`pop(0)` moves a raising artifact to a warned-about index, is
`test_aot_compile_module_warns_again_about_a_replaced_index` in #197195;
both replacements reuse the key `(0, "RuntimeError")`, so what separates the
two tests is the binding verdict, not the key, and the pop test passes under
either misplacement.

The two swallowing handlers are pinned by disjoint tests, because an index
whose LAST dispatch evaluation raised is never re-evaluated in the report,
and one that raised earlier and then answered takes its reason from that
re-evaluation. The dispatch handler's pins are here: make it re-raise and
the nine tests here whose trees raise in dispatch fail on the tree's own
raise escaping the call -- the pybind boundary's `SystemError` for the two
`DictBranchModule` tests, the stubs' `RuntimeError` for the later-match,
raised-then-accepted and two dedup tests, the TorchFunction test's
`TORCH_CHECK`, the two-raiser test's stub raise arriving with no entry line
to count and the dispatch-record test's with [0] checked once -- while the
inconsistent-guard test, whose stub raises
nowhere, and the describer test, whose raise happens only in the report,
still pass. The report handler's pin is
`test_no_match_report_describes_the_other_entries_when_one_raises`, whose
patched `check_verbose` raises only in the report: make that handler
re-raise and it alone fails, on `ValueError: boom` escaping the call. That
test asserts `lines[2]` starts with `  [1] ` AND does not contain `guard
check raised`, so the other entry's line is its own guard's and not the
report's raise line. Widening the dispatch handler to `BaseException`
fails nothing here and exactly one test in #197219,
`test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`, whose
stub interrupts out of [1]'s tree after [0]'s raised: read as a non-match,
the interrupt ends in a `RuntimeError` report where the test asked for the
interrupt itself. Widening the report handler fails nothing: no test sends a
`BaseException` through the re-check, so that bound is documented above and
in the class docstring rather than pinned. The breadth does have one narrow
cost -- a raise that happens after a successful match (`guards.cpp:3849`
throws only when the result is true) is swallowed too, so a matching
artifact could be skipped. The dispatch passes inline
`_live_guard_manager().check` rather than calling `result.guard_check` so
that `prepare_f_locals` stays outside the `try`: an unbindable call then
surfaces as the `TypeError` a plain module call would raise, instead of
being read as "did not match". Both that placement and the bare `raise` on
an ordinary no-match already hold at the parent, so their pins --
`test_module_dispatch_wrong_arity_raises_type_error` and
`test_aot_compile_module_no_match_does_not_suppress_a_handled_exception` --
pass there too and sit above with the other negative pins, in #197219
and #197179 respectively; every test
this commit adds or whose assertion it changes fails or errors with the
parent's `aot_compile.py` under this test file.

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. It reads `<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>`, which is true
of two rejections and of a raise followed by a rejection alike, and the
raise it does not mention is on record anyway as the report's `from` chain.
`test_no_match_message_when_a_guard_answers_inconsistently`, the
two-rejection case, has its assertion moved to the new line here, so the old
wording does not leave this file green (measured below). The
raise-then-reject case that forced the change is the dispatch-record test's
[0]: `RaisesThenRejects` raises in the scan, returns False on the second
pass and accepts in `check_verbose`; `stub.checks == 2` says it was checked
exactly twice, the line is asserted whole and "twice" absent from the
report, so the old wording reports a count that stub never took. Its raise
survives in the chain alone: `__cause__` is `the first pass is unhappy`,
that text is asserted absent from the report, and the fix-or-drop advice
names [0], so the entry whose line is the accept line is still the one the
report says to fix; an earlier revision of #197179 carried a one-input copy
of this reading, folded into this test.

Three more things the report and the warning do are pinned by
`test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`:
two raising stubs, [0] opted out and [1] enabled, and the same call made
twice. The exception the `RuntimeError` is chained from is
`next(iter(raised.values()))`, the first index that RAISED, while the
fix-or-drop advice names the first raiser whose guards someone asked about;
those are different entries when an opted-out result raised first, and that
entry's line quotes no exception text, so the chain is the only place its
raise survives -- reading `raised[raiser]` there would delete an exception
rather than report it. The first call ends in a report whose `__cause__` is
[0]'s exception while the withheld line and the advice name [1]. Then [1]
opts out too and the second call reaches the last resort, which serves the
FIRST opted-out result while `warn_swallowed` iterates `raised`, so the
served index and the raising index need not coincide and the warning reads
each from its own source rather than from one of them twice: two warnings,
one per raise, both saying `dispatch served [0]`. [1]'s message holds a
form feed and a record separator, so its report line asserted whole is the
pin of `_raised_line`'s collapse as well, and the warning about the same
raise is asserted with both separators in place: the collapse is the report
line's alone, since only the report is read back with `splitlines()`, and a
warning that collapsed its quote too fails that assertion (measured below). #197179 adds to this test the
reading that the opted-out raiser's text is absent from the report, and
#197195's `test_aot_compile_module_last_resort_warns_about_another_index`
and `test_aot_compile_module_warns_about_every_input_that_raised` pin the
same shape on the serving path, the last-resort one with a served result
that never raised. A missing global and a raiser in one report is the case
where the missing global's own hint, the fix-or-drop line and the
`ModelInput` line stand on disjoint entries, in that order (#197179).

Every stub whose LAST evaluation raises in a test that builds a report
derives from `NeverReChecked`, a base #197188 adds with two users of its
own, re-basing the two-raiser test's `Raises` on it in the same commit: its
`check_verbose` raises a message naming the re-check. The report never re-checks an entry whose last
evaluation raised, so that method is unreachable today; a regression that
reaches it then fails on "the report re-checked a tree that raised in
dispatch" rather than on an `AttributeError` dressed up as the tree's own
raise, which aliasing `check_verbose` to `check` would let pass by printing
the expected raise line. Here `Raises` defines no `check_verbose` at all, so a
report that re-checked it fails the test on an `AttributeError` line where
the raise line asserted whole is expected (measured below) -- the same
regression, caught less legibly. The dispatch-record test's `RaisesTwice`,
this commit's other stub whose last evaluation raises, inherits its
sibling's accepting `check_verbose`, so the same regression prints the
accept line for [1] where its raise line is expected (measured below). The
other stubs need neither: the
later-match, raised-then-accepted and dedup stubs sit on serving paths and
meet no report, and the describer test patches `check_verbose` on a real
tree that answered in dispatch. The measurement that the convention catches
what the alias would hide is in #197188's message. What this
commit's own tests pin about that branch of the report is the real-tree
case: with `if i in unanswered:` forced to `if False:`, the report
re-evaluates the strided-nested-tensor tree in
`test_aot_compile_module_restores_torch_function_after_a_throw`, whose
`check_verbose` answers `dispatch key set mismatch` instead of throwing
again, and [0]'s line no longer reads `<guard check raised RuntimeError: `
(measured). That convention -- a stub whose last evaluation raises
derives from `NeverReChecked`, one that answers and reaches the report
defines its own `check_verbose`, one on a serving path meets no report and
needs neither -- is stated once, in `NeverReChecked`'s docstring, rather
than re-derived at each stub.

The tests that reach a raise through the `DICT_NOT_CONTAINS` leaf depend on
the dead `result == -1` check above staying dead: restoring it turns their
raises into ordinary mismatches and they have to be rewritten, which the key
classes say. So the dispatch semantics that do not depend on how a tree
raised are each also pinned by a stub guard manager, which no fix to that
leaf touches: serving a later match over a raise and the veto with two stub
raisers, here; a raise, a rejection and an accept out of one stub in the
dispatch-record test; and the last resort's own-raiser path in the dedup
tests. #197188's `test_no_match_message_quotes_a_tree_that_raised_then_answered`
reaches the veto through the leaf; its stub twin, which an earlier revision of
#197179 carried, repeated seven of its eight assertions and was folded into
it, the entry-line count it added landing there (#197179's message says
so). The
message assertions match whole report lines and count only the `  [` entry
lines, rather than pinning the report's total line count; where a test in
#197188 or #197179 asserts how often a real key class was compared, it
is `assertGreaterEqual`, since how many times codegen has a guard tree
consult a key is not this commit's business, and the stub tests pin an exact
evaluation count where it is.

Test census: ten new tests, one changed assertion
(`test_no_match_message_when_a_guard_answers_inconsistently`, for the
re-check line's wording) and one rewritten
(`test_aot_compile_module_restores_torch_function_after_a_throw`, which
#197049 below added saying the throw propagates; it now asserts the report
the throw becomes -- one `  [` entry line for the one input, the only report
content in this file a test did not author, reading `[0] <guard check
raised RuntimeError: ` with `doesn't support strides` in it, and no
`GLOBAL_STATE changed` anywhere, which is the line [0] would carry if
`GuardManagerWrapper.check`'s restore of the TorchFunction TLS were
removed; what ATen says stays a substring pin, as on the function path). The
three other tests written with this change -- the raise line without the
boundary clause and its `__cause__` reading, and the raised-then-rejected
report -- are #197188, together with the two fixtures only they and the
commits above use, `RaisesThenHits` and `NeverReChecked`; 16 more sit above
it -- the report's remaining lines, seven, in #197179; the warning's other
paths, its text and its dedup key, six, in #197195; the exits that record
nothing and the binding, three, in #197219 -- all four split off for review
budget. Earlier revisions of those commits carried tests since folded into,
or subsumed by, tests here, in #197188 or landed before this stack, each
described in the commit that dropped it, and none took a pin with it (first
FAQ below). This commit adds the
two fixtures its own tests use, `RaisesOnCompare` and `DictBranchModule`,
which #197188, #197179, #197195, #197220 and #197257 use as well; #197179
adds the one key class only its own test uses, `HitsThenRaises`.

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_serves_a_later_match_after_an_earlier_raise
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_no_match_report_describes_the_other_entries_when_one_raises
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_again_about_a_replaced_single_result
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_serves_a_tree_that_raised_and_then_accepted
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_compiled_model_keeps_its_warning_dedup_out_of_the_constructor
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
```

The whole file runs 263 tests, `OK (skipped=6)`; the parent runs 10 fewer.
The twelve were also run against the parent's `torch/_dynamo/aot_compile.py`
under this test file, and all twelve fail or error: the six whose trees
raise in dispatch on the tree's own raise escaping the call (the pybind
boundary's `SystemError` for the two `DictBranchModule` tests,
`RuntimeError: guard tree is unhappy` for the later-match stub and the
first dedup test, `RuntimeError: the first artifact is unhappy` for the
second, `RuntimeError: the scan is unhappy` for the raised-then-accepted
stub), the describer test on `ValueError: boom` escaping, the
inconsistent-guard test on the old "rejected this call twice" wording, and
the TorchFunction and two-raiser tests on their entry-line counts
(`Scalars are not equal!`; `Expected 2 but got 0.` for the two-raiser
test), the parent's propagated raise being the whole message, and the
dispatch-record test on its check count (`Expected 2 but got 1.`: [0]'s scan
raise left the call before [1] was checked, and `assertRaises(RuntimeError)`
catches that raise as readily as the report), and the constructor test on
`AttributeError: 'AOTCompiledModel' object has no attribute '_warned'`,
the parent having no such field. Each fix below was then reverted on its
own against the whole file with the four commits above applied -- #197188's
three, #197179's seven, #197195's six and #197219's three, whose messages
list their own -- and only the named tests failed:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result
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_warns_once_per_model_not_per_process
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_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_aot_compiled_model_keeps_its_warning_dedup_out_of_the_constructor
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise
```

Reading the warning's raiser off the served index fails
`test_aot_compile_module_serves_a_later_match_after_an_earlier_raise` with
`[1]'s guard check raised RuntimeError: guard tree is unhappy` logged for a
raise from [0], and the two-raiser test with `Expected 2 but got 1.` on `len(logs.output)` (and, above, #197195's four warning tests that read a served index and #197219's interrupt test). Skipping an index
in `raised` on the second pass fails
`test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted`: the
call ends in a report chained from `RuntimeError: the scan is unhappy`
where a served graph was expected, and the dispatch-record test, whose [0]
is then checked once (`Expected 2 but got 1.`) (and, above, the raised-then-accepted test's report twin in #197188 and #197179's last-raise test). Handing an opted-out raiser the enabled
tree's advice -- forcing the `_guard_check_enabled` test in
`warn_swallowed` true -- fails
`test_aot_compile_module_warns_once_per_model_not_per_process` with
`'opted out of guard checks, but' not found in` a warning that reads `Fix
or drop input [0]` (and nothing above: the last-resort wording test #197195 once carried was folded into this one).
Appending the boundary clause to every raise line fails the two-raiser
and dispatch-record tests on [1]'s line and
`test_no_match_report_describes_the_other_entries_when_one_raises`, whose
`[0]` line is asserted whole: `<guard check raised ValueError: boom
(through the guard tree's pybind boundary)>` where `<guard check raised
ValueError: boom>` is expected (and, above, both `NeverReChecked` tests in #197188 and five report tests in #197179). Removing the veto's
`_guard_check_enabled` gate so any raise releases the last resort serves the
opted-out graph -- `x * 5` for a call whose correct answer is `x * 2` -- and
fails `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`
with `dispatch served 5.0, not a raise`, and the two-raiser test with
`RuntimeError not raised` (and, above, one test in #197188 and one in #197179). 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 the dispatch-record test on [0]'s: `'  [0]
<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>' not found in [..., '  [0] <guards rejected this call
twice and then accepted it here: ...']` (and #197150's `test_no_match_message_when_guarded_state_changes_before_the_report` below, which asserts the same line; nothing above). `raised.setdefault(i, e)` fails the dispatch-record test alone,
with `'  [1] <guard check raised RuntimeError: pass 2 unhappy>' not found in
[..., '  [1] <guard check raised RuntimeError: pass 1 unhappy>', ...]`;
without that test it passes every other test in the file (measured), which
is the gap the test closes (and #197179's one-input twin, `test_no_match_message_quotes_the_last_raise_at_one_index`, fails the same way). 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`: the
re-check answers `dispatch key set mismatch` instead of throwing, and [0]'s
line no longer reads `<guard check raised RuntimeError: ` (and, above, six `NeverReChecked` stubs fail on their re-check message: two in #197188, four in #197179). Deleting the dedup -- the `(i, kind) in warned` test and the
`add` beside it -- fails both dedup tests on the repeat call that has to be
silent, with `Unexpected logs found` quoting the second warning (and two
warning tests in #197195). Never
starting the dedup over (forcing the `_same_results` test in
`warn_swallowed` true) and gating the reset on two or more results each
fail `test_aot_compile_module_warns_again_about_a_replaced_single_result`
with `no logs of level WARNING or higher triggered` on the call after the
swap (the first also fails #197195's `test_aot_compile_module_warns_again_about_a_replaced_index`; the second fails nothing else in the file). Making the
report's `check_verbose` handler re-raise fails
`test_no_match_report_describes_the_other_entries_when_one_raises` alone
here, on `ValueError: boom` escaping the call (and two in #197179, whose stubs raise only in the re-check). Making
the dispatch handler re-raise fails the nine tests here whose trees raise in
dispatch, on the raise escaping, and neither the inconsistent-guard test
nor the describer test (; above, it fails three in #197188, four in #197179, five in #197195 and two in #197219, every test whose tree raises in dispatch). Four reverts fail only the two-raiser and constructor tests here (above,
the dropped collapse also fails #197179's odd-separators test, and the
served-index swap #197195's four warning tests and #197219's interrupt
test):
chaining `raised[raiser]` fails the two-raiser test with `'checked\x0ctree\x1eis unhappy' != 'the opted-out tree is unhappy'` on
the chained text; dropping the
raise line's separator collapse (`return line`) fails it with `'  [1] <guard check raised RuntimeError:
checked tree is unhappy>' not found in [..., '  [1] <guard check raised
RuntimeError: checked', 'tree', 'is unhappy>', ...]`;
logging the raising index as the served one fails it with `Expected 2 but got 1.` on
`warned.count("dispatch served [0]")`; and
`init=True` on `_warned` fails the constructor test with `'_warned' unexpectedly found in ['model',
'compiled_results', '_warned']`. Forcing
`if i in unanswered:` to `if False:` fails the two-raiser test as well,
with [1]'s line reading `<guard check raised AttributeError:
'Raises' object has no attribute 'check_verbose'>` where the raise line
asserted whole is expected, and the dispatch-record test, whose [1] line
then reads the accept line its inherited `check_verbose` produces where
`<guard check raised RuntimeError: pass 2 unhappy>` is expected. Five reverts fail one test each and nothing else in the file: unwrapping
every exception to its `__cause__` (`cause = e.__cause__`) fails the
dispatch-record test, `'ValueError' unexpectedly found in` a report whose
[1] line reads `<guard check raised ValueError: x (through the guard tree's
pybind boundary)>`; reading `_guard_check_enabled` per entry in the report's
loop instead of once fails the describer test, `'guard check raised'
unexpectedly found in "  [1] <opted out of guard checks; withheld because
[None]'s guard check raised>"`; `default=((), set())` in place of `_warned`'s
factory fails the constructor test, `unexpectedly identical: set()`;
withholding the scan's match once a raise is on record (`if accepts(i,
result) and not raised:`) fails the later-match test, `Expected 1 but got
2.` on the raiser's check count; and collapsing the warning's quote as the
report line's is fails the two-raiser test on the raw `checked\x0ctree\x1eis
unhappy` warning line. The other reverts -- `__context__` for
`__cause__`, keying the dedup on the `SystemError` pybind hands back, and
either handler widened to `BaseException` -- fail nothing here; the first
fails #197188's `test_no_match_message_reads_the_cause_not_the_handled_exception` alone, the second #197195's `test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise` alone, the dispatch
handler's widening #197219's interrupt test alone and the report
handler's nothing in the file, so that bound stays documented rather than pinned.

> **FAQ: an earlier revision of this commit owned 25 more tests, and with them
> the pins of `_unwrapped_raise` reading `__cause__` and stopping at
> `SystemError`, of `except Exception` letting a `KeyboardInterrupt` or
> `SystemExit` out of `accepts()`, of the exception-type half of the dedup
> key, of the serve after a raise being the scan's, and of the two exits that
> discard a recorded raise. Restore them?**
>
> They were moved, not deleted: the round that split this commit for review
> budget put them in the four tests-only commits directly above, and the
> whole test file at the top of the four is what every measurement above ran
> (the review of that revision could not run the suite). Decision by
> decision, with the mutation each test fails on: `__cause__` rather than
> `__context__` is #197188's
> `test_no_match_message_reads_the_cause_not_the_handled_exception`, whose
> stub raises a bare `SystemError` inside an `except Boom:` block, so
> `__context__` quotes `Boom`; `KeyboardInterrupt` and `SystemExit` leaving
> `accepts()` as themselves is #197219's
> `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`, whose
> [1] raises each in turn under `assertRaisesRegex(interrupt, ...)`, so
> `except BaseException` ends the call in a report instead; the type half of
> the dedup key is #197195's
> `test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise`, where a
> `ValueError` and a `TypeError` at index 0 log twice, so a key on the index
> alone fails its `len(logs.output) == 2`; a later result's bind raising
> `TypeError` with a raise on record and nothing logged is #197219's
> `test_module_dispatch_later_result_that_cannot_bind_raises_type_error`,
> under `assertNoLogs`; and an interrupt out of a later tree leaving with
> nothing logged is the interrupt test above, under `assertNoLogs` as well.
> Two of the decisions named were pinned nowhere in the stack, and this
> revision pins them here rather than in a commit above: the `SystemError`
> condition on the unwrap -- the boundary test above raises a plain
> `RuntimeError` with nothing chained, which an unconditional unwrap reads the
> same -- is the dispatch-record test's [1], raised `from ValueError("x")`; and
> the serve after a raise being the scan's, which the later-match test had
> asserted only through its warning, is that test's check count. Both
> measured above.

> **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`
> at the top of `accepts()` is outside the `try`, 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, every path
> that builds a report chains one, and a call that ends in neither leaves as
> the exception that ended it and records nothing, whatever ended it. 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. Recording it here would mean a handler around everything
> `accepts()` deliberately lets through, and a fourth warning text for it.

> **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: `_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.**
>
> Both cases need a raise the guard tree does not produce. A second boundary
> would have to come from an accessor calling Python that itself returns with
> an error set, and those clear rather than nest: `LAMBDA_GUARD::check_nopybind`
> (`guards.cpp:1918-1924`) is `if (x == nullptr) { PyErr_Clear(); return
> false; }`, and `GetAttrGuardAccessor` (`:5322`) and
> `PythonLambdaGuardAccessor` (`:7287`) do the same, so the one
> `_PyErr_FormatFromCause` hop at the boundary between the tree and dispatch is
> the only hop there is. An explicit `raise SystemError(...) from
> ValueError(...)` reaches dispatch only from a Python-level guard manager on
> `_artifacts.guard_manager`, the route the two `except Exception` handlers
> above are drawn for, and costs one clause in one message line. A `while` loop
> would be a change no test in this file can make load-bearing, so it is not
> made.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 4c3b4628f54b03a8f4703b8a952e5e07dc144b62
Pull-Request: https://github.com/pytorch/pytorch/pull/196826
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…fter a raise

Test-only, split for review budget from `[aot_compile] Tolerate a guard tree
that raises during module dispatch` (#196826), two commits below, whose
`torch/_dynamo/aot_compile.py` this commit does not touch. The seven 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. It also adds the one key class only
its own test uses, `HitsThenRaises`, between `RaisesOnCompare` (#196826) and
`RaisesThenHits` (#197188), the comment on `RaisesOnCompare` counts three such
keys again, and one assertion each goes into #196826's
`test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` and
#197188's `test_no_match_message_quotes_a_tree_that_raised_then_answered`
(both below). The warning's other paths, the exits that record nothing and
four more things the parent already did are #197195, directly above, which
adds its tests around these without touching them.

The report, after a raise.
`test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators`: the
raise line is the one report entry whose text is arbitrary user data, so a
message carrying `\x0c`, `\r`, `\x1e` and `\u2028` collapses to the one entry
`  [0] <guard check raised RuntimeError: page break rec sep line>` rather
than splitting across several; the message holds no spaces, so the whole-line
assertion says all four separators arrived and were collapsed. The report's
total line count -- four: header, entry, fix-or-drop advice, `ModelInput`
advice -- is the count a split entry moves; counting the entries that start
with `  [`, as this test did before, reads 1 either way, the first fragment
being the only one that starts so (measured below).
`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, `unhappy on pass 2`, and `pass 1` appears nowhere. #196826's
`test_no_match_report_reads_the_dispatch_record_after_a_raise` 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).
Its `stub.checks == 2` is the exact count a `NeverReChecked` stub allows.
The chain carrying the FIRST index that raised while the advice names the
first ENABLED one is #196826'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. A previous
revision had a test of its own for that shape; four of its five assertions
were that test's, so it is folded into it instead (FAQ below).
`test_no_match_message_keeps_the_advice_beside_a_raise` and
`test_no_match_message_keeps_the_advice_beside_a_withheld_opt_out`: a
missing global and a raiser in one report, where the missing global's own
hint, the fix-or-drop line and the `ModelInput` line stand on disjoint
entries; both pin that order, locate each line through the class's
`_line_index` so a dropped advice line reads as a message diff instead of as
a `StopIteration` from inside the test, and then read what the located 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 -- `[0]'s guard check
raised while checking this call` with no opt-out in the list, `[0]'s raise,
not a guard failure, is what withheld` with one -- since `fix or drop that
artifact` ends both sentences. Both hide the leaked Dynamo globals first, as
every other test here that captures a `ScaleModule` does -- the two-input one
is the `_aot_compile_mode_branches` fixture and says so -- and both register
the name's restore before deleting it, as `_install_global_probe` does and
says, so an interrupt in between leaves it in place. The three-input one's
opted-out [2] is made unsatisfiable by its dtype, and has to be: `mode`
traces dynamic on that third compile, after [0] and [1] recompiled on it, so
its else-branch guard is `L['mode'] != 1` and accepts the `mode=2` call (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 #196826'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).
`test_no_match_message_when_only_the_report_raises` and its stub twin
`test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check`: both
dispatch passes got a clean rejection and only the re-check raised, so the
entry carries the raise itself -- only a dispatch raise is chained onto the
report -- and the `ModelInput` advice still applies. Both assert the entry
line whole against `splitlines()`, as every other entry-line assertion here
does. `_raised_line` prints the same line from either handler, so both twins
also pin 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 stub twin pins `stub.checks == 2` besides, both dispatch passes
having answered. Measured on the stub twin with its `check()` raising the same
`RuntimeError` instead of rejecting, so the raise is dispatch's and the entry
line reads the same: it fails on `__cause__` reading `RuntimeError('the
re-check is unhappy')` where None is expected, and with that assertion
removed on `'fix or drop that artifact' unexpectedly found` in the report.
The leaf version pins `key.compares >= 3`, the third evaluation the report
made rather than reusing a dispatch answer; a lower bound, since how often
one evaluation probes a key is codegen's business. `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 the entry line and the compare
count reading the same, which is why the leaf version pins the two readings
above too. Measured, in an earlier revision of this PR, with a wrapper around
the real guard manager that calls `check()` twice: the entry-line,
compare-count and `ModelInput` assertions all pass against it,
`assertIsNone(__cause__)` fails with the pybind `SystemError` as the cause,
and `assertNotIn("fix or drop that artifact")` fails on the report reading
`[0]'s guard check raised while checking this call; fix or drop that
artifact.` above the same entry line.
#197188's `test_no_match_message_quotes_a_tree_that_raised_then_answered` --
[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: 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; seven of its eight assertions were the leaf test's,
string for string, so the count lands there instead (FAQ below). The
`NeverReChecked` convention itself is exercised by
four stubs here (the odd-separators, two advice-order and last-raise tests),
one in #196826 and two in #197188: with `if i in unanswered:` forced to `if
False:`, all seven fail on "the report re-checked a tree that raised in
dispatch" (the four here and #196826's measured against this commit, the two
in #197188 in its message), and with `check_verbose` aliased to `check` under
the same mutation six of the seven pass -- only
`test_no_match_message_quotes_the_last_raise_at_one_index` still fails, on
its exact `stub.checks == 2` reading 3.

One thing the parent already did, kept.
`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_report_keeps_a_raise_on_one_line_past_odd_separators
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_keeps_the_advice_beside_a_withheld_opt_out
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_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check
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
```

The whole file runs 273 tests, `OK (skipped=6)`; #197188 runs seven fewer.
`lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean. The
seven were also run against the `torch/_dynamo/aot_compile.py` of #196826's
parent under this test file: six fail or error -- the leaf test on
`ValueError: boom on compare 3` escaping the call; the odd-separators and
last-raise tests on a count (`Scalars are not equal!`); and three on a report
line that is not there, the stub's
`RuntimeError` caught but carrying no report (`'  [0] <guard check raised
RuntimeError: the scanned tree is unhappy>' not found in ['the scanned tree
is unhappy']`) -- and the one that pins what the parent already did passes,
as it should; `raise RuntimeError(report) from None` fails it with `True is
not False` on `__suppress_context__`.

Each fix in #196826 was then reverted on its own against the tests of this
commit, and only the named tests failed (#197195's message lists its own):

```
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_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_keeps_the_advice_beside_a_withheld_opt_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_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
```

Dropping the `continue` from the report's withheld branch fails #197188's
`test_no_match_message_quotes_a_tree_that_raised_then_answered` on the count
this commit adds to it, 3 entry lines where there are 2 inputs (`Expected 2
but got 3`), and #196826's 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.
Chaining `raised[raiser]` instead of `next(iter(raised.values()))` fails
nothing here and the two-raisers test with `__cause__` reading `checked tree
is unhappy` where `the opted-out tree is unhappy` should be.
`raised.setdefault(i, e)` fails
`test_no_match_message_quotes_the_last_raise_at_one_index` with `unhappy on
pass 1` where `pass 2` is expected (and #196826's
`test_no_match_report_reads_the_dispatch_record_after_a_raise` 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 `unhappy on
pass 1`; the two-input test passes it, its chain being [0]'s only raise.
Restoring the old "rejected this call twice and then accepted" wording fails
nothing here: #196826's `..._reads_the_dispatch_record_after_a_raise` asserts
that line whole, and #197150's two tests assert it through
`_ACCEPTED_IN_THE_REPORT`. 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 `stub.checks` reading 1 where 2 is expected, the tree never
re-evaluated (and #196826's `..._reads_the_dispatch_record_after_a_raise` on
the same count, #197188's raised-then-answered test on `key.compares`,
#196826's raised-and-then-accepted test on the raise escaping). Removing the veto's
condition (`if True:`) fails the withheld-advice test here with
`RuntimeError not raised` (and #197188's raised-then-answered test and
#196826's two-raisers and does-not-reach-an-opted-out tests, on
`dispatch served 5.0, not a raise` or the same `not raised`). Dropping the raise line's separator collapse fails
`test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` alone
here, on `Expected 4 but got 8` lines, the entry arriving as five; under the
same mutant the entry-start count this test used before still reads 1, and
with the whole-line assertion removed that count passes it. Dropping the raise
line's two-space indent fails the six tests here that assert an entry line
whole (odd-separators, last-raise, both advice-order, both re-check-only) and
nothing else here. Hinting entry 0 instead of the entry that named the global
(`hinted.setdefault(hint, []).append(0)`) fails both advice-order tests on
`'For [1]:' not found in 'For [0]: a guarded global is missing ...'` (and
#197149's `hints_only_the_entry_that_named_a_missing_global`). Emitting the
withheld sentence for every raiser (`if withheld:` to `if raiser is not
None:`) fails `test_no_match_message_keeps_the_advice_beside_a_raise` on
`lines[fix]` reading `[0]'s raise, not a guard failure, is what withheld ...`
(and #196826's `survives_a_raising_guard` and
`..._reads_the_dispatch_record_after_a_raise` on the advice they pin);
dropping the no-opt-out advice altogether (`elif False:`) fails that test in
`_line_index`, no line found, and the odd-separators test on 3 lines where 4
are expected (and the same two in #196826). Making the report's `check_verbose` handler re-raise fails
`test_no_match_message_when_only_the_report_raises` and
`test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check` on the
re-check's raise escaping the call -- the leaf test on `ValueError: boom on
compare 3`, the stub test finding `the re-check is unhappy` alone where the
report line is expected -- (and #196826's describer test); widening that
handler to `BaseException` fails nothing. Making the dispatch handler re-raise
fails four of the seven, the three that pass being the two re-check-only
tests and the negative pin. Forcing `if i in unanswered:` to `if False:` fails the
four `NeverReChecked` stubs here on their re-check message (and the two in
#197188, #196826's two-raisers and `..._reads_the_dispatch_record_after_a_raise`
tests, and #197049's restores-torch-function test, whose trees are re-checked);
with `check_verbose` aliased to `check` under the same mutation, only
`test_no_match_message_quotes_the_last_raise_at_one_index` still fails here,
on `stub.checks` reading 3 (`Expected 2 but got 3`), #196826's
`..._reads_the_dispatch_record_after_a_raise` and #197049's test still failing
below. 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: in `test_no_match_message_keeps_the_advice_beside_a_withheld_opt_out`,
> the third input is traced with `mode=0`, so its `L['mode'] == 0` guard
> already rejects the one call made, `model(x, 2)`; is the float64 dtype
> redundant?**
>
> No, measured: with a float32 third input the test fails with `RuntimeError
> not raised`, the scan serving opted-out [2]. Its guard is not `L['mode'] ==
> 0`: [0] and [1] already recompiled on `mode`, so the third trace takes it
> as dynamic and the else branch guards `L['mode'] != 1`, which `mode=2`
> satisfies (read off `check_verbose` of that result: `result=True` on
> `mode=2`, `L['mode'] != 1` as the failing part on `mode=1`; the same for a
> third input at mode 3). With the float64 input, [2]'s tree rejects the call
> on `tensor 'L['x']' dtype mismatch. expected Double, actual Float`. The
> comment now says why the mode cannot do it.

> **FAQ: why does a test-only commit add a line to a test #196826 owns
> instead of keeping its own test for the chain-versus-advice split?**
>
> Because that test and #196826's two-raisers test were the same
> construction -- two `ScaleModule` inputs, a `Raises(NeverReChecked)` taking
> a message, [0] opted out with `the opted-out tree is unhappy`, [1] raising
> -- and four of its five assertions (the withheld line, the raise line, the
> `not a guard failure` advice, `__cause__`) were 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 #196826 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 two re-check-only tests come as a leaf/stub pair; why does the
> raised-then-answered shape get no stub twin, and why does its new count go
> into a test #197188 owns?**
>
> The re-check-only pair differ in what they can observe: the leaf twin's
> `HitsThenRaises(hits=2)` rests on codegen probing the key once per
> evaluation, and the stub twin removes that dependency. A stub twin of
> #197188's `test_no_match_message_quotes_a_tree_that_raised_then_answered`
> -- [0] raising in the scan through a stub `check` and rejecting on the
> second pass, opted-out [1] withheld -- would not: that test's
> `key.compares >= 3` is already the codegen-independent lower bound its
> comment says it is, and every message reading in the shape (the rejection
> quoted at [0], no raise line, the withheld line, the `not a guard failure`
> advice, `Add a ModelInput`, the raise in the chain) is a string equality no
> leaf behaviour moves. A previous revision of this PR had such a twin; seven
> of its eight assertions were the leaf test's, and its one new reading, the
> `  [` entry-line count, is one line that lands as well on the leaf test's
> two-entry report -- measured above, it fails there on `Expected 2 but got
> 3` under the dropped `continue`. The line lands here rather than in #197188
> for the reason the FAQ above gives for #196826: this is the commit that
> adds the reading.

> **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: #196826'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, withheld-for-every-raiser and no-advice
> 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 #197150's two tests.

> **FAQ: `test_no_match_message_quotes_the_last_raise_at_one_index` shares
> three of its four assertions with that same test; 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 and #197257 above assert, 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 three shared assertions stay because they are
> 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]>
ghstack-source-id: de4c99d
Pull-Request: #197179
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [no-ci] [aot_compile] Say when a no-match report entry's guards accepted the call the dispatch refused [aot_compile] Say when a no-match report entry's guards accepted the call the dispatch refused Sep 16, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

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


The code is otherwise ready and every previously-flagged item is now fixed, but the one finding from last round still stands: the new entry diagnoses a single cause for a condition that has a second, config-independent one — guarded state changing between the last dispatch check and the report.

Full review

PR Review: #197150

Summary

Adds a branch to AOTCompiledModel._no_match_report so a report entry whose check_verbose accepts the call prints an explanatory line instead of a bare [i], plus a test pinning the raise, the three tree evaluations, the entry text, and the entry count. The implementation is correct; the open question is what the entry's text asserts.

Code Quality

  • The entry names one cause; a second is reachable in a default build and this file treats it as in scope. torch/_dynamo/aot_compile.py:1605-1609 diagnoses the report-time accept as a guard that does not answer consistently — nondeterminism inside the guard. But the same entry appears when every guard is perfectly deterministic and the guarded state moved between the re-check pass (:1577-1579) and the report's check_verbose (:1604). Nothing is snapshotted at bind time: prepare_f_locals (:630-643) copies only cell contents and bound locals — guarded globals are not in that dict at all — while GlobalsGuardAccessor::check_nopybind re-descends the live globals dict pointer captured at build time (torch/csrc/dynamo/guards.cpp:6519-6531), DictGetItemGuardAccessor issues a fresh PyDict_GetItem per evaluation (:5765, :5776), and TensorCheck::check re-reads dtype / sym_sizes() / sym_strides() / key_set() off the live tensor each time (:217-235). RootGuardManager also rebuilds LocalState per evaluation (:4380-4383, :4438-4441), so process-global torch state is re-sampled too.

    This is not a hypothetical the file excludes. __call__ holds no lock across the passes, and RootGuardManager explicitly drops the GIL around its own lock acquisition (guards.cpp:4372), so other threads run between passes even in a GIL build; a GC finalizer rebinding a guarded global reaches it single-threaded. The file's own _binding_verdict comment says "A hint, not a lock: the last writer wins" (aot_compile.py:1526-1531), and two existing tests interleave a RecordedThread with a live dispatch (test/dynamo/test_aot_compile.py:2342, :2371). A reader who hits that case is sent hunting for a nondeterministic guard when the guard is correct and the program raced — the same wrong-thing-named failure the branch exists to prevent, and the reason the branch does not quote the guards it just passed.

    The description's FAQs argue at length for naming a single cause, but they argue it against the tag-safe fast path — correctly dropped, since find_tag_safe_roots() needs use_recursive_dict_tags_for_guards, False by default (torch/_dynamo/config.py:497). Neither FAQ addresses this cause, which needs no config flag. Widening the tail costs one clause and keeps the entry true of every build; the golden string at :2689 and the docstring's ellipsis at :1518 would follow. Fix this →

Recommendation

Needs Discussion — on the message's tail only, unchanged from last round. Everything else is ready.

All previously-raised findings are now closed, and I re-derived each rather than taking the fix on trust:

  • The description now quotes the shipped single-clause form and reframes the tag-safe material as a dropped draft, so the merged commit message no longer explains wording no report emits. Its stated 210-test count is right.
  • The class docstring covers the third line kind (aot_compile.py:1513-1521); its <... accepted it here: ...> ellipsis is why that paragraph will not go stale if the tail changes.
  • The test calls _aot_compile_mode_branches() (:2678), regaining the _hide_leaked_dynamo_globals() sweep in the order _install_global_probe's docstring requires (:2155-2156).
  • The continue at :1610 is load-bearing under test, and the entry-count assertion at :2694-2695 is the only thing covering it — the assertIn checks alone would not catch its removal.

Also verified this round:

  • The continue skips nothing that could have mattered. Every GuardDebugInfo with result == true comes from the two-arg constructor (guards.cpp:1737-1740), which leaves verbose_code_parts an empty py::list; the reason-carrying forms are reached only under if (!result) or with a literal false. So _names_a_missing_global over an accepting entry's parts is vacuously false and _missing_global_hint() could never have fired for it — skipping the hint-collection at :1612-1613 loses nothing, and the pre-change code emitted a bare [i] with no hint.
  • _install_global_probe's signature change is fully propagated. Exactly two call sites (test_aot_compile.py:2441, :2679), both unpack the pair; no other caller in the tree and no subclass override.
  • The new test's cleanup ordering is sound. _aot_compile_mode_branches registers _hide_leaked_dynamo_globals' restore first, so LIFO pops the CountedKey before restore iterates the module dict calling str methods on its keys; probe.compares is asserted before any cleanup runs, and g.pop(probe, None) hits the identity short-circuit in CountedKey.__eq__ (:596-598) so it cannot perturb the count.
  • Conventions match. assertIn on substrings plus a splitlines() structural assertion mirrors the siblings at :2069-2081 and :2096-2107, and [0] L['mode'] == 0 is asserted identically at :2096.

One thing I considered and am not filing: a report where every entry takes the new branch is reachable (single-result model, misses=2), leaving the footer's "Add a ModelInput" as the only advice under an entry the branch exists to say is not a real mismatch. The description's footer FAQ already answers this — a captured ModelInput for this call gets a tree that matches on the first evaluation, so the inconsistent entry stops being consulted — which makes the footer actionable rather than contradictory there.

Not verified empirically: torch is not built in this checkout, so python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently could not be run here. Everything above is source reading.

· branch `gh/bobrenjc93/1204/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Folded into #196823 (the no-match report now ships with the accepted-in-report line, the empty-parts line and the one-line normalisation); closing this slice.

@bobrenjc93 bobrenjc93 closed this Sep 16, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1204/head branch November 21, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant