wurk 1.20.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 68607081f66bca6632668d2f456e66dfe87906ec13fa0582fac43868c5c11793
4
- data.tar.gz: cb235411d7e504bccfdc83766540a6d5b6e9df3b2e41447efbc8928565be35d4
3
+ metadata.gz: 6c1512080d8eb946fdd63cc52d263fafa240112d0191c56f132dd9f9e6d76713
4
+ data.tar.gz: 10eced0a7c6177fe53a199462c8ab9eb90a44fd77a31dbf90f5d34a0a5c4fdd4
5
5
  SHA512:
6
- metadata.gz: 386b8055b1fcd9de03d0451a0393df9af87f4746f6846c869ffae59fa6307eab8d3120bca67e2b9e85b98d68202fe2e8bf50833d086c0eaade01ce0090edf3d1
7
- data.tar.gz: 927b92fb1a5fbbc69a4eea1945aeb659adc10eb9b1755678f6d214d356ac8b8a9f40893d6163482bbe50f7912dbbe46b0fe805e9781e59ad978005ba90ce653a
6
+ metadata.gz: 8b2830ee68c2fbe1664f8e52a5517cbb472ed0ec2a373466b9036c14766d27118b9b9ea989f13cd4c0e0508059be5596f6244b3633ee050b3ccdf67b066ef7fc
7
+ data.tar.gz: 596c783c1ef2c37754b1964904d98e6bdd3aab0d73bf881a05388d09d41f093d428690307190704c644c8b5e9506e2b320792f7aaaaf896192fbc08ca8a55a39
data/README.md CHANGED
@@ -308,7 +308,7 @@ Wurk is MIT and stays that way. If what you need is a commercial support contrac
308
308
 
309
309
  `bundle install && restart`. The worker command stays as it was: Wurk ships `sidekiq` and `sidekiqswarm` executables, so `bundle exec sidekiq -C config/sidekiq.yml` in a Procfile or manifest keeps working. Wurk reads and writes the same Redis schema, so there is no data migration: Wurk picks up the queues, schedules, retries, batches and periodic loops Sidekiq left behind. Running Sidekiq and Wurk workers against one Redis *at the same time* is tested for stock Sidekiq 8 only, which may roll from one to the other under the conditions the guide lists; for a Sidekiq 7.x, Pro or Enterprise app a live production move is a **drain cutover** (stop Sidekiq's workers, confirm nothing is in flight, start Wurk), with a matching rollback. The [production cutover](https://github.com/developerz-ai/wurk/blob/main/docs/migrate-from-sidekiq.md#9-production-cutover) section has every step and command. The upstream suites of sidekiq-cron, sidekiq-unique-jobs, sidekiq-failures and sentry-sidekiq run against Wurk in the [`ecosystem` CI job](https://github.com/developerz-ai/wurk/blob/main/.github/workflows/ecosystem.yml) (see [`test/ecosystem/`](https://github.com/developerz-ai/wurk/tree/main/test/ecosystem)). sidekiq-scheduler, sidekiq-status and sidekiq-throttled are target additions tracked in [docs/idea/14-ecosystem-compat.md](https://github.com/developerz-ai/wurk/blob/main/docs/idea/14-ecosystem-compat.md).
310
310
 
311
- **Keeping a `sidekiq-*` add-on gem?** Those gems declare `add_dependency "sidekiq"`, which would reinstall real Sidekiq next to Wurk. Satisfy it with Wurk's git-only [`sidekiq` shim gem](https://github.com/developerz-ai/wurk/tree/main/ecosystem/sidekiq-shim) instead, pinned to the tag of the Wurk release you run: `gem "sidekiq", github: "developerz-ai/wurk", tag: "v1.20.0", glob: "ecosystem/sidekiq-shim/*.gemspec"`. Only sidekiq-cron, sidekiq-unique-jobs, sidekiq-failures and sentry-sidekiq are exercised that way, by the `ecosystem` workflow; treat the others as untested.
311
+ **Keeping a `sidekiq-*` add-on gem?** Those gems declare `add_dependency "sidekiq"`, which would reinstall real Sidekiq next to Wurk. Satisfy it with Wurk's git-only [`sidekiq` shim gem](https://github.com/developerz-ai/wurk/tree/main/ecosystem/sidekiq-shim) instead, pinned to the tag of the Wurk release you run: `gem "sidekiq", github: "developerz-ai/wurk", tag: "v1.21.0", glob: "ecosystem/sidekiq-shim/*.gemspec"`. Only sidekiq-cron, sidekiq-unique-jobs, sidekiq-failures and sentry-sidekiq are exercised that way, by the `ecosystem` workflow; treat the others as untested.
312
312
 
313
313
  Full walkthrough — config side-by-side, the Redis key/`sidekiq_options` mapping, known incompatibilities, moving sidekiq-cron schedules over (`rake wurk:import:cron`), and the production cutover and rollback playbook: **[docs/migrate-from-sidekiq.md](https://github.com/developerz-ai/wurk/blob/main/docs/migrate-from-sidekiq.md)**. On the night, keep the **[incident runbook](https://github.com/developerz-ai/wurk/blob/main/docs/runbook.md)** open.
314
314
 
@@ -15,6 +15,9 @@ module Wurk
15
15
  class BookkeepingFailed < ::StandardError; end
16
16
 
17
17
  STORE_ERRORS = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError].freeze
18
+ # How a lock script's error is raised, by either copy of sidekiq-unique-jobs.
19
+ # Dragonfly words a refusal at maxmemory as one.
20
+ SCRIPT_ERRORS = %w[Wurk::UniqueJobs::Script::LuaError SidekiqUniqueJobs::Script::LuaError].freeze
18
21
  # Past this many owed jobs the oldest is reported and dropped.
19
22
  MEMORY = 10_000
20
23
  RETRY_EVERY = 1.0
@@ -30,7 +33,10 @@ module Wurk
30
33
  @next_try = 0.0
31
34
 
32
35
  class << self
33
- def store_error?(error) = STORE_ERRORS.any? { |klass| error.is_a?(klass) }
36
+ def store_error?(error)
37
+ STORE_ERRORS.any? { |klass| error.is_a?(klass) } ||
38
+ (SCRIPT_ERRORS.include?(error.class.name) && UniqueJobsCompat::OOM.match?(error.message))
39
+ end
34
40
 
35
41
  # Reports the failure, tries the owed writes once, keeps what did not land.
36
42
  def settle(job, error, pool:, config:)
@@ -97,12 +103,14 @@ module Wurk
97
103
  true
98
104
  end
99
105
 
100
- # Locksmith#unlock only drops a lock this jid holds. Both digests: an
106
+ # Locksmith#unlock only drops a lock this run holds: the write can land long
107
+ # after the job, when its jid is running again elsewhere. Both digests: an
101
108
  # until_and_while_executing job takes its base lock back when an error
102
109
  # crosses it, on top of the `:RUN` lock it may still hold.
103
110
  def release_unique_locks(job)
104
111
  locksmith = UniqueJobsCompat.locksmith_class
105
- digests(job).each { |digest| locksmith.new(job.merge('lock_digest' => digest)).unlock }
112
+ # A #dup is still this run's payload (UniqueJobs::Run); a #merge need not be.
113
+ digests(job).each { |digest| locksmith.new(job.dup.update('lock_digest' => digest)).unlock }
106
114
  end
107
115
 
108
116
  def digests(job)
@@ -0,0 +1,15 @@
1
+ -- Wurk only: a run enters the lock its jid already holds (taken at push, or left
2
+ -- by a run that crashed or is still unwinding) and becomes its holder: the value
3
+ -- beside the jid is from now on this run's, so an earlier run of the same jid can
4
+ -- neither unlock nor renew it. Takes nothing: a jid that is not in LOCKED gets 0
5
+ -- and no key is written. Every key is in KEYS.
6
+ -- KEYS = [digest, queued, primed, locked, info, changelog, digests, expiring_digests]
7
+ -- ARGV = [jid, run]
8
+ local locked, job_id, run = KEYS[4], ARGV[1], ARGV[2]
9
+
10
+ if redis.call("HEXISTS", locked, job_id) == 0 then
11
+ return 0
12
+ end
13
+
14
+ redis.call("HSET", locked, job_id, run)
15
+ return 1
@@ -1,10 +1,13 @@
1
1
  -- sidekiq-unique-jobs 8.x lock.lua: take the lock once the queued jid was primed
2
2
  -- (the blocking path). Every key is in KEYS.
3
3
  -- KEYS = [digest, queued, primed, locked, info, changelog, digests, expiring_digests]
4
- -- ARGV = [jid, pttl, lock_type, limit, lock_score, now, max_history, script_name]
4
+ -- ARGV = [jid, pttl, lock_type, limit, lock_score, now, max_history, script_name, run]
5
+ -- `run` is Wurk's: the token of the run taking the lock (see unique_jobs_claim.lua),
6
+ -- empty when a push takes it. The gem writes `now` in its place.
5
7
  local digest, queued, primed, locked, info, changelog, digests, expiring = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8]
