Repository navigation
Exception correctness: $! after an ensure that jumps, causes of C#-raised errors, refined === in rescue, backtrace frames and lines - #204
Merged
Conversation
…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]>
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
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. View limit details
|
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]>
This was referenced Nov 11, 2026
Merged
This was referenced Nov 19, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:CompilationThresholddefault), sync-compiled (1) and compiled (0), on net10.0 and net11.0.1.
$!survives anensurethat returns (found in #192) - fixedbefore:
#<RuntimeError: boom>twice (the swallowed exception became the next raise's cause) · after (CRuby):nil,nilThe body now saves
$!on entry, and the ensure clause's own finally restores it unless the clause completed: areturn,break,next,throw, or abreakfrom 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
ensureon .NET 9+ (found in #194) - fixedbefore (compiled, net10.0/net11.0):
x.rb:2:in 'Object#m',x.rb:2:in 'Object#m',x.rb:3:in '<main>'(a top-levelbegin/ensurealso 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_StackLevelTooDeep1caught 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
whileloops (found in #189) - fixedbefore:
["-e:16707566:in '<main>'"]· after (CRuby):["-e:1:in '<main>'"]. Alsocaller_locations,Thread#backtraceof 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; mprinted only themframe): the catch-site walk skipped the catching frame'sRunas 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'sSourceLineMarkernow 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 aCompiledFrameExpressionwith its own line records, and saved code drops markers, so nothing else pays.4.
causeis nil for C#-raised exceptions in a rescue clause (found in #192's review) - fixedbefore:
nil,nil· after (CRuby):#<RuntimeError: a>,#<RuntimeError: b>. Alsonil.foo,[].fetch,Integer("x")in rescue clauses, rescue modifiers (raise "e" rescue 1/0) and ensure clauses, and the cause line of the thread'sreport_on_exceptionmessage.#194's
RescuePassCommitand #192'sPassEnsurecovered 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#newreplaces the exception (HandleException).5. A refined
Module#===is not used byrescue- fixedbefore:
RuntimeErrorescapes · after (CRuby)::refined.CompareExceptioncalls a refined===through a scope-carrying site when one is active where the clause is written (MRI'scheck_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 throughCompareExceptiondecides, as it must.6.
Enumerator#nextbacktraces lack the generator frames - not fixed (deeper than it looks)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'(pathnil, lineno 0 inbacktrace_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'sFiberandEnumerator.__iter_fiber_for__frames all sit there), (b) a frame forEnumerator::Generator#each, which IronRuby's generator does not have (it calls the block throughProc#call), and (c) MRI's progname-and-no-line format plusnil/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.> FAILED.SPEC_REF, Debug, master vs branch, net10.0 (branch also net11.0): language 2935/0 failures/1 error (the knownsend_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.reviewskill, independent agent): one Should-fix (the loop record kept a returned frame's locals alive, reproduced withObjectSpace::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-linebegin … ensure … endreports 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,
tasksetone 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):p20e20(20ensures)r20(20 non-matchingrescues)throwthrough 20ensureswhileat top level (compiled loop in an interpreted frame), ns/iterNo 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


Confidence Score: 5/5
The PR appears safe to merge; no actionable issues were found.Summary
This PR fixes exception state and backtraces:
===from their own scope.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#nextgenerator 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