Skip to content

[dynamo] Name a recursion overflow while pickling guard state in its PackageError - #196477

Closed
bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1142/basefrom
gh/bobrenjc93/1142/head
Closed

bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1142/basefrom
gh/bobrenjc93/1142/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

A guard rooted at an fqn-mismatched function is now traversed rather than
dropped, so pickle walks whatever user data hangs off it. A deep but finite
object graph, or a pathological __reduce__ that hands back a fresh object
every time and never memoizes, overflows the recursion limit inside dump.
The previous commit's broad mapping already turns that into a PackageError
(a bypass, or an error under strict_precompile) rather than a raw
RecursionError that hard-fails a program that compiled fine before; this
gives it a dedicated clause and message, since the interpreter's "maximum
recursion depth exceeded while calling a Python object" says nothing about
which stage overflowed. Walking the object graph to report WHERE is skipped
deliberately: it would recurse again off an already exhausted stack.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_recursing_guarded_value_overflow_is_a_package_error

On the previous commit the test gets a PackageError with the interpreter's
message and fails the regex.

Authored with an AI assistant.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 9, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 25 Pending

As of commit 42fc04a with merge base e67c870 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


Review: [dynamo] Name a recursion overflow while pickling guard state in its PackageError

  • Gather context (diff vs origin/gh/bobrenjc93/1142/base)
  • Read torch/_dynamo/guards.py:4685-4697 in context
  • Read the new test + fixture in context
  • Check clause ordering, sibling pickler, and non-strict bypass path
  • Post review

The change is correct and well-placed — the RecursionError clause sits before the broad except Exception, so it wins, and the message is a real improvement over "RecursionError: maximum recursion depth exceeded..."; below are a few nits, the notable ones being an inverted message phrasing and a redundant config.patch on the new test.

Detailed review

Correctness

The core logic is right, and I confirmed the two things that could have made it a no-op:

  1. Clause ordering. RecursionError is a subclass of RuntimeError, so the pre-existing except Exception at torch/_dynamo/guards.py:4698 already caught it. The new clause is placed above it, so it takes precedence. Correct.
  2. The raise reaches the right consumer. pickle_guards_state is only called from CheckFunctionManager.serialize_guards (torch/_dynamo/guards.py:5072), whose caller catches exc.PackageError at guards.py:4909 and either re-raises under strict_precompile/strict_error or calls bypass_package. So the claim in the comment ("bypass it, or raise under strict_precompile") holds.

I also agree with the deliberate omission of a "where did it overflow" walk. By the time the handler runs the stack has unwound back to pickle_guards_state, so there is headroom — but any traversal would be re-walking exactly the graph that just blew up, with no termination argument. Skipping it is the right call, and documenting why it was skipped is worth the line.

Message phrasing (worth fixing)

"guard state exceeded the recursion limit while pickling"

This reads inverted: the guard state didn't exceed anything, the pickling recursion did. The PR title already has the better phrasing — suggest matching it:

"exceeded the recursion limit while pickling guard state"

The test regex ("exceeded the recursion limit") matches either way, so this is a free change.

Separately, the message is purely diagnostic — a user who hits this under strict_precompile has no stated path forward. Consider whether a hint (raise sys.setrecursionlimit, or drop the offending value via guard_filter_fn) is warranted, or note explicitly that it isn't actionable. Optional; the surrounding messages in this function are similarly bare.

Test nits

test/dynamo/test_guard_serialization.py:1163 — the @torch._dynamo.config.patch(strict_precompile=True) decorator is redundant. TestGuardSerialization is already decorated with @torch._dynamo.config.patch({"strict_precompile": True}) at line 1078. The immediately-preceding sibling test test_unserializable_guarded_value_is_a_package_error relies on exactly that and says so in a comment ("strict_precompile is on for this class, so it re-raises"). Two adjacent tests with identical requirements shouldn't express them differently — drop the decorator and match the sibling.