6
8
  local job_id, pttl, lock_type, limit, lock_score = ARGV[1], tonumber(ARGV[2]), ARGV[3], tonumber(ARGV[4]), ARGV[5]
7
9
  local now, max_history, script_name = tonumber(ARGV[6]), tonumber(ARGV[7]), ARGV[8]
10
+ local run = ARGV[9] or ""
8
11
 
9
12
  local function log(message, prev_jid)
10
13
  if not max_history or max_history == 0 then return end
@@ -24,6 +27,7 @@ local function drop_queued()
24
27
  end
25
28
 
26
29
  if redis.call("HEXISTS", locked, job_id) == 1 then
30
+ if #run > 0 then redis.call("HSET", locked, job_id, run) end
27
31
  log("Duplicate")
28
32
  drop_queued()
29
33
  return job_id
@@ -41,7 +45,7 @@ else
41
45
  if #lock_score == 0 then score = now end
42
46
  redis.call("ZADD", digests, score, digest)
43
47
  end
44
- redis.call("HSET", locked, job_id, now)
48
+ redis.call("HSET", locked, job_id, #run > 0 and run or now)
45
49
  drop_queued()
46
50
 
47
51
  if pttl and pttl > 0 then
@@ -1,14 +1,26 @@
1
1
  -- Wurk only: sidekiq-unique-jobs 8.x has no refresh. Pushes out the expiry of a
2
2
  -- lock this jid still holds, re-applying from now what lock.lua and
3
3
  -- queue_and_lock.lua set when the lock was taken. Takes nothing: a jid that is
4
- -- not in LOCKED gets 0 and no key is written. Every key is in KEYS.
4
+ -- not in LOCKED, or is there for a later run of it, gets 0 and no key is written.
5
+ -- Every key is in KEYS.
5
6
  -- KEYS = [digest, queued, primed, locked, info, changelog, digests, expiring_digests]
6
- -- ARGV = [jid, pttl, now]
7
- -- Returns 1 when this jid holds the lock, 0 otherwise.
7
+ -- ARGV = [jid, pttl, now, run]
8
+ -- `run` is the token of the run renewing (see unique_jobs_claim.lua), empty when
9
+ -- the caller is known by jid alone.
10
+ -- Returns 1 when the caller holds the lock, 0 otherwise.
8
11
  local digest, locked, info, expiring = KEYS[1], KEYS[4], KEYS[5], KEYS[8]
9
- local job_id, pttl, now = ARGV[1], tonumber(ARGV[2]), tonumber(ARGV[3])
12
+ local job_id, pttl, now, run = ARGV[1], tonumber(ARGV[2]), tonumber(ARGV[3]), ARGV[4]
10
13
 
11
- if redis.call("HEXISTS", locked, job_id) == 0 then
14
+ -- A value that is another run's mark (fifteen decimals, UniqueJobs::Run.token). Any
15
+ -- other value says only that the jid holds the lock: one the gem or an older Wurk
16
+ -- wrote, or a snapshot put back.
17
+ local function another_runs(holder)
18
+ local decimals = string.match(holder, "^%d+%.(%d+)$")
19
+ return #run > 0 and holder ~= run and decimals and #decimals == 15
20
+ end
21
+
22
+ local holder = redis.call("HGET", locked, job_id)
23
+ if not holder or another_runs(holder) then
12
24
  return 0
13
25
  end
14
26
 
@@ -2,10 +2,21 @@
2
2
  -- lock (or the lock was orphaned), nil while another holder keeps it. The "1"
3
3
  -- pushed to QUEUED wakes a job blocked on the lock. Every key is in KEYS.
4
4
  -- KEYS = [digest, queued, primed, locked, info, changelog, digests, expiring_digests]
5
- -- ARGV = [jid, pttl, lock_type, limit, lock_score, now, max_history, script_name, sync_locked]
5
+ -- ARGV = [jid, pttl, lock_type, limit, lock_score, now, max_history, script_name, sync_locked, run]
6
+ -- `run` is Wurk's: the token of the run unlocking (see unique_jobs_claim.lua), empty
7
+ -- when the unlock is the jid's. A lock marked by another run of the jid is left whole.
6
8
  local digest, queued, primed, locked, info, changelog, digests = KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7]
7
9
  local job_id, lock_type, limit = ARGV[1], ARGV[3], tonumber(ARGV[4])
8
10
  local now, max_history, script_name, sync_locked = tonumber(ARGV[6]), tonumber(ARGV[7]), ARGV[8], ARGV[9] == "1"
11
+ local run = ARGV[10] or ""
12
+
13
+ -- A value that is another run's mark (fifteen decimals, UniqueJobs::Run.token). Any
14
+ -- other value says only that the jid holds the lock: one the gem or an older Wurk
15
+ -- wrote, or a snapshot put back.
16
+ local function another_runs(holder)
17
+ local decimals = string.match(holder, "^%d+%.(%d+)$")
18
+ return #run > 0 and holder ~= run and decimals and #decimals == 15
19
+ end
9
20
 
10
21
  local function log(message, prev_jid)
11
22
  if not max_history or max_history == 0 then return end
@@ -24,10 +35,19 @@ if sync_locked and limit <= 1 then
24
35
  return job_id
25
36
  end
26
37
 
27
- local holds_lock = redis.call("HEXISTS", locked, job_id) == 1
38
+ local holder = redis.call("HGET", locked, job_id)
39
+ local holds_lock = holder and true or false
40
+ if holder and another_runs(holder) then
41
+ log("Superseded by a later run")
42
+ return nil
43
+ end
28
44
  if not holds_lock then
29
- redis.call("LREM", queued, -1, job_id)
30
- redis.call("LREM", primed, -1, job_id)
45
+ -- A run that held the lock left the line when it took it: an entry of its jid
46
+ -- there now is a later run's.
47
+ if #run == 0 then
48
+ redis.call("LREM", queued, -1, job_id)
49
+ redis.call("LREM", primed, -1, job_id)
50
+ end
31
51
  local others = redis.call("LLEN", queued) + redis.call("LLEN", primed) + redis.call("HLEN", locked)
32
52
  if others > 0 then
33
53
  log("Yielding to other lock holders")
data/lib/wurk/manager.rb CHANGED
@@ -7,7 +7,7 @@ module Wurk
7
7
  # One per Capsule. Lives inside each forked child and owns the Processor
8
8
  # pool. Replaces dead processors on the fly (replace-on-die), forwards
9
9
  # the quiet/stop signals received by the Swarm to its processors, and
10
- # ensures in-flight UnitsOfWork are bulk_requeued before threads are killed.
10
+ # ensures the in-flight UnitsOfWork of threads it kills are bulk_requeued.
11
11
  #
12
12
  # Lifecycle:
13
13
  # * `start` — spawn each processor thread.
@@ -77,7 +77,7 @@ module Wurk
77
77
 
78
78
  # Graceful shutdown: quiet first, then poll for workers to clear.
79
79
  # If the deadline elapses with workers still alive we fall through to
80
- # hard_shutdown, which bulk_requeues their UoWs before killing threads.
80
+ # hard_shutdown, which kills their threads and bulk_requeues their UoWs.
81
81
  def stop(deadline)
82
82
  quiet
83
83
  # Lifecycle hooks (e.g. :quiet) can be async; give them a tick to settle
@@ -135,42 +135,107 @@ module Wurk
135
135
  @shutdown&.call
136
136
  end
137
137
 
138
- # Reached when the deadline expired with workers still busy. Atomically
139
- # move their in-flight UoWs private→public (Reliable#bulk_requeue) BEFORE
140
- # raising Wurk::Shutdown into the threads, so a job killed mid-perform is
141
- # re-run once (Sidekiq's at-least-once contract). `job` is read off another
142
- # thread, so a Processor can ACK between this map and the requeue — but
143
- # bulk_requeue's guard skips the RPUSH on a miss, so a job that
144
- # finished in that window is not resurrected onto the public queue.
138
+ # How long killed threads may take to unwind before what is left of their jobs
139
+ # is requeued anyway, and how long the process gives the last of them after
140
+ # that. Inside what the Launcher and the Swarm allow a Manager past its
141
+ # deadline (Launcher::TEARDOWN_GRACE, the shortest).
142
+ UNWIND_GRACE = 2
143
+ STRAGGLER_GRACE = 1
144
+ UNWIND_POLL = 0.02
145
+ private_constant :UNWIND_POLL
146
+
147
+ # Reached when the deadline expired with workers still busy: raise
148
+ # Wurk::Shutdown into each, and move every unfinished job from the private list
149
+ # back to the public queue (Reliable#bulk_requeue), where it runs again from the
150
+ # top (Sidekiq's at-least-once contract), as soon as its own thread has ended.
151
+ # What has not ended within UNWIND_GRACE is requeued under its running thread.
152
+ #
153
+ # In that order because a requeued job is running elsewhere within a
154
+ # millisecond, and an unwinding run still has `ensure` blocks to go: it
155
+ # releases limiter slots, saves an iteration cursor, rolls back. A run past its
156
+ # requeue does all that beside the run that replaced it. Waiting costs no job:
157
+ # until the move it sits in the private list, which a SIGKILL leaves for the
158
+ # reaper. A fetcher with no private list has nothing holding the payload
159
+ # meanwhile, so its jobs go back first.
145
160
  #
146
- # The kill sits in an `ensure`: a bulk_requeue that raises (Redis down
147
- # mid-drain) must not leave the processors running — embedded, the host
148
- # keeps living after #stop, and those threads would carry on executing jobs
149
- # over pools the launcher is about to reset. The requeue error still
150
- # propagates to the caller, which reports it.
161
+ # `job` is read off another thread and before the kill, after which a
162
+ # Processor drops it. One that had finished, or was booking its retry, when the
163
+ # interrupt was sent ACKs it (Processor#cut_short?), and bulk_requeue's guard
164
+ # skips the RPUSH on a miss.
165
+ #
166
+ # Every processor is killed even when a requeue raises (Redis down mid-drain):
167
+ # embedded, the host keeps living after #stop, and those threads would carry
168
+ # on executing jobs over pools the launcher is about to reset. The requeue
169
+ # error still propagates to the caller, which reports it.
151
170
  def hard_shutdown
152
171
  cleanup = workers_snapshot
153
- requeue_in_flight(cleanup)
154
- ensure
155
- if cleanup
156
- cleanup.each(&:kill)
157
- # The caller typically `exit`s immediately after we return; give
158
- # threads a brief window to run their `ensure` blocks.
159
- wait_for(::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + 3) { workers_empty? }
172
+ return if cleanup.empty?
173
+
174
+ units = cleanup.to_h { |worker| [worker, worker.job] }.compact
175
+ if capsule.fetcher.is_a?(Fetcher::Reliable)
176
+ unwind_then_requeue(cleanup, units)
177
+ else
178
+ requeue_then_kill(cleanup, units.values)
160
179
  end
180
+ ensure
181
+ # The caller typically `exit`s immediately after we return; give threads
182
+ # that outlived the requeue a brief window to run their `ensure` blocks.
183
+ wait_for_unwind(cleanup, STRAGGLER_GRACE) if cleanup
161
184
  end
162
185
 
163
186
  private
164
187
 
165
- def requeue_in_flight(cleanup)
166
- return if cleanup.empty?
188
+ def unwind_then_requeue(cleanup, units)
189
+ interrupt(cleanup, units.values)
190
+ requeue_as_they_end(units)
191
+ ensure
192
+ # Also flushes the ACKs of the threads that ended, with nothing left to move.
193
+ capsule.fetcher.bulk_requeue(units.values)
194
+ end
167
195
 
168
- jobs = cleanup.map(&:job).compact
169
- logger.warn { "Terminating #{cleanup.size} busy threads" }
170
- log_interrupted(jobs)
196
+ # Drops from `units` what it has put back. A refused requeue leaves the rest to
197
+ # the caller's, at the end of the wait: one more try, not one every poll.
198
+ def requeue_as_they_end(units)
199
+ deadline = monotonic + UNWIND_GRACE
200
+ until units.empty? || monotonic >= deadline
201
+ ended = units.reject { |worker, _| running?(worker) }
202
+ return wait_for_unwind(units.keys, deadline - monotonic) unless requeued?(ended.values)
203
+
204
+ ended.each_key { |worker| units.delete(worker) }
205
+ sleep UNWIND_POLL
206
+ end
207
+ end
208
+
209
+ def requeued?(jobs)
210
+ capsule.fetcher.bulk_requeue(jobs) if jobs.any?
211
+ true
212
+ rescue StandardError => e
213
+ capsule.config.handle_exception(e, { context: 'Error requeueing a job interrupted by shutdown' })
214
+ false
215
+ end
216
+
217
+ def requeue_then_kill(cleanup, jobs)
171
218
  # `&.` like #quiet: a TERM in the pre-prepare! window (traps install
172
219
  # before launcher.run) reaches here with no fetcher built yet.
173
220
  capsule.fetcher&.bulk_requeue(jobs)
221
+ ensure
222
+ interrupt(cleanup, jobs)
223
+ wait_for_unwind(cleanup, UNWIND_GRACE)
224
+ end
225
+
226
+ def interrupt(cleanup, jobs)
227
+ cleanup.each(&:kill)
228
+ logger.warn { "Terminating #{cleanup.size} busy threads" }
229
+ log_interrupted(jobs)
230
+ end
231
+
232
+ def running?(worker) = worker.thread&.alive?
233
+ def monotonic = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
234
+
235
+ # Polled rather than joined: a join re-raises what ended the thread.
236
+ def wait_for_unwind(cleanup, seconds)
237
+ deadline = monotonic + seconds
238
+ sleep UNWIND_POLL while cleanup.any? { |worker| running?(worker) } && monotonic < deadline
174
239
  end
175
240
 
176
241
  # One WARN per job a deploy cut short, because each one runs again from the
@@ -20,13 +20,16 @@ module Wurk
20
20
  # fleet does not). #record reports a failed count, which may or may not have
21
21
  # landed (a lost reply); the schedule-promote script cannot report, and drops it.
22
22
  #
23
- # Fields are encoded `script_safe`, escaping `/` as Redis's cjson does, so a
24
- # pair the schedule-promote script counts lands on the same field.
23
+ # Fields are escaped as Redis's cjson escapes them (CJSON_ESCAPES), so a pair the
24
+ # schedule-promote script counts lands on the same field. json's `script_safe`
25
+ # escaped `/` until 3.2.0.
25
26
  module Deaths
26
27
  MAX_SERIES = 500
27
28
  UNKNOWN = 'unknown'
28
29
  OTHER = 'other'
29
30
  OVERFLOW = ::JSON.generate([OTHER, OTHER]).freeze
31
+ # What cjson escapes and json does not.
32
+ CJSON_ESCAPES = { '/' => '\\/', "\u007f" => '\u007f' }.freeze
30
33
  # Name, help and type of the `/metrics` family (Metrics::Prometheus), whose
31
34
  # samples are #samples. Read from shared Redis, so every scrape target
32
35
  # reports the same value: aggregate with `max`.
@@ -49,8 +52,8 @@ module Wurk
49
52
  def field(payload)
50
53
  job = payload.is_a?(::String) ? parse(payload) : payload
51
54
  job = {} unless job.is_a?(::Hash)
52
- ::JSON.generate([label(job['queue']) || UNKNOWN, label(job['wrapped']) || label(job['class']) || UNKNOWN],
53
- script_safe: true)
55
+ ::JSON.generate([label(job['queue']) || UNKNOWN, label(job['wrapped']) || label(job['class']) || UNKNOWN])
56
+ .gsub(%r{[/\u007f]}, CJSON_ESCAPES)
54
57
  end
55
58
 
56
59
  # `[[{ 'queue' => q, 'class' => c }, count], …]` from an HGETALL reply
@@ -69,6 +69,8 @@ module Wurk
69
69
  @config = capsule
70
70
  @callback = callback
71
71
  @done = false
72
+ @interrupted = false
73
+ @performed = false
72
74
  @job = nil
73
75
  @thread = nil
74
76
  @reloader = resolve_reloader(capsule.config[:reloader])
@@ -92,6 +94,8 @@ module Wurk
92
94
  @done = true
93
95
  return if @thread.nil?
94
96
 
97
+ # First the flag, then the raise: a job can swallow a raise (#cut_short?).
98
+ @interrupted = true
95
99
  @thread.raise ::Wurk::Shutdown
96
100
  @thread.value if wait
97
101
  end
@@ -272,6 +276,7 @@ module Wurk
272
276
  # arrives while deferred is delivered when this frame returns, after the
273
277
  # outcome is booked.
274
278
  def process(uow)
279
+ @performed = false
275
280
  Thread.handle_interrupt(IGNORE_SHUTDOWN_INTERRUPTS) { process_deferred(uow) }
276
281
  ensure
277
282
  uow.release_claim if uow.respond_to?(:release_claim)
@@ -289,7 +294,7 @@ module Wurk
289
294
  # on that exit as on every other.
290
295
  job_hash = parse_or_kill(jobstr)
291
296
  run_job(uow, job_hash, queue, jobstr) if job_hash
292
- ack = true
297
+ ack = !cut_short?
293
298
  rescue Wurk::JobRetry::Skip
294
299
  # A middleware booked the outcome itself (Limiter::Rescheduled, the
295
300
  # interrupt handler's re-push, Encryption's dead routing) — not a
@@ -326,6 +331,29 @@ module Wurk
326
331
  end
327
332
  end
328
333
 
334
+ # Told to stop before its `perform` completed, so not finished, whatever it
335
+ # made of the interrupt: jobs rescue Exception, raise out of an `ensure`,
336
+ # rewrite the error. Not ACKed and no retry booked; the payload stays in the
337
+ # private list for Manager#hard_shutdown to put back. `@performed` is set by
338
+ # this thread and `@interrupted` before the raise that follows it, so a job
339
+ # that completed first is seen as completed.
340
+ def cut_short? = @interrupted && !@performed
341
+
342
+ # Turns any way out of the block, returning included, into the interruption
343
+ # it is. Handled and Skip pass: their job is booked already.
344
+ def surface_interrupt
345
+ result = yield
346
+ raise ::Wurk::Shutdown if cut_short?
347
+
348
+ result
349
+ rescue Wurk::JobRetry::Handled, ::Wurk::Shutdown
350
+ raise
351
+ rescue Exception # rubocop:disable Lint/RescueException
352
+ raise ::Wurk::Shutdown if cut_short?
353
+
354
+ raise
355
+ end
356
+
329
357
  # Sidekiq's contract (processor.rb, "Job raised exception"): every job
330
358
  # failure the retry layer handled reaches config.error_handlers once, with
331
359
  # the job's own exception — `Handled` is raised from inside the retry
@@ -340,6 +368,7 @@ module Wurk
340
368
  # reason would loop forever, re-running `perform` every time, so it goes to
341
369
  # the morgue instead.
342
370
  def settle_internal_failure(uow, job_hash, jobstr, error)
371
+ return false if cut_short?
343
372
  return kill_unbookable(job_hash, jobstr, error) if unbookable?(error)
344
373
 
345
374
  requeue(uow)
@@ -424,14 +453,16 @@ module Wurk
424
453
  # there books a retry instead of escaping the retry layer.
425
454
  def dispatch(job_hash, queue, jobstr)
426
455
  @retrier.global(jobstr, queue) do
427
- @job_logger.prepare(job_hash) do
428
- @job_logger.call(job_hash, queue) do
429
- stats(jobstr, queue) do
430
- Wurk::Profiler.call(job_hash) do
431
- @reloader.call do
432
- instance = build_instance(job_hash)
433
- @retrier.local(instance, jobstr, queue) do
434
- yield instance
456
+ surface_interrupt do
457
+ @job_logger.prepare(job_hash) do
458
+ @job_logger.call(job_hash, queue) do
459
+ stats(jobstr, queue) do
460
+ Wurk::Profiler.call(job_hash) do
461
+ @reloader.call do
462
+ instance = build_instance(job_hash)
463
+ @retrier.local(instance, jobstr, queue) do
464
+ surface_interrupt { yield instance }
465
+ end
435
466
  end
436
467
  end
437
468
  end
@@ -457,21 +488,20 @@ module Wurk
457
488
  # still owes Redis goes to FinishedJobCleanup. The rescues sit outside the
458
489
  # interruptible scope, so a Shutdown cannot land between them and the ACK.
459
490
  def execute_job(instance, job_hash, queue)
460
- performed = false
461
491
  Thread.handle_interrupt(ALLOW_SHUTDOWN_INTERRUPTS) do
462
492
  @capsule.server_middleware.invoke(instance, job_hash, queue) do
463
493
  RedisPool.job_performing!
464
- result = instance.perform(*job_hash['args'])
465
- performed = true
494
+ result = surface_interrupt { instance.perform(*job_hash['args']) }
495
+ @performed = true
466
496
  result
467
497
  end
468
498
  end
469
499
  rescue Wurk::Shutdown => e
470
- raise unless performed
500
+ raise unless @performed
471
501
 
472
502
  settle_finished_job(job_hash, e)
473
503
  rescue StandardError => e
474
- raise unless performed && FinishedJobCleanup.store_error?(e)
504
+ raise unless @performed && FinishedJobCleanup.store_error?(e)
475
505
 
476
506
  settle_finished_job(job_hash, e)
477
507
  end
@@ -231,17 +231,29 @@ module Wurk
231
231
  end
232
232
 
233
233
  def execute(&)
234
- executed = locksmith.execute do
235
- yield
236
- item[JID]
237
- ensure
238
- unlock_and_callback
239
- end
234
+ executed = locksmith.execute { perform_and_unlock(&) }
240
235
  return if executed
241
236
 
242
237
  reflect(:execution_failed, item)
243
238
  call_strategy(origin: :server, &)
244
239
  end
240
+
241
+ private
242
+
243
+ # A run cut short by a shutdown keeps its lock, as one that crashed does:
244
+ # the job is put back and re-enters it by jid. Released, it would go to
245
+ # whoever waits, and the job would come back to a conflict, which drops,
246
+ # buries or re-pushes it. The gem releases it.
247
+ def perform_and_unlock
248
+ interrupted = false
249
+ yield
250
+ item[JID]
251
+ rescue Wurk::Shutdown
252
+ interrupted = true
253
+ raise
254
+ ensure
255
+ unlock_and_callback unless interrupted
256
+ end
245
257
  end
246
258
 
247
259
  # WhileExecuting whose conflicts always go to the dead set.
@@ -255,8 +267,11 @@ module Wurk
255
267
  class UntilAndWhileExecuting < BaseLock
256
268
  def lock(origin: :client, &) = client_lock(origin: origin, &)
257
269
 
270
+ # A job that holds its runtime lock has started before and was cut short. Its
271
+ # push lock went then, to a successor for all we know, and no longer says
272
+ # whether it may run.
258
273
  def execute
259
- if locksmith.unlock
274
+ if locksmith.unlock || runtime_lock.locked?
260
275
  runtime_lock.execute { return yield }
261
276
  else
262
277
  reflect(:unlock_failed, item)
@@ -8,35 +8,15 @@ module Wurk
8
8
  # run (which a crashed run then holds for just as long). Wurk only: the gem
9
9
  # sets a lock's TTL once, when the lock is taken.
10
10
  #
11
- # One script (`unique_jobs_refresh.lua`) checks that the jid is still in the
12
- # lock's LOCKED hash and only then re-applies the expiry; it never takes a
13
- # lock, so a refresh that comes too late returns false and the caller
14
- # decides what a lost lock means for its run.
11
+ # One script (`unique_jobs_refresh.lua`) checks that this run (see Run) still
12
+ # holds the lock and only then re-applies the expiry; it never takes a lock, so
13
+ # a refresh that comes too late, or from a run a later one of the same jid
14
+ # superseded, returns false and the caller decides what that means for it.
15
15
  class LockRefresh
16
16
  # The types whose lock during `perform` is the runtime one, `<digest>:RUN`.
17
17
  # until_and_while_executing gave up its push lock when `perform` started.
18
18
  RUNTIME_LOCKS = [Lock::WhileExecuting, Lock::UntilAndWhileExecuting].freeze
19
19
 
20
- # The payload of every unique job running in this process, by jid, so the
21
- # job (or a thread it started) can name its lock by jid alone. Filled by
22
- # the server middleware around `perform`.
23
- module Running
24
- @items = {}
25
- @mutex = ::Mutex.new
26
-
27
- class << self
28
- def track(item)
29
- jid = item[JID]
30
- @mutex.synchronize { @items[jid] = item }
31
- yield
32
- ensure
33
- @mutex.synchronize { @items.delete(jid) }
34
- end
35
-
36
- def [](jid) = @mutex.synchronize { @items[jid] }
37
- end
38
- end
39
-
40
20
  def initialize(job, ttl: nil)
41
21
  @item = item_for(job)
42
22
  @pttl = pttl_for(ttl)
@@ -44,7 +24,8 @@ module Wurk
44
24
 
45
25
  def call
46
26
  UniqueJobs.redis do |conn|
