Skip to content

[dynamo] Raise a typed, guard-naming error when package guard serialization fails - #195287

Closed
bobrenjc93 wants to merge 15 commits into
gh/bobrenjc93/1084/basefrom
gh/bobrenjc93/1084/head
Closed

bobrenjc93 wants to merge 15 commits into
gh/bobrenjc93/1084/basefrom
gh/bobrenjc93/1084/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

When a guard cannot be serialized into a compile package, the failure surface
was untyped in both directions: serialize_guards raised a bare PackageError
whose message named only the guard TYPE, and on the non-strict path the
CheckFunctionManager swallowed it entirely, leaving guards_state None so
convert_frame raised a bare AssertionError("check_fn.guards_state must not be
None"). A consumer that reacts to serialization failures (the precompile
consumer added later in this stack) could then only distinguish that failure
from any other AssertionError by matching the message text.

serialize_guards now raises GuardSerializationError (a PackageError subclass
carrying guard_type and the guard's source name, with a message-compatible
rendering so existing matchers keep working); the non-strict CheckFunctionManager
records the swallowed error as guards_serialization_failure; and convert_frame
raises a typed PackageError CHAINED to that cause instead of the bare
AssertionError. Consumers can now catch PackageError and inspect cause for
the exact guard instead of parsing message text. aot_compile builds guards with
strict_error=True, so a serialization failure raises there directly and its
guards_state-None assertion stays a plain defensive AssertionError (there is no
swallowed cause to chain to).

Two failure modes that previously escaped the typed surface (and therefore also
skipped the non-strict swallow, surfacing as InternalTorchDynamoError) are
closed: the unserializable TYPE_MATCH/BUILTIN_MATCH branch (a class defined in
local scope) raised a bare TypeError and now raises GuardSerializationError with
the same actionable message, and pickle_guards_state converted only
AttributeError, so a TypeError or PicklingError from an unpicklable guarded
value (e.g. a threading.Lock) propagated raw; the except is broadened to cover
them (still chaining the original error as cause). Both paths are pinned by
non-strict package tests asserting the typed chain.

The stored exception is traceback-stripped before being recorded: the walk
follows cause only (every link we own is chained with raise ... from, and
context may belong to an exception the caller is handling), guarded against
a cyclic explicit-cause chain. A live traceback
would pin the guard-build frames -- the GuardBuilder holding the user frame's
scopes, the OutputGraph -- on the long-lived CheckFunctionManager, defeating the
deliberate anti-leak cleanup at the end of init and leaking one build's
state per suppressed failure in a long-running job. The formatted traceback that
bypass_package logs is captured before stripping, and a test pins traceback
is None on the chained cause.

Authored with an AI assistant.

Test Plan:

python test/dynamo/test_guard_serialization.py   # 68 tests, OK (2 skipped)
python test/dynamo/test_aot_compile.py           # 42 tests, OK (5 skipped)
python test/dynamo/test_package.py               # 64 tests, OK (40 skipped, 1 xfail)
lintrunner <touched files>                        # ok

Design note on the non-strict path. When guard serialization fails with
strict_precompile off, CheckFunctionManager records the failure and marks the
package entry bypassed, and convert_frame then raises a typed PackageError
chained to the specific guard. Continuing to compile without the package entry
was considered instead: the bypass machinery (bypass_package,
CompilePackage.bypass_current_entry) suggests it, but this frame has always
hard-failed here (upstream raised a bare AssertionError), and package consumers
(torch.compiler.precompile in particular) rely on a raise they can classify.
Raising typed is the conservative choice; honoring the bypass end to end is a
separate change.