test/dynamo/test_guard_serialization.py:1172 — uses torch._dynamo.exc.PackageError where PackageError is already imported at line 25 and used bare by the sibling test at line 1160. Use the bare name.

test/dynamo/test_guard_serialization.py:282-290 — the fixture is fine, and I want to note the non-obvious part is deliberate: the recursion comes from the reduce args tuple holding a fresh instance, not from self.inner. self.inner is never read during the walk. Keeping __init__(self, inner=None) is nevertheless the right choice — it makes the __reduce__ well-formed rather than a reduce that would TypeError on the rebuild, so the test is exercising the recursion limit and nothing else. That is a subtle enough point that the existing one-line comment could say it: something like # Recursion is via the reduce args, not self.inner; inner just keeps the reduce well-formed.

flag = 2.0 as a class attribute (vs. UnpicklableGuardedDefault setting it in __init__) is a harmless divergence — keep_default_attribute reads it either way.

Comment length

The new comment is 10 lines guarding 3 lines of code, and its first two sentences restate the block comment 5 lines above it (guards.py:4678-4680, "Anything dump raises means a guarded value cannot be serialized, which is a bypass..."). Per the repo's Coding Style Guidelines ("Minimize comments; be concise"), the load-bearing parts are (a) what overflows — pathological __reduce__ / deep finite graph — and (b) why no location is reported. The bypass-vs-crash framing is already established above. Roughly half the block could go.

Scope observations (not blockers)

  • Only pickler.dump is protected. pytree.tree_leaves(state.output_graph.local_scope) at guards.py:4650 and the keep_portable_guards_unsafe block at guards.py:4666 sit outside the try. A sufficiently deep local_scope would still surface a raw RecursionError. Inherited from the previous commit's structure, so out of scope here, but worth knowing the guarantee is "dump cannot raise raw", not "guard serialization cannot raise raw".
  • The sibling pickler is unprotected. FunctionPicklerBase's docstring says it exists "so a fix in one pickler cannot be missed in the other", but AOTCompilePickler.dump at torch/_dynamo/aot_compile.py:276 has no equivalent handling — a pathological __reduce__ there still produces a raw RecursionError. The two picklers have genuinely different error contracts (AOT raises RuntimeError on pickler.errors), so this may well be intentional; flagging in case it isn't.
  • Non-strict path formats a deep traceback. bypass_package is called with traceback=traceback.format_exc().split("\n") (guards.py:4914), which for a recursion-limit unwind means formatting ~1000 frames into a list and shipping it to trace_structured. traceback's _RECURSIVE_CUTOFF only collapses 3+ consecutive identical (file, lineno, name) triples, and pickle's recursion cycles through several distinct frames per level, so compression will be poor. Pre-existing (the broad clause already routed RecursionError here), just noting the log-bloat is now a named, expected path rather than an accident.
  • Low-confidence flakiness note. The C _pickle accelerator with a Python reducer_override burns both Python frames and C stack per level. On builds with a small thread stack (debug/ASAN), C-stack exhaustion could beat Py_EnterRecursiveCall's RecursionError and segfault instead of raising. CPython 3.12+ has separate C-recursion protection so this should be fine on normal builds; only worth a second thought if this test shows up flaky on a sanitizer job.

Verification

I did not run the test — this checkout has no built torch and no .venv, and per CLAUDE.md I did not attempt to install one. The Test Plan commands should be run locally:

python test/dynamo/test_guard_serialization.py -k test_recursing_guarded_value_overflow_is_a_package_error

The PR notes the test fails the regex (but still gets a PackageError) on the parent commit, which is exactly the right negative control for a message-only change.

· branch `gh/bobrenjc93/1142/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Folded into #196470: the RecursionError clause is a message-only change on top of the broad PackageError mapping, so it now lands with that mapping; its test was rewritten to a shape reachable at that commit.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant