diff --git a/changelog/fixed/heartbeat-slot-lock-dance.md b/changelog/fixed/heartbeat-slot-lock-dance.md new file mode 100644 index 00000000..b8cca08d --- /dev/null +++ b/changelog/fixed/heartbeat-slot-lock-dance.md @@ -0,0 +1 @@ +Activity heartbeats release the Ruby GVL while calling Core, preventing deadlock when a custom activity slot notification needs a Ruby callback while Core holds its activity mutex. diff --git a/temporalio/ext/src/worker.rs b/temporalio/ext/src/worker.rs index 7ddae667..55ea4ab6 100644 --- a/temporalio/ext/src/worker.rs +++ b/temporalio/ext/src/worker.rs @@ -11,7 +11,7 @@ use crate::{ client::Client, enter_sync, error, id, lazy_id, new_error, runtime::{AsyncCommand, Runtime, RuntimeHandle}, - util::{AsyncCallback, SendSyncBoxValue, Struct}, + util::{AsyncCallback, SendSyncBoxValue, Struct, without_gvl}, }; use futures::{StreamExt, stream::BoxStream}; use futures::{future, stream}; @@ -363,7 +363,13 @@ impl Worker { let heartbeat = ActivityHeartbeat::decode(unsafe { proto.as_slice() }) .map_err(|err| error!("Invalid proto: {}", err))?; let worker = self.core.borrow().as_ref().unwrap().clone(); - worker.record_activity_heartbeat(heartbeat); + // Core may hold its activity mutex while waiting for a Ruby custom-slot + // callback. Keeping the GVL while acquiring that mutex deadlocks both. + let mut heartbeat = Some(heartbeat); + without_gvl( + || worker.record_activity_heartbeat(heartbeat.take().unwrap()), + || {}, + ); Ok(()) } diff --git a/temporalio/test/worker_test.rb b/temporalio/test/worker_test.rb index 75e2129a..413f33c3 100644 --- a/temporalio/test/worker_test.rb +++ b/temporalio/test/worker_test.rb @@ -360,6 +360,45 @@ def test_custom_slot_supplier_simple ) end + class HeartbeatingSlotActivity < Temporalio::Activity::Definition + def execute(value) + 3.times do + GC.start + Temporalio::Activity::Context.current.heartbeat(value) + end + value + end + end + + class HeartbeatingSlotWorkflow < Temporalio::Workflow::Definition + def execute(value) + Temporalio::Workflow.execute_activity(HeartbeatingSlotActivity, value, + start_to_close_timeout: 10, heartbeat_timeout: 5) + end + end + + def test_custom_slot_supplier_heartbeat_contention + supplier = TrackingSlotSupplier.new + worker = Temporalio::Worker.new( + client: env.client, + task_queue: "tq-#{SecureRandom.uuid}", + workflows: [HeartbeatingSlotWorkflow], + activities: [HeartbeatingSlotActivity], + tuner: Temporalio::Worker::Tuner.new( + workflow_slot_supplier: supplier, + activity_slot_supplier: supplier, + local_activity_slot_supplier: supplier + ) + ) + worker.run do + handles = 16.times.map do |value| + env.client.start_workflow(HeartbeatingSlotWorkflow, value, + id: "wf-#{SecureRandom.uuid}", task_queue: worker.task_queue) + end + handles.each_with_index { |handle, value| assert_equal value, handle.result } + end + end + class BlockingSlotSupplier < Temporalio::Worker::Tuner::SlotSupplier::Custom attr_reader :canceled_contexts