Skip to content

Thread.new: let finished threads be collected (DLR ThreadLocal, Thread.list registry) - #208

Merged
Largo merged 3 commits into
masterfrom
claude/issue-89-thread-new
Nov 11, 2026
Merged

Largo merged 3 commits into
masterfrom
claude/issue-89-thread-new

Conversation

@Largo

@Largo Largo commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Part of #89 (the Thread.new.join item).

What was wrong

A perf profile of a Thread.new { }.join loop put most of the process CPU on the finalizer thread, in the CLR's ThreadStore::RemoveThread. A heap dump taken during the loop showed why. The CLR's thread list held about 4,700 dead threads; a plain C# create/join loop holds about 500. Their Thread objects were unreachable, but they had been promoted to gen 2. Two things had kept them alive:

  1. The DLR's ThreadLocal<T> (InterpretedFrame.CurrentFrame). Each entry held its owning Thread, and an entry outlives its thread until the array next grows. The CLR keeps a dead thread's native record and its ManagedThreadId until the Thread is finalized. So ids were not reused, the array grew by one element per new id (copying itself each time), and the list the finalizer walks for each removal stayed thousands of entries long.
  2. RubyThreadInfo._registered (the list behind Thread.list). It kept a finished thread until the next prune, which comes up to 64 thread creations later, or later still when many threads are alive. That was enough for the thread to be promoted.

The new test checks this directly: 20 joined threads were all still alive after three full collections on master (on net10.0 and net11.0); with this branch none are.

Changes

  • DLR patch 0108-ThreadLocal-no-dead-thread-roots.patch: an entry carries a per-thread token object instead of the Thread. A ConditionalWeakTable maps a Thread to its token, weakly, for TryGetValue (patch 0001, used by Thread#backtrace). A finished thread is then collected and its id reused, and a new thread with that id replaces the stale entry the first time it uses the slot. The patch is documented in Build/dlr-patches/README.md. All patches apply in order to DLR_REF.
  • ThreadOps.RubyThreadStart: as its last step it removes the thread's info from _registered (searching from the end of the list). Thread.list already left out threads that are not alive.
  • Tests:
    • Thread_FinishedThreadCollected1 prints 20 on master and 0 here.
    • Dlr_ThreadLocalOwner1: a finished thread is collected; new threads start without its value, including one that gets its id when the CLR reuses it; TryGetValue reads another live thread's value.

This change does not touch ThreadOps.Fiber.cs or RubyUtils.cs.

Numbers

Measured 2026-11-11, Release, taskset -c 3. Each figure is the best of 5 × 20k threads after a warm-up, over three interleaved rounds. The box was at load 13–21, so the ranges are wide.

net10.0 master net10.0 branch net11.0 master net11.0 branch CRuby 4.0.9
main-thread CPU / thread 51–63 µs 49–58 µs 48–55 µs 41–47 µs 27–34 µs
process CPU / thread 152–186 µs 142–171 µs 148–173 µs 124–143 µs 51–60 µs
finalizer-thread CPU, 50k threads 0.47 s 0.19 s 0.38–1.24 s 0.14–0.18 s
bytes allocated / thread 6.3–7.7 KB 3.1–3.2 KB 6.2–6.5 KB 3.4–3.6 KB
dead threads in the CLR's list during the loop ~4,700 ~200
joined threads alive after full GCs (of 20) 20 0 20 0

What is left is the cost of creating and destroying the CLR thread itself. A C# loop of new Thread(...).Start(); Join() costs 39–52 µs main-thread CPU and 112–145 µs process CPU on the same box. UnsafeStart makes no measurable difference. 75 % of the bytes that are still allocated per thread are the runtime's own thread-static array (GetGCThreadStaticsByIndexSlow).

Pooling CLR threads: evaluated, not done

A pool of parked workers would cost about 8–15 µs per hand-off, plus about 2.5 µs for a distinct identity object. Pooling is not safe in IronRuby today, because a Ruby Thread is its System.Threading.Thread:

  • Thread.current must be a new object for each Thread.new, but a pooled worker's Thread.CurrentThread is the worker.
  • Making it work would mean redirecting about 118 Thread.CurrentThread sites and every CLR call on a Ruby thread object (Join, IsAlive, ThreadState, Interrupt, Name, Priority, ManagedThreadId).
  • It would also mean re-keying the async-exception tables in RubyUtils and the fiber ownership in ThreadOps.Fiber.cs.

That is a redesign of the threading identity, and it would conflict with the concurrent Thread#raise/fiber work.

Checked

  • IronRuby.Tests passes in full on net10.0 and net11.0 (Debug).
  • ruby/spec, master against this branch on net11.0 Release: core/thread, core/mutex, core/queue, core/conditionvariable, core/fiber, core/kernel/sleep_spec.rb, library/monitor and library/timeout give the same results on both. That includes the existing Queue#initialize into/to wording error.
  • The branch's spec run was repeated 3 times, twice with two runs in parallel. Under that load Timeout.timeout raises specified error type when it times out fails now and then; master fails it alone too (1 run in 3 on master, 2 in 3 on the branch).
  • The project review skill, run by a separate agent, reported no defects.

Local DLR checkouts need 0108 applied (git -C ../dlr apply Build/dlr-patches/0108-*.patch); otherwise check-dlr-patches.sh fails the build.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 4/5

The PR appears safe to merge, with a non-blocking gap in the ID-reuse test.

Fix All in Claude CodeFindings

  1. P2 Reused slots may go untested ▶
Fix with agent prompt
### Issue 1
Src/IronRuby.Tests/Runtime/MiscTests.cs:2546-2548
`Dlr_ThreadLocalOwner1` can pass without exercising a reused `ManagedThreadId`. The loop creates 20 threads but never checks whether one gets the finished thread's ID. If every thread gets a fresh slot, both freshness checks pass even if the owner check is broken.

Return the original ID from the helper, collect between bounded batches, and assert that reuse occurred before counting this case as covered.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Lets finished Ruby threads be collected sooner:

  • Thread-local values no longer keep finished threads alive.
  • Finished Ruby threads leave the registry as soon as their blocks end.

The new ownership test should also check that it actually exercised a reused ID.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Thread runs Ruby code] --> B[DLR slot stores owner token]
  C[Weak table maps Thread to token] --> B
  A --> D[Ruby block finishes]
  D --> E[Remove info from registered list]
  E --> F[Thread can be collected]
  F --> G[ID can be reused]
  G --> H[New owner token replaces stale slot]
Loading

Reviews (1) · Last reviewed commit: "Thread: drop a finished thread from the ..." · Reviewed by Greptile

Largo and others added 3 commits November 11, 2026 18:24
Thread.new { }.join cost ~51-64 us main-thread CPU and ~150-190 us process
CPU (CRuby 4.0.9: 27-33 / 51-59 us on the same loaded box). A perf profile
of 100k threads put 35-62 % of the process's samples on the finalizer
thread in the CLR's ThreadStore::RemoveThread, plus GetThreadList during
GC suspensions. A heap dump taken mid-loop showed why: ~4,700 dead threads
in the CLR's thread list (a plain C# create/join loop has ~500), their
Thread objects unreachable but promoted to gen 2. They had been held by the
DLR's ThreadLocal<InterpretedFrame> (InterpretedFrame.CurrentFrame), whose
entries held their owning Thread and outlive the thread until the array
next grows. The CLR keeps a dead thread's native record and its
ManagedThreadId until the Thread is finalized, so ids were not reused,
the array kept growing by one (a copy per new id) and the list the
finalizer walks for each removal stayed thousands long. 20 joined Ruby
threads were all still alive after three full collections.

Patch 0108 gives each entry a per-thread token object instead of the
Thread (a ConditionalWeakTable maps a Thread to its token, weakly, for
TryGetValue from patch 0001). A finished thread is collected, its id is
reused, and a new thread with that id replaces the stale entry on first
use.

Measured 2026-11-11, Release, `taskset -c 3`, warm-up then best of 5 x
20k threads, three interleaved rounds on a box at load 13-21 (before ->
after; CRuby 4.0.9 27-33 / 51-59 us):
- net10.0: 51-60 / 152-176 -> 49-55 / 142-164 us (thread / process CPU)
- net11.0: 48-55 / 159-173 -> 41-47 / 124-136 us
- finalizer-thread CPU for 50k threads (net11.0): 0.38-1.21 -> 0.14-0.17 s
- allocation per thread: 6.3-7.7 KB -> 3.1-3.6 KB (the array copies)
- dead threads in the CLR's list mid-loop: ~4,700 -> ~200
- joined threads alive after full GCs: 20 of 20 -> 0

What is left is creating and destroying the CLR thread itself: a C# loop
of new Thread(...).Start(); Join() costs 39-52 / 112-145 us here.

Tests: Thread_FinishedThreadCollected1 (fails on master with 20),
Dlr_ThreadLocalOwner1 (a finished thread is collected; new threads, the
one reusing its id included, start without its value; TryGetValue reads
another live thread's value).

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RubyThreadInfo._registered, the list Thread.list enumerates, kept a
finished thread's info until the next prune: up to 64 thread creations
later, or twice as many as were registered at the last prune. Until then
the finished Thread was reachable, so the GCs in between promoted it, and
it stayed, with the CLR's record of the dead thread, until a gen-2
collection. With DLR patch 0108 alone, the 20 joined threads of
Thread_FinishedThreadCollected1 were still all alive after full
collections; RubyThreadStart now removes its info as its last step
(searching from the end, where a thread that finishes usually is).
Thread.list already left out threads that are not alive, so what it
reports does not change.

Also fixes Dlr_ThreadLocalOwner1, which read ThreadLocal.Value (which
gives the thread an entry) before asking TryGetValue whether it had one.

Part of #89.

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 22 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 86 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 b472994 and b5ad1b6.

Files selected for processing: 5

  • Build/dlr-patches/0108-ThreadLocal-no-dead-thread-roots.patch
  • Build/dlr-patches/README.md
  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/MiscTests.cs
  • Src/Libraries/Builtins/ThreadOps.cs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment on lines +2546 to +2548
// Whichever ids they get - the finished thread's among them, once the CLR hands it out again - new
// threads start with nothing, and their values are their own.
for (int i = 0; i < 20; i++) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Reused slots may go untested

Dlr_ThreadLocalOwner1 can pass without exercising a reused ManagedThreadId. The loop creates 20 threads but never checks whether one gets the finished thread's ID. If every thread gets a fresh slot, both freshness checks pass even if the owner check is broken.

Return the original ID from the helper, collect between bounded batches, and assert that reuse occurred before counting this case as covered.

Prompt To Fix With AI
This is a comment left during a code review.
Path: Src/IronRuby.Tests/Runtime/MiscTests.cs
Line: 2546-2548

Comment:
**Reused slots may go untested**

`Dlr_ThreadLocalOwner1` can pass without exercising a reused `ManagedThreadId`. The loop creates 20 threads but never checks whether one gets the finished thread's ID. If every thread gets a fresh slot, both freshness checks pass even if the owner check is broken.

Return the original ID from the helper, collect between bounded batches, and assert that reuse occurred before counting this case as covered.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

@Largo
Largo merged commit eed1405 into master Nov 11, 2026
7 checks passed
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