47
- Script.call(:unique_jobs_refresh, conn, keys: key.to_a, argv: [@item[JID], @pttl, UniqueJobs.now_f])
27
+ Script.call(:unique_jobs_refresh, conn, keys: key.to_a,
28
+ argv: [@item[JID], @pttl, UniqueJobs.now_f, run_token])
48
29
  end == 1
49
30
  end
50
31
 
@@ -53,12 +34,12 @@ module Wurk
53
34
  def item_for(job)
54
35
  item = case job
55
36
  when ::Hash then job
56
- when ::String then running(job)
37
+ when ::String then running(Run.of_jid(job), job)
57
38
  else
58
39
  raise ::ArgumentError, "expected a job payload, a jid or a job instance, got #{job.inspect}" \
59
40
  unless job.class.respond_to?(:get_sidekiq_options)
60
41
 
61
- running(job.jid)
42
+ running(Run.of_worker(job) || Run.of_jid(job.jid), job.jid)
62
43
  end
63
44
  [JID, LOCK, LOCK_DIGEST].each do |field|
64
45
  raise ::ArgumentError, "not a unique job payload: no `#{field}` in #{item.inspect}" unless item[field]
@@ -66,10 +47,19 @@ module Wurk
66
47
  item
67
48
  end
68
49
 
69
- def running(jid)
70
- Running[jid] || raise(::ArgumentError,
71
- "no job #{jid.inspect} is running under a Wurk::UniqueJobs lock in this process; " \
72
- 'refresh_lock! by jid works only inside its perform (or a thread it started)')
50
+ def running(run, jid)
51
+ return run.item if run
52
+
53
+ raise ::ArgumentError, "no job #{jid.inspect} is running under a Wurk::UniqueJobs lock in this process; " \
54
+ 'refresh_lock! by jid works only inside its perform (or a thread it started)'
55
+ end
56
+
57
+ # A payload that is not the running job's own object is known by jid only:
58
+ # the run of that jid here answers for it, and a payload that runs nowhere
59
+ # in this process renews by jid.
60
+ def run_token
61
+ marks = Run.marks_of(@item) || Run.of_jid(@item[JID])&.marks
62
+ marks&.fetch(key.digest, nil).to_s
73
63
  end
74
64
 
75
65
  # Seconds, from the caller or else the TTL the lock was taken with: the
@@ -129,14 +129,17 @@ module Wurk
129
129
  def execute
130
130
  raise InvalidArgument, '#execute needs a block' unless block_given?
131
131
 
132
- acquired = UniqueJobs.redis { |conn| locked?(conn) || acquired_blocking?(conn, nil) }
132
+ # Minted before the script that writes it: a run killed in between must
133
+ # still recognize its mark.
134
+ marks[key.digest] = Run.token if marks
135
+ acquired = UniqueJobs.redis { |conn| claimed?(conn) || acquired_blocking?(conn, nil) }
133
136
  yield if acquired
134
137
  end
135
138
 
136
139
  def unlock(conn = nil) = unlock!(conn)
137
140
 
138
141
  def unlock!(conn = nil)
139
- jid = run_script(:unique_jobs_unlock, conn, argv + [@sync_locked ? 1 : 0])
142
+ jid = run_script(:unique_jobs_unlock, conn, argv + [@sync_locked ? 1 : 0, run_token])
140
143
  reflect(:unlocked, item) if jid == job_id
141
144
  jid
142
145
  end
@@ -178,7 +181,7 @@ module Wurk
178
181
  write_lock_info(conn)
179
182
  return false unless primed?(conn, wait)
180
183
 
181
- !run_script(:unique_jobs_lock, conn, argv).nil?
184
+ !run_script(:unique_jobs_lock, conn, argv + [run_token]).nil?
182
185
  end
183
186
 
184
187
  def primed?(conn, wait)
@@ -206,7 +209,7 @@ module Wurk
206
209
  end
207
210
 
208
211
  # The lock's own arguments, then what every script appends: the time, the
209
- # changelog cap and the gem's script name; unlock's sync flag goes last.
212
+ # changelog cap and the gem's script name; what only one script takes goes last.
210
213
  def run_script(script, conn, args)
211
214
  injected = [UniqueJobs.now_f, UniqueJobs.config.max_history.to_i, Script::NAMES.fetch(script)]
212
215
  full = args.first(5) + injected + args.drop(5)
@@ -215,6 +218,33 @@ module Wurk
215
218
  UniqueJobs.redis { |c| Script.call(script, c, keys: key.to_a, argv: full) }
216
219
  end
217
220
 
221
+ def marks = Run.marks_of(item)
222
+
223
+ # Empty until this run has entered the lock: what it does to any other lock
224
+ # (the push lock of until_and_while_executing) is by jid, as in the gem.
225
+ def run_token = marks&.fetch(key.digest, nil).to_s
226
+
227
+ # Enters a lock this jid already holds, as its newest run.
228
+ def claimed?(conn)
229
+ return locked?(conn) unless marks
230
+
231
+ Script.call(:unique_jobs_claim, conn, keys: key.to_a, argv: [job_id, run_token]) == 1
232
+ rescue RedisClient::CommandError, Script::LuaError => e
233
+ raise unless UniqueJobsCompat::OOM.match?(e.message)
234
+
235
+ claimed_unmarked?(conn)
236
+ end
237
+
238
+ # A server at maxmemory refuses the mark, and the lock was taken at push: the
239
+ # job runs, its lock its jid's as in the gem. The mark goes with the refusal,
240
+ # or the unlock would take what it finds there for a later run's. Dragonfly
241
+ # words the refusal as a failed script, so it arrives as a LuaError.
242
+ def claimed_unmarked?(conn)
243
+ held = locked?(conn)
244
+ marks.delete(key.digest) if held
245
+ held
246
+ end
247
+
218
248
  def argv = [job_id, config.pttl, config.type.to_s, config.limit.to_i, item[AT].to_s]
