Project

General

Profile

Actions

Bug #22720

open

Fork child crashes with `[BUG] unexpected THREAD_KILLED` when a fiber-scheduler fiber was waiting on a Mutex

Bug #22720: Fork child crashes with `[BUG] unexpected THREAD_KILLED` when a fiber-scheduler fiber was waiting on a Mutex

Added by saddestmartian (sad mart) 1 day ago.

Status:
Open
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-12-03T23:00:19Z master bcd243e8e8) +PRISM [x86_64-linux]
[ruby-core:127850]

Description

Since Ruby 4.0.0, if a non-blocking fiber in another thread is waiting on a Thread::Mutex through a fiber scheduler when the process forks, unlocking (or locking and unlocking) that mutex in the child aborts the child.

class MiniScheduler
  def block(blocker, timeout = nil) = Fiber.yield
  def unblock(blocker, fiber) = nil
  def kernel_sleep(duration = nil) = Fiber.yield
  def io_wait(io, events, timeout) = Fiber.yield
  def fiber(&blk) = Fiber.new(blocking: false, &blk).tap(&:resume)
  def fiber_interrupt(fiber, exception) = nil
  def close = nil
end
m = Mutex.new
m.lock
t = Thread.new { Fiber.set_scheduler(MiniScheduler.new); Fiber.schedule { m.lock }; sleep }
Thread.pass until t.stop?
pid = fork { m.unlock; exit!(0) }
p Process.wait2(pid)[1]
# 3.1 - 3.4: exit 0
# 4.0.10 / master: [BUG] unexpected THREAD_KILLED, SIGABRT

Variant: with two scheduler fibers waiting, m.unlock in the parent immediately followed by fork { m.lock; m.unlock } crashes the same way, with m unlocked at fork time.

The fiber-scheduler wait path in do_mutex_lock (thread_sync.c, around lines 301-317) queues an on-stack sync_waiter but does not set th->locking_mutex, so the at-fork cleanup (terminate_atfork_i -> rb_mutex_abandon_locking_mutex / rb_mutex_abandon_keeping_mutexes) never drops it. The child's rb_mutex_unlock_th then walks a waiter node that lives on a dead thread's fiber stack. Before 8eea9a5020 (GitHub #15354, [Bug #21717]) that waiter took the scheduler branch and called the dead thread's scheduler; now th->scheduler is nil, so it reaches rb_bug("unexpected THREAD_KILLED"). This looks like the fiber-scheduler counterpart of [Bug #15383] / [Bug #14578], whose fix (0fd53f519f) removed Mutex's fork_gen and relies on locking_mutex. Queue and ConditionVariable still reset their waiters lazily with fork_gen and are not affected.

A possible fix is to give rb_mutex_t the same lazy fork_gen reset that queue_fork_check does; resetting only the mutexes held by the forking thread would miss the second variant. I have a regression test for test/fiber/test_mutex.rb (it fails today with the child's SIGABRT) and can send it as a pull request if that is useful.

No data to display

Actions

Also available in: PDF Atom