Repository navigation
Deep recursion: $RecursionLimit = Infinity goes to 100000 levels, on a thread with a large stack - #2121
Conversation
…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>
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
Fixed:
Remaining difference: a single long call that never reaches Found on master, unchanged here:
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: 🤖 Generated with Claude Code |
|
Follow-ups to the two master bugs listed above:
Both are independent of this PR and branch from master. 🤖 Generated with Claude Code |
…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>
|
Interesting. Give me some time to research this and think about it. |
|
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. |
|
I looked at 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:
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:
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. |
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. |
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. |
|
I measured this. Removing |
Address some `mypy` and `ruff` errors
(`isort` errors are covered by `ruff`).
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. |
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. |
|
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>
|
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 |
|
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. |
Found while running the examples of Skiena and Pemmaraju's Computational Discrete Mathematics with Combinatorica, which runs
DepthFirstTraversal,ConnectedQ,BiconnectedComponents,EulerianQ,Bridgesand others underBlock[{$RecursionLimit = Infinity}, ...]. Since #2080, Infinity there was capped at the largest integer$RecursionLimit(512), soDepthFirstTraversal[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:RecursionError→$Aborted$Aborted(a fixed C-call counter that ignores stack size)RecursionError("Stack overflow (used 8144 kB)") →$AbortedA 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_DEPTHtoday can crash 3.11. Mathics3 used to run the evaluation on a thread withthreading.stack_size(python_stack_size(...))when that variable was raised (7a0fa0e); #1177 (stopit for TimeConstrained) removed it, andpython_stack_size()stayed unused.Proposal (this PR)
$RecursionLimit = Infinitygoes toMAX_INFINITE_RECURSION_DEPTH= 100000 (settings.DEFAULT_MAX_INFINITE_RECURSION_DEPTH), and no longer to the largest integer$RecursionLimit. The integer range stays 20..512 (orMATHICS_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.KeyboardInterruptis 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 theinterrupt>menu at its nextcheck_stopped(). TimeConstrained already targets the evaluating thread's id, so it works unchanged.reclimafter aRecursionErrorgives the limit in effect where it happened. It used to give the one restored after leaving the Block ("Recursion depth of 200 exceeded" insideBlock[{$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)
DepthFirstTraversal[GridGraph[20, 20], 2, Edge]DepthFirstTraversal[GridGraph[50, 50], 1]$Aborted$AbortedDepthFirstTraversal[Path[3000], 1]$Aborted$AbortedFull 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 andtest/test_interrupt.py). In aMathicsSession,KeyboardInterruptreaches the caller and no thread is left behind.Open questions
RecursionErroris reported as "Recursion depth of 100000 exceeded." when Python stopped at about 10000 levels. Better wording? Perhaps a message of its own.🤖 Generated with Claude Code