Skip to content

Refinements: only refined calls pay, and the JIT and OSR keep working - #2

Closed
sholden wants to merge 11 commits into
fix/clr-extensions-stale-overloadsfrom
perf/refinements
Closed

sholden wants to merge 11 commits into
fix/clr-extensions-stale-overloadsfrom
perf/refinements

Conversation

@sholden

@sholden sholden commented Oct 29, 2026 •

Copy link
Copy Markdown
Owner

Defining a refinement anywhere used to slow down the whole program, whether or not anything ever using'd it. RegisterRefinedModule switched the method JIT off for the rest of the process and set a global flag. Under that flag every fast path in call dispatch stood down: precompiled dispatchers, rules shared across receiver classes, the respond_to? and send intrinsics, the JIT's direct keyword calls and OSR loops. Every method compiled after that point also allocated a scope side object on each call to remember the refinements of its def. A benchmark that defines one refinement and never activates it ran about 45% slower than the same benchmark without it.

With this PR a refinement costs something only at the calls it can change.

What CRuby, JRuby, YJIT and ZJIT do

CRuby marks a method entry REFINED, per class and method name, when a refinement defines a method of that name. Only a call that lands on a REFINED entry searches the caller's cref for active refinements. Every other call runs as if refinements didn't exist.

YJIT and ZJIT give up on a call site that hits a REFINED entry. YJIT exits to the interpreter there and counts it as send_refined_method. ZJIT keeps a generic send instead of a direct call and records SendNotOptimizedMethodType(Refined). Everything else compiles as usual.

JRuby decides at compile time which scopes might see refinements. Only call sites in those scopes get a RefinedCachingCallSite, which looks methods up with the scope's refinements, and those sites don't use invokedynamic.

IronRuby now keeps an index like CRuby's REFINED entries, so the binder can tell cheaply and exactly whether a refinement could change a call. It also keeps more compiled than the two JITs do. A method body's refinements are fixed once its def runs, so the method JIT compiles with them instead of giving up.

What changed

  • RubyContext keeps an index from each refined module to the method names its refinements define, plus a lock-free set of every refined name. A method added to or removed from a refinement registers its name and re-versions the classes below the refined module, so calls that were bound without a guard bind again.
  • A call is refinement sensitive only if a refinement of the receiver's class, or of one of its ancestors, defines a method of that name. Only those calls take the lexical guard. Precompiled dispatchers, shared rules, respond_to?(:sym) folding and the JIT's direct keyword calls step aside only for those (class, name) pairs.
  • The method JIT keeps compiling after a refinement appears. It resolves the operators it would inline and the self-calls it would bind directly under the refinements active where the method was defined, the same way the method's call sites resolve them, so a refined + stays a real call. OSR loops do the same with their scope's refinements and check them on entry. JitRuntime.Disable() is gone.
  • A method defined where nothing is using'd compiles with no refinement record. Where there is a record, it's a field of the method scope instead of a per-call allocation.
  • RefinementActivation instances are interned by contents, so a using in one file no longer fails the guards of refined calls in other files.
  • "#{x}" and &x take the refinement-aware path only when some refinement defines to_s, to_proc or the symbol's method.

Bugs fixed on the way

All three fail on master and match CRuby here.

  1. A method added to, redefined in or removed from an active refinement outside its refine block was ignored by call sites that had already run.
  2. A refined operator added after a method turned hot was ignored the same way.
  3. A method defined before anything was refined, but first called after, saw a using that came later in its file.
def before(s) = (s.r rescue :plain)
module R; refine(String) { def r = :refined }; end
before('x')   # :plain
using R
before('x')   # master: :refined, CRuby and this PR: :plain

Numbers

Release build, net10.0, on Linux.

The first benchmark runs fib(31) and 12 million small allocations, and defines one refinement that it never usings. master takes 2.99–3.25 s. This PR takes 2.06–2.11 s, against 2.05–2.09 s for the same program without the refinement.

A hot call to an active refinement, 3 million calls, takes 0.56–0.63 s against 0.52–0.53 s for the same call to an ordinary method. That 10–20% is the guard.

Across the 63 benchmarks in Util/bench, the geometric mean is 1.002 times master's. respond_to and sort_strings got 15–20% faster. A few others moved on the first run and came back within the noise on a rerun.

Tests

  • New Refinements1–7 in Src/IronRuby.Tests/Runtime/RefinementTests.cs cover methods arriving late in a refinement, refined operators after a method turned hot, sensitivity per name and per class with module and CLR class refinements, respond_to?, conversions, a def re-run under a using, and a def that ran before anything was refined.
  • New Util/refinement-binding-matrix.rb exercises the bound paths. IronRuby prints the same as CRuby 4.0 with the JIT and OSR on and off. Section 9 of Util/jit-matrix.rb now checks what the JIT compiles once a refinement exists, and it matches CRuby too. The existing Util/refinement-matrix.rb prints the same as on master.
  • IronRuby.Tests passes with 0 failures. ruby/spec spec/language passes with 2935 examples and 0 failures. These refinement-related core specs pass with 205 examples and 0 failures:
spec/core/module/{refine,using,refinements,used_refinements,instance_method}_spec.rb
spec/core/refinement spec/core/main/using_spec.rb spec/core/symbol/to_proc_spec.rb
spec/core/kernel/{send,public_send,respond_to,method}_spec.rb

Stack

  1. CLR extension methods reach a method group used before using_clr_extensions #1 fixes stale CLR overloads after using_clr_extensions
  2. Refinements: only refined calls pay, and the JIT and OSR keep working #2, this PR
  3. using System::Linq: CLR extension methods scoped like C#'s using directive #3 scopes CLR extension methods with using. It needs this PR, but this PR doesn't need it and can merge on its own.

🤖 Generated with Claude Code

Follows Largo#41, which skips Module#const_set's caller lookup while ruby4.rb
runs as the core prelude - but only under --disable-gems, where the host
loads ruby4.rb itself. In an ordinary startup gem_prelude.rb requires it,
the flag is never set, and every const_set in the prelude still walks the
stack; Errno::EHWPOISON.const_source_location(:Errno) even answered
gem_prelude.rb:7.

- Loader: ruby4.rb counts as the core prelude whenever LoadCorePrelude
  loads it, directly or from gem_prelude.rb.
- Module#const_set records no location for the prelude's constants, so
  const_source_location answers [] for them, as MRI does for its C core.
- The Errno loop assigns a fresh class's constants (klass::Errno = ...)
  rather than calling const_set on ~120 new receivers, each of which
  bound a call-site rule.
- The backtrace builder finds the classes that copy a module in with one
  scan of IronRuby.Libraries per process, not one per module.
- Encoding.name_list / Encoding.list reuse one encoding list.
- On .NET the console no longer probes the .NET Framework configuration
  system, which could only fail with a FileNotFoundException.

`ir -e ''` 0.871 -> 0.852 s, --disable-gems 0.572 -> 0.566 s (R2R,
median of 20 interleaved runs on a loaded host).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sholden added a commit that referenced this pull request Oct 29, 2026
… 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]>
sholden added a commit that referenced this pull request Oct 29, 2026
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]>
Largo and others added 5 commits October 29, 2026 14:44
- A file ruby4.rb requires from outside its own directory - an argf.rb
  earlier on the load path, say - runs with the core-prelude marker
  lifted, so its constants keep their source locations.
- The Encoding list cache is gone: Encoding.GetEncodings() includes the
  encodings of providers registered later, which a cached list would
  never show, and on master the list is cheap enough already.
- The console host's config-probe bypass is gone: the DLR CI builds
  against (922753f8) already skips ConfigurationManager when there is no
  .config file, and the override would also have ignored the
  configuration of an application deriving from RubyConsoleHost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…signal at a timeout, MRI's timeout errors

The wait_spec failures in Util/sweep-core.tsv were stale (fixed by 4c5d542 and 4b0848c):
spec/core/conditionvariable passes, 11 of 11. Comparing against MRI 4.0 turned up three
problems the specs do not cover:

- #wait on a mutex the thread does not hold raised ThreadError but left the thread queued
  as a waiter. The next #signal went to it: the real waiter slept through its timeout, and
  the failed caller kept a latched wake that cut its next sleep short.
- #signal woke a waiter outside the waiter-list lock, so one whose timeout ran out at the
  same moment answered nil, the signal was lost, and the wake stayed latched. The wake is
  now sent under the lock, and a waiter that finds itself taken off the list counts as
  signalled and clears the latch.
- #wait(mutex, timeout) took Queue#pop's conversion: a negative timeout returned at once
  and other types got "no implicit conversion". It now shares Mutex#sleep's conversion,
  which also learns MRI's RangeError for a Bignum, NaN and Infinity.

Util/condvar-matrix.rb diffs these against CRuby.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…so on, as in MRI

The Threading library defined them at the top level and ruby4.rb aliased them into
Thread, so their name - and with it #inspect, #name and every error message that
names the class - was "Mutex" where MRI says "Thread::Mutex". They are now defined
in Thread (DefineIn) and the top-level names are the aliases.

