Skip to content

Commit dbab4f9

Browse files
ceritiumclaude
andcommitted
Acquire concurrency locks by key when dispatching several jobs
Dispatching a set of jobs with concurrency controls acquires each job's semaphore one by one, inside the transaction that dispatches the whole set, and in whatever order the jobs come in. Two dispatchers whose batches share concurrency keys can then acquire them in opposite order and deadlock, and so can bulk enqueues. The batch that's aborted stays scheduled, so no job is lost and the limits hold, but the dispatcher that hits the error is delayed. Go through the jobs by concurrency key instead, so everyone acquires the locks they share in the same order. Within a key, jobs keep their id order, so the same job as before gets the lock first. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Acq8BRNz9v7w9mKYLYRdCi
1 parent 73602fe commit dbab4f9

3 files changed

Lines changed: 106 additions & 1 deletion

File tree

‎app/models/solid_queue/job/executable.rb‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,12 @@ def dispatch_all_at_once(jobs)
3939
ReadyExecution.create_all_from_jobs jobs
4040
end
4141

42+
# Each job acquires its concurrency lock here, and holds it until the
43+
# transaction dispatching the whole set ends. Going through them by
44+
# concurrency key makes everyone dispatching at the same time acquire
45+
# the locks they share in the same order, so they can't deadlock.
4246
def dispatch_all_one_by_one(jobs)
43-
jobs.each(&:dispatch)
47+
jobs.sort_by { |job| [ job.concurrency_key, job.id ] }.each(&:dispatch)
4448
end
4549

4650
def successfully_dispatched(jobs)
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
class ConcurrentDispatchingTest < ActiveSupport::TestCase
6+
self.use_transactional_tests = false
7+
8+
class NonOverlappingJob < ApplicationJob
9+
limits_concurrency key: ->(key) { key }
10+
11+
def perform(key)
12+
end
13+
end
14+
15+
setup do
16+
# SQLite allows a single writer at a time, so two dispatchers never hold
17+
# locks at once.
18+
skip "SQLite serializes all writes" if SolidQueue::Record.connection_pool.db_config.adapter == "sqlite3"
19+
20+
@original_wait = SolidQueue::Semaphore.method(:wait)
21+
end
22+
23+
teardown do
24+
SolidQueue::Semaphore.define_singleton_method(:wait, @original_wait) if @original_wait
25+
end
26+
27+
test "dispatchers with jobs for the same concurrency keys in different order don't deadlock" do
28+
# By job id: one, two, two, one. In batches of two, a dispatcher gets the
29+
# first two jobs and another one, skipping those, the other two.
30+
jobs = %w[ one two two one ].map do |key|
31+
NonOverlappingJob.set(wait: 1.minute).perform_later(key)
32+
SolidQueue::Job.last
33+
end
34+
travel_to 2.minutes.from_now
35+
36+
errors = dispatch_in_two_batches_at_once
37+
38+
assert_empty errors
39+
assert_equal 0, SolidQueue::ScheduledExecution.count
40+
41+
# The first job for each key gets the lock
42+
assert_equal [ :ready, :ready, :blocked, :blocked ], jobs.map { |job| job.reload.status }
43+
end
44+
45+
private
46+
# Two dispatchers, each with a batch of two jobs. Each one, after acquiring
47+
# its first lock, gives the other the chance to acquire its first one too,
48+
# so that both hold a lock when they go for the second.
49+
def dispatch_in_two_batches_at_once
50+
acquired_first = [ Concurrent::Event.new, Concurrent::Event.new ]
51+
pause_after_first_lock(acquired_first)
52+
53+
dispatchers = 2.times.map do |index|
54+
Thread.new do
55+
Thread.current[:dispatcher] = index
56+
# The second one starts once the first has its batch and its first lock
57+
acquired_first[0].wait(5.seconds) if index == 1
58+
59+
SolidQueue::Record.connection_pool.with_connection do
60+
SolidQueue::ScheduledExecution.dispatch_next_batch(2)
61+
end
62+
63+
nil
64+
rescue => error
65+
error
66+
end
67+
end
68+
69+
dispatchers.map(&:value).compact
70+
end
71+
72+
def pause_after_first_lock(acquired_first)
73+
original_wait = @original_wait
74+
75+
SolidQueue::Semaphore.define_singleton_method(:wait) do |job|
76+
original_wait.call(job).tap do
77+
index = Thread.current[:dispatcher]
78+
79+
if index && !acquired_first[index].set?
80+
acquired_first[index].set
81+
acquired_first[1 - index].wait(2.seconds)
82+
end
83+
end
84+
end
85+
end
86+
end

‎test/models/solid_queue/job_test.rb‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,21 @@ class DiscardableNonOverlappingGroupedJob2 < NonOverlappingJob
227227
assert_not not_enqueued.successfully_enqueued?
228228
end
229229

230+
test "enqueue jobs in bulk acquiring their concurrency locks by key" do
231+
results = 3.times.map { JobResult.create!(queue_name: "default") }
232+
233+
acquired = []
234+
SolidQueue::Semaphore.stubs(:wait).with { |job| acquired << [ job.concurrency_key, job.id ] }.returns(true)
235+
236+
# Two jobs for each key, with the keys in descending order
237+
active_jobs = (results.reverse + results.reverse).map { |result| NonOverlappingJob.new(result) }
238+
ActiveJob.perform_all_later(active_jobs)
239+
240+
# By key and, within a key, in the order they were enqueued
241+
assert_equal 6, acquired.size
242+
assert_equal acquired.sort, acquired
243+
end
244+
230245
test "discard ready job" do
231246
AddToBufferJob.perform_later(1)
232247
job = SolidQueue::Job.last

0 commit comments

Comments
 (0)