Skip to content

Exception correctness: $! after an ensure that jumps, causes of C#-raised errors, refined === in rescue, backtrace frames and lines - #204

Merged
Largo merged 3 commits into
masterfrom
claude/exception-correctness
Nov 11, 2026
Merged

Largo merged 3 commits into
masterfrom
claude/exception-correctness

Conversation

@Largo

@Largo Largo commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Fixes a group of exception and backtrace bugs that #189, #192 and #194 found and noted as pre-existing on master. CRuby 4.0.9 is the reference; every "after" below matches its output, interpreted (-X:CompilationThreshold default), sync-compiled (1) and compiled (0), on net10.0 and net11.0.

1. $! survives an ensure that returns (found in #192) - fixed

def m; begin; raise "boom"; ensure; return 42; end; end
m; p $!
begin; raise "later"; rescue => e; p e.cause; end

before: #<RuntimeError: boom> twice (the swallowed exception became the next raise's cause) · after (CRuby): nil, nil

The body now saves $! on entry, and the ensure clause's own finally restores it unless the clause completed: a return, break, next, throw, or a break from a block it yields to ends the exception, as MRI's $! (the errinfo of the innermost rescue/ensure frame still running) says. An exception the clause raises still gets the handled one as its cause: a filter around the statements decides it before that finally runs (compiled: a real filter that lets it through; interpreted: a catch that also captures the backtrace, then throws again).

2. Duplicate frame for a raise in an ensure on .NET 9+ (found in #194) - fixed

class A < StandardError; end; class B < StandardError; end
def m; raise A; ensure; raise B; end
begin; m; rescue => e; puts e.backtrace; end

before (compiled, net10.0/net11.0): x.rb:2:in 'Object#m', x.rb:2:in 'Object#m', x.rb:3:in '<main>' (a top-level begin/ensure also gained <main>:0) · after (CRuby): x.rb:2:in 'Object#m', x.rb:3:in '<main>'

.NET 9+'s managed exception handling puts both the funclet (the finally block) and the method body in the exception's own trace; stack walks and net8.0 are right. Compiled Ruby methods can call themselves with no frame in between (the first attempt, dropping any adjacent duplicate, collapsed deep recursion: Exception_StackLevelTooDeep1 caught it), so a statement of an ensure clause now sets its frame record's line negated (no extra store), and an exception's backtrace drops the frame right below a frame of the same compiled method whose record was in an ensure clause. Recursion from a body and from an ensure clause keep every frame (in the test).

3. Line 16707566 in hot while loops (found in #189) - fixed

i=0; while i < 3000; i+=1; p caller(0,1) if i == 2999; end

before: ["-e:16707566:in '<main>'"] · after (CRuby): ["-e:1:in '<main>'"]. Also caller_locations, Thread#backtrace of a thread spinning in such a loop, const_source_location, and exception backtraces. And an exception rescued inside such a loop lost the outermost frame (def m; while ...; begin; raise "x" if i == 2999; rescue => e; p e.backtrace; end; end; end; m printed only the m frame): the catch-site walk skipped the catching frame's Run as if the throw-site trace had ended with it, when it ended with the loop's DynamicMethod.

A frame running a loop the interpreter compiled (CompiledLoopInstruction) stays at the loop's instruction, whose sequence point is the cleared one. The loop compiler's reduction of a statement's SourceLineMarker now stores the line in a record of the interpreted frame (PrecompiledFrames.GetLoopLine), held in a hidden variable of the frame: a null check and a store per statement. Records are matched by the frame's depth in the interpreted chain, which is all an exception's saved interpreted frames can be matched by; the record lets go of the frame when the loop is left (review finding: it kept the frame's locals alive). Every other compiled lambda is a CompiledFrameExpression with its own line records, and saved code drops markers, so nothing else pays.

4. cause is nil for C#-raised exceptions in a rescue clause (found in #192's review) - fixed

begin; begin; raise "a"; rescue; 1/0; end; rescue => e; p e.cause; end
begin; begin; raise "b"; rescue 42; end; rescue => e; p e.cause; end

before: nil, nil · after (CRuby): #<RuntimeError: a>, #<RuntimeError: b>. Also nil.foo, [].fetch, Integer("x") in rescue clauses, rescue modifiers (raise "e" rescue 1/0) and ensure clauses, and the cause line of the thread's report_on_exception message.

#194's RescuePassCommit and #192's PassEnsure covered exceptions passing other frames in the first pass. What was left was the frame that rescued: its clauses' finally restores $! before the handler around them (CanRescue) reads it. That handler now gets the exception the clauses ran for (CanRescueAfterClauses). A cause a filter decided is also kept when a class's own #new replaces the exception (HandleException).

5. A refined Module#=== is not used by rescue - fixed

class E1 < StandardError; end
module Yes; refine E1.singleton_class do; def ===(o) = o.message == "match me"; end; end
using Yes
p(begin; raise "match me"; rescue E1; :refined; end)

before: RuntimeError escapes · after (CRuby): :refined. CompareException calls a refined === through a scope-carrying site when one is active where the clause is written (MRI's check_match). #194's rescue filter now stands down only when === itself is refined, instead of for any refinement anywhere in the process; with a refined === the path through CompareException decides, as it must.

6. Enumerator#next backtraces lack the generator frames - not fixed (deeper than it looks)

e = Enumerator.new { |y| y << 1; raise "in gen" }; e.next
begin; e.next; rescue => ex; puts ex.backtrace; end

CRuby: x.rb:1:in 'block in <main>', x.rb:in 'Enumerator::Generator#each', x.rb:in 'Enumerator#each'; IronRuby: the first line only (master and branch).

CRuby's fiber stack ends in C functions with no Ruby frame below them, which it prints as #{progname}:in 'label' (path nil, lineno 0 in backtrace_locations). IronRuby defers a library frame to the next frame with a location, and at the bottom of an enumerator's fiber there is none, so they are dropped. Emitting them needs (a) the fiber machinery below them left out (Kernel#catch, Thread.handle_interrupt, the prelude's Fiber and Enumerator.__iter_fiber_for__ frames all sit there), (b) a frame for Enumerator::Generator#each, which IronRuby's generator does not have (it calls the block through Proc#call), and (c) MRI's progname-and-no-line format plus nil/0 locations. Left for a separate change.

Tests

New, expected output CRuby's: Exception_EnsureJumpCurrentException1, Exception_CauseRaisedInClause1 (interpreting and compiling engines), Exception_RescueRefinedCaseEquality1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1 (interpreting, CompilationThreshold 1 and compiling engines), Backtrace_CompiledLoopLineFrameReleased1.

  • IronRuby.Tests (Debug): net10.0 and net11.0 PASSED, 0 > FAILED.
  • ruby/spec at CI's SPEC_REF, Debug, master vs branch, net10.0 (branch also net11.0): language 2935/0 failures/1 error (the known send_spec "to/into Proc" wording, both), core/exception 250/0, kernel raise 45/0, caller 20/0, caller_locations 18/0, core/thread 395/0, core/fiber 188/0, core/enumerator 432/0 - identical.
  • Review (the repo's review skill, independent agent): one Should-fix (the loop record kept a returned frame's locals alive, reproduced with ObjectSpace::WeakMap + GC.start), fixed in b33c37c with a test. Notes, both pre-existing and unchanged from master: a raise later in the same statement as a one-line begin … ensure … end reports the ensure clause's line; the cleared sequence point right after a loop (while … end.zork) still shows the loop's line or 16707566.

Timing

Release, taskset one core, main-thread CPU, best of 5 × 3000 after 1000 warm-up, base/new/new/base interleaved; the box was at load 8-30, so the ranges are wide. µs per operation (loops: ns per iteration):

net10.0 base net10.0 new net11.0 base net11.0 new
raise rescued in place, depth 0 13-20 13-20 10-13 10-17
same, depth 200 60-93 57-93 60-87 60-100
p20 57-90 57-93 50-67 53-83
e20 (20 ensures) 130-210 137-237 120-203 130-210
r20 (20 non-matching rescues) 57-123 57-117 47-117 50-117
throw through 20 ensures 30-53 33-60 27-47 33-47
hot while at top level (compiled loop in an interpreted frame), ns/iter 73-103 67-103 77-107 77-97

No difference outside the noise. A first version of fix 3 (a thread-local lookup per statement) cost the hot loop ~10-20 %; the per-frame record variable removed that.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; no actionable issues were found.

Summary

This PR fixes exception state and backtraces:

  • Ensure and rescue clauses keep the right exception and cause.
  • Rescue clauses use a refined === from their own scope.
  • Backtraces show an ensure method only once.
  • Backtraces keep source lines and catching frames in compiled loops.

The new tests cover the changed paths, including loop-frame release and recursion. No actionable issues were found. Tests were not run during this review.

Largo explicitly deferred missing Enumerator#next generator frames. Largo also acknowledged the existing same-statement line errors after ensure clauses and loops.

Reviews (1) · Last reviewed commit: "A loop's line record lets go of its fram..." · Reviewed by Greptile

Largo and others added 3 commits November 11, 2026 11:31
…es, refined === in rescue

Three exception-semantics bugs, each pre-existing on master and found in #192/#194:

- An ensure clause left by a jump (return, break, next, throw, a break from a
  block it yields to) swallows the exception it ran for, but $! kept it, so the
  next raise got it as its cause. MRI's $! is the errinfo of the innermost rescue
  or ensure frame still running: nil again once the clause is left. The body now
  saves $! on entry and the ensure clause's own finally restores it unless the
  clause completed. An exception the clause raises still gets the handled one as
  its cause: a filter around the statements decides it before the finally runs
  (compiled a real filter that lets the exception through; the interpreter
  catches, also capturing the backtrace there, and throws again).

- An exception C# threw in a rescue clause (`1/0', `nil.foo', `rescue 42'), a
  rescue modifier, or an ensure clause had no cause: the clauses' finally block
  restored $! before the handler around them (CanRescue) read it. That handler
  now gets the exception the clauses ran for (CanRescueAfterClauses). #194's
  RescuePassCommit and #192's PassEnsure covered the cases where the exception
  passes a frame in the first pass; this covers the frame that rescued. A cause
  a filter decided is also kept when a class's own #new replaces the exception.

- A refinement of `===' active where a rescue clause is written is what MRI's
  rescue calls (check_match). CompareException now calls it through a
  scope-carrying site when one is in play, and #194's rescue filter now stands
  down only when `===' itself is refined rather than for any refinement.

Tests: Exception_EnsureJumpCurrentException1, Exception_CauseRaisedInClause1
(interpreted and compiled engines), Exception_RescueRefinedCaseEquality1;
expected output is CRuby 4.0.9's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eal lines in hot loops

- On .NET 9 and later (its managed exception handling) an exception thrown from a
  catch or finally block has the method twice in its own CLR trace: the funclet
  and the body that called it. A compiled Ruby method's ensure clause is such a
  block, so `def m; raise A; ensure; raise B; end' gave `m, m, <main>' (and a
  top-level begin/ensure an extra `<main>:0'). net8.0 and stack walks are right.
  Compiled Ruby methods can call themselves with no frame in between, so
  adjacency alone does not tell a funclet: a statement of an ensure clause now
  sets its frame record's line negated (SourceLineMarker.InEnsure, no extra
  store), and an exception's backtrace drops the frame right below a frame of
  the same compiled method whose record was in an ensure clause.

- A frame running a loop the interpreter has compiled (CompiledLoopInstruction)
  stays at the loop's instruction, whose sequence point is the cleared one the
  loop starts with: caller, caller_locations, Thread#backtrace and exception
  backtraces reported line 16707566 (0xFEEFEE). The compiled loop is a
  DynamicMethod with no line information, so the loop compiler's reduction of a
  statement's SourceLineMarker now stores the line in a record of the
  interpreted frame (PrecompiledFrames.GetLoopLine), held in a hidden variable
  of the frame: a null check and a store per statement. Records are kept by the
  frame's depth in the interpreted chain, which is all an exception's saved
  interpreted frames can be matched by. Every other compiled lambda is a
  CompiledFrameExpression (its own line records) and saved code drops markers.
  An exception rescued inside such a loop also lost the outermost frame: the
  catch-site walk skipped the catching frame's Run method as if the throw-site
  trace had ended with it, when it ended with the loop's DynamicMethod.

Tests: Backtrace_RaiseInEnsure1 (also recursion from an ensure clause and from
a body), Backtrace_CompiledLoopLine1 (interpreted, CompilationThreshold 1 and
compiled engines); expected output is CRuby 4.0.9's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review finding on the previous commit: the record PrecompiledFrames.GetLoopLine
hands a frame running a loop the interpreter compiled held the InterpretedFrame
until another frame of the thread wrote a loop line, so a method that ran a hot
loop kept its locals alive after it returned. With
`def build; big = Big.new; $w[1] = big; while i < 5000; i += 1; end; end`,
`$w[1]` survived 10 GC.start calls (CRuby, master: collected) at
CompilationThreshold 1 and the default.

The loop that owns the record variable now clears the record's frame and the
variable in a finally as it is left; the record keeps its depth and line, which
the backtrace of an exception that left the loop reads. Test
Backtrace_CompiledLoopLineFrameReleased1.

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

coderabbitai Bot commented Nov 11, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 13 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 82 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a8275a4 and b33c37c.

Files selected for processing: 12

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/BacktraceTests.cs
  • Src/IronRuby.Tests/Runtime/ExceptionTests.cs
  • Src/Ruby/Compiler/Ast/Body.cs
  • Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs
  • Src/Ruby/Compiler/Ast/Instructions/SourceLineMarker.cs
  • Src/Ruby/Compiler/Ast/ScopeBuilder.cs
  • Src/Ruby/Compiler/AstGenerator.cs
  • Src/Ruby/Runtime/PrecompiledCode.cs
  • Src/Ruby/Runtime/RubyExceptionData.cs
  • Src/Ruby/Runtime/RubyOps.cs
  • Src/Ruby/Runtime/RubyStackTraceBuilder.cs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@Largo
Largo merged commit 0ab276b into master Nov 11, 2026
7 checks passed
Largo added a commit that referenced this pull request Nov 11, 2026
Brings in #202 (Integer.sqrt, String#hash) and #204 (exception fixes),
which change ruby4.rb and the code the startup library compiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Largo added a commit that referenced this pull request Nov 11, 2026
…nvalid

PersistedAssemblyBuilder writes a try block nested in a handler after the
clause of that handler; ECMA-335 II.19 wants inner clauses first, and the
JIT rejects such a method with InvalidProgramException at its first call.
Ruby's ensure compiles to that shape whenever the ensure holds a rescue,
and since #204 every ensure that runs Ruby code does (its finally has a
try with a filter that sets $!'s cause). With master merged, 43 methods
of the startup library were invalid - IO.pipe, IO.popen, a Fiber's block
(`ir -e 'p Fiber.new { 1 }.resume'` threw and then hung), Data#hash,
Tempfile.create, Set#each, PrettyPrint#nest... - and 2 before #204. The
startup checks never call them, so the library passed them.

ExceptionClauses.Reorder rewrites each method's clause table of the saved
file in place (same entries, inner ones first). Checked: a one-method
repro (`begin yield ensure @x -= 1 end`) went from InvalidProgramException
to valid; the whole library from 43 methods the JIT rejects to 0 of 5,483;
the repro above prints 1 with the library as without it.

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.

1 participant