The SymInt reducer now raises PackageError rather than RuntimeError so every
serialization failure in the pickler is typed uniformly, and the up-front check
tests the guard's unserializable flag regardless of its own type, since
BUILTIN_MATCH, SEQUENCE_LENGTH, export-mode TENSOR_MATCH and
FAKE_SCRIPT_TYPE_MATCH all set it (the first three by running TYPE_MATCH on the
same guard), so a local-scope sequence type or fake script type is reported as
a GuardSerializationError too, even when a guard filter has dropped the sibling
TYPE_MATCH guard. The three TYPE_MATCH-family guard types stay exempt from the
derived-type check because BUILTIN_MATCH derives an ID_MATCH on the
builtins-dict entry, which serializes. On the non-strict path
the recorded exception chain has its frames released (walking cause only,
so an unrelated in-flight exception's traceback is never touched) and the
formatted traceback is attached as an exception note on Python 3.11+.

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

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 15 Cancelled Jobs, 10 Pending

As of commit dae4e2b with merge base 3d3d3f4 (image):

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 29, 2026
…zation fails

When a guard cannot be serialized into a compile package, the failure surface
was untyped in both directions: serialize_guards raised a bare PackageError
whose message named only the guard TYPE, and on the non-strict path the
CheckFunctionManager swallowed it entirely, leaving guards_state None so
convert_frame raised a bare AssertionError("check_fn.guards_state must not
be None"). Consumers that need to react to serialization failures
(torch.compiler.precompile does today) were left string-matching that
assertion message to distinguish it from every other AssertionError.

serialize_guards now raises GuardSerializationError (a PackageError subclass
carrying guard_type and the guard's source name, with a message-compatible
rendering so existing matchers keep working); the non-strict
CheckFunctionManager records the swallowed error as
guards_serialization_failure; and convert_frame raises a typed PackageError
CHAINED to that cause instead of the bare AssertionError (aot_compile's
sibling assertion is converted the same way for consistency). Consumers can
now catch PackageError and inspect __cause__ for the exact guard instead of
parsing message text.

The stored exception is traceback-stripped (its whole cause/context chain)
before being recorded: a live __traceback__ would pin the guard-build frames
-- the GuardBuilder holding the user frame's scopes, the OutputGraph -- on
the long-lived CheckFunctionManager, defeating the deliberate anti-leak
cleanup at the end of __init__ and leaking one build's state per suppressed
failure in a long-running job. The formatted traceback that bypass_package
logs is captured before stripping, and a test pins __traceback__ is None on
the chained cause.

Authored with an AI assistant.

Test Plan:

```
python test/dynamo/test_guard_serialization.py   # 61 tests, OK (1 skipped; 1 new, 1 extended)
python test/dynamo/test_aot_compile.py           # 42 tests, OK
python test/dynamo/test_package.py               # 64 tests, OK (23 skipped, 1 expected failure)
lintrunner <touched files>                       # ok
```

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

ghstack-source-id: d12a9d2
Pull-Request: #195287
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…zation fails

When a guard cannot be serialized into a compile package, the failure surface
was untyped in both directions: serialize_guards raised a bare PackageError
whose message named only the guard TYPE, and on the non-strict path the
CheckFunctionManager swallowed it entirely, leaving guards_state None so
convert_frame raised a bare AssertionError("check_fn.guards_state must not
be None"). Consumers that need to react to serialization failures
(torch.compiler.precompile does today) were left string-matching that
assertion message to distinguish it from every other AssertionError.

serialize_guards now raises GuardSerializationError (a PackageError subclass
carrying guard_type and the guard's source name, with a message-compatible
rendering so existing matchers keep working); the non-strict
CheckFunctionManager records the swallowed error as
guards_serialization_failure; and convert_frame raises a typed PackageError
CHAINED to that cause instead of the bare AssertionError (aot_compile's
sibling assertion is converted the same way for consistency). Consumers can
now catch PackageError and inspect __cause__ for the exact guard instead of
parsing message text.

The stored exception is traceback-stripped (its whole cause/context chain)
before being recorded: a live __traceback__ would pin the guard-build frames
-- the GuardBuilder holding the user frame's scopes, the OutputGraph -- on
the long-lived CheckFunctionManager, defeating the deliberate anti-leak
cleanup at the end of __init__ and leaking one build's state per suppressed
failure in a long-running job. The formatted traceback that bypass_package
logs is captured before stripping, and a test pins __traceback__ is None on
the chained cause.

Authored with an AI assistant.

Test Plan:

```
python test/dynamo/test_guard_serialization.py   # 61 tests, OK (1 skipped; 1 new, 1 extended)
python test/dynamo/test_aot_compile.py           # 42 tests, OK
python test/dynamo/test_package.py               # 64 tests, OK (23 skipped, 1 expected failure)
lintrunner <touched files>                       # ok
```

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

ghstack-source-id: d12a9d2
Pull-Request: #195287
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 53s —— View job


The typed-error direction is reasonable, but the PR is justified by a consumer that does not exist (torch.compiler.precompile is a make_fx path that never reaches Dynamo guard serialization), and the traceback-stripping loop mutates exceptions it does not own — I'd request changes.

Full review

PR Review: #195287

Summary

Introduces GuardSerializationError (a PackageError carrying guard_type/guard_name), records the swallowed failure on CheckFunctionManager.guards_serialization_failure, and converts two AssertionErrors into cause-chained PackageErrors. The core idea is sound, but the stated motivation is factually incorrect, the aot_compile half is self-declared dead code, and the traceback-stripping loop reaches exceptions outside this code's ownership.

Code Quality

  • torch/_dynamo/guards.py:4822-4827 — the chain walk follows __context__, which can reach an exception this code does not own. __context__ is set implicitly by CPython to whatever exception was being handled when the inner raise occurred. If user code calls a compiled function from inside an except: block, the walk reaches that outer handler's exception and nulls its __traceback__. Nothing bounds the traversal to exceptions created inside serialize_guards. This is narrow (needs save_guards=True, a real serialization failure, non-strict) and it's debuggability loss rather than corruption — but it is entirely avoidable. The whole loop, the stripped id-set, and the cycle guard disappear if you construct a fresh exception instead of storing the caught one:

    self.guards_serialization_failure = exc.GuardSerializationError(e.guard_type, e.guard_name)

    That satisfies every assertion the new test makes (isinstance, guard_type, __traceback__ is None) with no chain traversal and no mutation of shared objects. It needs an isinstance(e, GuardSerializationError) branch since the except also catches plain PackageError, but that is still smaller than the current loop. Fix this →

  • torch/_dynamo/aot_compile.py:439-447 — the comment concedes this branch is unreachable. "Practically unreachable (build_guards above runs strict, so a serialization failure raises directly)." strict_error=True is passed at line 436, so guards.py:4814 always re-raises and guards_state is never None here. Per CLAUDE.md ("Don't add error handling, fallbacks, or validation for scenarios that can't happen"), this should stay the plain AssertionError it was, or the branch should be removed. Changing it "for consistency" adds a raise path that cannot execute.

  • torch/_dynamo/aot_compile.py:447 and convert_frame.py:1972 — from <a variable that is None> is from None, which suppresses context rather than preserving it. raise X from Y sets __suppress_context__ = True unconditionally, including when Y is None. On the aot_compile path guards_serialization_failure is always None (previous point), so that line is literally raise exc.PackageError(...) from None — it discards the implicit __context__ the old bare AssertionError would have carried. The comment claiming it is "cause-chained like convert_frame's" describes behavior the code does not have. Guard the from clause, or drop it where the cause cannot exist.

  • torch/_dynamo/exc.py:434-437 — the docstring names consumers that cannot reach this error. It cites "caching precompile, aot_compile, torch.compiler.precompile". torch.compiler.precompile is the make_fx capture path in torch/_precompile.py (see its module docstring: "make_fx tracer by default; Dynamo planned"; :1380 rejects any non-make_fx tracer, and the module has zero references to CompilePackage/aot_compile/guards_state) and never invokes Dynamo guard serialization; aot_compile runs strict and so never sees the swallowed form. Naming speculative consumers in a docstring is exactly the rot CLAUDE.md warns about.

  • torch/_dynamo/aot_compile.py:443 — function-local from torch._dynamo import exc. The file already does module-level from . import convert_frame (line 21) and relative imports for siblings (lines 22, 26). If the local import is for cycle avoidance, that is non-obvious and the reason belongs in a comment; otherwise use the module-level relative form, as convert_frame.py:88 does.

API Design

  • guard_type and guard_name have no consumer anywhere in the tree. grep finds GuardSerializationError only at its definition, the two raise sites, and the new tests; no code anywhere in the repo string-matches "guards_state" or "must not be None" inside an except handler. The PR's premise — that a consumer today string-matches the assertion message — does not hold. The only except AssertionError in this neighbourhood is torch/_precompile_driver.py:316, and it fails to be the claimed consumer twice over: it matches Inductor's assert_size_stride text ("expected size"/"stride"/"wrong number of dimensions") and re-raises anything else unchanged, and per that module's own docstring the file is never imported or executed by torch — its function bodies are emitted verbatim into the generated artifact, so it wraps runtime execution of an already-compiled graph and cannot sit on any compile path. So this adds a public-ish attribute surface plus a state field for a hypothetical future caller, which CLAUDE.md asks you not to do ("Don't design for hypothetical future requirements"). Either land the consumer in the same stack so the attributes are exercised by real code, or trim to just the typed class without the extra fields. At minimum, the PR description and the exc.py docstring need correcting — as written they assert something untrue about the current tree.

Backward Compatibility

  • convert_frame.py:1971 changes a user-visible exception type from AssertionError to PackageError (a RuntimeError). Dynamo's own classification is unaffected — I checked this specifically: both types are on the re-raise allowlist at convert_frame.py:2206-2231, neither is in the soft_fail tuple at :2420, and the frame_exec_strategy branch at :2479 is dead for both, so the suppress_errors path treats them identically. But suppress_errors defaults to False (config.py:276), so this error does reach users by default, and any external code catching AssertionError around torch.compile with caching_precompile will now miss it. That is arguably the right direction, but it is an uncatalogued user-facing change — worth a release notes: label rather than topic: not user facing (Dr. CI has already flagged the missing label).

Testing

  • test/dynamo/test_guard_serialization.py:1101 and :1104,1117-1118 — the resets are redundant. common_utils.TestCase.run() already calls torch._dynamo.reset() before and after every test method (via _reset_dynamo_if_imported), and the class chain is TestGuardSerializationBase → torch._inductor.test_case.TestCase → torch._dynamo.test_case.TestCase. fn is test-local so its code object is fresh regardless. The nearest analogue in this file, test_ddp_module (~:1641), builds a CompilePackage + optimize(package=...) with no manual resets. Drop the leading reset and the try/finally, and dedent the body.

  • test/dynamo/test_guard_serialization.py:1096 — CompilePackage is re-imported locally although it is already imported at module scope (line 24).

  • The test asserts __traceback__ is None on the cause, which pins the mechanism rather than the property that matters. If the stripping is replaced by constructing a fresh exception (first Code Quality point), this assertion still passes — good — but consider asserting the actual invariant instead: that no GuardBuilder/OutputGraph stays reachable from the stored failure. As written, the test would not catch a regression where the traceback is cleared but some other reference keeps the build state alive.

Recommendation

Request Changes

Blocking: the __context__ traversal at guards.py:4822-4827 mutates exceptions the code does not own and is unnecessary given a simpler construction; the aot_compile.py branch is dead by the author's own comment and its from clause silently means from None; and the PR description plus the exc.py docstring both assert a string-matching consumer that does not exist in the tree, which needs correcting before this is reviewable on its merits. The new attributes have no in-tree consumer — landing the consumer alongside them (or trimming them) would settle whether the surface is the right shape.

· branch `gh/bobrenjc93/1084/head`

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: dynamo"

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Closing in favor of the canonical stack #195353-#195362 (now also #195911-#195929). Note for future readers: this change has no counterpart there yet; the code remains in this PR's history if it is wanted later.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant