Skip to content

[aot_compile] Tolerate a guard tree that raises during module dispatch - #196826

Closed
bobrenjc93 wants to merge 59 commits into
gh/bobrenjc93/1175/basefrom
gh/bobrenjc93/1175/head
Closed

bobrenjc93 wants to merge 59 commits into
gh/bobrenjc93/1175/basefrom
gh/bobrenjc93/1175/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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

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

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

How a guard tree raises

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

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

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

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

Recording a raise in dispatch

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

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

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

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

Interrupts are never an answer

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

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

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

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

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

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

The two records

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

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

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

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

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

What changes for a caller

Against the parent, four things change.

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

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

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

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

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

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

The single-result hot path

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

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

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

The opted-out last resort

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

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

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

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

The raise line

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

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

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

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

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

The report's own re-check

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

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

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

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

Left in place

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

Existing tests and fixtures

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

This commit adds the fixtures its own tests use:

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

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

Order to review

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

Test Plan:

python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raising_guard
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_tree_that_raised_then_answered_still_withholds
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_the_report_throws
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_doubly_wrapped_interrupt_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_interrupt_reaches_the_report
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_over_a_raising_leaf
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_raise_whose_str_raises
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_the_first_raise_recorded
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_guarded_state_changes_before_the_report
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report
python test/dynamo/test_aot_compile.py -k test_no_match_report_quotes_a_tree_that_raised_and_then_rejected
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out
python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_opt_out_flags_the_veto_read
python test/dynamo/test_aot_compile.py

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

Authored with the assistance of Claude Code.

FAQ: the report can lose a raise -- with [0] raising in both passes and
[1] raising in the scan and then rejecting cleanly, [1]'s raise reaches no
line, no footer and no link of the __cause__ chain -- and the footer names
the input that raised first rather than the first one checked. Fix both
here: have the footer enumerate every enabled raiser, or keep a raise line
beside the rejection.

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

FAQ: an earlier revision of this commit carried more tests -- every
stub-guard-manager test, the warning and its dedup. Where are they?

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

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

FAQ: _quoted catches only Exception, so a __str__ raising
KeyboardInterrupt escapes it and destroys a half-built report. Catch
BaseException there: the fallback string discloses the type anyway.

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

🤖 Generated with Claude Code

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

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

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

  • Correctness
    • _unwrapped_raise (torch/_dynamo/aot_compile.py:110-136) bounds its __cause__ walk with an id() set, so the self-closing chain CyclesOnCompare builds terminates instead of spinning
    • bound is filled for every index by accepts before _no_match_report reads bound[i], and the withheld branch's [{raiser}] cannot format None: reaching the report with an opt-out requires the veto to have fired on an enabled raiser
    • Continuing after a C++ throw is safe on the TorchFunction TLS because GuardManagerWrapper.check restores it in its except BaseException (torch/_dynamo/guards.py:770-779)
  • Preservation
    • The try covers manager.check() alone; prepare_f_locals and _live_guard_manager() stay outside it, so a bind TypeError still surfaces as itself rather than as a non-match
    • KeyboardInterrupt/SystemExit behind an unbroken SystemError chain are re-raised by all three handlers via _meant_an_exception, not swallowed as answers
  • Testing
    • 14 new tests in test/dynamo/test_aot_compile.py drive the real DICT_NOT_CONTAINS leaf (guards.cpp:2474-2481, whose result == -1 branch is dead under C &&) for the report line, the opt-out veto, doubly-wrapped interrupts and the cycle
    • test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs pins the raised.clear() on all three serving exits under disable_gc() (torch/testing/_internal/common_utils.py:5979)
  • Scope
    • Two files, one concern; AOTCompiledModel is documented private and experimental, and the caller-visible SystemError-to-RuntimeError change is stated in its docstring and pinned by test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught
    • No workflow, build, or policy-doc edits; nothing secret-bearing in the diff

reason: clean
Reviewed commit: 423daf8

Inference job

🐛 Report a wrong verdict

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

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

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

claude Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 43m 55s —— View job


Review complete

One-sentence summary: The new veto test is exactly the one asked for and the three declines are all correct, but the enabled[i] filter on raiser — which decides which index the withheld line and the footer name — is pinned by nothing here, and its discriminating shape is a one-character change to a test already in the file.

Full review

PR Review: #196826

Summary

Makes AOTCompiledModel dispatch and its no-match report tolerate a guard tree that raises instead of returning a bool.

I diffed this round's own contribution against the last:

git diff 1ce22656 423daf88 --stat
# test/dynamo/test_aot_compile.py | 17 +++++++++++++++++

The source is byte-identical; the only change is the 17-line test.

The new test is the one I specified, and it discriminates. test_aot_compile_module_tree_that_raised_then_answered_still_withholds (test:3458) drives _aot_compile_dict_branches({}, None), opts [1] out, patches [0]'s check with side_effect=[ValueError("boom in the scan"), False], and asserts check.call_count == 2 plus the withheld line. I traced the mutation myself: with map(enabled.__getitem__, unanswered) at :1900, [0]'s unanswered.discard(0) on the second pass (:1858) empties the set, any(...) is False, and the last-resort loop serves [1]'s x * 5 — so the assertRaises(RuntimeError) fails. It is also placed correctly, between the two existing veto tests, and check.call_count == 2 pins the raised-then-answered premise rather than leaving it implicit.

All three declines are correct. I confirmed by grep that none of the deferred pins exists in this file: pass 1 unhappy/pass 2 unhappy, Tried 0 compiled, and __suppress_context__ all return zero hits, and def test_no_match_report_reads_the_dispatch_record_after_a_raise, ..._with_no_results_... and ..._no_match_does_not_suppress_... are all absent. The reasoning holds in each case: every fixture here raises through the real DICT_NOT_CONTAINS leaf, whose text is fixed per index by construction, so there is no distinct second text to assert on without the stub trees the split adds; nothing in this file constructs an empty compiled_results; and the from None mutation needs a call made from inside an except block, which the _model_with_stub_trees harness supplies.

I re-verified all six C++ premises by reading, and all six hold — including claim 1, which four prior sub-agents have now misread the same way. DICT_CONTAINS::check_nopybind (guards.cpp:2474-2481) is int result = PyDict_Check(value) && PyDict_Contains(value, _key.ptr()); followed by if (result == -1). && is the logical operator, yielding only 0 or 1, so a -1 arrives as 1, the PyErr_Clear() at :2477 never runs, and the exception survives to the boundary. SET_CONTAINS (:2504-2512) identical. LAMBDA_GUARD::check_nopybind (:1918-1928) clears with no type filter; check_verbose_nopybind (:1930-1936) captures get_exception_message() first. SYMBOLIC_SHAPE_GUARD (:2834-2841) increments _args_seen and gates on == _nargs, with the buffers as members (:2893-2895) and resets only at :2837 and :2887-2889, gated off by default (config.py:560, guards.py:3549). RelationalGuard and all four subclasses are bare py::class_ with zero .def( (:7849-7871). catch appears nowhere in guards.cpp, and all four PyErr_Occurred hits are off the eval path.

I could not run the test suite (no importable torch, no reachable .venv), so the Test Plan is unverified from my side. All 20 -k names resolve to a def test_ in the file.

Testing

1. The enabled[i] filter on raiser is pinned by nothing, and its two consequences are report lines this commit authors.

:1961 is raiser = next((i for i in raised if enabled[i]), None). Mutating it to next(iter(raised), None) leaves the whole file green.

The filter only bites when the first-recorded raise came from an opted-out index while a later-recorded one is enabled — and that shape does reach the report, since any(map(enabled.__getitem__, raised)) at :1900 is satisfied by the later enabled raiser, so the veto fires and the last resort is skipped. Traced for _aot_compile_dict_branches({}, {}) with [0] opted out and both trees raising: raised insertion order is [0, 1], enabled == [False, True], so raiser is 1 with the filter and 0 without.

Under the mutation two lines this commit writes name the wrong index:

  • :1970-1973 → [0] <opted out of guard checks; withheld because [0]'s guard check raised> — self-referential, the opted-out input named as its own withholder, which is exactly what the comment at :1965-1967 says quoting its guards would do.
  • :2045-2048 → [0]'s raise, not a guard failure, is what withheld the opted-out input(s) above; fix or drop that artifact. — pointing the reader at the artifact whose raise, per ..._raise_from_an_opted_out_result_withholds_nothing, vetoes nothing.

I enumerated every disable_guard_check() test that reaches _no_match_report with a non-empty raised and none discriminates: ..._raising_tree_does_not_reach_an_opted_out_result (test:3425) and ..._tree_that_raised_then_answered_still_withholds (test:3458) both have raised == {0} with enabled == [True, False]; ..._reads_an_opted_out_tree_that_raised_as_opted_out (test:3615) has raised order [0, 1] but disables 1, so the disabled index is recorded second and the filter is a no-op; ..._reads_the_opt_out_flags_the_veto_read (test:3207) snapshots [True, True]. The two tests that do disable index 0 with it raising (test:3475, test:3631) never build a report — the veto does not fire and the last resort serves. grep "withheld because\|is what withheld" returns only test:3445, :3447, :3472, :3627, all naming [0], i.e. the first-recorded index either way.

test:3615 is the discriminating shape already: changing compiled_results[1] to compiled_results[0] at test:3622 flips it, since its own comment confirms the disabled index is in unanswered too.

One question before this is actionable. The description's FAQ says "The raiser-vs-__cause__ divergence the review asks to pin is pinned directly above, by test_aot_compile_module_two_raisers_in_the_report" — and I confirmed that name is absent from this file, so I cannot check what it asserts. If it asserts the withheld line and the footer on an opted-out-first-raiser shape, this is the same pin and the decline stands. If it asserts only the __cause__ chain (which is what its surrounding sentence is about), then the chain is pinned above while the filter is pinned nowhere, and the two are separable: the chain reads next(iter(raised.values())) at :1914 deliberately, while raiser reads the filtered index — same shape, different line, different assertion. Fix this →

2. The reason.__cause__ is not None half of the walk's condition is unpinned, on an exotic shape. :133 is while isinstance(reason, SystemError) and reason.__cause__ is not None:. Dropping the second clause makes reason become None for a SystemError with no __cause__: _meant_an_exception answers isinstance(None, Exception) == False, all three handlers re-raise, and a guard tree raising a plain uncaused SystemError escapes dispatch instead of being tolerated — and if it ever reached a report line, that line would read <guard check raised NoneType: None>. No test produces one: every SystemError in the file is either boundary-wrapped (always caused), CyclesOnCompare's pair, or WrapsAnInterruptOnCompare's explicit raise ... from, and grep finds no bare-SystemError side_effect. Low consequence — a leaf that raises SystemError with nothing chained is not a shape the real tree produces — so noting rather than requesting.

Recommendation

Needs Discussion — on finding 1, and specifically on whether it is the pin already deferred to #197390. The mutation changes two report lines this commit writes, on a path this commit builds, and the discriminating fixture is one character away from a test already here; but the description claims the raiser divergence is pinned one commit up, and I cannot read that test from this branch. If it asserts the withheld line rather than only the __cause__, the decline stands and this is Approve. Finding 2 is a note. Everything else checks out: the source moved zero bytes this round, all six C++ premises hold under direct reading, and the new test is exactly the one the last round asked for.

• branch `gh/bobrenjc93/1175/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Answering the one question from the last pass against the current head 423daf88805b (no code moved); the pin you could not read from this branch does assert the withheld line and the footer, so the decline stands.

1.

The enabled[i] filter on raiser is pinned by nothing, and its two consequences are report lines this commit authors. [...] If it asserts the withheld line and the footer on an opted-out-first-raiser shape, this is the same pin and the decline stands.

Declined here; pinned one commit up. #197390's test_aot_compile_module_two_raisers_in_the_report is exactly that shape: results[0].disable_guard_check() with both stub trees raising, so raised is recorded [0, 1] with enabled == [False, True]. It asserts the withheld line whole, [0] <opted out of guard checks; withheld because [1]'s guard check raised>, the footer "[1]'s raise, not a guard failure, is what withheld" on lines[3], and separately the chain, str(ctx.exception.__cause__) == "the opted-out tree is unhappy" (index 0's raise). Under raiser = next(iter(raised), None) both the withheld line and the footer would name [0] and that test fails on the whole-line read; #197390's own message records raised[raiser] for the chain failing it alone as well. #197390 is the tests-only commit split out of this one for review size and carries the last-resort, empty-results and last-wins pins for the same reason.

2.

The reason.__cause__ is not None half of the walk's condition is unpinned, on an exotic shape. [...] a leaf that raises a plain uncaused SystemError is not a shape the real tree produces -- so noting rather than requesting.

Declined, as noted: the boundary always chains, and no leaf in the tree raises a bare SystemError.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 5m 56s —— View job


Review complete

One-sentence summary: The answer resolves the only open question — the raiser-filter pin lives one commit up on exactly the shape that discriminates it — and with the source unchanged and every C++ premise re-verified, I have nothing left to block on.

Full review

PR Review: #196826

Summary

Makes AOTCompiledModel dispatch and its no-match report tolerate a guard tree that raises instead of returning a bool.

I first checked what moved:

git diff 1ce22656 HEAD --stat   # test/dynamo/test_aot_compile.py | 17 +++++
git diff 423daf88 HEAD --stat   # empty

The source is byte-identical to two rounds ago; the only change since my last pass is the 17-line veto test, which I reviewed then.

The open question is answered, and the answer is the one that settles it. Last round I said the enabled[i] filter on raiser (torch/_dynamo/aot_compile.py:1961) is free here, and that the decline stands if #197390's test_aot_compile_module_two_raisers_in_the_report asserts the withheld line and the footer rather than only the __cause__ chain. The reply says it asserts all three: the whole line [0] <opted out of guard checks; withheld because [1]'s guard check raised>, the footer on lines[3], and the chain separately as "the opted-out tree is unhappy" (index 0's raise). That is the discriminating shape — disable_guard_check() on [0] with both trees raising gives raised order [0, 1] and enabled == [False, True], so next(iter(raised), None) yields 0 and both the withheld line and the footer name the wrong index. I confirmed the stack branch is not fetchable from this checkout (git branch -r shows only .../1175/base and .../1175/head, and git ls-remote for the sibling refs is not permitted here), so I am taking the reply at its word on the assertion text — but its specificity about the fixture, the ordering and which line carries which claim is what a reader of that commit can check directly, and it matches the divergence the comment at :1957-1960 describes. The reasoning for placing it there also holds independently: raiser is local to _no_match_report (:1919) while the chain's from is at :1914 above it, so pinning the filter here would mean recomputing the raiser at the outer site for a shape only the tests-only commit builds.

I re-verified the load-bearing C++ premises by reading rather than trusting the docstring, and they hold — including the one five prior sub-agents have now misread the same way. DICT_CONTAINS::check_nopybind (guards.cpp:2474-2481) is int result = PyDict_Check(value) && PyDict_Contains(value, _key.ptr()); followed by if (result == -1). && is the logical operator, yielding only 0 or 1, so a -1 from PyDict_Contains arrives as 1, the PyErr_Clear() at :2477 never runs, and the exception survives to the pybind boundary — the branch is dead and the motivating case is real. SET_CONTAINS (:2504-2512) is identical in shape.

I also re-derived the report's invariants independently rather than carrying prior verdicts, and all hold: raised[i] (:1986) cannot KeyError, since every unanswered.add(i) is the line after raised[i] = e (:1819-1820, :1855-1856) and all three serving exits clear both; bound[i] (:1990) cannot KeyError, since the pass-2 loop (:1877) visits every index and accepts writes bound[i] (:1848) outside its try, with bound[0] written inline at :1833; bound[0] at :1845 is safe because shared needs len(results) > 1 (:1838), so the inline block ran and its only earlier exit is a return; and [{raiser}] cannot format None at :1972 or :2046, since both need a non-enabled result present, which with no enabled raiser means the veto loop at :1901 returns first. All 20 Test Plan -k names resolve to a def test_ among the file's 235.

I could not run the test suite (no importable torch, no reachable .venv), so the Test Plan is unverified from my side.

Notes

Nothing blocking. Two observations, neither a request:

1. The new veto test also exercises the reworded accept line without asserting it. In ..._tree_that_raised_then_answered_still_withholds (test:3458), [0] is discarded from unanswered on the second pass, so the report falls through to check_verbose(bound[0]) at :1990 — and only check is patched, so the real check_verbose runs against the d={} binding it was traced on and accepts. [0]'s entry line is therefore _ACCEPTED_IN_THE_REPORT. That is correct behaviour and already pinned by test_no_match_message_when_a_guard_answers_inconsistently, so the test is right to say nothing about it; noting only because a reader tracing the shape may expect a rejection line there.

2. The two prior declines stand as reasoned. raised.setdefault vs the last-wins record needs two distinct raise texts at one index, which the real DICT_NOT_CONTAINS leaf cannot produce (its text is fixed per index by construction); the empty-compiled_results report needs a shape nothing here constructs; and the from None mutation needs a call made from inside an except block. Each is pinned where its fixture lives. I re-confirmed by grep that none of pass 1 unhappy, Tried 0 compiled or __suppress_context__ appears in this file, consistent with all three living above.

Recommendation

Approve — thirty-six rounds in, the question that held the last pass at Needs Discussion is answered by the pin I asked about, on the shape that discriminates it, in the commit the split put it in. The source moved zero bytes this round and one byte-identical round before that, the C++ premises hold under direct reading, the report's invariants hold under exhaustive case analysis, the description matches the diff, and every decision reachable from this commit is pinned against a named mutation.

• branch `gh/bobrenjc93/1175/head`

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

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197220

pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…s and exits on stub guard trees (#197390)

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

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

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

## Fixtures and helper

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

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

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

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

## The report's own handler

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

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

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

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

## `__cause__`, not `__context__`

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

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

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

## A raise whose `str()` raises

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

## An artifact with no results

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

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

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

## The dispatch record after a raise

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

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

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

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

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

## Two raisers

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

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

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

## An interrupt propagates

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

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

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

## A later match after an earlier raise

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

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

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

## A tree that raised and then accepted

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

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

## Cross-cutting mutations

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

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

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

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises
python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_a_systemerror_cause_not_the_handled_exception
python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raise_whose_str_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_with_no_results_raises_the_no_match_report
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted
python test/dynamo/test_aot_compile.py
```

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

Authored with the assistance of Claude Code.

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

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

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

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

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

## What the warning looks like

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

## Order to review

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

## The change

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

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

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

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

## Serve and warn, rather than refuse

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

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

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

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

### The enabled advice

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

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

It holds at any index and needs no qualification.

### The opted-out advice

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

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

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

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

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

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

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

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

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

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

## When the one-shot is spent

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

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

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

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

## The unwrapped raise, quoted

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

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

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

## A per-model set beside weak references

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

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

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

## A method, gated at three sites

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

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

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

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

## Tests

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

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

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

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

Test Plan:

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

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

Authored with the assistance of Claude Code.

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

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

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

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

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

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

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

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

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

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

## Where this sits in the stack

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

## The two fixtures

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

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

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

## How the report quotes a raise

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

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

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

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

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

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

## When a tree that raised is evaluated again

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

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

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

## The `NeverReChecked` convention

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

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

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

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

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary
python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_the_cause_not_the_handled_exception
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered
python test/dynamo/test_aot_compile.py
```

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

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_the_cause_not_the_handled_exception
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary
```

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

Authored with the assistance of Claude Code.

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

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

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

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

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

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

## Where this sits in the stack

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

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

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

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

## The report, after a raise

### The last raise at one index

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

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

### The chain versus the advice

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

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

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

### The advice beside a raise

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

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

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

### A raise only in the report

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

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

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

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

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

### One entry line per input

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

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

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

## One thing the parent already did, kept

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

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

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_the_last_raise_at_one_index
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_beside_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_does_not_suppress_a_handled_exception
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered
python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises
python test/dynamo/test_aot_compile.py
```

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

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

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_the_last_raise_at_one_index
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_beside_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_does_not_suppress_a_handled_exception
python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered
python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw
```

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

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

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

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

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

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

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

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

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

Authored with the assistance of Claude Code.

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

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

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

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

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

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

## Where this sits in the stack

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

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

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

## The second pass logs one line about the raiser

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

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

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

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

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

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

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

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

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

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

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

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

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

## Ordinary dispatch is silent

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

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

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

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

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

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

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_last_resort_warns_about_another_index
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_about_a_replaced_index
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_ordinary_dispatch_warns_about_nothing
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_model_not_per_process
python test/dynamo/test_aot_compile.py
```

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

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

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197195
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…d the no-match report's call (#197220)

**Problem.** When every checked guard tree raised, the no-match report still ended with `Add a ModelInput covering this call`, which contradicts its own `fix or drop that artifact` line: a new input would guard the same dict and raise the same way.

**Fix.** Dispatch records which trees actually answered. The report advises a `ModelInput` only when some checked tree answered or the artifact holds no inputs, and otherwise says that every guard tree raised.

**Summary.** The commit below tolerates a guard tree that raises during module dispatch and reports the raise as that entry's line, but leaves the report's closing advice as it was at the parent: `Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy` is appended to every report. When every tree whose guards were asked about raised, nothing rejected the call, and an input covering it would guard the same dict and raise the same way, so the report told the caller both to fix or drop the artifact and to add an input -- two instructions that contradict each other. Dispatch now records `answered`, the indices that reached an answer in either pass, written on a rejection only, and the report advises a `ModelInput` whenever some checked tree answered (`coverable`) or the artifact holds no input at all. When no checked tree ever answered and two or more trees raised, a footer saying every guard tree raised replaces the advice, unless an opted-out result's line has already said the raise withheld it; a single raiser's own `fix or drop that artifact` line already says as much. Nothing served or raised changes -- the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto and the warning are untouched -- only the report's closing lines differ, and six of the eleven touched tests fail on the commit below's `aot_compile.py`.

## Where this sits in the stack

Split from `[no-ci] [aot_compile] Say what the no-match report's advice rests on after a raise` (#197050, the commit above) for review budget: this commit decides WHETHER the report's closing advice applies, and the sibling qualifies it when every rejection it rests on followed a raise.

## The contradiction

Measured on `DictBranchModule` with one input and a colliding key, the report at the commit below reads:

```
[0] <guard check raised ValueError: boom from __eq__ (through the guard tree's pybind boundary)>
[0]'s guard check raised while checking this call; fix or drop that artifact.
Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy -- ...
```

Nothing rejected the call, and an input covering it would guard the same dict and raise the same way. `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised` pins that report now ending on the fix-or-drop line.

## Recording who answered

```python
# AOTCompiledModel.__call__
raised: dict[int, Exception] = {}
unanswered: set[int] = set()
answered: set[int] = set()          # new: indices that ever reached an answer

try:
    answer = first._live_guard_manager().check(f_locals)
except Exception as e:
    raised[0] = e; unanswered.add(0); answer = False
else:
    answered.add(0)                 # new

def accepts(i, result):
    try:
        answer = result._live_guard_manager().check(f_locals)
    except Exception as e:
        raised[i] = e; unanswered.add(i); return False
    if answer:
        return True                 # an accept serves and builds no report
    # Recorded on a rejection only.
    unanswered.discard(i)
    answered.add(i)                 # new
    return False
```

Dispatch now records which entries reached an answer, and records it where the order is known rather than reconstructing it afterwards. `answered` holds the indices that reached an answer in either dispatch pass, which is what the `ModelInput` advice reads: an entry that answered and then raised did reject this call, so an input covering the call is on the table even though its own report line is that later raise. Keying that advice on the last evaluation instead drops it for exactly those entries -- measured: `coverable` read off `answered - unanswered` fails `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` with no `ModelInput` line at all. The write happens on a rejection only: an accept returns before it, since dispatch then serves and builds no report, so the result that accepts pays nothing for it.

## The two gated closing lines

```python
# _no_match_report
raiser = next((i for i in raised if enabled[i]), None)
coverable = any(results[i]._guard_check_enabled for i in answered)   # new
withheld = not all(enabled)
...
if raiser is not None:
    lines.append(f"[{raiser}]'s guard check raised while checking this call; fix or drop that artifact.")
if coverable or not results:                         # parent: unconditional
    lines.append("Add a ModelInput covering this call, or check whether guard_filter_fn kept ...")
if len(raised) > 1 and not withheld and not coverable:   # new footer
    lines.append("Every guard tree raised while checking this call; the reasons above are those raises, not guards this call failed.")
```

**The `ModelInput` line.** The report advises a `ModelInput` whenever at least one checked tree reached an answer (`coverable`, `any(results[i]._guard_check_enabled for i in answered)`, the shape the last-resort veto already uses over `raised`). `deserialize` accepts an artifact holding no inputs at all, where `aot_compile_module` refuses one: with no entries there is no raise to describe and nothing that could have answered, so that report carries the `ModelInput` line alone -- adding an input is exactly its advice. Dropping `not results` from the `ModelInput` gate fails `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` on the line going missing.

**The every-tree-raised footer.** When no checked tree ever answered, the entry lines above are all raises, and the one closing line a single raiser earns is the `fix or drop that artifact` line the commit below already emits for it: that raiser's entry line, that advice and a footer saying every tree raised would say `[0] raised` three times over, which is what the first version of this commit printed -- measured on `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`, whose four-line report closed with `[0]'s guard check raised while checking this call; fix or drop that artifact.` and then `Every guard tree raised while checking this call; ...`. So the footer that says the reasons above are the raises themselves, not guards this call failed, is added only once two or more trees raised and none answered: there the fix-or-drop line names one raiser of several, and without the footer nothing on the report says that no guard rejected the call.

```
# test_no_match_message_when_every_guard_tree_raised: two enabled trees, both raise, no opt-out
No AOT compiled graph matched this call. Tried 2 compiled input(s):
  [0] <guard check raised RuntimeError: the first tree is unhappy>
  [1] <guard check raised RuntimeError: the second tree is unhappy>
[0]'s guard check raised while checking this call; fix or drop that artifact.
Every guard tree raised while checking this call; the reasons above are those raises, not guards this call failed.
```

Under that gate every entry raised -- each entry either raised or answered, and an opted-out entry reaches the report only because an enabled raise withheld it, which the `not withheld` term excludes -- so `len(raised) > 1` counts the raisers and the entries alike. The two gates are independent `if`s: they are already exclusive on `coverable`, and an `elif` would read as an ordering that does not exist.

Each term of the footer's gate is pinned by a mutation:

| mutation | fails |
| --- | --- |
| gate on `raised` instead of `len(raised) > 1` | `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`, `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` (footer under a single raiser's line) |
| drop `not withheld` | `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` (a fifth line under its withheld line, which has already said what the raise cost) |
| drop `not coverable` | `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered` (footer beside the `ModelInput` advice it contradicts) |

## What changes against the commit below

Nothing served or raised changes: the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto and the warning are untouched. Only the report's closing lines differ: the `ModelInput` line is omitted when no checked tree ever answered and the artifact has inputs, so a single raiser's report ends on its fix-or-drop line, and an every-tree-raised line replaces the advice when two or more trees raised, none answered and no opt-out was withheld. Making the `ModelInput` line unconditional again fails `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`, `test_aot_compile_module_restores_torch_function_after_a_throw`, `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` and `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` on the line appearing.

The `AOTCompiledModel` docstring listed that advice as part of every report; it now says when the advice is present, what replaces it when no checked tree answered AND two or more trees raised -- the empty artifact has neither and gets the advice, not the replacement, which is what `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` pins -- that a single raiser's own line already says as much, and that the replacement too stays off a report whose withheld line has already said the raise withheld an opt-out.

## Tests

Five tests are new and six of the commit below's tests gain or change an assertion about the closing lines this commit adds or removes for their case. Of those eleven, six fail on the commit below's `aot_compile.py`:

- `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`, `test_aot_compile_module_restores_torch_function_after_a_throw` and `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`, on the `ModelInput` line appearing;
- `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators`, on the four lines it counted there -- header, entry, fix-or-drop advice, `ModelInput` advice -- against the three a single raiser's report has now.

The five that pass there do so because the parent's `ModelInput` line is unconditional and it has no every-tree-raised line to find; each is a pin here by the mutation named above:

- `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` (`not results`);
- `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` (`coverable` over `answered`, not over the last evaluation);
- `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered` (`not coverable` on the footer's gate);
- `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary` (`len(raised) > 1`);
- `test_no_match_message_when_only_the_report_raises`, which gains only an assertion that the every-tree-raised line is absent from its report, whose one tree answered.

## Review order

Review `answered` and its update in `accepts()`; the report's `coverable`; the two gated lines at the end of `_no_match_report`, the comment on the empty artifact and the comment on the footer's gate; the sentence of the `AOTCompiledModel` docstring that describes the report's closing lines; then, in the test file, `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` and `test_no_match_message_advises_an_input_after_an_answer_then_a_raise`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_every_guard_tree_raised
python test/dynamo/test_aot_compile.py -k test_no_match_message_drops_the_input_advice_when_the_one_tree_raised
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_when_one_of_two_raisers_answered
python test/dynamo/test_aot_compile.py -k test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_after_an_answer_then_a_raise
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result
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_two_raisers_in_the_report_and_then_the_warning
python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The eleven were also run against the commit below's
`torch/_dynamo/aot_compile.py` (six fail, the five named above pass), and
each gate was then mutated on its own -- `coverable` keyed on the last
evaluation, `not results` dropped, the `ModelInput` line made unconditional,
the footer gated on `raised` instead of `len(raised) > 1`, its `not
withheld` dropped, its `not coverable` dropped -- and the eleven rerun; only
the tests named above failed under each.

Authored with the assistance of Claude Code.

> **FAQ: `raiser` and `coverable` walk all results to filter by membership in
> a small set, where `any(results[i]._guard_check_enabled for i in
> answered)` is the same predicate in the shape already used at the veto.**
>
> Taken for `coverable`, which is exactly that line. Not for `raiser`: it does
> not walk all results. It is
> `next((i for i in raised if results[i]._guard_check_enabled), None)`
> -- already a walk of the small dict, and it needs the first such index in
> recording order rather than a bool, so there is no `any(...)` shape to move it
> to.

> **FAQ: `answered` never holds an accept -- the accept returns before the
> write -- so `rejected` would name what the set holds and make `coverable` a
> restatement rather than a derivation.**
>
> Kept as `answered`. It is the report's counterpart to `unanswered`, the
> commit below's name for the same property keyed on the LAST evaluation: `i
> in unanswered` decides whether an entry's line is its raise or a quoted
> guard, `i in answered` whether a `ModelInput` could cover it, and what both
> key on is that `check()` returned rather than raised. That every recorded
> answer was a rejection is what a report existing means, and it is written at
> the write (`Recorded on a rejection only`) and at `coverable` (`answered in
> either dispatch pass rejected this call`), the two places the set is read.
> The commit above adds `trusted` as a third set over the same indices and
> reads `answered - trusted`; renaming here would ripple through its four
> `answered` hunks for a word those two comments already supply.

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

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

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

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

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

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

Test Plan:

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

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

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

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

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

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

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

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

Authored with the assistance of Claude Code.

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

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

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

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

Test Plan:

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

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

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

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

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

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

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

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

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 02f1b6b
Pull-Request: #197219
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…ard for and which share a line (#197001)

**Problem.** The no-match report decides, entry by entry, whether its missing-global hint names "this `Module` instance's forward" or stays neutral ("the live scope this artifact was loaded against"), by comparing the dict `forward` resolves to against the dict each entry's guards hold. Nothing pinned that a caller-supplied `guard_globals=` dict stays neutral, or that in a report with two entries holding different dicts only the entry holding the resolved one is told which forward.

**Fix.** Two tests pin exactly that: one where no entry holds the resolved dict (and defining the name in the supplied dict then serves the call), and one where exactly one of two does, checked in both orders with a single resolve asserted. No source change.

**Summary.** Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Split twice more for review budget: the five-test revision of this commit died at the review bot's 60-minute ceiling, so the two tests that pin WHEN the report resolves `forward` -- only for a SUPPLIED scope, and once -- moved up into `[aot_compile] Pin when the no-match report resolves forward` (#197301), and the three-entry test that pins which entries share a hint line moved up into `[aot_compile] Pin that the no-match report shares one hint line across entries worded alike`. What stays here is the pair that pins WHICH entry the hint names a `forward` for: one where no entry is, and one where exactly one of two is. Both pass at the parent, whose report they pin, fail below the report commit (#196896) where no report exists, and each fails under a targeted edit of `_no_match_report` that no other test in the file catches, measured by editing the report and running the whole file. Two tests of the previous revision are gone, one because the footer gate it fenced is already fenced by two other tests and one because it is folded into the three-entry test's entry `[1]` in the commit above.

## What the report does at this tree

The report decides its hint per entry. An entry whose verbose parts name a whole missing global gets `_missing_global_hint(forward=...)`, with `forward` set when `resolved is not None and resolved is result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)` returned, run at most once, at the first hinted entry whose scope is SUPPLIED, and reused for every entry after it (when it runs, and that it runs once, is #197301's).

```
# the two wordings the tests tell apart
For [i]: a guarded global is missing from the live scope this artifact was loaded against; define it there ...   # neutral
For [i]: ... this GlobalConfigModule instance's forward resolves to ...                                          # named
```

## Both fail below the report commit

Both tests pass at the parent, whose report they pin, and fail below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there` substring the tests also look for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file:

| test | failure below the report commit |
| --- | --- |
| `..._hint_stays_neutral_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` |
| `..._names_forward_only_for_the_dict_it_resolves_to` | `Expected '_resolve_guard_scope' to be called once. Called 0 times` |

The one that compiles in its own body calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the other shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone.

## `test_no_match_message_hint_stays_neutral_for_a_supplied_scope`

```python
scope: dict[str, object] = {"__builtins__": builtins}          # never had AOT_HERMETIC_WEIGHT
compiled = AOTCompiledModel.deserialize(HermeticModule(), data, guard_globals=scope)
with self.assertRaises(RuntimeError) as ctx:
    compiled(x)
message = str(ctx.exception)
self.assertIn("[0] KeyError on G['AOT_HERMETIC_WEIGHT']", message)
self.assertIn("For [0]: a guarded global is missing from the live scope this artifact was loaded against; define it there", message)
self.assertNotIn("instance's forward", message)
# the advice, followed: the guards hold the supplied dict, and defining the name there serves the call
self.assertIs(compiled.compiled_results[0]._guard_globals, scope)
scope["AOT_HERMETIC_WEIGHT"] = AOT_HERMETIC_WEIGHT
self.assertEqual(compiled(x), x @ AOT_HERMETIC_WEIGHT)
```

It loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording under its `For [0]:` prefix, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time.

Reducing the compare to `resolved is not None` fails it with a report that names `this HermeticModule instance's forward`, and fails exactly two others: the landed #196818's `..._names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`, and this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose caller-supplied entry is then told which forward as well. #197048's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and its `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit.

What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed).

## `test_no_match_message_names_forward_only_for_the_dict_it_resolves_to`

```python
by_forward = AOTCompiledModel.deserialize(GlobalConfigModule(), data)                    # resolves scope from model.forward: this module's dict
by_caller = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=scope)  # a dict that never had the name
self.assertIs(by_forward.compiled_results[0]._guard_globals, globals())
self.assertIs(by_caller.compiled_results[0]._guard_globals, scope)
del GLOBAL_POOLING_CONFIG
pair = by_forward.compiled_results[:1] + by_caller.compiled_results[:1]
cases = ((pair, [named, neutral]), (pair[::-1], [neutral, named]))                        # both orders
for results, wording in cases:
    mixed = AOTCompiledModel(GlobalConfigModule(), results)
    with patch(target, wraps=_resolve_guard_scope) as resolves, self.assertRaises(RuntimeError) as ctx:
        mixed(x)
    resolves.assert_called_once_with(mixed.model)          # one resolve, asked about the model the report is for
    hints = [line for line in message.splitlines() if line.startswith("For [")]
    self.assertEqual([line[:9] for line in hints], ["For [0]: ", "For [1]: "], message)
    for hint, want in zip(hints, wording):
        self.assertIn(want, hint)
```

This is the shape that tells a per-entry `forward` from one shared across the report. Two SUPPLIED results whose guards hold different dicts -- one from `deserialize(GlobalConfigModule(), data)`, which resolves the scope from `model.forward` and so holds this module's dict, the one `_resolve_guard_scope` returns; one from `deserialize(..., guard_globals=scope)` with a dict that never had the name -- go into one `AOTCompiledModel` by hand, as `hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair, and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one resolve, asked about the model the report is for -- two `For [i]:` lines, and that the entry holding the resolved dict is the one told `this GlobalConfigModule instance's forward` while the other gets the live-scope wording.

| edit to `_no_match_report` | fails |
| --- | --- |
| decide `forward` once, at the first hinted entry, and apply it to every entry | this test alone, on the second entry's wording (`'the live scope this artifact was loaded against; define it there' not found in "For [1]: ... this GlobalConfigModule instance's forward resolves to ..."`) |
| resolve `_resolve_guard_scope(type(self.model)())` instead of `self.model` | this test on `expected call not found`, plus #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording |

Nothing else in the file catches the first edit: `..._names_the_resolved_module`'s two entries share one dict in each half, and `hints_each_scope`'s SUPPLIED entry is its only one. The line count does not catch that edit, because the resolved dict carries a `__name__` and the supplied one does not, so the two hints stay two sentences either way; the wording does. The `_with(mixed.model)` is what pins which module is resolved: asking about a fresh instance resolves to the same dict here, so the wording cannot tell, and a fresh instance does not carry the `forward` the two #197048 tests rebind.

## Two tests of the previous revision are gone

`test_no_match_message_advises_an_input_for_a_missing_global` and its `SelfModeBranchGlobalModule` fixture pinned the footer under a report whose every entry was hinted; the footer is unconditional, and returning before it when `sum(map(len, hinted.values())) == len(results)` fails two tests at this tree without it (both on `'Add a ModelInput' not found`): #196825's `test_aot_compile_module_absent_global_fails_guard` and #197048's `survives_a_forward_resolve_that_raises` (and, one commit up, #197301's `resolves_forward_only_for_a_supplied_scope`). Its other assertions -- that the `L['self'].mode` mismatch is absent from the first report and named by the second -- pinned the guard tree's install order and fail-count re-sort in guards.cpp, not the report.

`test_missing_key_inside_a_present_global_is_not_a_missing_global` is folded into the three-entry test's entry `[1]`, which fences the same substring edit, and rides with it in the commit above.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_forward_only_for_the_dict_it_resolves_to
python test/dynamo/test_aot_compile.py
```

The whole file is green here and on the parent commit.

## FAQ

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> the landed #196818, already fails under the edit that this commit's
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is not None`: the failures are `..._names_the_resolved_module`
> (`'loaded against; define it there' not found`), this test, and this commit's
> `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So
> the identity compare is fenced at #196818 as well, and the message says so
> instead of crediting this test alone. What this test alone covers is a
> `guard_globals=` dict that never had the name --
> `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does.

> **FAQ: The review found two of an earlier revision's five tests largely
> redundant with the base, and two report branches -- where `tried_forward` is
> set, and hint dedup keyed by text -- unpinned. What changed?**
>
> Both redundancies were measured and both tests are gone; both branches are
> now pinned, one in the commit above and one in #197301. Gating the footer on
> every entry being hinted, the edit
> `test_no_match_message_advises_an_input_for_a_missing_global` fenced, fails
> two tests at this tree without it -- #196825's `absent_global_fails_guard`
> and #197048's `survives_a_forward_resolve_that_raises` -- so that test and
> its fixture add no fence on the report, and its `L['self'].mode` assertions
> pin guards.cpp's accessor order, not this function. Replacing the report's
> whole-part predicate with a substring test, the edit
> `test_missing_key_inside_a_present_global_is_not_a_missing_global` fenced
> alone, and keying `hinted` by dict identity are both fenced by the
> three-entry `shares_a_hint_line_across_entries_worded_alike` in the commit
> above, so the fold loses no coverage and the module path still has its own
> pin of the predicate. The `tried_forward` mark is pinned by #197301's
> `resolves_forward_once_past_a_resolve_that_raises`.

> **FAQ: Every new test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the
> report the parent already ships, so every test passes on the parent's tree.
> The two measurements that stand in for it are above: each test fails under
> the tree below the report commit (#196896), where no report exists, and each
> fails under a targeted edit of `_no_match_report` that no other test in the
> file catches -- the mutation table is what shows the pins are not vacuous.

> **FAQ: The review listed `"; ".join(parts)` with more than one verbose code
> part per entry as uncovered. Why is there no test for it here?**
>
> Because that join is #197134's (`Keep a no-match report entry to one line
> that says what its guards answered`), whose
> `test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators` owns
> the entry format; how many parts an entry quotes has no bearing on the hint,
> which is what this commit pins. A multi-part entry test belongs next to that
> one, in that PR.

Authored with the assistance of Claude Code.

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

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

**Problem.** The no-match report from #196823 groups its missing-global hint by sentence, so two entries loaded against different caller dicts but worded alike share one `For [0, 2]:` line, and a nested-key `KeyError` stays off the hint; nothing in the file exercised a three-entry report, so none of that was pinned.

**Fix.** Add `test_no_match_message_shares_a_hint_line_across_entries_worded_alike`, the report's only three-entry test, which pins the shared non-contiguous hint line, the nested-key exclusion, the single resolve of the model's own forward and the footer's placement. No source change.

**Summary.** Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling; the two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here. It loads three SUPPLIED results from three `deserialize(GlobalConfigModule(), data, guard_globals=...)` calls, each holding a caller dict of its own, where `[0]` and `[2]` lack `GLOBAL_POOLING_CONFIG` and `[1]` has it bound to `{}` so its guard fails on the KEY. It pins four things at once: the hint lines are keyed by sentence and not by dict, so `[0]` and `[2]` share one non-contiguous `For [0, 2]:` line; `[1]`'s nested-key `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']` is the ordinary mismatch the whole-part match keeps off the hint; the report's one resolve is `assert_called_once_with(mixed.model)` on an `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so it returns `(None, reason)` without raising and no entry is told which forward; and the footer follows a report whose hinted list is non-contiguous. It passes at the parent, whose report it pins, and fails below the report commit (at #196896), where the no-match fall-through raises the function path's `GuardManager check failed` message with no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, on `Expected '_resolve_guard_scope' to be called once. Called 0 times`. Two targeted edits of `_no_match_report` that no other test in the file catches -- keying `hinted` by `(id(result._guard_globals), hint)`, and replacing `_names_a_missing_global` with a `"KeyError on G[" in part` substring test -- each fail this test alone, which is what shows the pin is not vacuous.

## Where this sits in the stack

Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling. The two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here.

## The fixture and the report it pins

```python
x = torch.randn(4, 8)
data = self._two_input_global_guard_artifact(x)
absent = {"__builtins__": builtins}                                   # no GLOBAL_POOLING_CONFIG
keyless = {**absent, "GLOBAL_POOLING_CONFIG": {}}                     # the global, without the key its guard reads
loads = [AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=s)
         for s in (absent, keyless, dict(absent))]                    # three SUPPLIED results, three distinct dicts
results = [loaded.compiled_results[0] for loaded in loads]
assert [r._guard_scope for r in results] == [_GuardScope.SUPPLIED] * 3
assert len({id(r._guard_globals) for r in results}) == 3

mixed = AOTCompiledModel(self._unresolvable_forward_module(), results)
with patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope) as resolves:
    with self.assertRaises(RuntimeError) as ctx:
        mixed(x)
resolves.assert_called_once_with(mixed.model)
```

The report the test asserts, line by line:

```
No AOT compiled graph matched this call. Tried 3 compiled input(s):
  [0] KeyError on G['GLOBAL_POOLING_CONFIG']
  [1] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']
  [2] KeyError on G['GLOBAL_POOLING_CONFIG']
For [0, 2]: a guarded global is missing from the live scope this artifact was loaded against; define it there ...
Add a ModelInput ...
```

`test_no_match_message_shares_a_hint_line_across_entries_worded_alike` is the report's first three-entry test (`Tried 3` appears nowhere else in the file). The three entry lines are asserted exactly, `len(hints) == 1`, the one hint starts with `For [0, 2]:` and does not contain `instance's forward`, and `Add a ModelInput` is the last line. It shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not call `_hide_leaked_dynamo_globals()`, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone.

## The four things it pins

**First, hint lines are keyed by sentence, not by dict.** `[0]` and `[2]` carry no `__name__`, so their neutral sentences are identical and they share one non-contiguous `For [0, 2]:` line. Keying `hinted` by `(id(result._guard_globals), hint)` instead fails it on the line count (`Expected 1 but got 2`) and nothing else in the file: `..._names_the_resolved_module`'s `For [0, 1]` entries share one dict object. The merge is the intended reading: a per-dict line would print the same sentence twice, and the sentence names no dict, so the reader could not tell the two lines apart; two entries that give one instruction get one line.

**Second, the nested-key mismatch stays off the hint.** `[1]` is the nested-key mismatch the whole-part match keeps off the hint: replacing the report's `_names_a_missing_global` with a `"KeyError on G[" in part` substring test fails it on `For [0, 1, 2]:` and nothing else in the file, the fence the dropped `test_missing_key_inside_a_present_global_is_not_a_missing_global` carried (see the FAQ); the predicate itself is pinned on the function path by `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`.

**Third, the report resolves the model's own forward, once.** The model is `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so the report's one resolve -- `assert_called_once_with(mixed.model)` -- returns `(None, reason)` without raising and no entry is told which forward; the fixture's three other uses pass no `guard_globals=`, so their results are RECONSTRUCTED and never reach the resolve. The `_with(mixed.model)` is what pins which model the report asks about: resolving `type(self.model)()` instead fails this test on `expected call not found`, along with #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` and #197001's `names_forward_only_for_the_dict_it_resolves_to`.

**Fourth, the footer follows a report whose hinted list is non-contiguous.**

## Where it is red

It passes at the parent, whose report it pins, and fails below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message: that message carries the missing-global hint sentence the test also looks for, but no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file, it fails on `Expected '_resolve_guard_scope' to be called once. Called 0 times`.

| mutation of `_no_match_report` | fails on | other tests in the file affected |
| --- | --- | --- |
| key `hinted` by `(id(result._guard_globals), hint)` | `Expected 1 but got 2` hint lines | none |
| `_names_a_missing_global` -> `"KeyError on G[" in part` | `For [0, 1, 2]:` | none |
| resolve `type(self.model)()` instead of `self.model` | `expected call not found` | #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises`, #197001's `names_forward_only_for_the_dict_it_resolves_to` |
| tree below the report commit (#196896) | `Expected '_resolve_guard_scope' to be called once. Called 0 times` | -- |

Test Plan:

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

The whole file is green here and on the parent commit.

## FAQ

> **FAQ: The report's comment on `hinted` says entries that share a scope
> share a sentence, but the dict is keyed by hint text, so two entries holding
> different dicts with identical wording collapse into one `For [0, 2]:` line.
> Is that intended, and why pin it rather than change it?**
>
> It is intended, and this commit changes no code. The hint sentence is the
> whole of what the reader gets: it names a scope only when the dict carries a
> `__name__` (`here vars(mod)`), and two caller-supplied dicts without one
> yield the identical sentence, so a per-dict line would print that sentence
> twice with nothing to tell the two lines apart. Two entries whose advice
> reads the same get one line; two entries whose advice differs -- a resolved
> module dict next to a supplied one, a CAPTURED entry next to a SUPPLIED one
> -- keep their own, which #197001's
> `names_forward_only_for_the_dict_it_resolves_to` and
> `hints_each_scope_a_mixed_model_failed_in` pin. The comment's "share a
> scope" is the common case of sharing a sentence, and belongs to #197149.

> **FAQ: An earlier revision had a separate
> `test_missing_key_inside_a_present_global_is_not_a_missing_global`. Where did
> it go?**
>
> Into this test's entry `[1]`, which fences the same edit: replacing the
> whole-part predicate with a substring test fails this test alone in the whole
> file, so the fold loses no coverage, and it buys the nested-key mismatch a
> place next to two whole-global ones in one report, where the point is that
> the hint skips it while the entry line still quotes it. The module path also
> keeps its own pin of the predicate on the function side.

> **FAQ: The test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the report
> the parent already ships, so it passes on the parent's tree. The two
> measurements that stand in for it are above: it fails under the tree below the
> report commit (#196896), where no report exists, and it fails under two
> targeted edits of `_no_match_report` that no other test in the file catches --
> the mutations are what show the pin is not vacuous.

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197569
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
**Problem.** The no-match report (#196823) resolves `self.model`'s `forward` to name the scope a missing global should be defined in, but nothing pinned WHEN it does so: only for an entry whose scope was SUPPLIED, at the first such entry whatever its index, and at most once even when the resolve raises. Each of those decisions could be silently loosened without any existing test noticing, because the report's wording reads the same either way.

**Fix.** Four tests that count calls into `_resolve_guard_scope` through a `patch(..., wraps=...)` instead of reading the text: no resolve for a CAPTURED scope, none for a RECONSTRUCTED one, one resolve at the first SUPPLIED entry even at index 1, and one resolve when it raises. No source change.

**Summary.** Tests only, for the no-match report the report commit (#196823) raises, split out of `[aot_compile] Pin which entries the no-match report's hint names forward for and which share a line` (#197001) for review budget after that commit's five-test revision died at the review bot's 60-minute ceiling: the four tests that pin WHEN the report resolves `forward` -- for a SUPPLIED scope only, and at most once -- are this commit, and the three that pin which entries the hint names it for stay below. The report at this tree resolves `forward` at most once per report: at the first hinted entry whose scope is SUPPLIED it marks the attempt (`tried_forward = True`) before the `try`, calls `_resolve_guard_scope(self.model)`, keeps what came back for every entry after it, never triggers for a CAPTURED or RECONSTRUCTED entry (neither hint names `forward`), and swallows a raising resolve once rather than re-running it for a later entry. Because the CAPTURED and RECONSTRUCTED hints never name `forward` and both entries after a raise read the same neutral sentence, the wording cannot pin any of that, so each test wraps `_resolve_guard_scope` in a `patch(..., wraps=...)` and asserts the call count and, where it matters, which module instance was asked. Each of the four passes at the parent, whose report it pins, and fails below the report commit, where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message with no `[i]` prefix, no `For [i]:` line and no `Tried N` header. What each catches, and which other tests in the file would catch the same edit, was measured by editing the report and running the whole file; every targeted edit fails exactly the test written for it and nothing else outside this commit.

## Where this sits in the stack

Split out of #197001 for review budget: that commit's five-test revision died at the review bot's 60-minute ceiling. The four tests that pin WHEN the report resolves `forward` are here; the three that pin which entries the hint names it for stay below in #197001. Which entries the resolved result is then applied to is #197001's business.

## What the report does at this tree

```python
# _no_match_report, as the tests below pin it
tried_forward = False
for i, result in enumerate(results):
    ...
    if any(map(_names_a_missing_global, parts)):        # a hinted entry
        if result._guard_scope is _GuardScope.SUPPLIED and not tried_forward:
            tried_forward = True                        # marked BEFORE the try: a raise is swallowed once
            try:
                resolved, unresolved = _resolve_guard_scope(self.model)
            except Exception as exc:
                unresolved = f"resolving it raised {type(exc).__name__}"   # the type only: str(exc) can raise again
        # CAPTURED and RECONSTRUCTED entries never reach the resolve: neither hint names forward
```

The report resolves `forward` at most once per report. At the first hinted entry whose scope is SUPPLIED it marks the attempt before the `try`, calls `_resolve_guard_scope(self.model)`, and keeps what came back for every entry after it; a CAPTURED or RECONSTRUCTED entry never triggers it, since neither hint names `forward` -- the first names the tracing module, the second the rebuilt scope; and a resolve that raises is swallowed once rather than re-run for a later entry. Review the three gate tests first, then the once test.

## Below the report commit

Each of the four passes at the parent, whose report it pins, and fails below the report commit (the commit under it raises no report), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `the module the compiled function was traced in` substring the first test also looks for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file:

| test | fails below the report commit on |
| --- | --- |
| `resolves_forward_only_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` |
| `resolves_no_forward_for_a_reconstructed_scope` | hint-line count, `Expected 1 but got 0` -- no `For [` line at all |
| `resolves_forward_once_past_a_resolve_that_raises` | resolve count, `Expected 1 but got 0` |
| `resolves_forward_at_the_first_supplied_entry` | the same count |

The two that capture compile in their own body and call `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the third only loads, and the fourth copies the mixed-scope arrangement of `test_no_match_message_hints_each_scope_a_mixed_model_failed_in`, which compiles without hiding them.

## Gate 1: no resolve for a CAPTURED scope

`test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the CAPTURED half of the pair whose SUPPLIED half, #197048's `test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the report.

```python
model = torch.compile(HermeticModule(), fullgraph=True, backend="eager",
                      options={"guard_filter_fn": keep_global_guards})
model._aot_compile([ModelInput(args=(x,), kwargs={}, contexts=[])])
assert model.forward.compiled_results[0]._guard_scope is _GuardScope.CAPTURED
resolve = patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope)
saved = globals().pop("AOT_HERMETIC_WEIGHT")
try:
    with resolve as resolves, self.assertRaises(RuntimeError) as ctx:
        model(x)
finally:
    globals()["AOT_HERMETIC_WEIGHT"] = saved
resolves.assert_not_called()                                   # the count is the pin
# message carries: "[0] KeyError on G['AOT_HERMETIC_WEIGHT']", exactly one "For [0]: ..." line
# naming "the module the compiled function was traced in", no "instance's forward", "Add a ModelInput"
```

It captures a plain `HermeticModule` in-process, pops the global, and asserts the CAPTURED wording arrives on the report's one `For [0]:` line with no `forward` named. It wraps `_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it was never invoked, since the wording alone cannot pin the gate: the CAPTURED hint never names `forward`, so it reads the same whether or not the resolve ran, and resolving it runs user code (`get_traced_fn` formats a forward it refuses). Dropping the SUPPLIED half of the gate, `if not tried_forward:`, fails it on the count, `Expected '_resolve_guard_scope' to not have been called. Called 1 times`, and in this file fails only it and the RECONSTRUCTED test below (`failures=2`): the CAPTURED hint ignores `forward`, and every SUPPLIED report test resolves either way.

## Gate 2: no resolve for a RECONSTRUCTED scope

`test_no_match_report_resolves_no_forward_for_a_reconstructed_scope` is the gate's other exclusion: it reads SUPPLIED, not "anything but CAPTURED", and a RECONSTRUCTED hint ignores `forward` too, so resolving there would run that user code for a sentence that cannot name it.

```python
data = self._two_input_global_guard_artifact(x)
with self.assertLogs("torch._dynamo.aot_compile", level="WARNING"):
    loaded = AOTCompiledModel.deserialize(self._unresolvable_forward_module(), data)   # forward is a functools.partial
results = loaded.compiled_results[:1]
assert results[0]._guard_scope is _GuardScope.RECONSTRUCTED
with resolve as resolves, self.assertRaises(RuntimeError) as ctx:
    AOTCompiledModel(loaded.model, results)(x)
resolves.assert_not_called()
# exactly one "For [0]: ..." line, naming "missing from the scope rebuilt from the artifact"
```

It loads the two-input artifact against a module whose `forward` is a `functools.partial` -- the load that rebuilds the scope rather than resolving one -- keeps the first result, and asserts the rebuilt-scope hint arrives on one `For [0]:` line with no resolve. No global is popped: the rebuilt scope never carried the name its guard reads. Loosening the gate to `is not _GuardScope.CAPTURED` fails this test alone in the file (`failures=1`, on the same never-called count), and no other test here catches that edit.

## Gate 3: the first SUPPLIED entry, not index 0

`test_no_match_report_resolves_forward_at_the_first_supplied_entry` pins that the gate fires at the first SUPPLIED entry whatever its index, which is what `not tried_forward` buys over an index test.

```python
loaded = AOTCompiledModel.deserialize(GlobalConfigModule(), self._two_input_global_guard_artifact(x))
captured = torch.compile(GlobalConfigModule(), ...); captured._aot_compile([...])
results = captured.forward.compiled_results + loaded.compiled_results[:1]
assert [r._guard_scope for r in results] == [_GuardScope.CAPTURED, _GuardScope.SUPPLIED]
inst = GlobalConfigModule()
mixed = AOTCompiledModel(inst, results)
saved = globals().pop("GLOBAL_POOLING_CONFIG")
try:
    with resolve as resolves, self.assertRaises(RuntimeError):
        mixed(x)
finally:
    globals()["GLOBAL_POOLING_CONFIG"] = saved
assert resolves.call_count == 1
assert resolves.call_args.args[0] is inst         # asked about the instance it was constructed with
```

Over a `[CAPTURED, SUPPLIED]` pair, built the way `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` builds one, the report still resolves once and asks about the instance it was constructed with. Rewriting the gate as `i == 0 and result._guard_scope is _GuardScope.SUPPLIED` fails this test alone in the file (`failures=1`, `Expected 1 but got 0`): that mixed-scope test never patches `_resolve_guard_scope`, and both arms of `_missing_global_hint` append the same `, here vars(...)`, so its wording survives the edit even though `[1]` loses the `instance's forward` naming.

## Once: the attempt is marked before the resolve

`test_no_match_report_resolves_forward_once_past_a_resolve_that_raises` pins where the attempt is marked.

```python
loads = [AOTCompiledModel.deserialize(inst, data) for _ in range(2)]    # two SUPPLIED results, this module's dict
results = [loaded.compiled_results[0] for loaded in loads]
mixed = AOTCompiledModel(inst, results)
inst.forward = functools.partial(HermeticModule.forward, inst)          # get_traced_fn refuses it...
with self.assertRaises(ValueError):
    _resolve_guard_scope(inst)                                          # ...and formatting it reaches extra_repr, which raises
saved = globals().pop("AOT_HERMETIC_WEIGHT")
try:
    with resolve as resolves, self.assertRaises(RuntimeError) as ctx:
        mixed(x)
finally:
    globals()["AOT_HERMETIC_WEIGHT"] = saved
# Not assert_called_once_with: a failure would repr inst, which raises.
assert resolves.call_count == 1
assert resolves.call_args.args[0] is inst
# message: "[0] KeyError on G[...]", "[1] KeyError on G[...]", one neutral
# "For [0, 1]: a guarded global is missing from the live scope this artifact was loaded against, here vars(<module>); define it there"
```

Two `deserialize(inst, data)` loads of one `RaisingReprModule` artifact give two SUPPLIED results holding this module's dict; `inst.forward` is then rebound to a `functools.partial`, which `get_traced_fn` refuses and formats into its error, reaching the module's `extra_repr` -- the test asserts `_resolve_guard_scope(inst)` itself raises `ValueError`. With the global popped, both entries are hinted and SUPPLIED, and the report resolves once (`call_count == 1`, asked about `inst`), swallows the raise, and words both `For [0, 1]:` neutral. Moving `tried_forward = True` below the resolve, inside the `try`, leaves it unset after the raise, so `[1]` re-runs the raising user code: that fails this test on the count (`Expected 1 but got 2`) and nothing else (`failures=1`). #197001's `names_forward_only` cannot see that edit, because its resolve succeeds and the mark is set either way, and `survives_a_forward_resolve_that_raises` has one result. The count carries the assertion, because the wording cannot: both entries read the same neutral sentence whether the resolve ran once or twice. It is checked as `call_count` and `call_args.args[0]` rather than `assert_called_once_with(inst)`, because mock formats a failed match with `repr(inst)`, which is the raise. The `args[0] is inst` check is what pins which module is asked: resolving `type(self.model)()` instead fails it (`failures=5` in the file: the others are #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording, since a fresh instance does not carry the `forward` those rebind, and #197001's `names_forward_only` and `shares_a_hint_line`, which check the same).

## Mutations, summarized

| edit to `_no_match_report` | fails in the whole file |
| --- | --- |
| drop the SUPPLIED half of the gate (`if not tried_forward:`) | `resolves_forward_only_for_a_supplied_scope`, `resolves_no_forward_for_a_reconstructed_scope` (`failures=2`) |
| loosen the gate to `is not _GuardScope.CAPTURED` | `resolves_no_forward_for_a_reconstructed_scope` alone (`failures=1`) |
| gate on `i == 0 and ... is _GuardScope.SUPPLIED` | `resolves_forward_at_the_first_supplied_entry` alone (`failures=1`, `Expected 1 but got 0`) |
| move `tried_forward = True` inside the `try` | `resolves_forward_once_past_a_resolve_that_raises` alone (`failures=1`, `Expected 1 but got 2`) |
| resolve `type(self.model)()` instead of `self.model` | `resolves_forward_once_past_a_resolve_that_raises` plus four wording tests in #197048 and #197001 (`failures=5`) |

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_no_forward_for_a_reconstructed_scope
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_at_the_first_supplied_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_once_past_a_resolve_that_raises
python test/dynamo/test_aot_compile.py
```

## FAQ

> **FAQ: Every new test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the
> report the parent already ships, so every test passes on the parent's tree.
> The measurements that stand in for it are above: each test fails under the
> tree below the report commit, where no report exists, and each fails under a
> targeted edit of `_no_match_report` that no test outside this commit catches
> -- moving the `tried_forward` mark below the resolve fails only
> `resolves_forward_once_past_a_resolve_that_raises`, dropping the SUPPLIED
> gate only the two tests that assert no resolve at all, loosening it to
> `is not _GuardScope.CAPTURED` only
> `resolves_no_forward_for_a_reconstructed_scope`, and pinning it to `i == 0`
> only `resolves_forward_at_the_first_supplied_entry`.

> **FAQ: Why pin the resolve with call counts instead of the report's text?**
>
> Because the text is the same on both sides of each edit. The CAPTURED hint
> never names `forward`, so `resolves_forward_only` reads identically whether
> the resolve ran or not, and so does the rebuilt-scope hint for
> `resolves_no_forward_for_a_reconstructed_scope`; and after a resolve that
> raises, both entries get
> the neutral sentence whether the raise happened once or twice, so
> `resolves_forward_once` reads identically too. Both edits are visible only
> as extra calls into user code -- `get_traced_fn` formatting a `forward` it
> refuses -- which is what the report avoids, and what `patch(...,
> wraps=_resolve_guard_scope)` counts without changing what the report does.

> **FAQ: Why `try/finally` around the popped global rather than `addCleanup`?**
>
> Both forms are in this file and neither is a correctness difference: the pop
> is undone before the next test either way. `try/finally` keeps the restore
> beside the pop, so the whole window the name is missing in reads in one
> place, which is what these two tests are about. Rewriting them to
> `addCleanup` would change no measurement, so it is churn on a tests-only
> diff.

Authored with the assistance of Claude Code.

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

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

**Problem.** Loading an AOT-compiled module onto an instance whose `forward` is `torch.compile(mod.forward)` (or a `torch._dynamo.disable`, `run`, `optimize` or `wrap_top_frame` wrapper over it) refused the live guard scope, because the wrapper is a plain function whose `__globals__` is `torch._dynamo.eval_frame`'s namespace; every result fell back to the rebuilt scope and a kept guard on a user global then failed every call with `KeyError on G['CFG']` and advice the pattern cannot follow.

**Fix.** `_resolve_guard_scope` now resolves THROUGH Dynamo's own wrappers -- `innermost_fn` over the `_torchdynamo_orig_callable` chain, then one `__wrapped__` hop per function that owns `external_utils`' dict -- so the scope is the user forward's module and the load serves; a wrapper that reaches the module's dispatch rather than its forward is refused with a reason naming what was reached.

**Summary.** `_resolve_guard_scope` hands `model.forward` to `get_traced_fn`, takes the resolved function's `__globals__` as the live guard scope, and refuses a scope that is a torch module's namespace; the documented compile-a-method pattern, `mod.forward = torch.compile(mod.forward)`, binds eval_frame's `functools.wraps`'d `compile_wrapper`, a plain function that is neither an `OptimizedModule` nor an `nn.Module` and whose own `__globals__` is `torch._dynamo.eval_frame`'s namespace, so on the parent the torch-namespace rule refused it, every result was RECONSTRUCTED, and a kept guard on a user global failed every call with `KeyError on G['CFG']`. The fix resolves through the wrapper: `innermost_fn` follows the `_torchdynamo_orig_callable` chain the wrappers `torch.compile`, both `torch._dynamo.disable` forms, `run`, `optimize` and `optimize_assert` return, and a `while` loop then follows `__wrapped__` from any function whose `__globals__` IS `vars(external_utils)`, one hop per stacked compile, which is what `config.wrap_top_frame` or a `trace_rules.check` skip wraps the target in (`wrap_inline`'s inner). The predicate is the dict's identity read through `_static_getattr` (`object.__getattribute__`), not `__module__` (which `functools.wraps` copies) and not "defined under `torch._dynamo`" (the decorators' `wraps`'d wrappers are the root frame a capture traces, so hopping through them would disagree with it), and a bound method owns no `__globals__` for that read, so it is never hopped. What the hop reaches is re-checked: an `nn.Module` (the module's dispatch under `wrap_top_frame`) is refused with a new reason, a function torch itself defines (`Module._wrapped_call_impl`, `Linear.forward`) is refused by the namespace rule with "resolves through a Dynamo wrapper to" in its reason, a `functools.partial` or C-implemented bound method falls into the shared `try` and gets the cannot-resolve reason, and a wraps-less `external_utils` function (`error_on_graph_break`'s inner) ends the loop where it stands and is refused byte-identically to the parent. The only behaviour change is that the compiled-forward, disabled, `run`/`optimize`, `wrap_top_frame` (depth 1 and 2), user-decorator-over-compiled and instance-rebound `wrap_numpy` shapes go from refused to served with the forward's own module as the scope; every other shape is still refused, with the reason now naming the target the wrapper reached, and `inspect.unwrap` and a one-hop `_torchdynamo_orig_callable` read were rejected as alternatives on measured mismatches with what a capture records.

## The bug

```python
class M(torch.nn.Module):
    def forward(self, x): return x * CFG.scale        # CFG is a module global; keep_global_guards keeps a guard on it

mod = M()
mod.forward = torch.compile(mod.forward, backend="eager")   # the documented compile-a-method pattern
wrapper = torch.compile(mod, fullgraph=True, backend="eager")
wrapper._load_aot_compiled_module(data)
# parent: every result RECONSTRUCTED, warning logged, reason:
#   "M.forward (function named M.forward) resolves to M.forward, whose globals are
#    torch._dynamo.eval_frame's namespace ...; bind the module's own forward, defined outside torch, as model.forward instead"
# parent: wrapper(x) -> KeyError on G['CFG'] and a hint repeating that advice
# now:    SUPPLIED scope = M's module dict; wrapper(x) follows CFG live
```

`mod.forward = torch.compile(mod.forward)` binds a plain function on the instance: eval_frame's `functools.wraps`'d `compile_wrapper`. It is neither an `OptimizedModule` (so `_unwrap_optimized_module` does not see it) nor an `nn.Module` (so that refusal does not either), and its own `__globals__` is `torch._dynamo.eval_frame`'s namespace, so on the parent the torch-namespace rule refuses it. Because `functools.wraps` copied the qualname, the reason reads "M.forward (function named M.forward) resolves to M.forward, whose globals are torch._dynamo.eval_frame's namespace ...; bind the module's own forward, defined outside torch, as model.forward instead": every result is RECONSTRUCTED and the load logs the no-live-scope warning. A kept guard on a global that rebuilt scope does not carry then fails every call with `KeyError on G['CFG']` and a hint repeating that advice, which the pattern cannot follow (the module's own forward is what was bound); a kept guard on a global the graph lifted compares against the serialized value and cannot fail, so the call answers with the captured value. Nothing is seeded into eval_frame's dict. `torch._dynamo.disable` (both wrappers), `torch._dynamo.run`, `optimize` and `config.wrap_top_frame` stacks are refused the same way, naming eval_frame's or `external_utils`' namespace. The capture side cannot produce any of these shapes (tracing a `compile_wrapper` dies on `set_eval_frame`), so this is a load-side mismatch only.

## The fix: resolve through the wrapper

```python
# _resolve_guard_scope, now
from torch._dynamo.eval_frame import _static_getattr, innermost_fn

forward = model.forward
described = ...                                   # describes forward AS GIVEN, not what the hop reaches
resolved = innermost_fn(forward)                  # follows the _torchdynamo_orig_callable chain
while _static_getattr(resolved, "__globals__") is vars(external_utils):
    wrapped = _static_getattr(resolved, "__wrapped__")
    if wrapped is None:
        break                                     # a wraps-less external_utils function ends the loop where it stands
    resolved = wrapped                            # one hop per stacked compile
if isinstance(resolved, torch.nn.Module):
    return None, f"{described} resolves through a Dynamo wrapper to an nn.Module, the module's dispatch rather than its forward; ..."
try:
    traced_fn = convert_frame.get_traced_fn(resolved)[0]   # parent: get_traced_fn(forward)
    scope = traced_fn.__globals__
except (RuntimeError, AttributeError):
    return None, <the parent's cannot-resolve reason>
namespace = _module_namespace_name(scope)
if namespace is not None and namespace.partition(".")[0] == "torch":
    via = "resolves through a Dynamo wrapper to" if resolved is not forward else "resolves to"
    return None, f"{described} {via} {traced_fn.__qualname__}, whose globals are {namespace}'s namespace, ..."
return scope, None
```

`innermost_fn` runs on a non-Module forward before `get_traced_fn`: it is what `_TorchDynamoContext.__call__` runs on everything it compiles, follows the `_torchdynamo_orig_callable` chain by `_torchdynamo_wrapper_id == id(fn)` and so stops at a wrapper Dynamo did not mint, and covers both disable wrappers, `run`, `optimize` and `optimize_assert`, which set the same pair.

That is not always the user's forward: when the compile wrapped its target in `external_utils.wrap_inline` (`config.wrap_top_frame`, or `trace_rules.check` true for a forward DEFINED under `torch/`), the chain ends on `wrap_inline`'s inner, a `functools.wraps` copy of the bound method that carries neither `_torchdynamo_orig_callable` nor a matching wrapper id. `inner` only calls the forward it wraps, and the module capture (`aot_compile_module` -> `aot_compile_fullgraph` on `model.forward`) never wraps, so the load follows `__wrapped__` while the resolved function OWNS `external_utils`' dict as its `__globals__`, one hop per stacked compile.

```python
# test_aot_compile_module_deserialize_unwraps_a_wrap_inline_forward, depth=2
with torch._dynamo.config.patch(wrap_top_frame=True):
    mod.forward = torch.compile(mod.forward, backend="eager")
    mod.forward = torch.compile(mod.forward, backend="eager")
resolved = innermost_fn(mod.forward)
# chain: [("inner", vars(external_utils)), ("inner", vars(external_utils))], then the bound forward
```

**The predicate.** It is that dict's identity, not "defined under `torch._dynamo`": `functools.wraps` copies `__module__`, so `inner` reports the forward's; and `torch._dynamo.decorators`' `wraps`'d wrappers (`nonstrict_trace`, `leaf_function`) are what the capture traces as its root frame, so hopping through them would disagree with it. The reads go through eval_frame's `_static_getattr`, which is `object.__getattribute__`: a bound method's `__globals__` is supplied by `method_getattro`'s delegation to `__func__`, not by the generic slot, so a bound method is never hopped (measured: `object.__getattribute__(bound, "__globals__")` raises `AttributeError` while `bound.__globals__` answers).

## What the hop can land on

**A wraps-less `external_utils` function.** One that carries no `__wrapped__` ends the loop where it stands, since the hop cannot reach the forward it stands in front of: `wrap_dunder_call_ctx_manager`'s inner, which `error_on_graph_break`, `patch_dynamo_config`, `disable_nested_graph_breaks` and `override_cudagraphs` all bind (measured: each yields a function of that qualname owning `external_utils`' dict with no `__wrapped__`), skips `functools.wraps` on purpose. Here it falls through to the namespace rule, which refuses it exactly as the parent does -- "inner resolves to inner, whose globals are torch._dynamo.external_utils's namespace ...; bind the module's own forward, defined outside torch" (byte-identical to the parent's reason; the forward in `inner`'s closure IS defined outside torch, so that advice is one the shape had already followed) -- and the commit above gives the shape its own reason.

**An `nn.Module`.** The `nn.Module` refusal then runs again on what the hop reached: under `config.wrap_top_frame` or a skip rule, `torch.compile(mod).forward` wraps the module itself (`OptimizedModule._initialize` hands it to `wrap_inline`), the module's dispatch rather than its forward, and without this refusal `get_traced_fn`'s Module branch would resolve that module to its forward and serve the dispatch shape.

```python
# test_aot_compile_module_deserialize_refuses_a_compiled_module_forward
with torch._dynamo.config.patch(wrap_top_frame=wrap_top_frame):
    inst.forward = torch.compile(inst, backend="eager").forward
# wrap_top_frame=True:  innermost_fn(...).__wrapped__ is inst -> "... resolves through a Dynamo wrapper to an nn.Module,
#                       the module's dispatch rather than its forward; bind that module's forward, or a wrapper over the
#                       forward rather than over the module, as model.forward instead"
# wrap_top_frame=False: innermost_fn(...) == inst.__call__ -> "... resolves through a Dynamo wrapper to Module._wrapped_call_impl,
#                       whose globals are torch.nn.modules.module's namespace, ..."
```

**A target `get_traced_fn` cannot resolve.** `get_traced_fn` and the `__globals__` read share one `try` -- `RuntimeError` for a callable that is neither function nor method (a hopped-to `functools.partial`), `AttributeError` for a C-implemented bound method (`torch.compile(t.sum)` hops to the builtin, whose `__func__` read raises) -- and the `except` returns the parent's cannot-resolve reason, which describes the forward as given ("get_traced_fn cannot resolve M.forward (function named wrap_inline.<locals>.inner) to a Python function; make model.forward a plain function or bound method"); for a hopped-to target that advice describes the `compile_wrapper`, a plain function that resolves fine, and the commit above names what the wrapper reached instead.

**A torch-defined function.** The torch-namespace reason says "resolves through a Dynamo wrapper to" when the hop was taken (`test_aot_compile_module_deserialize_hops_to_a_compiled_torch_forward`: `Linear.forward (function named Linear.forward) resolves through a Dynamo wrapper to Linear.forward, whose globals are torch.nn.modules.linear's namespace`, refused silently since the artifact roots no guard at a user global).

`innermost_fn`'s `AssertionError` on a non-callable `_torchdynamo_orig_callable` is not caught: every Dynamo site that sets the pair on a function checks `callable(fn)` first, and the `OptimizedModule` sites sit behind the as-given `nn.Module` refusal.

## Behaviour against the parent, per forward shape

"Refused" = `(None, reason)`, RECONSTRUCTED, no match at call for every kept guard on a global the rebuilt scope lacks; "served" = SUPPLIED with the named dict, guards re-read there, `__import_*` aliases seeded there.

| forward shape | parent | now |
| --- | --- | --- |
| `torch.compile(mod.forward)`, `torch._dynamo.run` / `optimize`, both `torch._dynamo.disable` wrappers, `config.wrap_top_frame` stacks of depth 1 and 2, `torch.compile(user_deco(mod.forward))`, `mod.forward = torch.compiler.wrap_numpy(mod.forward)` | refused (eval_frame's or external_utils' namespace) | served, the dict of the forward the wrapper wraps (the user module's; the decorator's module for `user_deco`, which is what a capture of that shape records). **The only behaviour change.** |
| `torch.compile(nn.Linear(..).forward)` | refused | refused; the reason now names `Linear.forward` in `torch.nn.modules.linear` instead of eval_frame |
| `inst.forward = torch.compile(inst).forward` | refused | refused; the reason now names `Module._wrapped_call_impl` (`wrap_top_frame` off) or "an nn.Module, the module's dispatch" (`wrap_top_frame` on) instead of eval_frame |
| `torch.compile(functools.partial(...))`, `torch.compile(x.sum)` | refused ("inner resolves to inner" / "Tensor.sum resolves to Tensor.sum, whose globals are eval_frame's namespace", measured) | refused; the reason is now the cannot-resolve one, since `get_traced_fn` fails on the partial / builtin the hop reached. Its advice describes the `compile_wrapper`; the commit above names the reached target |
| `torch._dynamo.error_on_graph_break(True)(mod.forward)` and the other three `wrap_dunder_call_ctx_manager` binders, a class-body `@torch.compiler.wrap_numpy` forward, `mod.forward = inst.__call__` after `torch.compile(Cls)`, `torch.compile(LazyLinear).forward`, `mod.forward = other.__call__`, an `nn.Module` bound as forward, an un-hopped builtin | refused | unchanged, byte-identical reason (measured). A bound method owns no `__globals__`, so the hop leaves it alone, and the wraps-less inner is left where it stands. The first three are reworded by the commit above |

## The instance-rebound `wrap_numpy` hop

The instance-rebound `wrap_numpy` hop is the one place the load sees through a wrapper the caller applied, and the class docstring says so inline: `wrap` is a plain function owning `external_utils`' dict and a `__wrapped__`, so it is hopped to the bound method, which a capture of that shape (root frame `wrap`) would not record. No such artifact exists -- `wrap`'s closure holds the bound method and with it the module instance, which `serialize` refuses -- and the one loadable combination, an artifact captured from the undecorated forward loaded onto that shape, resolves the user module, which is what that capture recorded. The `other.__call__` shape stays refused although a capture of it did record `nn.Module`'s namespace: accepting would seed a process-wide torch namespace, and a same-shape artifact still reports no match on its self guard.

## Two shorter unwraps, rejected

Both were rejected on measured behaviour.

- `inspect.unwrap` follows every `functools.wraps` chain, including a user decorator, but the capture traces the outermost plain function and records its `__globals__` as the scope (for `mod.forward = user_deco(mod.forward)` that is the decorator's module), so it would mismatch the capture for exactly that shape.
- A one-hop `getattr(forward, "_torchdynamo_orig_callable", forward)` is defeated by the same `wraps`: the copied `__dict__` carries `_torchdynamo_orig_callable`, so one hop jumps past a user wrapper over a compiled forward to the bound method, and a nested `torch.compile(torch.compile(f))` stays in eval_frame after one hop.

## The `deserialize` docstring

The docstring states the rule -- the function `model.forward` resolves to is the one bound as `forward` seen through the wrappers `torch.compile`, `torch._dynamo.disable`, `run`, `optimize` and `optimize_assert` return and through any function DEFINED IN `external_utils` that carries `__wrapped__` -- and flags the caller-applied exception inline, where the rule is stated ("of which torch.compiler.wrap_numpy and torch._dynamo.disable(recursive=False) are the two a caller applies -- but not through any other wrapper the caller applied"), so no sentence is false until a later one corrects it; the sentence after the rule gives `wrap_numpy`'s two forms, the forward's own module when rebound on the instance and a refused `external_utils` namespace when applied in the class body, where it binds a method that is not seen through. The docstring's list of no-live-scope causes gains the wraps-less `external_utils` function, the post-hop `nn.Module` and the hopped-target paths, each of which this commit refuses. The SUPPLIED no-match hint is untouched: it still says the guards hold the globals of "the function this <Type> instance's forward resolves to, since that is the one the load resolved", true of the resolution but silent about the wrapper it went through; the commit above sends it through too. The fallback reasons keep the shape-specific advice `_missing_global_hint` already splices after "rebuilt because" (pre-existing).

## Tests

Five new tests, eight cases with parametrization, each described under the Test Plan with the mutations that fail it:

- `test_aot_compile_module_deserialize_unwraps_a_compiled_forward`: the served result for `mod.forward = torch.compile(mod.forward)`, the SUPPLIED scope being this module's dict, and eval_frame's namespace gaining nothing.
- `test_aot_compile_module_deserialize_unwraps_a_wrap_inline_forward` (depth 1, 2): the same under `wrap_top_frame`, pinning the `("inner", vars(external_utils))` chain per stacked compile.
- `test_aot_compile_module_deserialize_unwraps_a_disabled_forward` (recursive True, False): the same for both disable wrappers, recording which mechanism reaches the bound method first.
- `test_aot_compile_module_deserialize_refuses_a_compiled_module_forward` (wrap_top_frame False, True): the two dispatch reasons, and that `vars(torch.nn.modules.module)` gains nothing.
- `test_aot_compile_module_deserialize_hops_to_a_compiled_torch_forward`: the hop lands on `Linear.forward`, refused silently since it reads no user global.

Test Plan:

Five new tests, 8 cases with parametrization, all failing with the parent's
aot_compile.py (`git show <parent>:torch/_dynamo/aot_compile.py` checked out
under this commit's test file: 5 errors, 3 failures). The five served-shape
cases error there with `No AOT compiled graph matched` (the refused load
rebuilt the scope, which lacks GLOBAL_POOLING_CONFIG); the three reason-text
cases fail on the reason string.
`..._deserialize_unwraps_a_compiled_forward` rebinds `mod.forward =
torch.compile(mod.forward)` and loads through `_load_aot_compiled_module`,
pinning the served result, the SUPPLIED scope being this module's dict and
eval_frame's namespace gaining nothing (a fence; the parent seeds nothing
either); `..._unwraps_a_wrap_inline_forward` (depth 1, 2) and
`..._unwraps_a_disabled_forward` (recursive True, False) pin the same for
those shapes and the wrapper chain they resolve through;
`..._deserialize_refuses_a_compiled_module_forward` (wrap_top_frame False,
True) pins the two dispatch reasons and that vars(torch.nn.modules.module)
gains nothing; `..._deserialize_hops_to_a_compiled_torch_forward` pins that
the hop lands on Linear.forward, refused silently since it reads no user
global.

Mutations at this commit, each run over the 8 cases the -k patterns below
select: with the hop's `while` made a single `if` (one hop) the depth_2
wrap_inline case reports no match and
`..._refuses_a_compiled_module_forward_wrap_top_frame_True` fails on the
reason (one hop lands on the second wrap_inline inner, in external_utils'
namespace; _initialize wraps the module, then __call__ wraps that inner);
with the post-hop nn.Module refusal removed only
`..._refuses_a_compiled_module_forward_wrap_top_frame_True` fails, on the
reason; with innermost_fn dropped (`resolved = forward`, hop kept) 7 of the
8 fail as on the parent and `..._unwraps_a_disabled_forward_recursive_False`
passes, because that wrapper owns external_utils' dict and carries
__wrapped__, so the hop alone reaches the bound method.

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

The full file reports `OK (skipped=6)` (311 tests).

> **FAQ: The `recursive` parametrization of `..._unwraps_a_disabled_forward`
> is over-determined: deleting `resolved = innermost_fn(forward)` from
> `_resolve_guard_scope` fails `recursive_True` only, because the non-recursive
> wrapper owns external_utils' dict and carries `__wrapped__`, so the hop
> rescues it; and the assertion that isolates the mechanism calls
> `eval_frame.innermost_fn` directly, a contract test for that function.**
>
> Both measured and both kept. The `recursive_False` case is not there to
> isolate a mechanism; it pins the served result for the one shape whose
> wrapper is an external_utils function that ALSO carries the
> `_torchdynamo_orig_callable` pair, which no other served case has, so a
> regression in either mechanism's handling of that shape would show here
> first. The case also pins `mod.forward.__wrapped__ == bound_forward`, which
> states that the hop would fire. The `innermost_fn(mod.forward) ==
> bound_forward` assertion records
> which mechanism reaches the bound method first (measured: with `innermost_fn`
> mutated to stop on external_utils-owned wrappers, `recursive_False` fails on
> that assertion and, with it removed, passes on the hop); the test's comment
> says that, and that only `recursive_True` catches a load that drops
> `innermost_fn`. Making the case discriminate against that mutation would
> mean asserting the hop did NOT fire, which is not a property the load has or
> should promise.

> **FAQ: `mod.forward = other.__call__` resolves to `Module._wrapped_call_impl`
> with no Dynamo wrapper in front, and a capture of that same shape records
> `vars(torch.nn.modules.module)` as `_extra_globals`. Why refuse a dict the
> capture agreed on?**
>
> Because accepting it seeds a process-wide torch namespace, and buys nothing:
> measured, a same-shape artifact (root frame `_wrapped_call_impl`, kept guards
> rooted at `G['_global_forward_hooks']` and `G['__import_npmod2']`) loaded onto
> a fresh `m.forward = other.__call__` module with
> `guard_globals=vars(torch.nn.modules.module)` still reports no match on every
> call -- the capture traced `other` as `self`, so its guard `not
> ___dict_contains('forward', L['self'].__dict__)` fails against the loaded
> model, whose `__dict__` carries the rebind. The refusal costs nothing served
> and keeps `__import_*` aliases and the `__builtins_dict___N` key out of
> nn.Module's dict;
> `test_aot_compile_module_deserialize_refuses_a_bound_module_call_forward` pins
> the shape one commit up (#197319); the refusal and the comment stating the
> tradeoff are here, and measured at this commit the shape is refused naming
> `torch.nn.modules.module`'s namespace.

> **FAQ: The comment says a `torch.compiler.wrap_numpy` forward is not hopped
> because a bound method owns no `__globals__`. An instance rebind `mod.forward
> = wrap_numpy(mod.forward)` stores the plain function `wrap`, which owns
> `vars(external_utils)` and `__wrapped__`, so it IS hopped -- and a capture of
> that shape records `external_utils`. Is that a live capture/load
> disagreement?**
>
> Real at the resolution level, unreachable end to end, so the comment now
> states both halves precisely and the hop is unchanged. Measured: the capture
> of the rebound shape records `_extra_globals = torch._dynamo.external_utils`
> (root code `wrap`) while `_resolve_guard_scope` on the same shape resolves the
> user module through one hop. But `_save_aot_compiled_module` on that capture
> raises `Failed to serialize the following objects: [PlainNp()]` -- `wrap`'s
> closure holds the bound method and with it the module instance -- so no such
> artifact exists. A class-body `@wrap_numpy` capture serializes but no load of
> it gets as far as the scope: `deserialize` dies in GraphPickler (`module
> 'torch._dynamo.utils' has no attribute 'wrapped_sum'`). The one loadable
> combination, an artifact captured from the undecorated forward loaded onto the
> instance-rebound shape, resolves the user module, which is exactly what that
> capture recorded, and serves. Stopping the hop on `wrap` (matching
> `wrap_inline`'s inner by code identity) would make THAT case disagree instead,
> for a shape nothing can observe.

> **FAQ: Is `resolved: Any` needed for pyrefly?**
>
> No; it was dropped. `lintrunner --take PYREFLY --
> torch/_dynamo/aot_compile.py` at this commit reports the identical set of
> eight pre-existing `_torch_function_state` missing-attribute diagnostics with
> and without the annotation. `innermost_fn` returns `Callable[..., Any]` and
> `_static_getattr` returns `Any`, so the `__wrapped__` reassignment already
> type-checks.

> **FAQ: The `torch.compile(torch.nn.Linear(8, 3))` test used to pin the load
> resolving `vars(torch.nn.modules.linear)` as the SUPPLIED scope; now it pins a
> refusal. Why did the behaviour change?**
>
> The introducing commit below now refuses any resolution whose `__globals__` is
> a torch module's live namespace, so a torch-defined forward is refused after
> the hop lands on it. The test
> (`..._deserialize_hops_to_a_compiled_torch_forward`) still proves what it was
> for -- the hop lands on `Linear.forward` and not on external_utils' inner,
> which the reason names -- and additionally pins that the fallback is silent:
> `Linear.forward` reads only torch's own globals, `_has_global_guards` is False
> under both filters, the call answers, and external_utils' namespace gains
> nothing.

> **FAQ: Why drop the `AssertionError` arm instead of giving it a reason?**
>
> Measured unreachable from any Dynamo-minted wrapper:
> `eval_frame.py:1337`/`:1571` and `decorators.py:119` set
> `_torchdynamo_orig_callable` only after `callable(fn)` passed, and the
> OptimizedModule sites (`eval_frame.py:1062`, `:1500`) are only reached when
> forward is an OptimizedModule, which the nn.Module refusal returns before
> `innermost_fn`. A hand-stamped pair now raises `innermost_fn`'s own
> `AssertionError` ("A callable function is expected, but <class 'int'> is
> provided") rather than a reason blaming `get_traced_fn`, which was never
> called.

> **FAQ: Is the fourth dispatch shape (`torch.compile(Cls)` rebinding
> `Cls.__call__`) pinned?**
>
> Yes, bound directly as `mod.forward = inst.__call__`
> (`test_aot_compile_module_deserialize_refuses_a_class_compiled_call_forward`,
> one commit up in #197319; measured here, the shape is refused with the
> torch-namespace reason naming `torch._dynamo.eval_frame`, byte-identical to
> the parent's). The reviewer's
> route `torch.compile(inst)` after `torch.compile(Cls)` raises `compile_wrapper
> already has a get_compiler_config attribute` in eval_frame, and
> `torch.compile(OptimizedModule)` does not re-wrap `__call__` (`innermost_fn`
> unwraps it to `_orig_mod.forward`), so neither is reachable;
> `torch._dynamo.disable(inst).forward` is refused the same way (measured).

> **FAQ: A previous revision of this PR returned three shape-specific reasons
> that this one does not -- the wraps-less external_utils function's own
> reason, a hopped-to target's own cannot-resolve reason, and the
> `co_qualname` naming of a `functools.wraps`'d wrapper. Were they dropped?**
>
> No: this commit was split in two, and all three, with the tests that pin
> them (`..._refuses_a_targetless_dynamo_wrapper`,
> `..._refuses_a_class_body_wrap_numpy_forward`,
> `..._refuses_a_class_compiled_call_forward`,
> `..._fallback_names_a_compiled_partial_forward`,
> `..._fallback_names_a_compiled_builtin_forward` and the three
> `..._hint_sees_through_a_wrapped_rebound_forward` cases), are the commit
> directly above, #197319. Measured at this commit against its parent, nothing
> served changes and no reason regresses:
> `error_on_graph_break(True)(mod.forward)`, a class-body
> `@torch.compiler.wrap_numpy` forward and `mod.forward = inst.__call__` after
> `torch.compile(Cls)` are refused with reasons byte-identical to the
> parent's, and `torch.compile(functools.partial(...))` /
> `torch.compile(x.sum)` are refused with the cannot-resolve text where the
> parent said "inner resolves to inner" / "Tensor.sum resolves to Tensor.sum"
> -- neither names the target the hop reached, which is what the commit above
> adds.

> **FAQ: The docstring's no-live-scope list names a
> `torch._dynamo.external_utils` function with no `__wrapped__` and a target
> reached by the hop that does not resolve itself, but this commit has no
> branch for either: the first falls through to the namespace rule and the
> second shares the cannot-resolve reason. Is the list wrong?**
>
> No -- it enumerates the causes of there being no live scope, not the reason
> strings, and both hold here (measured:
> `error_on_graph_break(True)(mod.forward)` is refused naming external_utils'
> namespace, and a hopped-to `functools.partial` is refused because
> `get_traced_fn` raises on it). Each cause is one the caller can act on;
> which of them gets a reason of its own is the commit above.

> **FAQ: Nothing in `test_aot_compile.py` mentions `wrap_numpy` at this
> commit, yet the docstring makes two claims about it.**
>
> The class-body arm is pinned one commit up by
> `..._deserialize_refuses_a_class_body_wrap_numpy_forward` (#197319);
> measured here, that shape is refused with the parent's reason. The arm that
> rebinds on the instance has no end-to-end test because no artifact reaches
> it --
> `serialize` refuses `wrap`'s closure, which holds the module instance, and a
> class-body capture dies in GraphPickler, both measured in the FAQ above --
> so the only half that could be asserted is a direct `_resolve_guard_scope`
> call on a shape no load can use.

This commit was authored with the assistance of an AI coding assistant.

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

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

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

**Problem.** #196908 taught the module load to resolve `model.forward` through Dynamo's own wrappers, but left three refusal messages describing the forward as if no wrapper were there (one even gave advice the shape had already followed, another attributed the wrong namespace) and left the missing-global hint silent about the wrapper the load saw through.

**Fix.** Wording only: refuse a wraps-less `external_utils` function with its own reason naming the decorators that produce it, name what a hopped wrapper reached when `get_traced_fn` cannot resolve it, name a `functools.wraps`'d wrapper by its code object instead of the copied `__qualname__`, and make the hint say the forward is seen through those wrappers. No shape flips between served and refused.

**Summary.** The commit below resolves `model.forward` through Dynamo's own wrappers (`innermost_fn`, then one `__wrapped__` hop per `external_utils`-owned function) but leaves three refusals describing the forward as the parent did, and leaves the SUPPLIED no-match hint silent about the wrapper the load went through. This commit changes wording only: no shape flips between served and refused (measured: `_resolve_guard_scope` returns None for the same shapes before and after, with the same scope for the served ones). A wraps-less `external_utils` function -- the `inner` that `error_on_graph_break`, `patch_dynamo_config`, `dont_skip_tracing`, `disable_nested_graph_breaks` and `override_cudagraphs` bind -- is refused with its own reason instead of falling through to the namespace rule, which rendered "inner resolves to inner ...; bind the module's own forward, defined outside torch", advice the shape had already followed; a hop that reaches something `get_traced_fn` cannot resolve (a `functools.partial` or a C-implemented bound method under `torch.compile`) names what the wrapper reached instead of advising "make model.forward a plain function or bound method", which described the `compile_wrapper`, a plain function that resolves fine. The torch-namespace reason names a function carrying a `__wrapped__` by its code object (`co_qualname`, falling back to `co_name`), because `functools.wraps` copied the wrappee's `__qualname__` onto it and the copied name would read "M.forward resolves to M.forward" or, worse, attribute the wrapper's namespace to the wrappee. The SUPPLIED hint now says the forward is seen "through the wrappers torch.compile, torch._dynamo.disable, run and optimize return and through any functools.wraps'd torch._dynamo.external_utils function to the function they wrap", the rule the `deserialize` docstring already states, so a reader is not sent to define the name in the wrapper's namespace, where it restores nothing.

## The wraps-less `external_utils` function

```python
# _resolve_guard_scope, the hop loop
while _static_getattr(resolved, "__globals__") is vars(external_utils):
    wrapped = _static_getattr(resolved, "__wrapped__")
    if wrapped is None:
        # parent: break, then fall through to the namespace rule
        hopped = resolved is not forward
        via = "resolves through a Dynamo wrapper to" if hopped else "is"
        return None, (
            f"{described} {via} a torch._dynamo.external_utils function with "
            "no __wrapped__ to see through to the forward it wraps -- the "
            "wrapper torch._dynamo.error_on_graph_break, patch_dynamo_config, "
            "dont_skip_tracing, disable_nested_graph_breaks and "
            "override_cudagraphs return skips functools.wraps; bind the "
            "forward that decorator wrapped as model.forward instead"
        )
    resolved = wrapped
```

`wrap_dunder_call_ctx_manager`'s inner, which `error_on_graph_break`, `patch_dynamo_config`, `dont_skip_tracing`, `disable_nested_graph_breaks` and `override_cudagraphs` all bind (measured: each yields a function of that qualname owning `external_utils`' dict with no `__wrapped__`), skips `functools.wraps` on purpose, as does `wrap_inline_with_error_on_graph_break`'s wrapper, which only ever lives on `compile_wrapper._torchdynamo_inline`, an attribute `innermost_fn` does not follow, so no public API binds it as a forward. The namespace rule rendered "inner resolves to inner ...; bind the module's own forward, defined outside torch", because `described` and `traced_fn` are the same un-wraps'd function and the forward in inner's closure IS defined outside torch, so the advice was one the shape had already followed.

```python
mod.forward = torch._dynamo.error_on_graph_break(True)(mod.forward)
# parent: GlobalConfigModule.forward (function named wrap_dunder_call_ctx_manager.<locals>.inner)
#         resolves to wrap_dunder_call_ctx_manager.<locals>.inner, whose globals are
#         torch._dynamo.external_utils's namespace ...; bind the module's own forward, defined outside torch
# now:    GlobalConfigModule.forward (function named wrap_dunder_call_ctx_manager.<locals>.inner) is a
#         torch._dynamo.external_utils function with no __wrapped__ to see through to the forward it
#         wraps -- the wrapper torch._dynamo.error_on_graph_break, patch_dynamo_config, dont_skip_tracing,
#         disable_nested_graph_breaks and override_cudagraphs return skips functools.wraps; bind the
#         forward that decorator wrapped as model.forward instead
```

The reason now describes the function as what it is, names the decorators that return such a wrapper, and advises binding the forward that decorator wrapped, which is where the user's forward actually is. It says "resolves through a Dynamo wrapper to" instead of "is" when `innermost_fn` or an earlier hop moved before the loop stopped.

## What a hopped wrapper reached

```python
try:
    traced_fn = convert_frame.get_traced_fn(resolved)[0]
    scope = traced_fn.__globals__
except (RuntimeError, AttributeError):
    if resolved is forward:                       # the un-hopped shape keeps the parent's reason
        return None, (f"get_traced_fn cannot resolve {described} to a Python function; "
                      "make model.forward a plain function or bound method so its own "
                      "globals are used instead")
    return None, (
        f"{described} resolves through a Dynamo wrapper to an instance of "
        f"{type(resolved).__name__}, which get_traced_fn cannot resolve to "
        "a Python function; bind a plain function or bound method as "
        "model.forward instead"
    )
```

When the hop reached something `get_traced_fn` cannot resolve -- `RuntimeError` for a callable that is neither function nor method (`torch.compile` over a `functools.partial` wraps it in `wrap_inline`, so the hop lands on the partial), `AttributeError` for a C-implemented bound method (`torch.compile(t.sum)` hops to the builtin, whose `__func__` read raises) -- the reason names what the wrapper reached. The cannot-resolve advice the commit below returned for both, "make model.forward a plain function or bound method", described the `compile_wrapper`, a plain function that resolves fine; the un-hopped builtin, bound as forward directly, keeps it.

```python
mod.forward = torch.compile(functools.partial(GlobalConfigModule.forward, mod), backend="eager")
# now: GlobalConfigModule.forward (function named wrap_inline.<locals>.inner) resolves through a
#      Dynamo wrapper to an instance of partial, which get_traced_fn cannot resolve to a Python
#      function; bind a plain function or bound method as model.forward instead
mod.forward = torch.compile(x.sum, backend="eager")
# now: ... (function named Tensor.sum) resolves through a Dynamo wrapper to an instance of
#      builtin_function_or_method, which get_traced_fn cannot resolve ...
mod.forward = x.sum
# unchanged: cannot resolve GlobalConfigModule.forward (builtin_function_or_method named Tensor.sum)
#            to a Python function; make model.forward a plain function or bound method ...
```

## A wraps'd wrapper, named by its code object

```python
what = traced_fn.__qualname__
wrapped = _static_getattr(traced_fn, "__wrapped__")
code = _static_getattr(traced_fn, "__code__")
if wrapped is not None and code is not None:
    what = (f"{getattr(code, 'co_qualname', code.co_name)}, a functools.wraps'd "
            f"wrapper over {getattr(wrapped, '__qualname__', what)}")
return None, (f"{described} {via} {what}, whose globals are {namespace}'s namespace, "
              "a torch module a load neither roots guards in nor seeds; bind the ...")
```

The torch-namespace reason names the function it refuses by its code object when that function carries a `__wrapped__`: `functools.wraps` copied the wrappee's `__qualname__` onto it, so the copied name would read "M.forward resolves to M.forward" (a class-body `torch.compiler.wrap_numpy` forward is a bound method of `external_utils`' `wrap`; `torch.compile(Cls)` rebinds `Cls.__call__` to a `compile_wrapper` over `Module._wrapped_call_impl`) or, worse, attribute the wrapper's namespace to the wrappee. Such a function is named "<co_qualname>, a functools.wraps'd wrapper over <wrappee qualname>"; `co_qualname` is 3.11+ and falls back to `co_name`, the convention this file already uses for the dropped-attribute warning. That code object is read with `_static_getattr`, like the `__wrapped__` probe above it, so a forward carrying one and not the other keeps the plain-qualname wording instead of raising (measured: a carrier with `__globals__`, `__wrapped__` and `__qualname__` but no `__code__` is refused by name here, where a plain `traced_fn.__code__` read raises `AttributeError` on it).

```python
class NumpyForwardModule(torch.nn.Module):
    @torch.compiler.wrap_numpy
    def forward(self, x): return x.sum(1)
# parent: NumpyForwardModule.forward (method named NumpyForwardModule.forward) resolves to
#         NumpyForwardModule.forward, whose globals are torch._dynamo.external_utils's namespace ...
# now:    ... resolves to wrap_numpy.<locals>.wrap, a functools.wraps'd wrapper over
#         NumpyForwardModule.forward, whose globals are torch._dynamo.external_utils's namespace ...

torch.compile(Compiled, backend="eager"); mod.forward = Compiled().__call__
# parent: ... resolves to Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's
#         namespace   (false: _wrapped_call_impl's globals are torch.nn.modules.module's)
# now:    ... resolves to _TorchDynamoContext.__call__.<locals>.compile_wrapper, a functools.wraps'd
#         wrapper over Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's namespace
```

## The SUPPLIED hint follows the resolution

```python
# _missing_global_hint
where = (
    # parent: f"the globals of the function {forward} resolves to, which is the dict the guards hold{named}"
    f"the globals of the function {forward} resolves to, seen through "
    "the wrappers torch.compile, torch._dynamo.disable, run and "
    "optimize return and through any functools.wraps'd "
    "torch._dynamo.external_utils function to the function they wrap, "
    f"which is the dict the guards hold{named}"
    if forward is not None
    else f"the live scope this artifact was loaded against{named}"
)
```

The hint said the guards hold the globals of "the function this <Type> instance's forward resolves to, since that is the one the load resolved", which for `mod.forward = torch.compile(mod.forward)` would name `compile_wrapper`. It now names the wrappers `innermost_fn` follows (every `_TorchDynamoContext` subclass sets the pair: `OptimizeContext` for `optimize`, `RunOnlyContext` for `run`, `DisableContext` for `disable`) and the hop's predicate, so it neither claims decorators' wrappers (`nonstrict_trace`, `leaf_function`, `substitute_in_graph`: not crossed, refused as torch namespaces) nor omits `wrap_numpy` (crossed, `external_utils`' `wrap`). This is the rule the `deserialize` docstring already states, in the same terms. The fallback reasons keep the shape-specific advice `_missing_global_hint` already splices after "rebuilt because" (pre-existing).

```python
inst.forward = torch.compile(inst.forward, backend="eager")   # or torch._dynamo.disable(..., recursive=...)
reloaded._load_aot_compiled_module(data); reloaded(x)
# [0] KeyError on G['AOT_HERMETIC_WEIGHT'] ... this HermeticModule instance's forward resolves to,
# seen through the wrappers torch.compile, torch._dynamo.disable, run and optimize return and through
# any functools.wraps'd torch._dynamo.external_utils function to the function they wrap, which is the
# dict the guards hold
inst.forward.__globals__["AOT_HERMETIC_WEIGHT"] = saved      # the wrapper's namespace: restores nothing
globals()["AOT_HERMETIC_WEIGHT"] = saved                     # the resolved function's: served
```

## Behaviour vs the commit below, per forward shape

Every shape is refused there and here; only the reason text moves.

| forward shape | commit below | this commit |
| --- | --- | --- |
| `torch._dynamo.error_on_graph_break(True)(mod.forward)` and the other four `wrap_dunder_call_ctx_manager` binders | "inner resolves to inner ...; bind the module's own forward, defined outside torch", advice the shape had already followed | an `external_utils` function with no `__wrapped__`; names those decorators; advises binding the forward the decorator wrapped |
| a class-body `torch.compiler.wrap_numpy` forward | "M.forward resolves to M.forward, whose globals are torch._dynamo.external_utils's namespace" | "resolves to wrap_numpy.<locals>.wrap, a functools.wraps'd wrapper over M.forward, whose globals are torch._dynamo.external_utils's namespace" |
| `mod.forward = inst.__call__` after `torch.compile(Cls)` | "Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's namespace" -- false, `_wrapped_call_impl`'s globals are `torch.nn.modules.module`'s | "_TorchDynamoContext.__call__.<locals>.compile_wrapper, a functools.wraps'd wrapper over Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's namespace" |
| `torch.compile(functools.partial(...))`, `torch.compile(x.sum)` | "get_traced_fn cannot resolve ... to a Python function; make model.forward a plain function or bound method" | names the `partial` / `builtin_function_or_method` the wrapper reached |
| no-match hint for a served-through-a-wrapper forward whose guarded global is missing | names the function the forward resolves to | names the wrappers the load saw through |
| `torch.compile(LazyLinear).forward`, `mod.forward = other.__call__`, an un-hopped builtin, every served shape | unchanged | byte-identical reason or scope |

A bound method owns no `__globals__`, so the hop leaves it alone, and none of the unchanged shapes resolve to a wraps'd function.

## Tests

- `test_no_match_message_hint_sees_through_a_wrapped_rebound_forward` (`compile`, `disable`, `disable_nonrecursive`) pins the hint's wording and that defining the name in the wrapper's namespace restores nothing.
- `test_aot_compile_module_deserialize_refuses_a_targetless_dynamo_wrapper` pins the wraps-less `external_utils` reason whole, that `dont_skip_tracing` binds the same inner (the shape `torch/export/_unlift.py` already assigns as an `nn.Module`'s forward), and that `external_utils`' namespace gains nothing.
- `test_aot_compile_module_deserialize_refuses_a_class_body_wrap_numpy_forward` (module-level `NumpyForwardModule`) pins the wraps-aware naming of `wrap` and the same fence.
- `test_aot_compile_module_deserialize_refuses_a_class_compiled_call_forward` pins the wraps-aware naming of the `compile_wrapper` that `torch.compile(Cls)` rebinds as `Cls.__call__`.
- `test_aot_compile_module_fallback_names_a_compiled_partial_forward` and `test_aot_compile_module_fallback_names_a_compiled_builtin_forward` pin the hopped-target reason whole through `_assert_forward_refused`; the latter also pins that the un-hopped builtin keeps the as-given cannot-resolve reason.
- `test_aot_compile_module_deserialize_refuses_a_lazy_module_forward` (both `wrap_top_frame` settings) and `test_aot_compile_module_deserialize_refuses_a_bound_module_call_forward` are regression fences for the hop's reach: a bound method is not hopped and its reason still reads "resolves to". They pass unchanged on the commit below.

The two wraps-aware pins compute the expected name with the same `getattr(code, "co_qualname", code.co_name)` the load uses, so they hold on 3.10 as well. Every wording case fails with the commit below's `aot_compile.py`; the Test Plan lists the mutations and which cases each one fails.

Test Plan:

New tests, some parametrized. Every wording case fails with the commit
below's aot_compile.py (`git show HEAD~1:torch/_dynamo/aot_compile.py`
checked out under this commit's test file), the hint cases on the hint's
wording and the reason cases on the reason string.
`..._hint_sees_through_a_wrapped_rebound_forward` (compile, disable,
disable_nonrecursive) pins the hint's wording and that defining the name in
the wrapper's namespace restores nothing;
`..._deserialize_refuses_a_targetless_dynamo_wrapper` pins the wraps-less
external_utils reason whole (error_on_graph_break's inner: owns
external_utils' dict, no __wrapped__), that dont_skip_tracing binds that same
inner -- the shape torch/export/_unlift.py already assigns as an nn.Module's
forward -- and that external_utils' namespace gains nothing;
`..._deserialize_refuses_a_class_body_wrap_numpy_forward` (module-level
NumpyForwardModule, its forward decorated in the class body) pins the
wraps-aware naming of `wrap` and the same fence;
`..._deserialize_refuses_a_class_compiled_call_forward` pins the wraps-aware
naming of the compile_wrapper torch.compile(Cls) rebinds as Cls.__call__;
`..._fallback_names_a_compiled_partial_forward` and
`..._fallback_names_a_compiled_builtin_forward` pin the hopped-target reason
whole, through _assert_forward_refused (full-string assertEqual on
_forward_not_resolved_reason, the warning, the hint's "rebuilt because"
splice, and eval_frame's namespace gaining nothing), the latter also that the
un-hopped builtin keeps the as-given cannot-resolve one. The two wraps-aware
pins compute the expected name with the same
`getattr(code, "co_qualname", code.co_name)` the load uses, so they hold on
3.10 as well.

Three cases are regression fences for the hop's reach rather than proofs of a
change and pass unchanged on the commit below:
`..._deserialize_refuses_a_lazy_module_forward` (both params; the bound
_call_lazy_check on either setting) and
`..._deserialize_refuses_a_bound_module_call_forward` pin that a bound method
is not hopped and its reason still reads "resolves to".

Mutations at this commit, each run over the cases the -k patterns below
select: with the wraps-less return removed (the hop
walks onto None, which the hopped-target branch then names as "an instance
of NoneType") only the targetless-wrapper case fails, on the reason; with
the hopped-target branch removed (every get_traced_fn failure returns the
as-given cannot-resolve reason) exactly the two fallback cases fail, on the
reason; with the wraps-aware naming removed exactly the class-body wrap_numpy
and class-compiled __call__ cases fail, on the reason; with the hint's
wording reverted exactly the three hint cases fail. The three fences pass
under every mutation.

```
python test/dynamo/test_aot_compile.py -k hint_sees_through
python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_targetless
python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_class_body
python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_class_compiled
python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_lazy
python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_bound
python test/dynamo/test_aot_compile.py -k fallback_names_a
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The full file reports `OK (skipped=6)`.

> **FAQ: A wraps-less external_utils function used to be refused as "a Dynamo
> wrapper without a resolvable target", then fell through to the namespace
> rule, and now has a reason again. Why not the earlier wording?**
>
> Because nothing short of code identity tells wrap_dunder_call_ctx_manager's
> inner from any other function owning external_utils' dict (normalize_as_list,
> is_compiling), so a reason that calls the function "a Dynamo wrapper" is not
> true of every function that reaches it, and the fall-through rendered "inner
> resolves to inner" with advice the shape had already followed. The reason now
> describes the function as what every function on this path is -- an
> external_utils function with no __wrapped__ to see through -- and names the
> decorators that return one; for a bare helper bound as forward, a
> shape no API produces, that description holds and only the advice is moot.

> **FAQ: Why name a wraps'd wrapper by `co_qualname`, which 3.10 lacks?**
>
> Because `__qualname__` is exactly what functools.wraps copied, so it cannot
> name the wrapper; the code object's name can, and `co_qualname` (3.11+) also
> names the decorator (`wrap_numpy.<locals>.wrap`). The fallback to `co_name`
> on 3.10 renders `wrap, a functools.wraps'd wrapper over M.forward`, still
> not a tautology, and is the convention this file already uses for the
> dropped-attribute warning. The two tests that pin the wording compute the
> expected name the same way.

> **FAQ: Why keep "the wrapper <decorators> return skips functools.wraps"
> rather than "the wrapper returned by <decorators> skips functools.wraps"?**
>
> Because the elided-that relative clause is this file's idiom for exactly this
> list: the comment above the hop and the SUPPLIED hint both read "the wrappers
> torch.compile, torch._dynamo.disable, run and optimize return". Rewording
> only this site would state the same thing in two grammars three lines apart,
> and it churns the golden string for no change in behaviour.

This commit was authored with the assistance of an AI coding assistant.

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

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

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

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

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

## Where they sit

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

## The helper and the stub

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

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

## The exits that record nothing

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

### A bare `SystemExit` out of a later tree

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

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

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

### A later result that cannot bind

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

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

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

### A call the one signature cannot take

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

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

## One bind per result, across both passes and the report

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

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

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

## What each test pins, by mutation

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

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

Test Plan:

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

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

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

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

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

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

> **FAQ: the file's inline raiser stubs -- four `class Raises`, two
> `class RaisingGuardManager`, and the `Interrupts` of
> `test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates` -- all
> duplicate the module-level `RaisingTree` these two tests adopt. Why not
> convert them too?**
>
> `git blame` puts every one of them in a test of #197188, #197220, #197390
> or #197391 below, and #197188, #197220 and #197390 are already approved,
> so the conversion cannot be folded into the commits that own the stubs
> either; doing it here would put edits to four other PRs' tests in a commit
> whose diff is otherwise three tests and one helper, and would shift the
> hunks #197050 and #197257 apply above. `RaisingTree` is module level and
> already adopted at 21 sites, so those owners can adopt it in one line each.

Authored with the assistance of Claude Code.

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

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

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

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

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

## The gate under test

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

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

## The test

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

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

Test Plan:

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

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

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

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

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

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

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

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

## Where this sits in the stack

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

## The report the commit below prints

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

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

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

## Recording `trusted`

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

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

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

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

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

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

The comment at that block gives the same two numbers.

## The caveat

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

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

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

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

## Why the stale-state clause is hedged

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

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

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

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

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

## What the caveat keys on

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

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

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

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

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

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

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

## The one real throw: `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`

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

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

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

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

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

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

## What does not change

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

## Stubs and the golden

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

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

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

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

## Tests

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

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

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

## Order to review

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

Test Plan:

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

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

Authored with the assistance of Claude Code.

## FAQ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Test Plan:

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

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

Authored with the assistance of Claude Code.

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

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

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

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

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

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

## The bug: bind first, check second

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

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

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

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

## The fix: check before `import_source`

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

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

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

## The other nine `import_source` callers

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

## Behaviour changes against the parent

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

## The test

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

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

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

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

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

Test Plan:

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

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

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

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

Authored with the assistance of Claude Code.

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

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

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

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

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

Test Plan:

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

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

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

Authored with the assistance of Claude Code.

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

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants