Skip to content

Deep recursion raises a rescuable SystemStackError instead of ending the process - #150

Merged
Largo merged 5 commits into
masterfrom
claude/stack-overflow
Nov 8, 2026
Merged

Largo merged 5 commits into
masterfrom
claude/stack-overflow

Conversation

@Largo

@Largo Largo commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Fixes #128. A recursion deeper than the stack now raises a SystemStackError that the program can rescue and continue from, as in CRuby. Before, the process died of a CLR stack overflow. This holds cold (interpreted) and warm (JIT), and for methods, define_method, lambdas, blocks, method_missing, ensure and threads.

What it took

  • A stack check at entry. RubyOps.RequireSufficientStack runs when a method or block scope is created, and JitRuntime.CheckStack runs at JIT method entry. StackLimit asks the OS for the thread's stack bounds and keeps a margin of 256 KB, or a quarter of the stack if that is less. The runtime's own TryEnsureSufficientExecutionStack keeps only 64 KB, too little for the filters that run while the error goes out.
  • No catch keeps the frames below it (DLR patch 0105). On CoreCLR a catch handler runs on top of the frames the exception came out of. The interpreter's Run, and the filter/fault lowering in TryStatementBuilder, rethrew from inside the catch, so getting the error out needed stack in proportion to the depth. Both now capture the exception with ExceptionDispatchInfo, leave the catch, and throw it from there. InterpretedFrame.GroupStackFrames collapses the catching frame that then appears twice, so backtraces are unchanged (core/kernel/public_send_spec caught this).
  • rescue bodies run after the handler, not inside it (Body.cs). Otherwise the rescue ran on the exhausted stack and its first call raised again.
  • The lambda unwinder filter is typed LambdaUnwinder, not Exception (Proc.cs, BlockDefinition.cs). Every lambda frame used to catch and rethrow, and with the change above that made a deep define_method unwind quadratic (37 s); it now takes about 1 s.
  • JIT methods carry the Ruby method's name. Their frames read in 'Object#jit' instead of :0:in 'jit$jit'.

Cost of the check (Linux, net10.0, Release, pinned to 2 cores, best runs, seconds)

master this PR this PR, check removed
fib(35), JIT 0.121–0.124 0.135–0.140 0.122–0.124
fib(30), JIT 0.013–0.015 0.014–0.015
fibs(27), compiled methods with scopes 0.089–0.095 0.092–0.096
blocks (2M each) 0.50–0.54 0.42–0.47

A JIT method checks the stack only before it calls itself, not at entry. A JIT body enters Ruby code without a scope only through a self-call, so a frame needs one check, before its first self-call, and fib's leaves make none (JitCompiler.StackCheckPlacer). In Release, CheckStack is inlined whole. On the main thread it compares the stack pointer with the main stack's bounds, four instructions; other threads read a thread-static.

fib, whose body is barely more than a self-call, is the worst case: about 10%. Without the check the branch runs at master's speed, so the check is the whole difference. Variants measured on fib(35) that were no better:

  • a check at entry: about 20%
  • the check not inlined: 13%
  • a depth counter passed down the self-calls, with the real check every 8 or 64 levels: about 10%; the extra argument alone cost that much
  • [SkipLocalsInit]: the DynamicMethod still zeroes the probe slot

Testing

  • New Exception_StackLevelTooDeep1 covers five recursion shapes plus a thread. Its expected output is CRuby 4.0's.
  • IronRuby.Tests passes: Linux net10.0, and Windows net10.0 and net8.0 (1088/1088, in a Windows 11 VM).
  • Util/parallel-sweep.sh: identical to master (core 44, library 0, language 1, command_line 0, security 2 failing).
  • Spec files with 0 failures: language rescue/ensure/retry/return/break/next/redo/throw/block/def/lambda/proc; core exception backtrace/cause/full_message, kernel raise/catch/lambda/send/public_send/caller, thread raise/handle_interrupt, proc, method/to_proc.

Not in this PR

  • Windows: 1 MB thread stacks limit recursion depth (Ractor copy, Ruby recursion) well below CRuby's #129 (Windows 1 MB stacks) stays open. Deep recursion is now rescuable on Windows too, but the depth is unchanged. Maximum depth on Windows, IronRuby vs CRuby 4.0.5: JIT method 1,631 vs 10,916 on the main thread and 3,016 vs 10,918 on Thread.new; block recursion 629 vs 1,151. On Linux IronRuby reaches 22,729 (CRuby 10,916). Getting more depth on Windows needs a bigger stack: a larger reserve for the main thread, or running the script on a thread with a larger maxStackSize.
  • A SystemStackError backtrace is much longer than CRuby's (about 168k frames against 10,081), and building it takes about 0.5 s.

🤖 Generated with Claude Code

Largo and others added 4 commits November 8, 2026 17:21
RubyOps.RequireSufficientStack raises SystemStackError when the stack runs
low. StackLimit asks the OS for the thread's stack bounds and keeps a 256 KB
margin (a quarter of a smaller stack), because the runtime's own 64 KB check
leaves too little for the exception's way out. On its own this does not save
a deep interpreted recursion: the DLR interpreter rethrows from inside its
catch, and on CoreCLR the rethrows nest (the next commit fixes that).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es below it

Continues 4225bdf5 (#128). The stack check fired, but the SystemStackError then
ended the process with a CLR stack overflow on its way out, or raised again in
the rescue. On CoreCLR a catch handler runs on top of the frames the exception
came out of, popped only when the catch is left; so

- Build/dlr-patches/0105: the DLR interpreter (Run, for a frame with only a
  finally to run) and TryStatementBuilder's filter/fault lowering rethrew from
  inside the catch, and the rethrows nested - stack in proportion to the depth.
  They leave the catch and rethrow from there (ExceptionDispatchInfo).
- Body.cs: a Ruby rescue clause, matching and body, ran inside the catch, with
  no more stack than the raise had; it runs after the handler now, still inside
  the try that restores $!. `begin ... rescue ... end` without rescue clauses
  is as it was.
- Proc.BuildCall and a block's nested-return filter caught every exception to
  find a LambdaUnwinder; they catch LambdaUnwinder only. With the rethrow
  above each catch cost a capture of the growing trace: a define_method
  recursion took 37 s to unwind, now 1 s.
- JIT-compiled bodies carry the generic body's encoded frame name, so a frame
  of one is "file:line:in 'Object#f'" in a backtrace, not ":0:in 'jit$f'".

Exception_StackLevelTooDeep1: method, interpreted method, define_method,
lambda, ensure, thread; the rescue calls methods; CRuby 4.0's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A thread-static read in JIT-compiled code made fib(30) 2.3x slower. An
address inside the main thread's stack window has room without it, and
JitRuntime.CheckStack writes that test out because the JIT stops inlining
one call deeper. fib(30): master 0.0225 s, before 0.052 s, now 0.029 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The interpreter now rethrows through an ExceptionDispatchInfo, and the trace
then has the catching Interpreter.Run frame twice, around the Throw frame.
Matched with the interpreted frames as two, it took the caller's, and
Kernel#public_send - whose TypeError comes out of an interpreted rule - came
out below its caller in the backtrace (core/kernel/public_send_spec).
InterpretedFrame.GroupStackFrames (patch 0105) makes them one frame again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds stack-bound checks to Ruby method and block scope creation and JIT-compiled methods. It raises SystemStackError when stack space is insufficient. It also changes exception handling so rescue clauses and deferred rethrows run after catch handlers exit, and adds deep-recursion coverage and JIT frame naming.

Changes: Stack exhaustion handling

Layer / File(s) Summary
Stack limits and Ruby scope checks
Src/Ruby/Runtime/StackLimit.cs, Src/Ruby/Runtime/RubyOps.cs
StackLimit obtains stack bounds on Windows, macOS, and Linux, with a runtime fallback when bounds are unavailable or invalid. Method and block scope creation paths check available stack space.
JIT recursion checks and frame names
Src/Ruby/Runtime/Jit/JitCompiler.cs, Src/Ruby/Runtime/Jit/JitRuntime.cs, Src/Ruby/Runtime/Calls/RubyMethodBody.cs, Src/Ruby/Runtime/Jit/JitStub.cs
The JIT tracks self-recursive calls and inserts CheckStack along expression paths. JIT wrappers pass lambda names to stubs, which can apply them to compiled lambdas.
Rescue and deferred exception propagation
Src/Ruby/Compiler/Ast/Body.cs, Build/dlr-patches/0105-rethrow-outside-catch.patch, Src/Ruby/Builtins/Proc.cs, Src/Ruby/Compiler/Ast/BlockDefinition.cs, Build/dlr-patches/README.md
Rescue matching and clauses run after the guarded body’s exception handler exits. The DLR patch captures exceptions and rethrows them after catch handlers exit. Lambda filters now match LambdaUnwinder rather than any exception.
Deep-recursion test coverage
Src/IronRuby.Tests/Runtime/ExceptionTests.cs, Src/IronRuby.Tests/RubyTests.cs
The registered test checks stack exhaustion across several recursion forms, including rescue, ensure, and thread behavior, and verifies that shallow recursion succeeds.

Estimated code review effort: 4 (Complex) | ~50 minutes

Sequence Diagram(s)

sequenceDiagram
  participant JITMethod
  participant JitRuntime
  participant StackLimit
  participant RubyOps
  JITMethod->>JitRuntime: CheckStack before a tracked self-call
  JitRuntime->>StackLimit: Check off-main-thread stack sufficiency when needed
  StackLimit-->>JitRuntime: Return stack sufficiency
  JitRuntime->>RubyOps: Throw stack-level-too-deep error when insufficient
Loading

Suggested reviewers: claude, sholden

Merge Risk: Minimal · up to a32cc

This change makes deep recursion raise a rescuable SystemStackError instead of terminating the process. No actionable merge-blocking risk was identified in the reviewed code.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title states the main change: deep recursion now raises a rescuable SystemStackError instead of terminating the process. The raw summary and objectives confirm this. The changes add stack checks i…
Linked Issues check Passed Issue #128 requires that deep recursion in JIT-compiled methods raise a rescuable SystemStackError instead of ending the process with a CLR stack overflow.

Implementation at the reviewed head:
- JitR…
Out of Scope Changes check Passed Each change connects to the #128 outcome or is disclosed:
- DLR patch 0105 (Build/dlr-patches) and the README entry: Interpreter.Run and TryStatementBuilder capture exceptions with ExceptionDispatchIn…
Full details: Title check

Explanation

The title states the main change: deep recursion now raises a rescuable SystemStackError instead of terminating the process. The raw summary and objectives confirm this. The changes add stack checks in JIT and interpreted paths (RubyOps.RequireSufficientStack, JitRuntime.CheckStack, StackLimit), change exception unwinding and rescue handling (Body.cs, BlockDefinition.cs, Proc.cs, the 0105 rethrow patch), and add the Exception_StackLevelTooDeep1 test. The title is specific and matches linked issue #128. It does not mention the exclusion of Windows depth changes, which is an acceptable omission.

Full details: Linked Issues check

Explanation

Issue #128 requires that deep recursion in JIT-compiled methods raise a rescuable SystemStackError instead of ending the process with a CLR stack overflow.

Implementation at the reviewed head:

  • JitRuntime.CheckStack (Src/Ruby/Runtime/Jit/JitRuntime.cs) compares the address of a stack local with the main-thread bounds (StackLimit._mainLow, _mainSize). Outside that range it calls StackLimit.IsSufficientOffMain. When the stack is insufficient, it calls RubyOps.ThrowStackLevelTooDeep().
  • StackLimit (Src/Ruby/Runtime/StackLimit.cs) reads the OS stack bounds per thread (Windows, macOS, Linux). It keeps the smaller of 256 KB or one quarter of the stack. It falls back to RuntimeHelpers.TryEnsureSufficientExecutionStack() only when the bounds are unavailable.
  • JitCompiler.StackCheckPlacer places CheckStack before the first self-call on each control-flow path. The compiler code was not read directly. This placement comes from the PR description and the change summary.
  • RubyOps.RequireSufficientStack covers interpreted method and block scope creation (from the change summary).
  • The unwinding changes (DLR patch 0105, Body.cs rescue after handler exit) let the error reach a rescue clause on an exhausted stack.

Tests: Exception_StackLevelTooDeep1 covers five recursion shapes and a thread. The author reports IronRuby.Tests passing on Linux and Windows. I did not run these tests.

The Windows depth limit (#129) is excluded by the PR. This does not affect #128, which asks for a rescuable error, not a greater depth.

Full details: Out of Scope Changes check

Explanation

Each change connects to the #128 outcome or is disclosed:

  • DLR patch 0105 (Build/dlr-patches) and the README entry: Interpreter.Run and TryStatementBuilder capture exceptions with ExceptionDispatchInfo and rethrow outside the catch. This reduces stack use during unwinding. InterpretedFrame.GroupStackFrames keeps backtraces unchanged.
  • Body.cs: rescue clauses run after the guarded handler exits, so the rescue does not run on the exhausted stack.
  • Proc.cs and BlockDefinition.cs: the lambda-unwinder filter is typed LambdaUnwinder. This avoids catch-and-rethrow in every lambda frame during deep unwinding.
  • RubyTests.cs: registers Exception_StackLevelTooDeep1, the test for this change.
  • JitStub.cs and RubyMethodBody.cs: JIT method frames now carry the Ruby method name (for example 'Object#jit' instead of 'jit$jit'). This does not affect recursion behavior. It is not required by #128, but the PR describes it and it changes only frame labels. The change is small and disclosed, so it is not treated as unrelated work.

No change was found that is unconnected to #128 or to the disclosed work.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 608d4bd and a32cc20.

Files selected for processing: 2

  • Src/Ruby/Runtime/Jit/JitCompiler.cs
  • Src/Ruby/Runtime/Jit/JitRuntime.cs

Included review availability: This review used your included allowance. 1 included review remains after this review. Your included PR review attempts over the past 7 days set your current allowance at 2 reviews per hour.

A JIT body enters Ruby code that makes no scope only by calling itself, so a
frame needs the check once, before its first self-call: fib's leaves make
none. CheckStack is inlined whole (it was measured on a Debug build, where
nothing is inlined into a DynamicMethod). Release, fib(32) best of 10:
master 0.0297 s, check at entry 0.035 s, now 0.0325 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

Deep recursion in JIT-compiled code kills the process instead of raising SystemStackError

1 participant