Skip to content

Refinements: cheaper lexical guards and precompiled dispatchers - #56

Merged
Largo merged 3 commits into
Largo:masterfrom
sholden:perf/refinement-guard-upstream
Oct 29, 2026
Merged

Largo merged 3 commits into
Largo:masterfrom
sholden:perf/refinement-guard-upstream

Conversation

@sholden

@sholden sholden commented Oct 29, 2026 •

Copy link
Copy Markdown

Refined calls currently check the caller's lexical refinements by walking scopes, and cannot use precompiled dispatchers. Calls in a method can instead check the refinement record captured by its def. This PR makes that check cheaper for ordinary Ruby refinements, independently of scoped CLR extensions.

  • Walk scopes in a loop, skipping repeated runtime checks.
  • Read the definition record directly for calls in a method or a block written directly in it, while respecting Module#refine block overrides and definitions run again under different refinements.
  • Use refinement-aware precompiled dispatchers for eligible Ruby methods, preserving the receiver class-version check and switching to compiled bodies when available.

Built on the merged #49. Contains only the three general refinement commits. The CLR namespace activation work and its integration tests belong to #50, which will be layered on this change.

One edge case is made consistent: when the same def runs again under other refinements while an earlier call is still executing, that running call sees the updated definition record even if its scope previously evaluated a string. Previously it retained the old refinements only in the string-eval case. CRuby retains the old refinements; the triggering top-level block behavior already differs in IronRuby.

Validation on Linux, Release, .NET 10:

  • Build succeeds with no warnings or errors.
  • Full IronRuby.Tests suite passes against the complete CI DLR patch series.
  • All 11 refinement tests pass in Debug as well as Release.
  • Refinement binding matrix matches CRuby with JIT/OSR enabled and disabled.
  • JIT matrix matches CRuby.
  • Refinement core specs: 100 examples, no failures or errors.
  • Language specs: 2,935 examples, no failures or errors.
  • New Refinements9–11 cover record changes, refine-block overrides, and dispatcher calls with arguments and blocks. Existing Refinements8 OSR regression coverage is preserved.

Summary by CodeRabbit

  • Bug Fixes
    • Improved Ruby refinement handling when methods are redefined, keeping refinement behavior consistent across subsequent and already-running calls, including calls within blocks and evaluated expressions.
    • Corrected refinement visibility in blocks executed by Module#refine.
    • Fixed refined method dispatch for calls with or without arguments and blocks.

sholden and others added 3 commits October 29, 2026 10:41
The rule of a call a refinement could change tests, on every call, that the
caller's scope has the refinements the call was bound under. The scope
answered by recursion. A block scope asked its parent, which asked its own,
and every step checked again that something had been refined, read the
context's refinement version and looked for the memo that only scopes with
rare state keep. For a call in a block in a method that was two calls and
some twenty dependent loads.

The rule now calls RubyScope.GetLexicalRefinements. It leaves out the
"anything refined?" test, since a rule with the guard is only built once
something has been refined, and that stays true. It walks the chain in a
loop. A scope without rare state has no `using' of its own and no memo, so a
block steps to its parent unless its Proc has a refine block's override, and
a method answers from its definition record. The first scope with rare state
answers from its memo, read in place, or takes the general step as before,
which recurses from there. GetActiveRefinements is the same walk behind the
"anything refined?" test, so every caller gets the answer it got before.

A refined call in a block in a method, 20 million calls on one core in
Release, took 0.75 s before and 0.66 s after, against 0.56 s for the same
call to an ordinary method. Made directly in the method it went from 0.68 s
to 0.63 s. Five million calls in a block at the top level went from 0.27 s to
0.25 s, against 0.22 s, and in a class body from 0.32 s to 0.29 s, against
0.25 s.

There are no new tests, since every answer is the same. Refinements1-7, the
refinement and binding matrices and the refinement specs cover the walk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… scopes

A method sees the refinements recorded where its `def' ran, and nothing can
`using' anything inside a method. So the scope of a method has exactly the
refinements its record holds. So does the scope of a block written directly
in one, unless a refine block is running the block, because Module#refine
puts an override on the Proc for as long as it runs.

The rule of a refined call made from such a scope now tests that instead of
walking. From a method scope it tests that the scope's record holds the
refinements the call was bound under. From a block scope it tests that the
block's parent is a method scope whose record holds them, and that no refine
block is running. The test is chosen for the kind of scope the call was bound
from, and the rule is shared like any other. The scope of another method with
the same refinements passes it, and any other scope fails it and is bound
with the walk.

- RubyUtils.EvaluateRefinementBlock counts the refine blocks running, in
  RubyOps.RefineBlocksRunning, around setting and restoring the override.
  While none is running no Proc has an override, so the walk also steps over
  a block scope without reading its Proc.
- RubyMethodBody.SetDefinitionRefinements bumps the refinement version when a
  `def' runs again under other refinements and compiled code may already use
  its record, so that a scope that memoized the old answer agrees with the
  rules that read the record. That changes one case. A call still running
  when its own `def' ran again under other refinements kept the old ones if
  its scope had evaluated a string, and saw the new ones otherwise. It now
  sees the new ones either way. CRuby keeps the old ones, but IronRuby only
  reaches this case because a block run before and after a top-level `using'
  sees it the second time, and CRuby's block doesn't.

I first gave each method body binders of its own, whose rules tested the
record without a type test. That was no faster, and a file of 2000 methods
calling LINQ's names took twice as long to warm up, because bodies no longer
shared rules.

