Skip to content

Commit 538dc9b

Browse files
rosaclaude
andcommitted
Give concurrency slots back only to the semaphore they came from
A semaphore counts free slots but doesn't know which jobs hold them, so any job that gave a slot back by key counted as a holder: - A job that ran past its duration gave its slot back to the semaphore created after its own expired, letting another job start while the new holder was still running (#827). - A job dispatched while its class was missing skipped its limits, but gave a slot back if it later ran where its class loads. - A job whose class was missing when it ran couldn't give back the slot it got when it was dispatched (#825). Now a job records the id of the semaphore it got a slot on, and its limit, in its serialized Active Job data, and gives the slot back only to that semaphore. A job that skips its limits records that it holds no slot. Jobs that got their slot before this change have nothing recorded and keep giving it back by key, until 2.0. The first two tests come from the reproduction in #827. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e371715 commit 538dc9b

7 files changed

Lines changed: 206 additions & 24 deletions

File tree

‎app/models/solid_queue/blocked_execution.rb‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def release
5151
destroy!
5252

5353
payload[:failed] = true
54-
elsif acquire_concurrency_lock
54+
elsif job.acquire_concurrency_lock
5555
promote_to_ready
5656
destroy!
5757

@@ -63,12 +63,7 @@ def release
6363

6464
private
6565
def set_expires_at
66-
duration = job.job_class ? job.concurrency_duration : SolidQueue.default_concurrency_control_period
67-
self.expires_at = duration.from_now
68-
end
69-
70-
def acquire_concurrency_lock
71-
Semaphore.wait(job)
66+
self.expires_at = job.concurrency_duration.from_now
7267
end
7368

7469
def promote_to_ready

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

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,15 @@ class Job
55
module ConcurrencyControls
66
extend ActiveSupport::Concern
77

8+
# Stored in the job's serialized Active Job data, which Active Job ignores when running the job
9+
CONCURRENCY_LOCK_KEY = "solid_queue_concurrency_lock"
10+
811
included do
912
has_one :blocked_execution
1013

11-
delegate :concurrency_limit, :concurrency_duration, to: :job_class
14+
delegate :concurrency_limit, to: :job_class
1215

13-
before_destroy :unblock_next_blocked_job, if: -> { concurrency_limited? && ready? }
16+
before_destroy :unblock_next_blocked_job, if: -> { concurrency_key.present? && ready? }
1417
end
1518

1619
class_methods do
@@ -29,6 +32,31 @@ def concurrency_limited?
2932
concurrency_key.present? && job_class.present?
3033
end
3134

35+
def concurrency_duration
36+
job_class ? job_class.concurrency_duration : SolidQueue.default_concurrency_control_period
37+
end
38+
39+
def acquire_concurrency_lock
40+
if concurrency_limited?
41+
if semaphore_id = Semaphore.wait(self)
42+
record_concurrency_lock(semaphore_id:, limit: concurrency_limit)
43+
end
44+
else
45+
# A job whose class doesn't load skips its limits. Record that it holds no slot,
46+
# so it doesn't give one back if it runs somewhere its class does load.
47+
record_concurrency_lock(semaphore_id: nil) if concurrency_key.present?
48+
true
49+
end
50+
end
51+
52+
def concurrency_lock
53+
arguments[CONCURRENCY_LOCK_KEY]
54+
end
55+
56+
def concurrency_lock_recorded?
57+
arguments.key?(CONCURRENCY_LOCK_KEY)
58+
end
59+
3260
def blocked?
3361
blocked_execution.present?
3462
end
@@ -42,16 +70,19 @@ def concurrency_on_conflict
4270
job_class.concurrency_on_conflict.to_s.inquiry
4371
end
4472

45-
def acquire_concurrency_lock
46-
return true unless concurrency_limited?
47-
48-
Semaphore.wait(self)
73+
def record_concurrency_lock(semaphore_id:, limit: nil)
74+
arguments[CONCURRENCY_LOCK_KEY] = { "semaphore_id" => semaphore_id, "limit" => limit }
75+
update_column :arguments, arguments
76+
true
4977
end
5078

5179
def release_concurrency_lock
52-
return false unless concurrency_limited?
53-
54-
Semaphore.signal(self)
80+
if concurrency_lock_recorded?
81+
concurrency_lock["semaphore_id"].present? && Semaphore.signal(self)
82+
else
83+
# Jobs dispatched before Solid Queue recorded their semaphore
84+
concurrency_limited? && Semaphore.signal(self)
85+
end
5586
end
5687

5788
def handle_concurrency_conflict

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ def prepare_all_for_execution(jobs)
2626
end
2727

2828
def dispatch_all(jobs)
29-
with_concurrency_limits, without_concurrency_limits = jobs.partition(&:concurrency_limited?)
29+
# Jobs with a concurrency key go one by one, so they record the slot they get, or that they skipped it
30+
with_concurrency_limits, without_concurrency_limits = jobs.partition { |job| job.concurrency_key.present? }
3031

3132
dispatch_all_at_once(without_concurrency_limits)
3233
dispatch_all_one_by_one(with_concurrency_limits)

‎app/models/solid_queue/semaphore.rb‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,10 @@ def initialize(job)
3131
@job = job
3232
end
3333

34+
# Returns the id of the semaphore the job got a slot on, or nil if there was none free
3435
def wait
3536
if semaphore = Semaphore.lock.find_by(key: key)
36-
semaphore.value > 0 && attempt_decrement
37+
semaphore.id if semaphore.value > 0 && attempt_decrement
3738
else
3839
attempt_creation
3940
end
@@ -48,22 +49,37 @@ def signal
4849

4950
def attempt_creation
5051
if Semaphore.create_unique_by(key: key, value: limit - 1, expires_at: expires_at)
51-
true
52+
acquired_semaphore_id
5253
else
5354
check_limit_or_decrement
5455
end
5556
end
5657

5758
def check_limit_or_decrement
58-
limit == 1 ? false : attempt_decrement
59+
acquired_semaphore_id if limit > 1 && attempt_decrement
60+
end
61+
62+
def acquired_semaphore_id
63+
Semaphore.where(key: key).pick(:id)
5964
end
6065

6166
def attempt_decrement
6267
Semaphore.available.where(key: key).update_all([ "value = value - 1, expires_at = ?", expires_at ]) > 0
6368
end
6469

6570
def attempt_increment
66-
Semaphore.where(key: key, value: ...limit).update_all([ "value = value + 1, expires_at = ?", expires_at ]) > 0
71+
semaphore_to_release.where(value: ...limit_for_release).update_all([ "value = value + 1, expires_at = ?", expires_at ]) > 0
72+
end
73+
74+
# A job only gives its slot back to the semaphore it got it from. If that one expired
75+
# and was deleted, a semaphore for the same key now belongs to other jobs.
76+
# Jobs dispatched before Solid Queue recorded their semaphore give it back by key.
77+
def semaphore_to_release
78+
if job.concurrency_lock_recorded?
79+
Semaphore.where(id: job.concurrency_lock["semaphore_id"])
80+
else
81+
Semaphore.where(key: key)
82+
end
6783
end
6884

6985
def key
@@ -77,6 +93,11 @@ def expires_at
7793
def limit
7894
job.concurrency_limit || 1
7995
end
96+
97+
# Recorded when the job got its slot, so it's known even if the job's class no longer loads
98+
def limit_for_release
99+
job.concurrency_lock&.dig("limit") || limit
100+
end
80101
end
81102
end
82103
end

‎test/integration/concurrency_controls_test.rb‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ class ConcurrencyControlsTest < ActiveSupport::TestCase
116116

117117
test "rely on dispatcher to unblock blocked executions with an available semaphore" do
118118
# Simulate a scenario where we got an available semaphore and some stuck jobs
119-
job = NonOverlappingUpdateResultJob.perform_later(@result, name: "A")
119+
job = SolidQueue::Job.find_by!(active_job_id: NonOverlappingUpdateResultJob.perform_later(@result, name: "A").job_id)
120120

121121
wait_for_jobs_to_finish_for(5.seconds)
122122
assert_no_unfinished_jobs
@@ -148,7 +148,7 @@ class ConcurrencyControlsTest < ActiveSupport::TestCase
148148

149149
test "rely on dispatcher to unblock blocked executions with an expired semaphore" do
150150
# Simulate a scenario where we got an available semaphore and some stuck jobs
151-
job = NonOverlappingUpdateResultJob.perform_later(@result, name: "A")
151+
job = SolidQueue::Job.find_by!(active_job_id: NonOverlappingUpdateResultJob.perform_later(@result, name: "A").job_id)
152152
wait_for_jobs_to_finish_for(5.seconds)
153153
assert_no_unfinished_jobs
154154

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
class SolidQueue::ConcurrencyLockTest < ActiveSupport::TestCase
6+
class NonOverlappingJob < ActiveJob::Base
7+
limits_concurrency key: "concurrency-lock-test", duration: 1.minute
8+
9+
def perform(name)
10+
end
11+
end
12+
13+
setup do
14+
@process = SolidQueue::Process.register(kind: "Worker", pid: 42, name: "worker-123")
15+
end
16+
17+
# From the reproduction in https://github.com/rails/solid_queue/issues/827
18+
test "a job that outlived its lock does not release the lock a later job acquired" do
19+
a = claim(NonOverlappingJob.perform_later("A"))
20+
21+
travel_to 2.minutes.from_now
22+
SolidQueue::Semaphore.expired.delete_all
23+
24+
b = claim(NonOverlappingJob.perform_later("B"))
25+
c = job_for(NonOverlappingJob.perform_later("C"))
26+
assert c.blocked?
27+
28+
a.perform
29+
30+
assert b.job.reload.claimed?
31+
assert c.reload.blocked?
32+
end
33+
34+
test "a job that outlived its lock does not leave the key over its limit" do
35+
a = claim(NonOverlappingJob.perform_later("A"))
36+
37+
travel_to 2.minutes.from_now
38+
SolidQueue::Semaphore.expired.delete_all
39+
40+
b = claim(NonOverlappingJob.perform_later("B"))
41+
c = job_for(NonOverlappingJob.perform_later("C"))
42+
d = job_for(NonOverlappingJob.perform_later("D"))
43+
44+
a.perform
45+
b.perform
46+
claim_job(c)
47+
48+
assert d.reload.blocked?
49+
end
50+
51+
test "a job that got its slot gives it back even if its class is missing when it runs" do
52+
a = claim(NonOverlappingJob.perform_later("A"))
53+
b = job_for(NonOverlappingJob.perform_later("B"))
54+
assert b.blocked?
55+
56+
# A worker on a release without the class claims and runs A
57+
a.job.update_column(:class_name, "RemovedJobClass")
58+
a = SolidQueue::ClaimedExecution.find(a.id)
59+
60+
assert_raises(SolidQueue::Job::ClassMissingError) { a.perform }
61+
62+
assert b.reload.ready?
63+
assert_equal 0, semaphore.value
64+
end
65+
66+
test "a job that skipped its limits because its class was missing doesn't give back a slot" do
67+
a = claim(NonOverlappingJob.perform_later("A"))
68+
b = job_for(NonOverlappingJob.perform_later("B"))
69+
70+
# Dispatched by a process without the class, so it takes no slot
71+
x = SolidQueue::Job.create!(queue_name: "default", class_name: "RemovedJobClass", active_job_id: SecureRandom.uuid,
72+
arguments: { "job_class" => "RemovedJobClass", "arguments" => [ "X" ] }, concurrency_key: a.job.concurrency_key)
73+
assert x.ready?
74+
75+
# ...and run by one that has it
76+
x.update_columns(class_name: NonOverlappingJob.name, arguments: x.arguments.merge("job_class" => NonOverlappingJob.name))
77+
claim_job(x).perform
78+
79+
assert a.job.reload.claimed?
80+
assert b.reload.blocked?
81+
end
82+
83+
test "a job dispatched before Solid Queue recorded its semaphore gives back its slot by key" do
84+
a = claim(NonOverlappingJob.perform_later("A"))
85+
b = job_for(NonOverlappingJob.perform_later("B"))
86+
a.job.update_column(:arguments, a.job.arguments.except(SolidQueue::Job::ConcurrencyControls::CONCURRENCY_LOCK_KEY))
87+
a = SolidQueue::ClaimedExecution.find(a.id)
88+
89+
a.perform
90+
91+
assert b.reload.ready?
92+
end
93+
94+
test "a blocked job records the semaphore it gets when it's released" do
95+
a = claim(NonOverlappingJob.perform_later("A"))
96+
b = job_for(NonOverlappingJob.perform_later("B"))
97+
assert a.job.concurrency_lock["semaphore_id"].present?
98+
assert_not b.concurrency_lock_recorded?
99+
100+
a.perform
101+
102+
assert b.reload.ready?
103+
assert_equal semaphore.id, b.concurrency_lock["semaphore_id"]
104+
assert_equal 1, b.concurrency_lock["limit"]
105+
end
106+
107+
test "jobs enqueued in bulk record the semaphore they get" do
108+
ActiveJob.perform_all_later([ NonOverlappingJob.new("A"), NonOverlappingJob.new("B") ])
109+
a, b = SolidQueue::Job.where(class_name: NonOverlappingJob.name).order(:id).to_a
110+
111+
assert a.ready?
112+
assert_equal semaphore.id, a.concurrency_lock["semaphore_id"]
113+
assert b.blocked?
114+
assert_not b.concurrency_lock_recorded?
115+
end
116+
117+
private
118+
def semaphore
119+
SolidQueue::Semaphore.sole
120+
end
121+
122+
def job_for(active_job)
123+
SolidQueue::Job.find_by!(active_job_id: active_job.job_id)
124+
end
125+
126+
def claim(active_job)
127+
claim_job(job_for(active_job))
128+
end
129+
130+
def claim_job(job)
131+
SolidQueue::ReadyExecution.claim(job.queue_name, 1, @process.id)
132+
SolidQueue::ClaimedExecution.find_by!(job_id: job.id)
133+
end
134+
end

‎test/models/solid_queue/semaphore_test.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ class SolidQueue::SemaphoreTest < ActiveSupport::TestCase
7272
class_name: "NonOverlappingUpdateResultJob",
7373
concurrency_key: concurrency_key,
7474
active_job_id: uuid,
75-
arguments: "{}",
75+
arguments: {},
7676
scheduled_at: Time.current
7777
})
7878
job_b_id = SolidQueue::Job.where(active_job_id: uuid).pick(:id)

0 commit comments

Comments
 (0)