ClassInitGenerator: a class nested in an unnamed extension of a CLR type was
qualified with the CLR name (System::Threading::Thread::Mutex). It now takes the
Ruby name another library of the assembly gives that type - the builtins'
[RubyClass("Thread", Extends = typeof(Thread))]. Regenerating also renames the
private loader methods of one Kernel extension (LoadIronRuby__Builtins__Kernel_*
to LoadKernel_*); nothing else in Initializers.Generated.cs changes.

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

A #signal could pick a waiter between its registration and a failed
RubyMutex.Unlock (a #wait on a mutex the thread does not hold). The cleanup's
LinkedList.Remove then threw InvalidOperationException instead of the
ThreadError, and the signal was lost to the real waiter. Unlocking and queueing
under the waiter-list lock closes the gap and makes the cleanup unnecessary.
(CodeRabbit review on Largo#42.)

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

Core prelude constants: no source location with gems either; Errno loop, backtrace names
Largo added 3 commits October 29, 2026 16:15
ConditionVariable#wait: no stale waiter after a failed wait, no lost signal at a timeout, MRI's timeout errors
…rloads

CLR extension methods reach a method group used before using_clr_extensions
Mutex, Queue, SizedQueue and ConditionVariable are Thread::Mutex and so on, as in MRI
sholden added a commit that referenced this pull request Oct 29, 2026
… 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]>
sholden added a commit that referenced this pull request Oct 29, 2026
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]>
sholden and others added 2 commits October 29, 2026 08:57
Defining any refinement used to switch off, for the whole program, every fast
path call dispatch has: precompiled dispatchers, rules shared across receiver
classes, the respond_to?/send intrinsics, direct keyword calls, OSR loops and
the method JIT (permanently, and process-wide). Every method compiled after it
also allocated a scope side object on each call to record its definition-time
refinements. A program that merely loaded a refinement ran ~45% slower.

What a refinement can affect is now tracked the way CRuby's REFINED method
entries do it: per refined module and method name. A call is refinement
sensitive only if some refinement of the receiver's class or one of its
ancestors has a method of that name; only those calls take the lexical guard,
and every other call is bound, dispatched and JIT-compiled as if nothing were
refined.

- RubyContext keeps { refined module -> names } (plus a lock-free set of all
  names). A method coming or going in a refinement registers its name and
  re-versions the classes below the refined module, so calls bound without the
  guard re-bind. This also fixes calls that kept their old target when a method
  was added to, redefined in or removed from an active refinement outside its
  refine block.
- Precompiled dispatchers, shared rules, respond_to?(:sym) folding and the JIT's
  direct keyword calls step aside only for sensitive (class, name) pairs.
- The method JIT resolves the operators and self-call a body binds under the
  refinements active where the body was defined, the way its call sites would,
  instead of standing down. OSR loops do the same with their scope's
  refinements, with an entry guard on them. JitRuntime's global kill switch is
  gone.
- A method defined where nothing is `using'd is compiled with no refinement
  record at all (a later def of the same body where one is active recompiles
  it, as before), and the record, where there is one, is a field of the method
  scope rather than a per-call allocation.
- RefinementActivation instances are interned by contents, so a `using' in one
  file no longer fails the guards of refined calls in every other file.
- "#{x}" and &x only take the refinement-aware path when some refinement has
  #to_s / #to_proc / the symbol's method.

A program that defines refinements without hot refined calls now runs at the
speed of one that defines none (2.1s against 3.0-3.2s before on the long run of
a fib + allocation benchmark); a hot refined call costs ~10-20% over a plain one
for the guard.

Refinements1-6 cover late arrivals in a refinement, refined operators after a
method turned hot, per-name and per-class sensitivity (module and CLR class
refinements), respond_to?, conversions, and a def re-run under a using.
Util/refinement-binding-matrix.rb diffs the bound paths against CRuby with the
JIT and OSR on and off; Util/jit-matrix.rb section 9 now checks what the JIT
compiles once a refinement exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A method body records the refinements active at its `def' only once something
has been refined. A method defined before that, but first called (compiled)
after, got an empty record that meant "follow the declaring scope", so a
`using' that came later in the scope it was written in reached into it:

  def before(s) = (s.r rescue :plain)
  module R; refine(String) { def r = :refined }; end
  before('x')   # :plain
  using R
  before('x')   # :refined - CRuby: :plain

A def that runs with nothing refined now marks its body, and a compilation for
its module with nothing recorded sees no refinements. A copy compiled for a
refinement (Refinement#import_methods) still follows the scope it was given.

Refinements7 and section 9 of Util/refinement-binding-matrix.rb cover it.

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

sholden commented Oct 29, 2026

Copy link
Copy Markdown
Owner Author

Moved upstream: Largo#49, rebased onto Largo's master (the fix it sat on merged there as Largo#43). The branch stays; #3 is based on it.

@sholden sholden closed this Oct 29, 2026
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