The same 20 million refined calls on one core went from 0.66 s to 0.62 s in a
block in a method and from 0.63 s to 0.60 s directly in it, against 0.56 to
0.58 s for an ordinary call. #2's benchmark of a hot refined call, run five
times as long, went from 1.96 s to 1.87 s, against 1.80 s.

Refinements8 covers a `def' run again under other refinements, with calls
bound against the old record in the method and in a block, and a call still
running, with and without an eval. In Refinements9, Module#refine runs a
block in a method, and one inside it, after their calls were bound against
the method's record. It fails if the rule or the walk ignores the count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A call a refinement could change never got a precompiled dispatcher, because
a dispatcher tested nothing but the receiver's class version. Where the rule
reads a method's record, a dispatcher can read it too. That is a call made
from the scope of a method, or of a block written directly in one. The
dispatcher tests that the scope is a method scope whose record holds the
refinements the call was resolved under, or a block scope whose parent's
record holds them while no refine block runs.

RubyCallAction.BindPrecompiled resolves such a call under the caller's
refinements and asks the RubyMethodInfo for a refined dispatcher. These are
variants of the WithScope and WithScopeAndBlock dispatchers, generated from
the same templates for arities 0 to 5. Like the others, a refined dispatcher
is pointed at the compiled body when the light compiler compiles it, and a
rule never is. Any other refined call gets a rule as before, and the
dispatchers of unrefined calls are unchanged.

#2's benchmark of a hot refined call, run five times as long on one core,
took 1.87 s with the rule and 1.81 s with the dispatcher, against 1.80 s for
the same call to an ordinary method.

Refinements10 makes refined calls on a Ruby object with no arguments, with
two and with a block, in a method and in a block in it. Then it runs the
`def' again under other refinements and has Module#refine run the block. It
fails if the dispatcher ignores the record or the refine block count.

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

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 10eb1e5a-aa67-4e7c-8dc5-2bd731c319cb
Commits

Reviewing files that changed from the base of the PR and between 3cc808e and 4e5b801.

Files ignored due to path filters: 2
  • Src/Ruby/Compiler/ReflectionCache.Generated.cs is excluded by !**/*.generated.*
  • Src/Ruby/Runtime/Calls/MethodDispatcher.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 10
  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/RefinementTests.cs
  • Src/Ruby/Compiler/ReflectionCache.cs
  • Src/Ruby/Runtime/Calls/MethodDispatcher.cs
  • Src/Ruby/Runtime/Calls/RubyCallAction.cs
  • Src/Ruby/Runtime/Calls/RubyMethodBody.cs
  • Src/Ruby/Runtime/Calls/RubyMethodInfo.cs
  • Src/Ruby/Runtime/RubyOps.cs
  • Src/Ruby/Runtime/RubyScope.cs
  • Src/Ruby/Runtime/RubyUtils.cs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

The change updates lexical refinement lookup, adds refinement-aware dispatch for scoped Ruby calls, and registers three regression tests for method redefinition, refinement blocks, and calls with arguments or blocks.

Changes: Refinement-aware method dispatch

Layer / File(s) Summary
Lexical refinement state
Src/Ruby/Runtime/RubyScope.cs, Src/Ruby/Runtime/Calls/RubyMethodBody.cs, Src/Ruby/Runtime/RubyOps.cs, Src/Ruby/Runtime/RubyUtils.cs
Lexical refinement lookup uses method definition records and refine-block state. Redefining a method updates its stored refinement activation and version.
Refinement-aware call dispatch
Src/Ruby/Compiler/ReflectionCache.cs, Src/Ruby/Runtime/Calls/RubyCallAction.cs, Src/Ruby/Runtime/Calls/MethodDispatcher.cs, Src/Ruby/Runtime/Calls/RubyMethodInfo.cs
Scoped calls resolve against captured refinements and use refined Ruby-object dispatchers. Dispatcher guards check the method definition record or eligible block context.
Refinement regression coverage
Src/IronRuby.Tests/Runtime/RefinementTests.cs, Src/IronRuby.Tests/RubyTests.cs
Three registered tests cover method redefinition, calls inside refinement blocks, and refined dispatch with arguments and blocks.

Priority: Normal

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

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant RubyCallAction
  participant RubyScope
  participant RubyMethodInfo
  participant RefinedMethodDispatcher
  RubyCallAction->>RubyScope: Read lexical refinements
  RubyCallAction->>RubyMethodInfo: Resolve method and request refined dispatcher
  RubyMethodInfo->>RefinedMethodDispatcher: Create dispatcher with refinement activation
  RefinedMethodDispatcher->>RubyScope: Check method record or eligible block context
Loading

Possibly related PRs

  • Largo/ironruby#49: Establishes refinement tracking and definition-time activation records that this change extends.
  • Largo/ironruby#50: Uses the same refinement activation path for scoped CLR extensions.
  • Largo/ironruby#22: Introduces method-definition refinement state and call infrastructure extended by this change.

Suggested reviewers: largo

Merge Risk: Minimal · up to 4e5b8

No demonstrated issue currently prevents merging after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main changes: optimized lexical refinement guards and precompiled refinement dispatchers.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 12 functions across 10 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Largo

Largo commented Oct 29, 2026

Copy link
Copy Markdown
Owner

@sholden thanks, this is great. A review turned up one small thing: EvaluateRefinementBlock raises RefineBlocksRunning and then computes the block's refinements still outside the try, so an exception there would leave the count raised for the life of the process. The fix is one commit on top of this exact head, on review/56-refine-counter (9e3bb66): it computes the activation first and moves the rest into the try.

I'm merging that branch with a merge commit, so this PR shows as merged with your commits as they are. Please don't force-push this branch in the meantime.

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