From 9cd0ca1a5bdc43b33980487738f8beca0235ae7a Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Thu, 17 Sep 2026 16:25:17 -0400 Subject: [PATCH 01/22] wip --- CHANGELOG.md | 12 ++ .../lib/temporalio/worker/thread_pool.rb | 81 +++++++-- .../rbi/temporalio/worker/thread_pool.rbi | 27 ++- .../worker/activity_executor/thread_pool.rbs | 2 +- .../sig/temporalio/worker/thread_pool.rbs | 13 +- .../test/sig/worker_thread_pool_test.rbs | 10 ++ temporalio/test/worker_activity_test.rb | 51 ++++++ temporalio/test/worker_thread_pool_test.rb | 170 ++++++++++++++++++ 8 files changed, 344 insertions(+), 22 deletions(-) create mode 100644 temporalio/test/sig/worker_thread_pool_test.rbs create mode 100644 temporalio/test/worker_thread_pool_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 89546f02..9e82f40e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,20 @@ to docs, or any other relevant information. ### Added +- `Temporalio::Worker::ThreadPool::ThreadContext` can be passed to `ThreadPool.new` as + `thread_context:` to wrap the body of each pool thread. The context's `call` receives a block + covering the thread's entire lifetime, so a resource acquired around it (a database connection, + say) can be reused by every activity that thread runs and released from an `ensure`. The default + context adds no behavior. + ### Changed +### Fixed + +- The RBS signature for `Worker::ActivityExecutor::ThreadPool#initialize` declared its parameter as + an `ActivityExecutor::ThreadPool` rather than the `Worker::ThreadPool` the method actually takes, + so passing a custom thread pool failed type checking. + ### Deprecated ### :boom: Breaking Changes diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index 4d8c7d60..7a970cd4 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -10,6 +10,39 @@ class ThreadPool # see MIT license at # https://github.com/ruby-concurrency/concurrent-ruby/blob/044020f44b36930b863b930f3ee8fa1e9f750469/LICENSE.txt + # Wraps the body of each pool thread, for acquiring a resource when a thread starts and + # releasing it when the thread exits. Since the block is invoked for the entire lifetime of + # the thread, a resource acquired around it can be released from an `ensure`. + # + # Not to be confused with an interceptor, which wraps a single activity execution. + # + # @note The same instance is used by every thread in the pool, so implementations must be + # thread safe. Per-thread state belongs in the block, not in the ThreadContext object. + class ThreadContext + # @return [ThreadContext] Default/shared context that just invokes the block. + def self.default + @default ||= NoOp.new + end + + # Invoke the given block for the lifetime of a pool thread. Implementations must invoke + # the block; a thread whose context does not yield never runs any work. + # + # @yield Block to invoke for the lifetime of the thread. + def call(&) + raise NotImplementedError + end + + # Context that adds no behavior, used when a pool is created without one. + # + # @!visibility private + class NoOp < ThreadContext + # @see ThreadContext.call + def call(&) + yield + end + end + end + # @return [ThreadPool] Default/shared thread pool instance with unlimited max threads. def self.default @default ||= new @@ -25,9 +58,12 @@ def self._monotonic_time # @param max_threads [Integer, nil] Maximum number of thread workers to create, or nil for unlimited max. # @param idle_timeout [Float] Number of seconds before a thread worker with no work should be stopped. Note, # the check of whether a thread worker is idle is only done on each new {execute} call. - def initialize(max_threads: nil, idle_timeout: 20) + # @param thread_context [ThreadContext] Invoked around the body of each thread this pool starts, for + # acquiring and releasing per-thread resources. Defaults to one that adds no behavior. + def initialize(max_threads: nil, idle_timeout: 20, thread_context: ThreadContext.default) @max_threads = max_threads @idle_timeout = idle_timeout + @thread_context = thread_context @mutex = Mutex.new @pool = [] @@ -123,6 +159,11 @@ def _worker_task_completed @mutex.synchronize { @completed_task_count += 1 } end + # @!visibility private + def _thread_context + @thread_context + end + private def locked_assign_worker(&block) # rubocop:disable Naming/PredicateMethod @@ -189,24 +230,28 @@ class Worker def initialize(pool, id) @queue = Queue.new @thread = Thread.new(@queue, pool) do |my_queue, my_pool| - catch(:stop) do - loop do - case block = my_queue.pop - when :stop - pool._remove_busy_worker(self) - throw :stop - else - begin - block.call - my_pool._worker_task_completed - my_pool._ready_worker(self, ThreadPool._monotonic_time) - rescue StandardError => e - # Ignore - warn("Unexpected execute block error: #{e.full_message}") - rescue Exception => e # rubocop:disable Lint/RescueException - warn("Unexpected execute block exception: #{e.full_message}") - my_pool._worker_died(self) + # Wraps the whole loop, so a context can hold a resource for the thread's lifetime and + # release it from an `ensure` however the loop ends. + my_pool._thread_context.call do + catch(:stop) do + loop do + case block = my_queue.pop + when :stop + pool._remove_busy_worker(self) throw :stop + else + begin + block.call + my_pool._worker_task_completed + my_pool._ready_worker(self, ThreadPool._monotonic_time) + rescue StandardError => e + # Ignore + warn("Unexpected execute block error: #{e.full_message}") + rescue Exception => e # rubocop:disable Lint/RescueException + warn("Unexpected execute block exception: #{e.full_message}") + my_pool._worker_died(self) + throw :stop + end end end end diff --git a/temporalio/rbi/temporalio/worker/thread_pool.rbi b/temporalio/rbi/temporalio/worker/thread_pool.rbi index 8f069417..f13e5a9f 100644 --- a/temporalio/rbi/temporalio/worker/thread_pool.rbi +++ b/temporalio/rbi/temporalio/worker/thread_pool.rbi @@ -6,8 +6,14 @@ class Temporalio::Worker::ThreadPool sig { returns(Temporalio::Worker::ThreadPool) } def self.default; end - sig { params(max_threads: T.nilable(Integer), idle_timeout: Float).void } - def initialize(max_threads: T.unsafe(nil), idle_timeout: T.unsafe(nil)); end + sig do + params( + max_threads: T.nilable(Integer), + idle_timeout: Float, + thread_context: Temporalio::Worker::ThreadPool::ThreadContext + ).void + end + def initialize(max_threads: T.unsafe(nil), idle_timeout: T.unsafe(nil), thread_context: T.unsafe(nil)); end sig { params(block: T.proc.void).void } def execute(&block); end @@ -36,3 +42,20 @@ class Temporalio::Worker::ThreadPool sig { void } def kill; end end + +class Temporalio::Worker::ThreadPool::ThreadContext + extend T::Sig + + sig { returns(Temporalio::Worker::ThreadPool::ThreadContext) } + def self.default; end + + sig { params(block: T.proc.void).void } + def call(&block); end +end + +class Temporalio::Worker::ThreadPool::ThreadContext::NoOp < Temporalio::Worker::ThreadPool::ThreadContext + extend T::Sig + + sig { params(block: T.proc.void).void } + def call(&block); end +end diff --git a/temporalio/sig/temporalio/worker/activity_executor/thread_pool.rbs b/temporalio/sig/temporalio/worker/activity_executor/thread_pool.rbs index 037f93b7..5af7d78c 100644 --- a/temporalio/sig/temporalio/worker/activity_executor/thread_pool.rbs +++ b/temporalio/sig/temporalio/worker/activity_executor/thread_pool.rbs @@ -4,7 +4,7 @@ module Temporalio class ThreadPool < ActivityExecutor def self.default: -> ThreadPool - def initialize: (?ThreadPool thread_poll) -> void + def initialize: (?::Temporalio::Worker::ThreadPool thread_pool) -> void end end end diff --git a/temporalio/sig/temporalio/worker/thread_pool.rbs b/temporalio/sig/temporalio/worker/thread_pool.rbs index 66986c9a..37ea9212 100644 --- a/temporalio/sig/temporalio/worker/thread_pool.rbs +++ b/temporalio/sig/temporalio/worker/thread_pool.rbs @@ -1,13 +1,23 @@ module Temporalio class Worker class ThreadPool + class ThreadContext + def self.default: -> ThreadContext + def call: { -> void } -> void + + class NoOp < ThreadContext + def call: { -> void } -> void + end + end + def self.default: -> ThreadPool def self._monotonic_time: -> Float def initialize: ( ?max_threads: Integer?, - ?idle_timeout: Float + ?idle_timeout: Float, + ?thread_context: ThreadContext ) -> void def execute: { -> void } -> void @@ -25,6 +35,7 @@ module Temporalio def _ready_worker: (Worker worker, Float last_message) -> void def _worker_died: (Worker worker) -> void def _worker_task_completed: -> void + def _thread_context: -> ThreadContext private def locked_assign_worker: { (?) -> untyped } -> void private def locked_enqueue: { (?) -> untyped } -> void private def locked_add_busy_worker: -> Worker? diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs new file mode 100644 index 00000000..0720e904 --- /dev/null +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -0,0 +1,10 @@ +class WorkerThreadPoolTest < Test + class RecordingContext < Temporalio::Worker::ThreadPool::ThreadContext + attr_reader entered: Queue + attr_reader exited: Queue + def initialize: (?var_value: String) -> void + def call: { -> void } -> void + end + + def wait_until: (?timeout: Float) { () -> boolish } -> boolish +end diff --git a/temporalio/test/worker_activity_test.rb b/temporalio/test/worker_activity_test.rb index b4ad7800..d00ba1c6 100644 --- a/temporalio/test/worker_activity_test.rb +++ b/temporalio/test/worker_activity_test.rb @@ -910,6 +910,57 @@ def test_custom_executor execute_activity(CustomExecutorActivity, activity_executors: { my_executor: CustomExecutor.new }) end + # Sets a thread-local for the lifetime of each pool thread and clears it on the way out, so a + # real activity can observe that it ran inside the context and the test can observe the teardown. + class ThreadContextRecorder < Temporalio::Worker::ThreadPool::ThreadContext + # Pool threads outlive the activity, so the exit is recorded on a queue the test can wait on. + attr_reader :exited + + def initialize + super + @exited = Queue.new + end + + def call + Thread.current[:thread_context_val] = 'acquired' + yield + ensure + Thread.current[:thread_context_val] = nil + @exited.push(Thread.current.name) + end + end + + class ThreadContextActivity < Temporalio::Activity::Definition + activity_executor :context_executor + + def execute + "context val: #{Thread.current[:thread_context_val]}" + end + end + + exclude_from_cloud :needs_cloud_adaptation, + 'The Go kitchen-sink worker does not receive Cloud TLS configuration.' + def test_thread_pool_thread_context_wraps_activity + context = ThreadContextRecorder.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + executor = Temporalio::Worker::ActivityExecutor::ThreadPool.new(pool) + + # The activity reads the value the context set before the thread began taking work. + assert_equal 'context val: acquired', + execute_activity(ThreadContextActivity, activity_executors: { context_executor: executor }) + + # The context is still holding the thread open, since the pool thread outlives the activity. + assert_empty context.exited + + # Shutting the pool down unwinds the thread through the context's `ensure`. + pool.shutdown + deadline = Time.now + 10 + sleep(0.02) while context.exited.empty? && Time.now < deadline + refute_empty context.exited, 'thread context did not release when the pool shut down' + ensure + pool&.kill + end + class ConcurrentActivity < Temporalio::Activity::Definition def initialize @started = Queue.new diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb new file mode 100644 index 00000000..1989ae4f --- /dev/null +++ b/temporalio/test/worker_thread_pool_test.rb @@ -0,0 +1,170 @@ +# frozen_string_literal: true + +require 'temporalio/worker/thread_pool' +require 'test' + +class WorkerThreadPoolTest < Test + # Records what happened on each thread it wraps. `entered`/`exited` are pushed to from pool + # threads, so they are queues rather than plain arrays. + class RecordingContext < Temporalio::Worker::ThreadPool::ThreadContext + attr_reader :entered, :exited + + def initialize(var_value: 'set-by-context') + super() + @var_value = var_value + @entered = Queue.new + @exited = Queue.new + end + + def call + Thread.current[:test_thread_context_var] = @var_value + @entered.push(Thread.current.name) + yield + ensure + Thread.current[:test_thread_context_var] = nil + @exited.push(Thread.current.name) + end + end + + def wait_until(timeout: 10) + deadline = Time.now + timeout + sleep(0.02) until yield || Time.now > deadline + yield + end + + def test_default_context_is_no_op + pool = Temporalio::Worker::ThreadPool.new + ran = Queue.new + pool.execute { ran.push(Thread.current[:test_thread_context_var]) } + assert_nil ran.pop + ensure + pool&.shutdown + end + + def test_context_wraps_work_on_the_thread + context = RecordingContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + + # The block the pool runs is the stand-in for an activity: it observes the variable the + # context set in its preamble. + seen = Queue.new + pool.execute { seen.push(Thread.current[:test_thread_context_var]) } + + assert_equal 'set-by-context', seen.pop + refute_empty context.entered + assert_empty context.exited, 'context must not have exited while the thread is still alive' + ensure + pool&.shutdown + end + + def test_context_wraps_every_thread_in_the_pool + context = RecordingContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + + # Occupy two threads at once so the pool has to start a second one. + release = Queue.new + seen = Queue.new + 2.times do + pool.execute do + seen.push(Thread.current[:test_thread_context_var]) + release.pop + end + end + assert_equal %w[set-by-context set-by-context], [seen.pop, seen.pop] + 2.times { release.push(nil) } + + assert_equal 2, pool.largest_length + assert_equal 2, context.entered.size + ensure + 2.times { release&.push(nil) } + pool&.shutdown + end + + # The doc's claim: `throw :stop` unwinds through the context, so graceful shutdown releases the + # resource via `ensure`. + def test_context_released_on_graceful_shutdown + context = RecordingContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + done = Queue.new + pool.execute { done.push(nil) } + done.pop + assert_empty context.exited + + pool.shutdown + + assert wait_until { !context.exited.empty? }, 'context did not exit on graceful shutdown' + end + + # Same claim, for the idle-timeout prune path, which also stops a thread with `throw :stop`. + def test_context_released_on_idle_timeout_prune + context = RecordingContext.new + # Prune checks run on `execute`, and only stop threads that have been idle longer than the + # timeout. Two threads are needed: `execute` hands the new task to one idle thread before + # pruning, so a second must remain in the ready list for there to be anything to prune. + pool = Temporalio::Worker::ThreadPool.new(idle_timeout: 0.05, thread_context: context) + release = Queue.new + started = Queue.new + 2.times do + pool.execute do + started.push(nil) + release.pop + end + end + 2.times { started.pop } + 2.times { release.push(nil) } + assert wait_until { pool.active_count.zero? }, 'threads did not go idle' + assert_equal 2, pool.largest_length + assert_empty context.exited + + # Let both threads age past the idle timeout, then drive a prune with one more task. + sleep(0.2) + pruned = wait_until do + pool.execute { nil } + !context.exited.empty? + end + assert pruned, 'context did not exit when its idle thread was pruned' + ensure + pool&.shutdown + end + + # The doc predicted `ThreadPool#kill` would NOT release the resource. It does: `Thread#kill` + # unwinds the stack and runs `ensure` blocks. + def test_context_released_on_kill + context = RecordingContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + started = Queue.new + blocked = Queue.new + pool.execute do + started.push(nil) + blocked.pop # never pushed to; the thread is killed while parked here + end + started.pop + assert_empty context.exited + + pool.kill + + assert wait_until { !context.exited.empty? }, 'context did not exit on kill' + end + + def test_context_that_raises_kills_only_its_own_thread + context = Class.new(Temporalio::Worker::ThreadPool::ThreadContext) do + def call + raise 'context failed' + end + end.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + + # The block never runs, because the context never yielded. + ran = Queue.new + _, err = capture_subprocess_io { pool.execute { ran.push(nil) } } + + assert(wait_until { ran.empty? }) + assert_includes err.to_s, 'context failed' if err && !err.empty? + ensure + pool&.kill + end + + def test_base_context_is_abstract + assert_raises(NotImplementedError) { Temporalio::Worker::ThreadPool::ThreadContext.new.call { nil } } + end +end From f3800f0eb3b4f5ae5ad5c5b0db23e9bff7f0c7b6 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Thu, 17 Sep 2026 16:47:22 -0400 Subject: [PATCH 02/22] wip --- .../test/sig/worker_thread_pool_test.rbs | 5 ++ temporalio/test/worker_thread_pool_test.rb | 64 ++++++++++++------- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index 0720e904..7edee034 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -6,5 +6,10 @@ class WorkerThreadPoolTest < Test def call: { -> void } -> void end + class RaisingContext < Temporalio::Worker::ThreadPool::ThreadContext + def call: { -> void } -> void + end + def wait_until: (?timeout: Float) { () -> boolish } -> boolish + def run_and_wait: (Temporalio::Worker::ThreadPool pool, ?timeout: Float) -> void end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index 1989ae4f..6b312e62 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -26,17 +26,35 @@ def call end end + # Polls the block until it returns truthy or `timeout` elapses, and returns the last result so + # callers can assert on it. The block is evaluated once per iteration, so a block with side + # effects runs a predictable number of times. def wait_until(timeout: 10) deadline = Time.now + timeout - sleep(0.02) until yield || Time.now > deadline - yield + loop do + result = yield + return result if result || Time.now > deadline + + sleep(0.02) + end + end + + # Blocks until the pool runs something on a thread, so the thread is known to exist and to have + # entered its context. Fails rather than hanging if that never happens. + def run_and_wait(pool, timeout: 10) + done = Queue.new + pool.execute { done.push(:ran) } + assert_equal :ran, done.pop(timeout:), 'pool never ran the block' end def test_default_context_is_no_op pool = Temporalio::Worker::ThreadPool.new ran = Queue.new - pool.execute { ran.push(Thread.current[:test_thread_context_var]) } - assert_nil ran.pop + # Wrapped, because the value under test is itself nil and a timed-out pop also returns nil. + pool.execute { ran.push({ value: Thread.current[:test_thread_context_var] }) } + seen = ran.pop(timeout: 10) + refute_nil seen, 'pool never ran the block' + assert_nil seen[:value] ensure pool&.shutdown end @@ -50,7 +68,7 @@ def test_context_wraps_work_on_the_thread seen = Queue.new pool.execute { seen.push(Thread.current[:test_thread_context_var]) } - assert_equal 'set-by-context', seen.pop + assert_equal 'set-by-context', seen.pop(timeout: 10) refute_empty context.entered assert_empty context.exited, 'context must not have exited while the thread is still alive' ensure @@ -80,14 +98,12 @@ def test_context_wraps_every_thread_in_the_pool pool&.shutdown end - # The doc's claim: `throw :stop` unwinds through the context, so graceful shutdown releases the - # resource via `ensure`. + # The doc's claim, for graceful shutdown. `shutdown` queues `:stop` for each worker; the worker + # thread itself then runs `throw :stop`, which unwinds out through the context's `ensure`. def test_context_released_on_graceful_shutdown context = RecordingContext.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - done = Queue.new - pool.execute { done.push(nil) } - done.pop + run_and_wait(pool) assert_empty context.exited pool.shutdown @@ -106,23 +122,26 @@ def test_context_released_on_idle_timeout_prune started = Queue.new 2.times do pool.execute do - started.push(nil) + started.push(:started) release.pop end end - 2.times { started.pop } + 2.times { assert_equal :started, started.pop(timeout: 10), 'thread never started' } 2.times { release.push(nil) } assert wait_until { pool.active_count.zero? }, 'threads did not go idle' - assert_equal 2, pool.largest_length + assert_equal 2, pool.length assert_empty context.exited - # Let both threads age past the idle timeout, then drive a prune with one more task. + # Let both threads age past the idle timeout, then drive a prune with one more task. Pruning + # only happens inside `execute`, so the poll has to keep feeding it work. sleep(0.2) pruned = wait_until do pool.execute { nil } !context.exited.empty? end assert pruned, 'context did not exit when its idle thread was pruned' + # The pruned thread is removed from the pool, not just told to stop. + assert wait_until { pool.length < 2 }, 'pruned thread was not removed from the pool' ensure pool&.shutdown end @@ -135,10 +154,10 @@ def test_context_released_on_kill started = Queue.new blocked = Queue.new pool.execute do - started.push(nil) + started.push(:started) blocked.pop # never pushed to; the thread is killed while parked here end - started.pop + assert_equal :started, started.pop(timeout: 10), 'thread never started' assert_empty context.exited pool.kill @@ -146,13 +165,14 @@ def test_context_released_on_kill assert wait_until { !context.exited.empty? }, 'context did not exit on kill' end + class RaisingContext < Temporalio::Worker::ThreadPool::ThreadContext + def call + raise 'context failed' + end + end + def test_context_that_raises_kills_only_its_own_thread - context = Class.new(Temporalio::Worker::ThreadPool::ThreadContext) do - def call - raise 'context failed' - end - end.new - pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + pool = Temporalio::Worker::ThreadPool.new(thread_context: RaisingContext.new) # The block never runs, because the context never yielded. ran = Queue.new From e5aae4ebae922e3ea60d9a9df923822ae123b568 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Thu, 17 Sep 2026 17:01:32 -0400 Subject: [PATCH 03/22] cleanup --- CHANGELOG.md | 11 +---------- temporalio/lib/temporalio/worker/thread_pool.rb | 9 ++------- 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e82f40e..c2ebf576 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,19 +22,10 @@ to docs, or any other relevant information. ### Added - `Temporalio::Worker::ThreadPool::ThreadContext` can be passed to `ThreadPool.new` as - `thread_context:` to wrap the body of each pool thread. The context's `call` receives a block - covering the thread's entire lifetime, so a resource acquired around it (a database connection, - say) can be reused by every activity that thread runs and released from an `ensure`. The default - context adds no behavior. + `thread_context:` to wrap the execution of the body of each pool thread. ### Changed -### Fixed - -- The RBS signature for `Worker::ActivityExecutor::ThreadPool#initialize` declared its parameter as - an `ActivityExecutor::ThreadPool` rather than the `Worker::ThreadPool` the method actually takes, - so passing a custom thread pool failed type checking. - ### Deprecated ### :boom: Breaking Changes diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index 7a970cd4..fb3ff20f 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -14,8 +14,6 @@ class ThreadPool # releasing it when the thread exits. Since the block is invoked for the entire lifetime of # the thread, a resource acquired around it can be released from an `ensure`. # - # Not to be confused with an interceptor, which wraps a single activity execution. - # # @note The same instance is used by every thread in the pool, so implementations must be # thread safe. Per-thread state belongs in the block, not in the ThreadContext object. class ThreadContext @@ -25,15 +23,13 @@ def self.default end # Invoke the given block for the lifetime of a pool thread. Implementations must invoke - # the block; a thread whose context does not yield never runs any work. + # the block. # # @yield Block to invoke for the lifetime of the thread. def call(&) raise NotImplementedError end - # Context that adds no behavior, used when a pool is created without one. - # # @!visibility private class NoOp < ThreadContext # @see ThreadContext.call @@ -230,8 +226,7 @@ class Worker def initialize(pool, id) @queue = Queue.new @thread = Thread.new(@queue, pool) do |my_queue, my_pool| - # Wraps the whole loop, so a context can hold a resource for the thread's lifetime and - # release it from an `ensure` however the loop ends. + # Run the entire loop inside the ThreadContext. my_pool._thread_context.call do catch(:stop) do loop do From 41978ec4bebcb166930dafc196a71708c97f557b Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Fri, 18 Sep 2026 12:20:45 -0400 Subject: [PATCH 04/22] cleanup --- temporalio/test/worker_activity_test.rb | 7 ++----- temporalio/test/worker_thread_pool_test.rb | 9 +-------- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/temporalio/test/worker_activity_test.rb b/temporalio/test/worker_activity_test.rb index d00ba1c6..0bb2c0f1 100644 --- a/temporalio/test/worker_activity_test.rb +++ b/temporalio/test/worker_activity_test.rb @@ -910,8 +910,7 @@ def test_custom_executor execute_activity(CustomExecutorActivity, activity_executors: { my_executor: CustomExecutor.new }) end - # Sets a thread-local for the lifetime of each pool thread and clears it on the way out, so a - # real activity can observe that it ran inside the context and the test can observe the teardown. + # Sets a thread-local for the lifetime of each pool thread. class ThreadContextRecorder < Temporalio::Worker::ThreadPool::ThreadContext # Pool threads outlive the activity, so the exit is recorded on a queue the test can wait on. attr_reader :exited @@ -945,14 +944,12 @@ def test_thread_pool_thread_context_wraps_activity pool = Temporalio::Worker::ThreadPool.new(thread_context: context) executor = Temporalio::Worker::ActivityExecutor::ThreadPool.new(pool) - # The activity reads the value the context set before the thread began taking work. assert_equal 'context val: acquired', execute_activity(ThreadContextActivity, activity_executors: { context_executor: executor }) - # The context is still holding the thread open, since the pool thread outlives the activity. + # The context is still active assert_empty context.exited - # Shutting the pool down unwinds the thread through the context's `ensure`. pool.shutdown deadline = Time.now + 10 sleep(0.02) while context.exited.empty? && Time.now < deadline diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index 6b312e62..c2b1784d 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -4,8 +4,6 @@ require 'test' class WorkerThreadPoolTest < Test - # Records what happened on each thread it wraps. `entered`/`exited` are pushed to from pool - # threads, so they are queues rather than plain arrays. class RecordingContext < Temporalio::Worker::ThreadPool::ThreadContext attr_reader :entered, :exited @@ -26,9 +24,7 @@ def call end end - # Polls the block until it returns truthy or `timeout` elapses, and returns the last result so - # callers can assert on it. The block is evaluated once per iteration, so a block with side - # effects runs a predictable number of times. + # Polls the block until it returns truthy or `timeout` elapses. def wait_until(timeout: 10) deadline = Time.now + timeout loop do @@ -50,7 +46,6 @@ def run_and_wait(pool, timeout: 10) def test_default_context_is_no_op pool = Temporalio::Worker::ThreadPool.new ran = Queue.new - # Wrapped, because the value under test is itself nil and a timed-out pop also returns nil. pool.execute { ran.push({ value: Thread.current[:test_thread_context_var] }) } seen = ran.pop(timeout: 10) refute_nil seen, 'pool never ran the block' @@ -63,8 +58,6 @@ def test_context_wraps_work_on_the_thread context = RecordingContext.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - # The block the pool runs is the stand-in for an activity: it observes the variable the - # context set in its preamble. seen = Queue.new pool.execute { seen.push(Thread.current[:test_thread_context_var]) } From 1a658d9f6942b35533d37a12f02f80539591e071 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Fri, 18 Sep 2026 12:26:01 -0400 Subject: [PATCH 05/22] cleanup --- temporalio/test/worker_thread_pool_test.rb | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index c2b1784d..d9ee53ba 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -72,9 +72,9 @@ def test_context_wraps_every_thread_in_the_pool context = RecordingContext.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - # Occupy two threads at once so the pool has to start a second one. release = Queue.new seen = Queue.new + # Ensure two threads are running. 2.times do pool.execute do seen.push(Thread.current[:test_thread_context_var]) @@ -91,8 +91,6 @@ def test_context_wraps_every_thread_in_the_pool pool&.shutdown end - # The doc's claim, for graceful shutdown. `shutdown` queues `:stop` for each worker; the worker - # thread itself then runs `throw :stop`, which unwinds out through the context's `ensure`. def test_context_released_on_graceful_shutdown context = RecordingContext.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) @@ -104,12 +102,9 @@ def test_context_released_on_graceful_shutdown assert wait_until { !context.exited.empty? }, 'context did not exit on graceful shutdown' end - # Same claim, for the idle-timeout prune path, which also stops a thread with `throw :stop`. def test_context_released_on_idle_timeout_prune context = RecordingContext.new - # Prune checks run on `execute`, and only stop threads that have been idle longer than the - # timeout. Two threads are needed: `execute` hands the new task to one idle thread before - # pruning, so a second must remain in the ready list for there to be anything to prune. + # We need two threads to make sure there is one that can be pruned. pool = Temporalio::Worker::ThreadPool.new(idle_timeout: 0.05, thread_context: context) release = Queue.new started = Queue.new @@ -125,22 +120,18 @@ def test_context_released_on_idle_timeout_prune assert_equal 2, pool.length assert_empty context.exited - # Let both threads age past the idle timeout, then drive a prune with one more task. Pruning - # only happens inside `execute`, so the poll has to keep feeding it work. + # Pruning only happens inside `execute`. sleep(0.2) pruned = wait_until do pool.execute { nil } !context.exited.empty? end assert pruned, 'context did not exit when its idle thread was pruned' - # The pruned thread is removed from the pool, not just told to stop. assert wait_until { pool.length < 2 }, 'pruned thread was not removed from the pool' ensure pool&.shutdown end - # The doc predicted `ThreadPool#kill` would NOT release the resource. It does: `Thread#kill` - # unwinds the stack and runs `ensure` blocks. def test_context_released_on_kill context = RecordingContext.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) @@ -148,7 +139,7 @@ def test_context_released_on_kill blocked = Queue.new pool.execute do started.push(:started) - blocked.pop # never pushed to; the thread is killed while parked here + blocked.pop # blocks end assert_equal :started, started.pop(timeout: 10), 'thread never started' assert_empty context.exited From 99e7c6587976688355e938f8c16b926851317fe7 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Fri, 18 Sep 2026 17:16:11 -0400 Subject: [PATCH 06/22] test_raising_context_kills_only_its_own_thread starts both threads at the top, and overtly records a raise and checks it. --- .../test/sig/worker_thread_pool_test.rbs | 4 +- temporalio/test/worker_thread_pool_test.rb | 46 +++++++++++++++---- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index 7edee034..dd7ab423 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -6,7 +6,9 @@ class WorkerThreadPoolTest < Test def call: { -> void } -> void end - class RaisingContext < Temporalio::Worker::ThreadPool::ThreadContext + class RaisesOnceContext < Temporalio::Worker::ThreadPool::ThreadContext + attr_reader raised: Queue + def initialize: -> void def call: { -> void } -> void end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index d9ee53ba..e7dede31 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -149,21 +149,49 @@ def test_context_released_on_kill assert wait_until { !context.exited.empty? }, 'context did not exit on kill' end - class RaisingContext < Temporalio::Worker::ThreadPool::ThreadContext + # Raises for the first thread only, so the second thread's context succeeds. + class RaisesOnceContext < Temporalio::Worker::ThreadPool::ThreadContext + attr_reader :raised + + def initialize + super + @mutex = Mutex.new + @raised = Queue.new + @first = true + end + def call - raise 'context failed' + should_raise = @mutex.synchronize { @first ? (@first = false) || true : false } + if should_raise + @raised.push(:raised) + raise 'context failed' + end + + yield end end - def test_context_that_raises_kills_only_its_own_thread - pool = Temporalio::Worker::ThreadPool.new(thread_context: RaisingContext.new) + def test_raising_context_kills_only_its_own_thread + context = RaisesOnceContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - # The block never runs, because the context never yielded. - ran = Queue.new - _, err = capture_subprocess_io { pool.execute { ran.push(nil) } } + # Submit both up front. The first worker's context raises, so that worker never completes a + # task and so never enters the ready list -- which makes the second `execute` create a fresh + # worker rather than reuse the dead one. + first = Queue.new + second = Queue.new + # Captured only to keep the dying thread's report_on_exception warning out of the test output. + capture_subprocess_io do + pool.execute { first.push(:ran) } + pool.execute { second.push(:ran) } + + assert_equal :raised, context.raised.pop(timeout: 10), 'context never raised' + assert_equal :ran, second.pop(timeout: 10), 'second thread never ran its work' + end - assert(wait_until { ran.empty? }) - assert_includes err.to_s, 'context failed' if err && !err.empty? + # Its worker is dead, so nothing can ever pop this block; no waiting needed to establish that. + assert_empty first, 'block ran even though its context raised' + assert_equal 2, pool.largest_length ensure pool&.kill end From f98c8769b6c91df9b4233aa36c94d9bfec2e8dae Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Mon, 28 Sep 2026 08:35:06 -0700 Subject: [PATCH 07/22] wip --- .../lib/temporalio/worker/thread_pool.rb | 13 ++++ .../test/sig/worker_thread_pool_test.rbs | 6 ++ temporalio/test/worker_thread_pool_test.rb | 66 +++++++++++++++++++ 3 files changed, 85 insertions(+) diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index fb3ff20f..71a54a40 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -251,6 +251,19 @@ def initialize(pool, id) end end end + # Block-level rescue on the Thread.new block above, so it runs on that thread. + rescue Exception => e # rubocop:disable Lint/RescueException + # Only reachable when the context itself raised; everything the loop can raise is + # handled inside it. Drop the worker so the pool does not keep an entry with a dead + # thread behind it, holding an undeliverable block. Removal is idempotent, so this is + # safe even if the loop already deregistered before the context raised on the way out. + # + # Deliberately not `_worker_died`: that adds a replacement, and a context that fails + # once usually fails every time, so the replacement dies the same way and spawns + # another without bound. The pool still recovers, because the next `execute` finds no + # ready worker and starts a fresh one -- driven by demand rather than by the failure. + warn("Unexpected thread context exception: #{e.full_message}") + my_pool._remove_busy_worker(self) end @thread.name = "temporal-thread-#{id}" end diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index dd7ab423..a19a27b3 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -12,6 +12,12 @@ class WorkerThreadPoolTest < Test def call: { -> void } -> void end + class AlwaysRaisesContext < Temporalio::Worker::ThreadPool::ThreadContext + attr_reader raised: Queue + def initialize: -> void + def call: { -> void } -> void + end + def wait_until: (?timeout: Float) { () -> boolish } -> boolish def run_and_wait: (Temporalio::Worker::ThreadPool pool, ?timeout: Float) -> void end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index e7dede31..b0a3a60e 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -196,6 +196,72 @@ def test_raising_context_kills_only_its_own_thread pool&.kill end + class AlwaysRaisesContext < Temporalio::Worker::ThreadPool::ThreadContext + attr_reader :raised + + def initialize + super + @raised = Queue.new + end + + def call + @raised.push(:raised) + raise 'context failed' + end + end + + # A worker whose context raises must not be left in the pool with a dead thread behind it. + def test_raising_context_removes_its_worker_from_the_pool + context = AlwaysRaisesContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + + capture_subprocess_io do + pool.execute { nil } + assert_equal :raised, context.raised.pop(timeout: 10), 'context never raised' + end + + # ThreadPool exposes `length` but no `empty?`. + assert wait_until { pool.length.zero? }, # rubocop:disable Style/ZeroLengthPredicate + 'dead worker was left in the pool' + ensure + pool&.kill + end + + # The cleanup must not ask for a replacement: a context that fails once generally fails every + # time, so replacing on failure spawns threads without bound. + def test_raising_context_does_not_spawn_replacement_threads + context = AlwaysRaisesContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + + capture_subprocess_io do + pool.execute { nil } + # Left on the queue rather than popped, so its size counts context invocations. + assert wait_until { !context.raised.empty? }, 'context never raised' + sleep(0.5) + end + + # One submission, one thread, so the context ran exactly once. Replacing the worker on failure + # produced tens of thousands of invocations here. + assert_equal 1, context.raised.size, 'context ran on replacement threads' + ensure + pool&.kill + end + + # `ThreadPool#kill` already drops every worker, so the cleanup must not resurrect any. + def test_kill_does_not_resurrect_workers + context = RecordingContext.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + run_and_wait(pool) + assert_equal 1, pool.length + + pool.kill + + assert wait_until { !context.exited.empty? }, 'context did not exit on kill' + sleep(0.3) + assert_equal 0, pool.length, 'kill left workers in the pool' + assert_equal 1, pool.largest_length, 'kill spawned a replacement thread' + end + def test_base_context_is_abstract assert_raises(NotImplementedError) { Temporalio::Worker::ThreadPool::ThreadContext.new.call { nil } } end From 7fd1f1eda515a7ddc55a2eeb204f5890c3b54740 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Tue, 29 Sep 2026 09:30:35 -0400 Subject: [PATCH 08/22] Remove worker from ready pool on TC failure. --- CHANGELOG.md | 4 ++ .../lib/temporalio/worker/thread_pool.rb | 36 ++++++++-- .../rbi/temporalio/worker/thread_pool.rbi | 6 ++ .../sig/temporalio/worker/thread_pool.rbs | 3 + .../test/sig/worker_thread_pool_test.rbs | 8 +++ temporalio/test/worker_thread_pool_test.rb | 67 +++++++++++++++++++ 6 files changed, 117 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2ebf576..eacbe991 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,10 @@ to docs, or any other relevant information. ### Fixed +- `Worker::ThreadPool#shutdown` no longer leaves stopped threads in the pool's internal ready list. + A block submitted after `shutdown` was previously handed to one of those dead threads and + silently never ran; it is now executed on a new thread. + ### Security ## [v1.9.0] - 2026-09-14 diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index 71a54a40..d6b432eb 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -22,8 +22,20 @@ def self.default @default ||= NoOp.new end + # @return [Boolean] Whether a thread whose context raised is replaced with a new one. + attr_reader :restart_worker + + # @param restart_worker [Boolean] What to do when {call} raises. When false, the thread is + # dropped from the pool and a new one is started only when more work arrives. When true, + # a replacement thread is started immediately, which invokes {call} again -- so a context + # that always raises will restart without bound. + def initialize(restart_worker: false) + @restart_worker = restart_worker + end + # Invoke the given block for the lifetime of a pool thread. Implementations must invoke - # the block. + # the block exactly once; invoking it again re-enters a loop the pool has stopped tracking, + # which blocks that thread forever and skips the rest of this method. # # @yield Block to invoke for the lifetime of the thread. def call(&) @@ -119,8 +131,10 @@ def queue_length # global default). def shutdown @mutex.synchronize do - # Stop all workers + # Stop all workers. None can still be ready once stopped, and a stale ready entry would + # have later work handed to a dead thread. @pool.each(&:stop) + @ready.clear end end @@ -160,6 +174,11 @@ def _thread_context @thread_context end + # @!visibility private + def _remove_ready_worker(worker) + @mutex.synchronize { @ready.reject! { |ready_worker, _| ready_worker.equal?(worker) } } + end + private def locked_assign_worker(&block) # rubocop:disable Naming/PredicateMethod @@ -258,12 +277,15 @@ def initialize(pool, id) # thread behind it, holding an undeliverable block. Removal is idempotent, so this is # safe even if the loop already deregistered before the context raised on the way out. # - # Deliberately not `_worker_died`: that adds a replacement, and a context that fails - # once usually fails every time, so the replacement dies the same way and spawns - # another without bound. The pool still recovers, because the next `execute` finds no - # ready worker and starts a fresh one -- driven by demand rather than by the failure. warn("Unexpected thread context exception: #{e.full_message}") - my_pool._remove_busy_worker(self) + # A restarted worker is put in the ready list before its context runs, so drop it from + # there first or the pool hands later work to this dead thread. + my_pool._remove_ready_worker(self) + if my_pool._thread_context.restart_worker + my_pool._worker_died(self) + else + my_pool._remove_busy_worker(self) + end end @thread.name = "temporal-thread-#{id}" end diff --git a/temporalio/rbi/temporalio/worker/thread_pool.rbi b/temporalio/rbi/temporalio/worker/thread_pool.rbi index f13e5a9f..77c03f3b 100644 --- a/temporalio/rbi/temporalio/worker/thread_pool.rbi +++ b/temporalio/rbi/temporalio/worker/thread_pool.rbi @@ -49,6 +49,12 @@ class Temporalio::Worker::ThreadPool::ThreadContext sig { returns(Temporalio::Worker::ThreadPool::ThreadContext) } def self.default; end + sig { returns(T::Boolean) } + attr_reader :restart_worker + + sig { params(restart_worker: T::Boolean).void } + def initialize(restart_worker: T.unsafe(nil)); end + sig { params(block: T.proc.void).void } def call(&block); end end diff --git a/temporalio/sig/temporalio/worker/thread_pool.rbs b/temporalio/sig/temporalio/worker/thread_pool.rbs index 37ea9212..49c798fd 100644 --- a/temporalio/sig/temporalio/worker/thread_pool.rbs +++ b/temporalio/sig/temporalio/worker/thread_pool.rbs @@ -3,6 +3,8 @@ module Temporalio class ThreadPool class ThreadContext def self.default: -> ThreadContext + attr_reader restart_worker: bool + def initialize: (?restart_worker: bool) -> void def call: { -> void } -> void class NoOp < ThreadContext @@ -36,6 +38,7 @@ module Temporalio def _worker_died: (Worker worker) -> void def _worker_task_completed: -> void def _thread_context: -> ThreadContext + def _remove_ready_worker: (Worker worker) -> void private def locked_assign_worker: { (?) -> untyped } -> void private def locked_enqueue: { (?) -> untyped } -> void private def locked_add_busy_worker: -> Worker? diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index a19a27b3..496af9e2 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -18,6 +18,14 @@ class WorkerThreadPoolTest < Test def call: { -> void } -> void end + class RestartingContext < Temporalio::Worker::ThreadPool::ThreadContext + def initialize: (fail_times: Integer) -> void + def count: -> Integer + def call: { -> void } -> void + end + + def ready_workers: (Temporalio::Worker::ThreadPool pool) -> Array[untyped] + def assert_no_stale_ready: (Temporalio::Worker::ThreadPool pool, String message) -> void def wait_until: (?timeout: Float) { () -> boolish } -> boolish def run_and_wait: (Temporalio::Worker::ThreadPool pool, ?timeout: Float) -> void end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index b0a3a60e..aa8fadac 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -262,6 +262,73 @@ def test_kill_does_not_resurrect_workers assert_equal 1, pool.largest_length, 'kill spawned a replacement thread' end + # Raises the first `fail_times` invocations, then yields. Each invocation is a fresh thread when + # restart_worker is on, so the count doubles as a count of threads started. + class RestartingContext < Temporalio::Worker::ThreadPool::ThreadContext + def initialize(fail_times:) + super(restart_worker: true) + @fail_times = fail_times + @mutex = Mutex.new + @count = 0 + end + + def count + @mutex.synchronize { @count } + end + + def call + n = @mutex.synchronize { @count += 1 } + raise "context failed (attempt #{n})" if n <= @fail_times + + yield + end + end + + def test_restart_worker_restarts_the_thread_until_the_context_succeeds + context = RestartingContext.new(fail_times: 10) + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + + capture_subprocess_io do + pool.execute { nil } + # Each restart re-invokes the context with no further work submitted, so reaching 11 means + # the 10 failures each produced a replacement thread. + assert wait_until { context.count >= 11 }, "context ran #{context.count} times, wanted 11" + end + + # The 11th invocation yielded, so that thread stays alive and restarting stops. + sleep(0.3) + assert_equal 11, context.count, 'context kept restarting after it stopped raising' + assert_equal 1, pool.length, 'the surviving thread is not in the pool' + ensure + pool&.kill + end + + # A worker dropped from the pool must also leave the ready list, or the pool hands later work to + # a dead thread and it silently never runs. `ready_workers` reaches in because the pool exposes + # no accessor for it. + def ready_workers(pool) + pool.instance_variable_get(:@ready).map(&:first) + end + + def assert_no_stale_ready(pool, message) + live = pool.instance_variable_get(:@pool) + orphans = ready_workers(pool).reject { |w| live.include?(w) } + assert_empty orphans, message + end + + def test_shutdown_leaves_no_stale_ready_workers + pool = Temporalio::Worker::ThreadPool.new + run_and_wait(pool) + assert_equal 1, ready_workers(pool).size, 'worker did not go idle' + + pool.shutdown + + # ThreadPool exposes `length` but no `empty?`. + assert wait_until { pool.length.zero? }, # rubocop:disable Style/ZeroLengthPredicate + 'worker was not removed from the pool' + assert_no_stale_ready(pool, 'shutdown left a stopped worker in the ready list') + end + def test_base_context_is_abstract assert_raises(NotImplementedError) { Temporalio::Worker::ThreadPool::ThreadContext.new.call { nil } } end From a6065855c067b50796c47a1264952f14bedab39d Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 11:24:35 -0400 Subject: [PATCH 09/22] revert shutdown change --- CHANGELOG.md | 4 --- .../lib/temporalio/worker/thread_pool.rb | 4 +-- .../test/sig/worker_thread_pool_test.rbs | 2 -- temporalio/test/worker_thread_pool_test.rb | 26 ------------------- 4 files changed, 1 insertion(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eacbe991..c2ebf576 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,10 +32,6 @@ to docs, or any other relevant information. ### Fixed -- `Worker::ThreadPool#shutdown` no longer leaves stopped threads in the pool's internal ready list. - A block submitted after `shutdown` was previously handed to one of those dead threads and - silently never ran; it is now executed on a new thread. - ### Security ## [v1.9.0] - 2026-09-14 diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index d6b432eb..fff5bc44 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -131,10 +131,8 @@ def queue_length # global default). def shutdown @mutex.synchronize do - # Stop all workers. None can still be ready once stopped, and a stale ready entry would - # have later work handed to a dead thread. + # Stop all workers @pool.each(&:stop) - @ready.clear end end diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index 496af9e2..ee709a75 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -24,8 +24,6 @@ class WorkerThreadPoolTest < Test def call: { -> void } -> void end - def ready_workers: (Temporalio::Worker::ThreadPool pool) -> Array[untyped] - def assert_no_stale_ready: (Temporalio::Worker::ThreadPool pool, String message) -> void def wait_until: (?timeout: Float) { () -> boolish } -> boolish def run_and_wait: (Temporalio::Worker::ThreadPool pool, ?timeout: Float) -> void end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index aa8fadac..7c1b94ed 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -303,32 +303,6 @@ def test_restart_worker_restarts_the_thread_until_the_context_succeeds pool&.kill end - # A worker dropped from the pool must also leave the ready list, or the pool hands later work to - # a dead thread and it silently never runs. `ready_workers` reaches in because the pool exposes - # no accessor for it. - def ready_workers(pool) - pool.instance_variable_get(:@ready).map(&:first) - end - - def assert_no_stale_ready(pool, message) - live = pool.instance_variable_get(:@pool) - orphans = ready_workers(pool).reject { |w| live.include?(w) } - assert_empty orphans, message - end - - def test_shutdown_leaves_no_stale_ready_workers - pool = Temporalio::Worker::ThreadPool.new - run_and_wait(pool) - assert_equal 1, ready_workers(pool).size, 'worker did not go idle' - - pool.shutdown - - # ThreadPool exposes `length` but no `empty?`. - assert wait_until { pool.length.zero? }, # rubocop:disable Style/ZeroLengthPredicate - 'worker was not removed from the pool' - assert_no_stale_ready(pool, 'shutdown left a stopped worker in the ready list') - end - def test_base_context_is_abstract assert_raises(NotImplementedError) { Temporalio::Worker::ThreadPool::ThreadContext.new.call { nil } } end From efa01e2e5b8084723a8e69e1930f824c08a453bc Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 12:33:43 -0400 Subject: [PATCH 10/22] cleanup --- .../lib/temporalio/worker/thread_pool.rb | 23 +++++++++++-------- temporalio/test/worker_thread_pool_test.rb | 5 ++-- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index fff5bc44..04742b1b 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -2,7 +2,7 @@ module Temporalio class Worker - # Implementation of a thread pool. This implementation is a stripped down form of Concurrent Ruby's +# Implementation of a thread pool. This implementation is a stripped down form of Concurrent Ruby's # `CachedThreadPool`. class ThreadPool # Much of this logic taken from @@ -14,10 +14,19 @@ class ThreadPool # releasing it when the thread exits. Since the block is invoked for the entire lifetime of # the thread, a resource acquired around it can be released from an `ensure`. # + # The `call` wrapper should not raise. `call` has the responsibility for calling the + # passed block exactly once, and rescuing all exceptions and errors. If the `call` wrapper + # cannot invoke the block, the block is not re-queued. + # + # If the `call` wrapper does raise, the exception is swallowed, and the worker dies. + # The `restart_worker` constructor parameter determines whether a new worker is + # immediately created to replace the one that died. It defaults to false to avoid + # a rapid fail-and-restart loop. + # # @note The same instance is used by every thread in the pool, so implementations must be # thread safe. Per-thread state belongs in the block, not in the ThreadContext object. class ThreadContext - # @return [ThreadContext] Default/shared context that just invokes the block. + # @return [ThreadContext] Default context that just invokes the block. def self.default @default ||= NoOp.new end @@ -268,16 +277,10 @@ def initialize(pool, id) end end end - # Block-level rescue on the Thread.new block above, so it runs on that thread. rescue Exception => e # rubocop:disable Lint/RescueException - # Only reachable when the context itself raised; everything the loop can raise is - # handled inside it. Drop the worker so the pool does not keep an entry with a dead - # thread behind it, holding an undeliverable block. Removal is idempotent, so this is - # safe even if the loop already deregistered before the context raised on the way out. - # + # Handles raises inside the ThreadContext. Drops the worker, and creates a replacement + # iff restart_worker is true. warn("Unexpected thread context exception: #{e.full_message}") - # A restarted worker is put in the ready list before its context runs, so drop it from - # there first or the pool hands later work to this dead thread. my_pool._remove_ready_worker(self) if my_pool._thread_context.restart_worker my_pool._worker_died(self) diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index 7c1b94ed..7145e4cc 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -46,10 +46,9 @@ def run_and_wait(pool, timeout: 10) def test_default_context_is_no_op pool = Temporalio::Worker::ThreadPool.new ran = Queue.new - pool.execute { ran.push({ value: Thread.current[:test_thread_context_var] }) } + pool.execute { ran.push(42) } seen = ran.pop(timeout: 10) - refute_nil seen, 'pool never ran the block' - assert_nil seen[:value] + assert_equal seen, 42, 'pool never ran the block' ensure pool&.shutdown end From bb2fe09d24bef9744d55652b698daeeadc883185 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 12:59:57 -0400 Subject: [PATCH 11/22] Consolidate test contexts --- .../test/sig/worker_thread_pool_test.rbs | 16 +--- temporalio/test/worker_thread_pool_test.rb | 85 +++++++------------ 2 files changed, 31 insertions(+), 70 deletions(-) diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index ee709a75..2a5b1883 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -6,20 +6,8 @@ class WorkerThreadPoolTest < Test def call: { -> void } -> void end - class RaisesOnceContext < Temporalio::Worker::ThreadPool::ThreadContext - attr_reader raised: Queue - def initialize: -> void - def call: { -> void } -> void - end - - class AlwaysRaisesContext < Temporalio::Worker::ThreadPool::ThreadContext - attr_reader raised: Queue - def initialize: -> void - def call: { -> void } -> void - end - - class RestartingContext < Temporalio::Worker::ThreadPool::ThreadContext - def initialize: (fail_times: Integer) -> void + class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext + def initialize: (fail_times: Numeric, ?restart_worker: bool) -> void def count: -> Integer def call: { -> void } -> void end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index 7145e4cc..f2c13850 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -148,30 +148,30 @@ def test_context_released_on_kill assert wait_until { !context.exited.empty? }, 'context did not exit on kill' end - # Raises for the first thread only, so the second thread's context succeeds. - class RaisesOnceContext < Temporalio::Worker::ThreadPool::ThreadContext - attr_reader :raised - - def initialize - super + # Raises the first `fail_times` invocations, then yields. `count` is the number of + # invocations/threads. + class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext + def initialize(fail_times:, restart_worker: false) + super(restart_worker:) + @fail_times = fail_times @mutex = Mutex.new - @raised = Queue.new - @first = true + @count = 0 + end + + def count + @mutex.synchronize { @count } end def call - should_raise = @mutex.synchronize { @first ? (@first = false) || true : false } - if should_raise - @raised.push(:raised) - raise 'context failed' - end + n = @mutex.synchronize { @count += 1 } + raise "context failed (attempt #{n})" if n <= @fail_times yield end end def test_raising_context_kills_only_its_own_thread - context = RaisesOnceContext.new + context = CountingContext.new(fail_times: 1) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) # Submit both up front. The first worker's context raises, so that worker never completes a @@ -184,7 +184,7 @@ def test_raising_context_kills_only_its_own_thread pool.execute { first.push(:ran) } pool.execute { second.push(:ran) } - assert_equal :raised, context.raised.pop(timeout: 10), 'context never raised' + assert wait_until { context.count >= 1 }, 'context never raised' assert_equal :ran, second.pop(timeout: 10), 'second thread never ran its work' end @@ -195,28 +195,14 @@ def test_raising_context_kills_only_its_own_thread pool&.kill end - class AlwaysRaisesContext < Temporalio::Worker::ThreadPool::ThreadContext - attr_reader :raised - - def initialize - super - @raised = Queue.new - end - - def call - @raised.push(:raised) - raise 'context failed' - end - end - # A worker whose context raises must not be left in the pool with a dead thread behind it. def test_raising_context_removes_its_worker_from_the_pool - context = AlwaysRaisesContext.new + context = CountingContext.new(fail_times: Float::INFINITY) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) capture_subprocess_io do pool.execute { nil } - assert_equal :raised, context.raised.pop(timeout: 10), 'context never raised' + assert wait_until { context.count >= 1 }, 'context never raised' end # ThreadPool exposes `length` but no `empty?`. @@ -229,19 +215,18 @@ def test_raising_context_removes_its_worker_from_the_pool # The cleanup must not ask for a replacement: a context that fails once generally fails every # time, so replacing on failure spawns threads without bound. def test_raising_context_does_not_spawn_replacement_threads - context = AlwaysRaisesContext.new + context = CountingContext.new(fail_times: Float::INFINITY) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) capture_subprocess_io do pool.execute { nil } - # Left on the queue rather than popped, so its size counts context invocations. - assert wait_until { !context.raised.empty? }, 'context never raised' + assert wait_until { context.count >= 1 }, 'context never raised' sleep(0.5) end # One submission, one thread, so the context ran exactly once. Replacing the worker on failure # produced tens of thousands of invocations here. - assert_equal 1, context.raised.size, 'context ran on replacement threads' + assert_equal 1, context.count, 'context ran on replacement threads' ensure pool&.kill end @@ -263,28 +248,8 @@ def test_kill_does_not_resurrect_workers # Raises the first `fail_times` invocations, then yields. Each invocation is a fresh thread when # restart_worker is on, so the count doubles as a count of threads started. - class RestartingContext < Temporalio::Worker::ThreadPool::ThreadContext - def initialize(fail_times:) - super(restart_worker: true) - @fail_times = fail_times - @mutex = Mutex.new - @count = 0 - end - - def count - @mutex.synchronize { @count } - end - - def call - n = @mutex.synchronize { @count += 1 } - raise "context failed (attempt #{n})" if n <= @fail_times - - yield - end - end - def test_restart_worker_restarts_the_thread_until_the_context_succeeds - context = RestartingContext.new(fail_times: 10) + context = CountingContext.new(fail_times: 10, restart_worker: true) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) capture_subprocess_io do @@ -298,6 +263,14 @@ def test_restart_worker_restarts_the_thread_until_the_context_succeeds sleep(0.3) assert_equal 11, context.count, 'context kept restarting after it stopped raising' assert_equal 1, pool.length, 'the surviving thread is not in the pool' + + live = pool.instance_variable_get(:@pool) + ready = pool.instance_variable_get(:@ready).map(&:first) + assert_empty ready.reject { |w| live.include?(w) }, 'restarts left dead workers in the ready list' + + ran = Queue.new + 10.times { pool.execute { ran.push(:ran) } } + assert wait_until { ran.size == 10 }, "only #{ran.size} of 10 tasks ran after the restarts" ensure pool&.kill end From 05501e5218273070e3e2d433c65b9fd0274d1c61 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 13:01:16 -0400 Subject: [PATCH 12/22] cleanup --- temporalio/test/worker_thread_pool_test.rb | 44 +++++++++++----------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index f2c13850..7214f389 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -24,6 +24,28 @@ def call end end + # Raises the first `fail_times` invocations, then yields. `count` is the number of + # invocations/threads. + class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext + def initialize(fail_times:, restart_worker: false) + super(restart_worker:) + @fail_times = fail_times + @mutex = Mutex.new + @count = 0 + end + + def count + @mutex.synchronize { @count } + end + + def call + n = @mutex.synchronize { @count += 1 } + raise "context failed (attempt #{n})" if n <= @fail_times + + yield + end + end + # Polls the block until it returns truthy or `timeout` elapses. def wait_until(timeout: 10) deadline = Time.now + timeout @@ -148,28 +170,6 @@ def test_context_released_on_kill assert wait_until { !context.exited.empty? }, 'context did not exit on kill' end - # Raises the first `fail_times` invocations, then yields. `count` is the number of - # invocations/threads. - class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext - def initialize(fail_times:, restart_worker: false) - super(restart_worker:) - @fail_times = fail_times - @mutex = Mutex.new - @count = 0 - end - - def count - @mutex.synchronize { @count } - end - - def call - n = @mutex.synchronize { @count += 1 } - raise "context failed (attempt #{n})" if n <= @fail_times - - yield - end - end - def test_raising_context_kills_only_its_own_thread context = CountingContext.new(fail_times: 1) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) From 8f87b2e931cda69ed7b8d3d3dbff906b5c6d521c Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 13:18:09 -0400 Subject: [PATCH 13/22] cleanup, moved sleep outside capture --- temporalio/test/worker_thread_pool_test.rb | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index 7214f389..c0146643 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -179,7 +179,6 @@ def test_raising_context_kills_only_its_own_thread # worker rather than reuse the dead one. first = Queue.new second = Queue.new - # Captured only to keep the dying thread's report_on_exception warning out of the test output. capture_subprocess_io do pool.execute { first.push(:ran) } pool.execute { second.push(:ran) } @@ -188,7 +187,6 @@ def test_raising_context_kills_only_its_own_thread assert_equal :ran, second.pop(timeout: 10), 'second thread never ran its work' end - # Its worker is dead, so nothing can ever pop this block; no waiting needed to establish that. assert_empty first, 'block ran even though its context raised' assert_equal 2, pool.largest_length ensure @@ -205,15 +203,12 @@ def test_raising_context_removes_its_worker_from_the_pool assert wait_until { context.count >= 1 }, 'context never raised' end - # ThreadPool exposes `length` but no `empty?`. assert wait_until { pool.length.zero? }, # rubocop:disable Style/ZeroLengthPredicate 'dead worker was left in the pool' ensure pool&.kill end - # The cleanup must not ask for a replacement: a context that fails once generally fails every - # time, so replacing on failure spawns threads without bound. def test_raising_context_does_not_spawn_replacement_threads context = CountingContext.new(fail_times: Float::INFINITY) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) @@ -221,18 +216,15 @@ def test_raising_context_does_not_spawn_replacement_threads capture_subprocess_io do pool.execute { nil } assert wait_until { context.count >= 1 }, 'context never raised' - sleep(0.5) end - # One submission, one thread, so the context ran exactly once. Replacing the worker on failure - # produced tens of thousands of invocations here. - assert_equal 1, context.count, 'context ran on replacement threads' + sleep(0.5) + assert_equal 1, context.count, 'context ran on new replacement threads' ensure pool&.kill end - # `ThreadPool#kill` already drops every worker, so the cleanup must not resurrect any. - def test_kill_does_not_resurrect_workers + def test_kill_does_not_spawn_replacement_threads context = RecordingContext.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) run_and_wait(pool) @@ -246,8 +238,6 @@ def test_kill_does_not_resurrect_workers assert_equal 1, pool.largest_length, 'kill spawned a replacement thread' end - # Raises the first `fail_times` invocations, then yields. Each invocation is a fresh thread when - # restart_worker is on, so the count doubles as a count of threads started. def test_restart_worker_restarts_the_thread_until_the_context_succeeds context = CountingContext.new(fail_times: 10, restart_worker: true) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) @@ -259,10 +249,9 @@ def test_restart_worker_restarts_the_thread_until_the_context_succeeds assert wait_until { context.count >= 11 }, "context ran #{context.count} times, wanted 11" end - # The 11th invocation yielded, so that thread stays alive and restarting stops. sleep(0.3) assert_equal 11, context.count, 'context kept restarting after it stopped raising' - assert_equal 1, pool.length, 'the surviving thread is not in the pool' + assert_equal 1, pool.length, 'only the last restart should leave a thread in the pool' live = pool.instance_variable_get(:@pool) ready = pool.instance_variable_get(:@ready).map(&:first) From 43f4c3afd8432918ca296c55e7487a558d69ff9f Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 13:34:17 -0400 Subject: [PATCH 14/22] combine test context recorders --- .../test/sig/worker_thread_pool_test.rbs | 7 --- temporalio/test/thread_context_recorder.rb | 29 ++++++++++++ temporalio/test/worker_activity_test.rb | 22 +-------- temporalio/test/worker_thread_pool_test.rb | 45 ++++++------------- 4 files changed, 44 insertions(+), 59 deletions(-) create mode 100644 temporalio/test/thread_context_recorder.rb diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_pool_test.rbs index 2a5b1883..75179df2 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_pool_test.rbs @@ -1,11 +1,4 @@ class WorkerThreadPoolTest < Test - class RecordingContext < Temporalio::Worker::ThreadPool::ThreadContext - attr_reader entered: Queue - attr_reader exited: Queue - def initialize: (?var_value: String) -> void - def call: { -> void } -> void - end - class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext def initialize: (fail_times: Numeric, ?restart_worker: bool) -> void def count: -> Integer diff --git a/temporalio/test/thread_context_recorder.rb b/temporalio/test/thread_context_recorder.rb new file mode 100644 index 00000000..d66498ca --- /dev/null +++ b/temporalio/test/thread_context_recorder.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require 'temporalio/worker/thread_pool' + +# Thread context for tests: sets a thread-local for the lifetime of each pool thread and clears it +# on the way out, so work running on that thread can observe it and a test can observe the +# teardown. `entered` and `exited` are queues because they are pushed to from pool threads, which +# outlive the work they run. +class ThreadContextRecorder < Temporalio::Worker::ThreadPool::ThreadContext + VALUE_KEY = :thread_context_value + + attr_reader :entered, :exited + + def initialize(value: 'acquired') + super() + @value = value + @entered = Queue.new + @exited = Queue.new + end + + def call + Thread.current[VALUE_KEY] = @value + @entered.push(Thread.current.name) + yield + ensure + Thread.current[VALUE_KEY] = nil + @exited.push(Thread.current.name) + end +end diff --git a/temporalio/test/worker_activity_test.rb b/temporalio/test/worker_activity_test.rb index 0bb2c0f1..f0b79f6e 100644 --- a/temporalio/test/worker_activity_test.rb +++ b/temporalio/test/worker_activity_test.rb @@ -8,6 +8,7 @@ require 'temporalio/testing' require 'temporalio/worker' require 'test' +require 'thread_context_recorder' class WorkerActivityTest < Test also_run_all_tests_in_fiber @@ -910,30 +911,11 @@ def test_custom_executor execute_activity(CustomExecutorActivity, activity_executors: { my_executor: CustomExecutor.new }) end - # Sets a thread-local for the lifetime of each pool thread. - class ThreadContextRecorder < Temporalio::Worker::ThreadPool::ThreadContext - # Pool threads outlive the activity, so the exit is recorded on a queue the test can wait on. - attr_reader :exited - - def initialize - super - @exited = Queue.new - end - - def call - Thread.current[:thread_context_val] = 'acquired' - yield - ensure - Thread.current[:thread_context_val] = nil - @exited.push(Thread.current.name) - end - end - class ThreadContextActivity < Temporalio::Activity::Definition activity_executor :context_executor def execute - "context val: #{Thread.current[:thread_context_val]}" + "context val: #{Thread.current[ThreadContextRecorder::VALUE_KEY]}" end end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index c0146643..7f1df867 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -2,28 +2,9 @@ require 'temporalio/worker/thread_pool' require 'test' +require 'thread_context_recorder' class WorkerThreadPoolTest < Test - class RecordingContext < Temporalio::Worker::ThreadPool::ThreadContext - attr_reader :entered, :exited - - def initialize(var_value: 'set-by-context') - super() - @var_value = var_value - @entered = Queue.new - @exited = Queue.new - end - - def call - Thread.current[:test_thread_context_var] = @var_value - @entered.push(Thread.current.name) - yield - ensure - Thread.current[:test_thread_context_var] = nil - @exited.push(Thread.current.name) - end - end - # Raises the first `fail_times` invocations, then yields. `count` is the number of # invocations/threads. class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext @@ -76,13 +57,13 @@ def test_default_context_is_no_op end def test_context_wraps_work_on_the_thread - context = RecordingContext.new + context = ThreadContextRecorder.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) seen = Queue.new - pool.execute { seen.push(Thread.current[:test_thread_context_var]) } + pool.execute { seen.push(Thread.current[ThreadContextRecorder::VALUE_KEY]) } - assert_equal 'set-by-context', seen.pop(timeout: 10) + assert_equal 'acquired', seen.pop(timeout: 10) refute_empty context.entered assert_empty context.exited, 'context must not have exited while the thread is still alive' ensure @@ -90,7 +71,7 @@ def test_context_wraps_work_on_the_thread end def test_context_wraps_every_thread_in_the_pool - context = RecordingContext.new + context = ThreadContextRecorder.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) release = Queue.new @@ -98,11 +79,11 @@ def test_context_wraps_every_thread_in_the_pool # Ensure two threads are running. 2.times do pool.execute do - seen.push(Thread.current[:test_thread_context_var]) + seen.push(Thread.current[ThreadContextRecorder::VALUE_KEY]) release.pop end end - assert_equal %w[set-by-context set-by-context], [seen.pop, seen.pop] + assert_equal %w[acquired acquired], [seen.pop, seen.pop] 2.times { release.push(nil) } assert_equal 2, pool.largest_length @@ -113,7 +94,7 @@ def test_context_wraps_every_thread_in_the_pool end def test_context_released_on_graceful_shutdown - context = RecordingContext.new + context = ThreadContextRecorder.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) run_and_wait(pool) assert_empty context.exited @@ -124,7 +105,7 @@ def test_context_released_on_graceful_shutdown end def test_context_released_on_idle_timeout_prune - context = RecordingContext.new + context = ThreadContextRecorder.new # We need two threads to make sure there is one that can be pruned. pool = Temporalio::Worker::ThreadPool.new(idle_timeout: 0.05, thread_context: context) release = Queue.new @@ -154,7 +135,7 @@ def test_context_released_on_idle_timeout_prune end def test_context_released_on_kill - context = RecordingContext.new + context = ThreadContextRecorder.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) started = Queue.new blocked = Queue.new @@ -218,14 +199,14 @@ def test_raising_context_does_not_spawn_replacement_threads assert wait_until { context.count >= 1 }, 'context never raised' end - sleep(0.5) - assert_equal 1, context.count, 'context ran on new replacement threads' + sleep(0.5) + assert_equal 1, context.count, 'context ran on new replacement threads' ensure pool&.kill end def test_kill_does_not_spawn_replacement_threads - context = RecordingContext.new + context = ThreadContextRecorder.new pool = Temporalio::Worker::ThreadPool.new(thread_context: context) run_and_wait(pool) assert_equal 1, pool.length From f384e7530dd552ef74e43d564a42f499924ecad0 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 13:52:09 -0400 Subject: [PATCH 15/22] readme --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/README.md b/README.md index ba765e59..1a074dad 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ Also see: - [Activity Heartbeating and Cancellation](#activity-heartbeating-and-cancellation) - [Activity Worker Shutdown](#activity-worker-shutdown) - [Activity Concurrency and Executors](#activity-concurrency-and-executors) + - [Per-Thread Setup for the Thread Pool Executor](#per-thread-setup-for-the-thread-pool-executor) - [Activity Testing](#activity-testing) - [Telemetry](#telemetry) - [Metrics](#metrics) @@ -1084,6 +1085,50 @@ Technically the executor can be customized. The `activity_executors` worker opti symbol and the value as a `Temporalio::Worker::ActivityExecutor` implementation. Users should usually not need to customize this. If general code is needed to run around activities, users should use interceptors instead. +#### Per-Thread Setup for the Thread Pool Executor + +To acquire a resource once per thread and reuse it across every activity that thread runs -- a database connection, say +-- pass a `Temporalio::Worker::ThreadPool::ThreadContext` when constructing a thread pool. The context's `call` method +receives a block that executes the worker's assigned tasks, and should be called exactly once. `call` should not +raise. Acquired resources should be released in an `ensure`, not directly after `yield`: + +```ruby +class DatabaseConnectionContext < Temporalio::Worker::ThreadPool::ThreadContext + def call + connection = MyDatabase.connect + Thread.current[:my_connection] = connection + yield + # not reached + ensure + Thread.current[:my_connection] = nil + connection&.close + end +end + +pool = Temporalio::Worker::ThreadPool.new(thread_context: DatabaseConnectionContext.new) +executor = Temporalio::Worker::ActivityExecutor::ThreadPool.new(pool) + +worker = Temporalio::Worker.new( + client:, + task_queue: 'my-task-queue', + activities: [MyActivity], + activity_executors: Temporalio::Worker::ActivityExecutor.defaults.merge(default: executor) +) +``` + +Note: + +* You must explicitly constructd and use a pool and exeuctor with your custom thread context. The default pool + has no context. +* `call` must invoke the block exactly once. Invoking it again re-enters a loop the pool has stopped tracking, which + blocks that thread forever; not invoking it means the thread never runs any work. +* Clean up in an `ensure`, not after the `yield`. The block is left via a non-local exit when the thread stops, so code + written after the `yield` does not run. +* This is not an interceptor. A context wraps a thread's whole lifetime, not a single activity execution. To run code + around each activity, use an interceptor instead. +* The `call` wrapper should not raise. If it does, work already queued on the worker is dropped silently (and thus + will time out and be retried). + #### Activity Testing Unit testing an activity can be done via the `Temporalio::Testing::ActivityEnvironment` class. Simply instantiate the From 39db667ddae01b54b33c4c3facecfdad6b5d08ef Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 14:03:10 -0400 Subject: [PATCH 16/22] clarify loop exit behavior --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1a074dad..0e330f81 100644 --- a/README.md +++ b/README.md @@ -1098,7 +1098,6 @@ class DatabaseConnectionContext < Temporalio::Worker::ThreadPool::ThreadContext connection = MyDatabase.connect Thread.current[:my_connection] = connection yield - # not reached ensure Thread.current[:my_connection] = nil connection&.close @@ -1118,16 +1117,19 @@ worker = Temporalio::Worker.new( Note: -* You must explicitly constructd and use a pool and exeuctor with your custom thread context. The default pool +* You must explicitly construct and use a pool and executor with your custom thread context. The default pool has no context. * `call` must invoke the block exactly once. Invoking it again re-enters a loop the pool has stopped tracking, which blocks that thread forever; not invoking it means the thread never runs any work. -* Clean up in an `ensure`, not after the `yield`. The block is left via a non-local exit when the thread stops, so code - written after the `yield` does not run. +* Clean up in an `ensure`. On a normal stop the block returns and code after the `yield` does run, but + `Temporalio::Worker::ThreadPool#kill` terminates the thread without letting the block return, so only an `ensure` + runs on every path. * This is not an interceptor. A context wraps a thread's whole lifetime, not a single activity execution. To run code around each activity, use an interceptor instead. * The `call` wrapper should not raise. If it does, work already queued on the worker is dropped silently (and thus - will time out and be retried). + will time out and be retried). The thread is dropped from the pool, and a new one is started when more work + arrives. Pass `restart_worker: true` to the `ThreadContext` constructor to start a replacement immediately instead; + a context that always raises will then restart without bound. #### Activity Testing From 138a6ce371e99738d636d0e02b289201d1427a8f Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 14:22:30 -0400 Subject: [PATCH 17/22] Add tests for post-yield code running (stop) or not running (kill). --- temporalio/test/thread_context_recorder.rb | 11 +++++--- temporalio/test/worker_thread_pool_test.rb | 29 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/temporalio/test/thread_context_recorder.rb b/temporalio/test/thread_context_recorder.rb index d66498ca..e23173fb 100644 --- a/temporalio/test/thread_context_recorder.rb +++ b/temporalio/test/thread_context_recorder.rb @@ -4,17 +4,21 @@ # Thread context for tests: sets a thread-local for the lifetime of each pool thread and clears it # on the way out, so work running on that thread can observe it and a test can observe the -# teardown. `entered` and `exited` are queues because they are pushed to from pool threads, which -# outlive the work they run. +# teardown. `entered`, `returned` and `exited` are queues because they are pushed to from pool +# threads, which outlive the work they run. +# +# `returned` records reaching the statement after the `yield`, which only happens when the block +# returns normally -- not when the thread is killed inside it. class ThreadContextRecorder < Temporalio::Worker::ThreadPool::ThreadContext VALUE_KEY = :thread_context_value - attr_reader :entered, :exited + attr_reader :entered, :returned, :exited def initialize(value: 'acquired') super() @value = value @entered = Queue.new + @returned = Queue.new @exited = Queue.new end @@ -22,6 +26,7 @@ def call Thread.current[VALUE_KEY] = @value @entered.push(Thread.current.name) yield + @returned.push(Thread.current.name) ensure Thread.current[VALUE_KEY] = nil @exited.push(Thread.current.name) diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index 7f1df867..bfbab3bf 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -151,6 +151,35 @@ def test_context_released_on_kill assert wait_until { !context.exited.empty? }, 'context did not exit on kill' end + def test_stop_runs_code_after_the_yield + context = ThreadContextRecorder.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + run_and_wait(pool) + assert_empty context.returned + + pool.shutdown + + assert wait_until { !context.exited.empty? }, 'context did not exit on graceful shutdown' + refute_empty context.returned, 'stop did not return through the context; code after the yield never ran' + end + + def test_kill_does_not_run_code_after_the_yield + context = ThreadContextRecorder.new + pool = Temporalio::Worker::ThreadPool.new(thread_context: context) + started = Queue.new + blocked = Queue.new + pool.execute do + started.push(:started) + blocked.pop # blocks + end + assert_equal :started, started.pop(timeout: 10), 'thread never started' + + pool.kill + + assert wait_until { !context.exited.empty? }, 'context did not exit on kill' + assert_empty context.returned, 'kill let the context return normally' + end + def test_raising_context_kills_only_its_own_thread context = CountingContext.new(fail_times: 1) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) From 3a0e3146789e12abf49f62a4dc943f788fc81bf4 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 14:26:00 -0400 Subject: [PATCH 18/22] Use safe_capture_io --- temporalio/test/worker_thread_pool_test.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_pool_test.rb index bfbab3bf..9cd98a30 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_pool_test.rb @@ -189,7 +189,7 @@ def test_raising_context_kills_only_its_own_thread # worker rather than reuse the dead one. first = Queue.new second = Queue.new - capture_subprocess_io do + safe_capture_io do pool.execute { first.push(:ran) } pool.execute { second.push(:ran) } @@ -208,7 +208,7 @@ def test_raising_context_removes_its_worker_from_the_pool context = CountingContext.new(fail_times: Float::INFINITY) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - capture_subprocess_io do + safe_capture_io do pool.execute { nil } assert wait_until { context.count >= 1 }, 'context never raised' end @@ -223,7 +223,7 @@ def test_raising_context_does_not_spawn_replacement_threads context = CountingContext.new(fail_times: Float::INFINITY) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - capture_subprocess_io do + safe_capture_io do pool.execute { nil } assert wait_until { context.count >= 1 }, 'context never raised' end @@ -252,7 +252,7 @@ def test_restart_worker_restarts_the_thread_until_the_context_succeeds context = CountingContext.new(fail_times: 10, restart_worker: true) pool = Temporalio::Worker::ThreadPool.new(thread_context: context) - capture_subprocess_io do + safe_capture_io do pool.execute { nil } # Each restart re-invokes the context with no further work submitted, so reaching 11 means # the 10 failures each produced a replacement thread. From 67487fddf0241e6299cd3fbd76862d8102dc5048 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 15:11:14 -0400 Subject: [PATCH 19/22] Use assert_eventually instead of wait_util. test_base_context_is_abstract uses a real thread pool. Rename WorkerThreadPoolTest to WorkerThreadContextTest etc. --- ...est.rbs => worker_thread_context_test.rbs} | 3 +- temporalio/test/worker_activity_test.rb | 4 +- ..._test.rb => worker_thread_context_test.rb} | 60 +++++++++---------- 3 files changed, 32 insertions(+), 35 deletions(-) rename temporalio/test/sig/{worker_thread_pool_test.rbs => worker_thread_context_test.rbs} (75%) rename temporalio/test/{worker_thread_pool_test.rb => worker_thread_context_test.rb} (79%) diff --git a/temporalio/test/sig/worker_thread_pool_test.rbs b/temporalio/test/sig/worker_thread_context_test.rbs similarity index 75% rename from temporalio/test/sig/worker_thread_pool_test.rbs rename to temporalio/test/sig/worker_thread_context_test.rbs index 75179df2..6fc5ad94 100644 --- a/temporalio/test/sig/worker_thread_pool_test.rbs +++ b/temporalio/test/sig/worker_thread_context_test.rbs @@ -1,10 +1,9 @@ -class WorkerThreadPoolTest < Test +class WorkerThreadContextTest < Test class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext def initialize: (fail_times: Numeric, ?restart_worker: bool) -> void def count: -> Integer def call: { -> void } -> void end - def wait_until: (?timeout: Float) { () -> boolish } -> boolish def run_and_wait: (Temporalio::Worker::ThreadPool pool, ?timeout: Float) -> void end diff --git a/temporalio/test/worker_activity_test.rb b/temporalio/test/worker_activity_test.rb index f0b79f6e..62381fe8 100644 --- a/temporalio/test/worker_activity_test.rb +++ b/temporalio/test/worker_activity_test.rb @@ -933,9 +933,7 @@ def test_thread_pool_thread_context_wraps_activity assert_empty context.exited pool.shutdown - deadline = Time.now + 10 - sleep(0.02) while context.exited.empty? && Time.now < deadline - refute_empty context.exited, 'thread context did not release when the pool shut down' + assert_eventually { refute_empty context.exited, 'thread context did not release when the pool shut down' } ensure pool&.kill end diff --git a/temporalio/test/worker_thread_pool_test.rb b/temporalio/test/worker_thread_context_test.rb similarity index 79% rename from temporalio/test/worker_thread_pool_test.rb rename to temporalio/test/worker_thread_context_test.rb index 9cd98a30..14d27484 100644 --- a/temporalio/test/worker_thread_pool_test.rb +++ b/temporalio/test/worker_thread_context_test.rb @@ -4,7 +4,7 @@ require 'test' require 'thread_context_recorder' -class WorkerThreadPoolTest < Test +class WorkerThreadContextTest < Test # Raises the first `fail_times` invocations, then yields. `count` is the number of # invocations/threads. class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext @@ -27,17 +27,6 @@ def call end end - # Polls the block until it returns truthy or `timeout` elapses. - def wait_until(timeout: 10) - deadline = Time.now + timeout - loop do - result = yield - return result if result || Time.now > deadline - - sleep(0.02) - end - end - # Blocks until the pool runs something on a thread, so the thread is known to exist and to have # entered its context. Fails rather than hanging if that never happens. def run_and_wait(pool, timeout: 10) @@ -101,7 +90,7 @@ def test_context_released_on_graceful_shutdown pool.shutdown - assert wait_until { !context.exited.empty? }, 'context did not exit on graceful shutdown' + assert_eventually { refute_empty context.exited, 'context did not exit on graceful shutdown' } end def test_context_released_on_idle_timeout_prune @@ -118,18 +107,17 @@ def test_context_released_on_idle_timeout_prune end 2.times { assert_equal :started, started.pop(timeout: 10), 'thread never started' } 2.times { release.push(nil) } - assert wait_until { pool.active_count.zero? }, 'threads did not go idle' + assert_eventually { assert_equal 0, pool.active_count, 'threads did not go idle' } assert_equal 2, pool.length assert_empty context.exited # Pruning only happens inside `execute`. sleep(0.2) - pruned = wait_until do + assert_eventually do pool.execute { nil } - !context.exited.empty? + refute_empty context.exited, 'context did not exit when its idle thread was pruned' end - assert pruned, 'context did not exit when its idle thread was pruned' - assert wait_until { pool.length < 2 }, 'pruned thread was not removed from the pool' + assert_eventually { assert_operator pool.length, :<, 2, 'pruned thread was not removed from the pool' } ensure pool&.shutdown end @@ -148,7 +136,7 @@ def test_context_released_on_kill pool.kill - assert wait_until { !context.exited.empty? }, 'context did not exit on kill' + assert_eventually { refute_empty context.exited, 'context did not exit on kill' } end def test_stop_runs_code_after_the_yield @@ -159,7 +147,7 @@ def test_stop_runs_code_after_the_yield pool.shutdown - assert wait_until { !context.exited.empty? }, 'context did not exit on graceful shutdown' + assert_eventually { refute_empty context.exited, 'context did not exit on graceful shutdown' } refute_empty context.returned, 'stop did not return through the context; code after the yield never ran' end @@ -176,7 +164,7 @@ def test_kill_does_not_run_code_after_the_yield pool.kill - assert wait_until { !context.exited.empty? }, 'context did not exit on kill' + assert_eventually { refute_empty context.exited, 'context did not exit on kill' } assert_empty context.returned, 'kill let the context return normally' end @@ -193,7 +181,7 @@ def test_raising_context_kills_only_its_own_thread pool.execute { first.push(:ran) } pool.execute { second.push(:ran) } - assert wait_until { context.count >= 1 }, 'context never raised' + assert_eventually { assert_operator context.count, :>=, 1, 'context never raised' } assert_equal :ran, second.pop(timeout: 10), 'second thread never ran its work' end @@ -210,11 +198,10 @@ def test_raising_context_removes_its_worker_from_the_pool safe_capture_io do pool.execute { nil } - assert wait_until { context.count >= 1 }, 'context never raised' + assert_eventually { assert_operator context.count, :>=, 1, 'context never raised' } end - assert wait_until { pool.length.zero? }, # rubocop:disable Style/ZeroLengthPredicate - 'dead worker was left in the pool' + assert_eventually { assert_equal 0, pool.length, 'dead worker was left in the pool' } ensure pool&.kill end @@ -225,7 +212,7 @@ def test_raising_context_does_not_spawn_replacement_threads safe_capture_io do pool.execute { nil } - assert wait_until { context.count >= 1 }, 'context never raised' + assert_eventually { assert_operator context.count, :>=, 1, 'context never raised' } end sleep(0.5) @@ -242,7 +229,7 @@ def test_kill_does_not_spawn_replacement_threads pool.kill - assert wait_until { !context.exited.empty? }, 'context did not exit on kill' + assert_eventually { refute_empty context.exited, 'context did not exit on kill' } sleep(0.3) assert_equal 0, pool.length, 'kill left workers in the pool' assert_equal 1, pool.largest_length, 'kill spawned a replacement thread' @@ -256,7 +243,7 @@ def test_restart_worker_restarts_the_thread_until_the_context_succeeds pool.execute { nil } # Each restart re-invokes the context with no further work submitted, so reaching 11 means # the 10 failures each produced a replacement thread. - assert wait_until { context.count >= 11 }, "context ran #{context.count} times, wanted 11" + assert_eventually { assert_operator context.count, :>=, 11, 'context did not restart until it succeeded' } end sleep(0.3) @@ -269,12 +256,25 @@ def test_restart_worker_restarts_the_thread_until_the_context_succeeds ran = Queue.new 10.times { pool.execute { ran.push(:ran) } } - assert wait_until { ran.size == 10 }, "only #{ran.size} of 10 tasks ran after the restarts" + assert_eventually { assert_equal 10, ran.size, 'not all tasks ran after the restarts' } ensure pool&.kill end def test_base_context_is_abstract - assert_raises(NotImplementedError) { Temporalio::Worker::ThreadPool::ThreadContext.new.call { nil } } + pool = Temporalio::Worker::ThreadPool.new(thread_context: Temporalio::Worker::ThreadPool::ThreadContext.new) + + ran = Queue.new + # The thread warns before dropping itself from the pool, so an empty pool means the message has + # already been written. + _, err = safe_capture_io do + pool.execute { ran.push(:ran) } + assert_eventually { assert_equal 0, pool.length, 'abstract context left its worker in the pool' } + end + + assert_includes err, 'NotImplementedError' + assert_empty ran, 'block ran even though the context is abstract' + ensure + pool&.kill end end From 1e0627c4243dffb9946da12b5cb040ce6ee7e447 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 15:19:42 -0400 Subject: [PATCH 20/22] Fix test race condition --- temporalio/test/worker_thread_context_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/test/worker_thread_context_test.rb b/temporalio/test/worker_thread_context_test.rb index 14d27484..d0325c1e 100644 --- a/temporalio/test/worker_thread_context_test.rb +++ b/temporalio/test/worker_thread_context_test.rb @@ -186,7 +186,7 @@ def test_raising_context_kills_only_its_own_thread end assert_empty first, 'block ran even though its context raised' - assert_equal 2, pool.largest_length + assert_equal 2, context.count, 'a second thread was not created' ensure pool&.kill end From 7e82fb87c50f5bef66adc8d8b7e876111e9f2411 Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Wed, 30 Sep 2026 16:38:45 -0400 Subject: [PATCH 21/22] Factor out worker main loop and thread context exception handling. --- .../lib/temporalio/worker/thread_pool.rb | 80 ++++++++++--------- .../sig/temporalio/worker/thread_pool.rbs | 3 + 2 files changed, 46 insertions(+), 37 deletions(-) diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index 04742b1b..72ee622e 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -251,43 +251,7 @@ def locked_worker_died(worker) class Worker def initialize(pool, id) @queue = Queue.new - @thread = Thread.new(@queue, pool) do |my_queue, my_pool| - # Run the entire loop inside the ThreadContext. - my_pool._thread_context.call do - catch(:stop) do - loop do - case block = my_queue.pop - when :stop - pool._remove_busy_worker(self) - throw :stop - else - begin - block.call - my_pool._worker_task_completed - my_pool._ready_worker(self, ThreadPool._monotonic_time) - rescue StandardError => e - # Ignore - warn("Unexpected execute block error: #{e.full_message}") - rescue Exception => e # rubocop:disable Lint/RescueException - warn("Unexpected execute block exception: #{e.full_message}") - my_pool._worker_died(self) - throw :stop - end - end - end - end - end - rescue Exception => e # rubocop:disable Lint/RescueException - # Handles raises inside the ThreadContext. Drops the worker, and creates a replacement - # iff restart_worker is true. - warn("Unexpected thread context exception: #{e.full_message}") - my_pool._remove_ready_worker(self) - if my_pool._thread_context.restart_worker - my_pool._worker_died(self) - else - my_pool._remove_busy_worker(self) - end - end + @thread = Thread.new(@queue, pool) { |my_queue, my_pool| worker_loop(my_queue, my_pool) } @thread.name = "temporal-thread-#{id}" end @@ -305,6 +269,48 @@ def stop def kill @thread.kill end + + private + + def worker_loop(my_queue, my_pool) + my_pool._thread_context.call do + catch(:stop) do + loop do + case block = my_queue.pop + when :stop + my_pool._remove_busy_worker(self) + throw :stop + else + begin + block.call + my_pool._worker_task_completed + my_pool._ready_worker(self, ThreadPool._monotonic_time) + rescue StandardError => e + # Ignore + warn("Unexpected execute block error: #{e.full_message}") + rescue Exception => e # rubocop:disable Lint/RescueException + warn("Unexpected execute block exception: #{e.full_message}") + my_pool._worker_died(self) + throw :stop + end + end + end + end + end + rescue Exception => e # rubocop:disable Lint/RescueException + handle_thread_context_exception(my_pool, e) + end + + # Removes the worker, and creates a replacement iff restart_worker is true. + def handle_thread_context_exception(my_pool, err) + warn("Unexpected thread context exception: #{err.full_message}") + my_pool._remove_ready_worker(self) + if my_pool._thread_context.restart_worker + my_pool._worker_died(self) + else + my_pool._remove_busy_worker(self) + end + end end private_constant :Worker diff --git a/temporalio/sig/temporalio/worker/thread_pool.rbs b/temporalio/sig/temporalio/worker/thread_pool.rbs index 49c798fd..a9787abb 100644 --- a/temporalio/sig/temporalio/worker/thread_pool.rbs +++ b/temporalio/sig/temporalio/worker/thread_pool.rbs @@ -52,6 +52,9 @@ module Temporalio def <<: (Proc block) -> void def stop: -> void def kill: -> void + + private def worker_loop: (Thread::Queue my_queue, ThreadPool my_pool) -> void + private def handle_thread_context_exception: (ThreadPool my_pool, Exception err) -> void end end end From bba1f16b46304ff458beeefdd5d4b8d1150f0a8f Mon Sep 17 00:00:00 2001 From: Greg Travis Date: Thu, 1 Oct 2026 08:09:45 -0400 Subject: [PATCH 22/22] cleanup --- temporalio/lib/temporalio/worker/thread_pool.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/lib/temporalio/worker/thread_pool.rb b/temporalio/lib/temporalio/worker/thread_pool.rb index 72ee622e..37f611f6 100644 --- a/temporalio/lib/temporalio/worker/thread_pool.rb +++ b/temporalio/lib/temporalio/worker/thread_pool.rb @@ -2,7 +2,7 @@ module Temporalio class Worker -# Implementation of a thread pool. This implementation is a stripped down form of Concurrent Ruby's + # Implementation of a thread pool. This implementation is a stripped down form of Concurrent Ruby's # `CachedThreadPool`. class ThreadPool # Much of this logic taken from