219
249
 
220
250
  def write_lock_info(conn)
@@ -82,7 +82,7 @@ module Wurk
82
82
  def call(worker, item, _queue, &)
83
83
  return yield unless lockable?(worker, item)
84
84
 
85
- with_context(:server) { LockRefresh::Running.track(item) { lock_instance.execute(&) } }
85
+ with_context(:server) { Run.track(worker, item) { lock_instance.execute(&) } }
86
86
  end
87
87
  end
88
88
  end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module Wurk
6
+ module UniqueJobs
7
+ # One execution of a unique job. A jid can be running twice: an interrupted
8
+ # run still unwinding while its requeued payload runs elsewhere, or a process
9
+ # cut off from Redis whose job was reclaimed. The lock admits both, since by
10
+ # jid they are one job and crash recovery depends on it, so each run marks the
11
+ # lock it enters with a token of its own (the value beside its jid in LOCKED)
12
+ # and the newest mark is the holder. A run that finds another mark there has
13
+ # been superseded: it unlocks and renews nothing.
14
+ #
15
+ # What a run leaves on the payload object it was given is its marks, a Hash of
16
+ # Strings that Marshal and #dup carry along: whatever unlocks or renews later
17
+ # with that object, or a copy of it, is still this run. Never in its JSON: the
18
+ # payload goes back to Redis unchanged.
19
+ class Run
20
+ IVAR = :@wurk_unique_marks
21
+ private_constant :IVAR
22
+
23
+ @running = []
24
+ @mutex = ::Mutex.new
25
+
26
+ class << self
27
+ # Around the server half of a lock: a new run of `item`, in #running for
28
+ # as long as the block takes.
29
+ def track(worker, item)
30
+ run = new(worker, item)
31
+ item.instance_variable_set(IVAR, run.marks)
32
+ @mutex.synchronize { @running << run }
33
+ yield
34
+ ensure
35
+ @mutex.synchronize { @running.delete_if { |other| other.equal?(run) } }
36
+ end
37
+
38
+ # The marks of the run this payload belongs to, nil for one that never ran:
39
+ # digest to the mark the run has put on that lock.
40
+ def marks_of(item) = item.instance_variable_get(IVAR)
41
+
42
+ def of_worker(worker) = @mutex.synchronize { @running.find { |run| run.worker.equal?(worker) } }
43
+
44
+ # The run of `jid` on this thread, else the oldest in this process. Two at
45
+ # once cannot be told apart from another thread, and of the two the oldest
46
+ # is the superseded one: a holder told "no" stops and is retried, an
47
+ # impostor told "yes" goes on beside the holder.
48
+ def of_jid(jid)
49
+ @mutex.synchronize do
50
+ runs = @running.select { |run| run.item[JID] == jid }
51
+ runs.size > 1 ? runs.find(&:here?) || runs.first : runs.first
52
+ end
53
+ end
54
+
55
+ # Wire-compatible: what the gem keeps beside a jid in LOCKED is the time,
56
+ # and its dashboard reads it back as one. This is the time too, with
57
+ # random digits below the microsecond to make it this run's alone. Fifteen
58
+ # decimals is also how the scripts know a mark: a lock time, which a server
59
+ # prints from a double, cannot have as many.
60
+ def token = format('%.6f%09d', UniqueJobs.now_f, ::SecureRandom.random_number(10**9))
61
+ end
62
+
63
+ attr_reader :worker, :item, :marks
64
+
65
+ def initialize(worker, item)
66
+ @worker = worker
67
+ @item = item
68
+ @thread = ::Thread.current
69
+ @marks = {}
70
+ end
71
+
72
+ def here? = @thread.equal?(::Thread.current)
73
+ end
74
+ end
75
+ end
@@ -5,6 +5,7 @@ require_relative 'unique_jobs/constants'
5
5
  require_relative 'unique_jobs/errors'
6
6
  require_relative 'unique_jobs/reflections'
7
7
  require_relative 'unique_jobs/job'
8
+ require_relative 'unique_jobs/run'
8
9
  require_relative 'unique_jobs/locksmith'
9
10
  require_relative 'unique_jobs/on_conflict'
10
11
  require_relative 'unique_jobs/lock'
data/lib/wurk/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Wurk
4
- VERSION = '1.20.0'
4
+ VERSION = '1.21.0'
5
5
  end
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.20.0",
3
- "timestamp": "2026-11-24T02:15:30.375Z"
2
+ "version": "1.21.0",
3
+ "timestamp": "2026-11-25T13:22:05.544Z"
4
4
  }
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: wurk
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.20.0
4
+ version: 1.21.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - developerz.ai
@@ -359,6 +359,7 @@ files:
359
359
  - lib/wurk/lua/refresh_slots.lua
360
360
  - lib/wurk/lua/status_write.lua
361
361
  - lib/wurk/lua/throttle_slot.lua
362
+ - lib/wurk/lua/unique_jobs_claim.lua
362
363
  - lib/wurk/lua/unique_jobs_delete.lua
363
364
  - lib/wurk/lua/unique_jobs_delete_by_digest.lua
364
365
  - lib/wurk/lua/unique_jobs_delete_job_by_digest.lua
@@ -487,6 +488,7 @@ files:
487
488
  - lib/wurk/unique_jobs/require/sidekiq-unique-jobs.rb
488
489
  - lib/wurk/unique_jobs/require/sidekiq_unique_jobs.rb
489
490
  - lib/wurk/unique_jobs/require/sidekiq_unique_jobs/web.rb
491
+ - lib/wurk/unique_jobs/run.rb
490
492
  - lib/wurk/unique_jobs/sidekiq_unique_jobs.rb
491
493
  - lib/wurk/unique_jobs/web.rb
492
494
  - lib/wurk/unique_jobs/web/views/_paging.erb