Skip to content

Deep recursion: $RecursionLimit = Infinity goes to 100000 levels, on a thread with a large stack - #2121

Merged
rocky merged 7 commits into
masterfrom
deep-recursion-stack
Nov 9, 2026
Merged

rocky merged 7 commits into
masterfrom
deep-recursion-stack

Conversation

@tombouctou

@tombouctou tombouctou commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Found while running the examples of Skiena and Pemmaraju's Computational Discrete Mathematics with Combinatorica, which runs DepthFirstTraversal, ConnectedQ, BiconnectedComponents, EulerianQ, Bridges and others under Block[{$RecursionLimit = Infinity}, ...]. Since #2080, Infinity there was capped at the largest integer $RecursionLimit (512), so DepthFirstTraversal[GridGraph[20, 20], 2, Edge] ended in $RecursionLimit::reclim (WMA: instant).

This needs a decision on what Infinity should mean, so here is a proposal with measurements. Please push back on the policy.

What actually bounds a deep recursion

The C stack, not sys.setrecursionlimit. Matching a pattern with a Condition or PatternTest goes through C calls that take C stack on every Mathics3 level. A Combinatorica DFS takes 4 levels per vertex. With the cap raised (MATHICS_MAX_RECURSION_DEPTH=100000), DepthFirstTraversal[Path[3000], 1] (≈12000 levels) on the 8 MB main thread gives:

Python main thread thread with a large stack
3.11 segmentation fault 3000
3.12, 3.13 RecursionError → $Aborted $Aborted (a fixed C-call counter that ignores stack size)
3.14 RecursionError ("Stack overflow (used 8144 kB)") → $Aborted 3000

A recursion that never leaves Python code (f[k_] := 1 + f[k-1]) uses no C stack and reaches 100000 levels on all four.

So raising MATHICS_MAX_RECURSION_DEPTH today can crash 3.11. Mathics3 used to run the evaluation on a thread with threading.stack_size(python_stack_size(...)) when that variable was raised (7a0fa0e); #1177 (stopit for TimeConstrained) removed it, and python_stack_size() stayed unused.

Proposal (this PR)

  • $RecursionLimit = Infinity goes to MAX_INFINITE_RECURSION_DEPTH = 100000 (settings.DEFAULT_MAX_INFINITE_RECURSION_DEPTH), and no longer to the largest integer $RecursionLimit. The integer range stays 20..512 (or MATHICS_MAX_RECURSION_DEPTH).
  • Evaluation.evaluate() runs on a thread with a large stack on 3.11 and 3.14+, where it helps; not on 3.12/3.13, where it can't, and not on emscripten. The stack is 4 KB per level (measured 0.7–1.4 KB on macOS arm64 and Linux x86_64): 382 MB of address space for 100000 levels, committed only as used. If the thread can't be started, it evaluates on the calling thread.
  • SIGINT reaches only the main thread. A KeyboardInterrupt is passed on to the evaluating thread (async_raise, as TimeConstrained does). The CLI's interrupt handler sees the evaluation is on another thread and hands over: the evaluating thread runs the interrupt> menu at its next check_stopped(). TimeConstrained already targets the evaluating thread's id, so it works unchanged.
  • reclim after a RecursionError gives the limit in effect where it happened. It used to give the one restored after leaving the Block ("Recursion depth of 200 exceeded" inside Block[{$RecursionLimit = Infinity}]).

On 3.12/3.13 the DFS above stops cleanly at 1000–2000 vertices whatever we do; fewer Python frames per Mathics3 level is the only way further there.

Results (Linux x86_64, 8 MB main stack; same on macOS arm64)

3.11 3.12 3.13 3.14
DepthFirstTraversal[GridGraph[20, 20], 2, Edge] 399 399 399 399
DepthFirstTraversal[GridGraph[50, 50], 1] 2500 $Aborted $Aborted 2500
DepthFirstTraversal[Path[3000], 1] 3000 $Aborted $Aborted 3000

Full pytest on 3.14 and 3.11: 4533 passed, 0 failed. Doctests OK on both. Ctrl-C in the CLI: every option of the interrupt> menu, tested in a pseudo-terminal against master (see the comment below and test/test_interrupt.py). In a MathicsSession, KeyboardInterrupt reaches the caller and no thread is left behind.

Open questions

  • On 3.12/3.13 the RecursionError is reported as "Recursion depth of 100000 exceeded." when Python stopped at about 10000 levels. Better wording? Perhaps a message of its own.
  • Is 100000 right for Infinity, or should Infinity mean "as deep as the stack allows" with no number?

🤖 Generated with Claude Code

tombouctou and others added 2 commits November 6, 2026 19:59
…a thread with a large stack

What bounds a deep recursion is the C stack, not sys.setrecursionlimit.
Matching a pattern with a Condition or a PatternTest goes through C calls
that take C stack on every Mathics3 level. The main thread has 8 MB, which
a recursive Combinatorica DepthFirstTraversal runs out of before 12000
levels (3000 vertices, 4 levels each). Python 3.11 then crashes with a
segmentation fault; 3.12 to 3.14 raise RecursionError.

Evaluation.evaluate() runs the evaluation on a thread whose stack is sized
for the deepest recursion allowed, as it did before #1177 when
MATHICS_MAX_RECURSION_DEPTH was raised. It does this on Python 3.11 and
3.14 on; 3.12 and 3.13 count C calls against a fixed limit that a larger
stack does not raise. The stack is 4 KB per level, measured at 0.7-1.4 KB:
382 MB of address space for 100000 levels, allocated only as it is used.

- $RecursionLimit = Infinity, as in Block[{$RecursionLimit = Infinity}, ...],
  goes to MAX_INFINITE_RECURSION_DEPTH, 100000, and no longer to the
  largest integer $RecursionLimit (512 by default).
- SIGINT reaches only the main thread. A KeyboardInterrupt is passed on
  to the evaluating thread. The CLI's interrupt handler hands the
  interrupt over, and the evaluating thread runs the interrupt menu at
  its next check_stopped().
- When Python runs out of stack, $RecursionLimit::reclim gives the limit
  in effect where it did, not the one restored after leaving the Block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…, a notice

Tried in a pseudo-terminal against master, every option of the interrupt
menu (abort, continue, show, inspect, exit, a second Ctrl-C) during a Do
loop, a Pause and a long Expand. With the evaluation thread:

- Ctrl-C during Pause[] never opened the menu: the pause slept on, and the
  interrupt stayed pending into the next input. Pause's sleep loop now
  takes a pending interrupt, as the signal cut into the sleep on the main
  thread.
- An interrupt still pending when an evaluation ends is dropped, so it
  cannot open the menu in the next one.
- A step that does not check for interrupts (a long call into SymPy)
  delays the menu. After 0.5 s a notice says Ctrl-C was seen.
- Only the evaluating thread takes a pending interrupt. The notice once
  printed through Mathics3 formatting, which ran the menu on the timer
  thread, and an abort there escaped.
- A second Ctrl-C while the menu is open is ignored, as the menu reads the
  answer.

show, inspect, continue, abort and exit now behave as on master.
test/test_interrupt.py has unit tests for the above and terminal tests
that drive the CLI through a pseudo-terminal (skipped without one); 7 of
its 8 tests fail without these changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tombouctou

Copy link
Copy Markdown
Collaborator Author

Ctrl-C with the evaluation on its own thread: tested and fixed (5b725a8)

I drove the CLI through a pseudo-terminal, pressing Ctrl-C as a keypress so the terminal driver sends SIGINT, and compared master with this branch. Each menu option was tried during a Do loop, a Pause[] and a long Expand (one long call into SymPy).

scenario master before 5b725a8 now
Do + abort / continue / show / inspect / exit ok ok ok
Pause[8]; 7 + Ctrl-C menu at once no menu; the interrupt stayed pending into the next input menu at once
Expand[(x+y+z+w)^40] + Ctrl-C menu at once menu after the step menu after the step, with a notice after 0.5 s
second Ctrl-C while the menu is open — queued another menu ignored

Fixed:

  • Pause[]'s sleep loop takes a pending interrupt.
  • An interrupt still pending when an evaluation ends is dropped.
  • Only the evaluating thread takes one. An earlier version of the notice printed through Mathics3 formatting and ran the menu on the timer thread.
  • A second Ctrl-C at an open menu is ignored.

test/test_interrupt.py has unit tests for these, plus terminal tests that drive the CLI through a pseudo-terminal (skipped without one). 7 of its 8 tests fail without the fix.

Remaining difference: a single long call that never reaches check_stopped (SymPy, NumPy) delays the menu until it returns. On the main thread, the signal handler ran as soon as control came back to Python bytecode.

Found on master, unchanged here:

  1. Abort at an idle prompt crashes the CLI. Ctrl-C at In[n]:=, then a: AbortInterrupt escapes interactive_eval_loop with a traceback, exit code 1.
  2. Leaving an inspect dialog aborts the interrupted evaluation. Ctrl-C during Pause[8]; 7, then i, then Ctrl-D prints General::timeout: Timeout reached. and Out[2]= $Aborted, rather than resuming with Out[1]= 7. (Return[] in the dialog gives Out[2]= None and stays in the dialog.)

I can open separate PRs for those two.

Test runs: full pytest 4536 passed. The 5 failures are order-dependent and happen on master too: test_eol, test_latex, test_tensor and test_literal_patterns pass file by file, and fail together on master as well. Doctests OK.

🤖 Generated with Claude Code

@tombouctou

Copy link
Copy Markdown
Collaborator Author

Follow-ups to the two master bugs listed above:

  1. CLI: an abort while reading input does not end the session #2122. A correction to what I wrote: an ordinary readline prompt does not crash on Ctrl-C. readline handles that Ctrl-C itself, and the interrupt menu never opens. The crash needs the SIGINT handler to run inside input(), as it does when a line was typed before readline set up the terminal (a script driving the CLI, maybe a fast paste). The fix makes the read-eval loop survive it.
  2. Leaving the inspect dialog resumes the interrupted evaluation #2123. Leaving the inspect dialog resumes the interrupted evaluation instead of aborting it with "Timeout reached".

Both are independent of this PR and branch from master.

🤖 Generated with Claude Code

tombouctou and others added 2 commits November 7, 2026 02:02
…ming bound

pty.fork() in a multi-threaded process may deadlock the child (Python warns
about it). The CLI is now started with subprocess and a helper that makes
the pseudo-terminal its controlling terminal (os.login_tty). The menu
during Pause must come well before the pause ends (< 5 s of 6 s left),
rather than within 2 s, which a loaded machine can miss.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…open on Linux

test_evaluation.py leaves a = a + a defined (on master too); a test file
that runs after it in the same xdist worker and uses a hits the recursion
limit (test_keys, test_abs). The terminal tests closed the parent's copy
of the pseudo-terminal's slave side at once; on Linux reading the master
side then fails with EIO until the CLI has opened it, so they never saw a
prompt there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rocky

rocky commented Nov 7, 2026

Copy link
Copy Markdown
Member

Interesting. Give me some time to research this and think about it.

@rocky

rocky commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Some miscellaneous information. The default recursion limit in the Mathematica V5 book examples is 256 in its error message. We have it set to 512. But looking at the Properties and Relations section of https://reference.wolfram.com/language/ref/$RecursionLimit.html reports 1024, and further down in the next example, 4096. So probably we should bump the default value.

Of course, this doesn't address the main concern. Just something I noticed while understanding what's up.

@rocky

rocky commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

I looked at sys.setrecursionlimit and sys.getrecursionlimit in Python 3.15, and IMHO this is a bit of a hack. It is unconditionally set to 1000, which, to me, seems a bit arbitrary.

I like the idea of setting a recursion limit for each thread that is set to be different from the main thread.

And I like the fixes in commit 5b725a8.

As to what Infinity means with respect to RecursionLimit, the only think I see is this:

The recursion limit can be set to Infinity allow any number of recursion steps

So the intent, I think, is that Infinity removes any hard number limit that would have otherwise succeeded given the constraints of your system.

In the 5th edition book on page 715 it warns:

You should be sure that this parameter is set small enough that you do not run out of stack space on your particular computer.

So my take is that the user takes responsibility if it is set to Infinity and the system crashes. Of course, that's not a nice behavior. Ideally, it would be nice if we could set it to the crash limit and go back far enough so we can still accommodate error handlers.

@rocky

rocky commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

So raising MATHICS_MAX_RECURSION_DEPTH today can crash 3.11

3.15 is being rolled in in PR #2125 and 3.11 is on its way out, so issues involving 3.11 have little importance, I think.

@rocky

rocky commented Nov 8, 2026

Copy link
Copy Markdown
Member

On 3.12/3.13 the DFS above stops cleanly at 1000–2000 vertices whatever we do; fewer Python frames per Mathics3 level is the only way further there.

There are timing/tracing decorators on evaluation, and that adds to the recursion levels per evaluation, and slows down evaluation a little. There is this subjective tradeoff between having the ability to trace and time execution this way and recursion levels and speed. I don't think it is worth removing it, but I am curious what others think.

One way to have things both ways is to duplicate the class so that there is a class with tracing/timing and a class without, and some sort of mechanism to switch between the two. In languages like C, C++, and Rust that have macros, this can be done without the maintenance burden of having to change both branches when a change to the class is made. But Python does not have such an ability.

@tombouctou

Copy link
Copy Markdown
Collaborator Author

I measured this. Removing @trace_evaluate entirely takes 24.6 Python frames per Mathics3 level down to 22.6, but on 3.12 and 3.13 it doesn't change how deep we get: the same recursion stops at level 4993 either way, and DepthFirstTraversal[Path[n], 1] works at 1000 and aborts at 1500 either way. The wrapper is a plain Python-to-Python call, so that fits the fixed C-call counter being the limit rather than Python frames. So I wouldn't duplicate the class for depth. The speed gain looks like up to 10–15%, but my timings were noisy, so that would need a proper benchmark and would be a separate question.

Address some `mypy` and `ruff` errors
    
(`isort` errors are covered by `ruff`).
@rocky

rocky commented Nov 8, 2026

Copy link
Copy Markdown
Member

I measured this. Removing @trace_evaluate entirely takes 24.6 Python frames per Mathics3 level down to 22.6, but on 3.12 and 3.13 it doesn't change how deep we get: the same recursion stops at level 4993 either way, and DepthFirstTraversal[Path[n], 1] works at 1000 and aborts at 1500 either way. The wrapper is a plain Python-to-Python call, so that fits the fixed C-call counter being the limit rather than Python frames. So I wouldn't duplicate the class for depth. The speed gain looks like up to 10–15%, but my timings were noisy, so that would need a proper benchmark and would be a separate question.

Thanks for investigating. We'll leave it open, then, as to whether to remove it or not. My take is to leave it in since it helps me a lot, but if others find it too costly, we can remove.

@rocky

rocky commented Nov 9, 2026

Copy link
Copy Markdown
Member

The speed gain looks like up to 10–15%, but my timings were noisy, so that would need a proper benchmark and would be a separate question.

I was thinking about this some more, and I think the tracing can be handled without the decorator either by monkey-patching or by using Python's newer sys.monitoring module. This might be a bit complicated, though, and would be handled outside of this codebase in Mathics3-Module-Trepan.

@rocky

rocky commented Nov 9, 2026

Copy link
Copy Markdown
Member

Looks like the test-interrupt program has a problem on macOS with Python 3.14 (but not Python 3.13). And I wonder what happens on 3.15?

On macOS a killed process cannot finish exiting while output it wrote to
the pseudo-terminal is unread, so wait() in the test's teardown blocked
until CI cancelled the job. The terminal tests run only where the
evaluation has its own thread, which is why 3.14 hung and 3.13 did not.

Also, from the review of #2127: Ctrl-C with no Evaluation on the stack
opens the interrupt menu again, exc_result is documented as SymbolNull,
and a stray # is gone from a comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tombouctou

Copy link
Copy Markdown
Collaborator Author

Fixed in 958037e. It was the test's teardown, not Mathics3: on macOS a killed process can't finish exiting while its output to the pty is unread, so wait() blocked. The terminal tests are skipped on 3.12/3.13 (no evaluation thread), which is why only 3.14 hung. I couldn't test 3.15 yet: on the alpha, the install fails with "Cython does not appear to be installed". The fix doesn't depend on the Python version.

@rocky

rocky commented Nov 9, 2026

Copy link
Copy Markdown
Member

All of this looks good, and remaining issues, like wording of error messages on can be addressed in future PRs.

There may be a SegFault in 3.11 still with this, but let's drop support for 3.11 in the next release, since 3.15 is coming in.

@rocky
rocky merged commit 53c4a7c into master Nov 9, 2026
15 of 16 checks passed
@rocky
rocky deleted the deep-recursion-stack branch November 9, 2026 13:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants