wurk 1.19.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: baff6a3f75bca45d6dbcbed8c3363b306ef0f37f8c48f9de0fac68f320ab9a79
4
- data.tar.gz: 3e1725ade18090f1d9eca95d0d3b016db9a15747f63bed75b4ef6cc95555982e
3
+ metadata.gz: 6c1512080d8eb946fdd63cc52d263fafa240112d0191c56f132dd9f9e6d76713
4
+ data.tar.gz: 10eced0a7c6177fe53a199462c8ab9eb90a44fd77a31dbf90f5d34a0a5c4fdd4
5
5
  SHA512:
6
- metadata.gz: 78be5c5f73decd87bda36782bde1ab6d3698b6fc05ad659d6b167c2fba7b7e63cb3250dc3c3ed07016addf03376bceecf6ffb67072ac6df0fbd6b88d975d1824
7
- data.tar.gz: 83e105bb40f2d95b89564cae52cd7fc85347bd6f131f822d91eac80b74d4ff45ee3c425e4a89fc87c8144717f0020b9a4de56584bfc1f03a76b72be074ae979e
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.19.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
 
data/lib/wurk/dead_set.rb CHANGED
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'job_set'
4
+ require_relative 'metrics/deaths'
4
5
 
5
6
  module Wurk
6
7
  # Capped ZSET of jobs that exhausted retries (the "morgue"). Bounded by
7
8
  # `dead_max_jobs` and `dead_timeout_in_seconds` config knobs — every
8
- # `kill` trims both axes. Death handlers fire by default — including on
9
+ # `kill` trims both axes, and counts the job into Metrics::Deaths, which
10
+ # the trim never touches. Death handlers fire by default — including on
9
11
  # API/UI kills, matching Sidekiq — unless `notify_failure: false`.
10
12
  #
11
13
  # Spec: docs/target/sidekiq-free.md §19.5, §17.2, §31.8.
@@ -52,8 +54,7 @@ module Wurk
52
54
  # malformed path has no parseable job to hand a handler. `max_jobs:` /
53
55
  # `timeout:` propagate to #trim (see there for the override rationale).
54
56
  def kill_raw(payload, max_jobs: nil, timeout: nil) # rubocop:disable Naming/PredicateMethod
55
- now = ::Process.clock_gettime(::Process::CLOCK_REALTIME)
56
- Wurk.redis { |conn| conn.call('ZADD', @name, now.to_s, payload) }
57
+ add(payload)
57
58
  trim(max_jobs: max_jobs, timeout: timeout)
58
59
  true
59
60
  end
@@ -65,8 +66,7 @@ module Wurk
65
66
  # receive `(job, ex)`. `max_jobs:` / `timeout:` propagate to the auto-trim;
66
67
  # see `#trim` for the rationale.
67
68
  def kill(message, opts = {})
68
- now = ::Process.clock_gettime(::Process::CLOCK_REALTIME)
69
- Wurk.redis { |conn| conn.call('ZADD', @name, now.to_s, message) }
69
+ add(message)
70
70
  trim(max_jobs: opts[:max_jobs], timeout: opts[:timeout]) if opts.fetch(:trim, true)
71
71
  fire_death_handlers(message, opts[:ex] || api_kill_error) if opts.fetch(:notify_failure, true)
72
72
  true
@@ -74,6 +74,14 @@ module Wurk
74
74
 
75
75
  private
76
76
 
77
+ def add(message)
78
+ now = ::Process.clock_gettime(::Process::CLOCK_REALTIME)
79
+ Wurk.redis do |conn|
80
+ conn.call('ZADD', @name, now.to_s, message)
81
+ Metrics::Deaths.record(conn, message)
82
+ end
83
+ end
84
+
77
85
  # Only the death handlers see it, so a kill that notifies none (a UI kill,
78
86
  # `kill_all` over a whole set) never pays for the caller's backtrace.
79
87
  def api_kill_error
@@ -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)
data/lib/wurk/keys.rb CHANGED
@@ -47,6 +47,12 @@ module Wurk
47
47
  # elapsed. Per-day variants append `:YYYY-MM-DD`. Spec: sidekiq-pro.md §7.
48
48
  STAT_EXPIRED = 'stat:expired'
49
49
 
50
+ # Jobs moved to the dead set, per queue and class (Metrics::Deaths): HASH,
51
+ # field = JSON `[queue, class]`, value = count. A Wurk extra like
52
+ # `status:` — Sidekiq keeps no death counter — and, unlike the capped
53
+ # `dead` set it counts into, it only ever grows.
54
+ STAT_DEATHS = 'stat:deaths'
55
+
50
56
  # TTL applied to per-day `stat:processed:*` / `stat:failed:*` /
51
57
  # `stat:expired:*` strings. 5 years, in seconds. Matches
52
58
  # Sidekiq::Launcher::STATS_TTL.
@@ -0,0 +1,12 @@
1
+ -- Counts one job into the death counter (Metrics::Deaths). A field already in
2
+ -- the hash always counts; a new one counts only while the hash holds fewer than
3
+ -- the cap, and into the overflow field past it, so junk payloads cannot grow
4
+ -- the hash, or a scrape of it, without bound.
5
+ -- KEYS = [deaths hash]
6
+ -- ARGV = [field, max fields, overflow field]
7
+ -- Returns the field's new count.
8
+ local field = ARGV[1]
9
+ if redis.call("hexists", KEYS[1], field) == 0 and redis.call("hlen", KEYS[1]) >= tonumber(ARGV[2]) then
10
+ field = ARGV[3]
11
+ end
12
+ return redis.call("hincrby", KEYS[1], field, 1)
@@ -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/lua.rb CHANGED
@@ -63,8 +63,10 @@ module Wurk
63
63
  # retry would starve the whole cluster's scheduled jobs. It is moved to the
64
64
  # dead set (scored `now`, like a kill) so it stays inspectable, and the
65
65
  # sweep continues. pcall keeps a failed decode from raising out of the script.
66
- # KEYS = [sorted_set, queues_set, dead_set]
67
- # ARGV = [now, queue_prefix, now_ms, batch]
66
+ # Each one moved is counted into the death counter the way
67
+ # `lua/count_death.lua` counts (Metrics::Deaths), under queue `unknown`.
68
+ # KEYS = [sorted_set, queues_set, dead_set, deaths_hash]
69
+ # ARGV = [now, queue_prefix, now_ms, batch, deaths_max_fields, deaths_overflow_field]
68
70
  # Returns the number of members handled (promoted or moved to dead).
69
71
  # Order matters: decode + push BEFORE zrem. Redis Lua has no rollback,
70
72
  # so a failed cjson.decode after a zrem would lose the job. Decode first;
@@ -126,6 +128,18 @@ module Wurk
126
128
  if not last then return job end
127
129
  return string.sub(job, 1, e) .. colon .. ARGV[3] .. string.sub(job, last + 1)
128
130
  end
131
+ local function label(v) if type(v) == "string" and v ~= "" then return v end end
132
+ -- Best effort, pcall only: a refused count (a wrong-typed key, maxmemory)
133
+ -- must not stop the ZREM below, or the member is re-buried every sweep.
134
+ local function count_death(decoded)
135
+ local job = type(decoded) == "table" and decoded or {}
136
+ local field = cjson.encode({"unknown", label(job["wrapped"]) or label(job["class"]) or "unknown"})
137
+ local size = redis.pcall("hlen", KEYS[4])
138
+ if redis.pcall("hexists", KEYS[4], field) == 0 and type(size) == "number" and size >= tonumber(ARGV[5]) then
139
+ field = ARGV[6]
140
+ end
141
+ redis.pcall("hincrby", KEYS[4], field, 1)
142
+ end
129
143
  local jobs = redis.call("zrangebyscore", KEYS[1], "-inf", ARGV[1], "LIMIT", 0, tonumber(ARGV[4]))
130
144
  for i = 1, #jobs do
131
145
  local job = jobs[i]
@@ -138,6 +152,7 @@ module Wurk
138
152
  redis.call("zadd", KEYS[3], ARGV[1], job)
139
153
  end
140
154
  redis.call("zrem", KEYS[1], job)
155
+ if type(q) ~= "string" then count_death(ok and decoded) end
141
156
  end
142
157
  return #jobs
143
158
  LUA
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
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require_relative '../keys'
5
+ require_relative '../lua'
6
+
7
+ module Wurk
8
+ module Metrics
9
+ # Cluster-wide, monotonic count of jobs moved to the dead set, per queue and
10
+ # class, in `stat:deaths` (Keys::STAT_DEATHS). The dead set is capped at
11
+ # `dead_max_jobs`: once full, every kill trims the oldest entry, so its size
12
+ # stops moving and cannot say how many jobs died. This count can.
13
+ #
14
+ # Labels come from the payload's `queue` and its `wrapped` class (an
15
+ # ActiveJob's own class) or `class`, never the jid or args. A field the
16
+ # payload cannot supply is `unknown`. Distinct pairs past MAX_SERIES fold
17
+ # into OVERFLOW (`lua/count_death.lua`).
18
+ #
19
+ # Best effort, and only Wurk writes it (a stock Sidekiq process in a mixed
20
+ # fleet does not). #record reports a failed count, which may or may not have
21
+ # landed (a lost reply); the schedule-promote script cannot report, and drops it.
22
+ #
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.
26
+ module Deaths
27
+ MAX_SERIES = 500
28
+ UNKNOWN = 'unknown'
29
+ OTHER = 'other'
30
+ OVERFLOW = ::JSON.generate([OTHER, OTHER]).freeze
31
+ # What cjson escapes and json does not.
32
+ CJSON_ESCAPES = { '/' => '\\/', "\u007f" => '\u007f' }.freeze
33
+ # Name, help and type of the `/metrics` family (Metrics::Prometheus), whose
34
+ # samples are #samples. Read from shared Redis, so every scrape target
35
+ # reports the same value: aggregate with `max`.
36
+ FAMILY = ['wurk_jobs_dead_total', 'Jobs moved to the dead set, by queue and class (stat:deaths).',
37
+ 'counter'].freeze
38
+
39
+ class << self
40
+ # Counts one death. Runs once, never replayed (`eval_once`), so a dropped
41
+ # socket can lose a count but never add one. Reported, not raised: the
42
+ # job is already in the dead set, and a caller that saw a raise would
43
+ # treat the kill as failed and kill it again.
44
+ def record(conn, payload, config: Wurk.configuration)
45
+ Lua::Loader.eval_once(conn, :count_death, keys: [Keys::STAT_DEATHS],
46
+ argv: [field(payload), MAX_SERIES, OVERFLOW])
47
+ rescue RedisClient::Error => e
48
+ config.handle_exception(e, context: 'dead-set death counter')
49
+ end
50
+
51
+ # The hash field for one payload: JSON `[queue, class]`.
52
+ def field(payload)
53
+ job = payload.is_a?(::String) ? parse(payload) : payload
54
+ job = {} unless job.is_a?(::Hash)
55
+ ::JSON.generate([label(job['queue']) || UNKNOWN, label(job['wrapped']) || label(job['class']) || UNKNOWN])
56
+ .gsub(%r{[/\u007f]}, CJSON_ESCAPES)
57
+ end
58
+
59
+ # `[[{ 'queue' => q, 'class' => c }, count], …]` from an HGETALL reply
60
+ # (a Hash under RESP3, a flat Array under RESP2), sorted by labels. Two
61
+ # fields that decode to the same labels (escaped differently by another
62
+ # writer) are summed.
63
+ def samples(reply)
64
+ pairs = reply.is_a?(::Hash) ? reply : Array(reply).each_slice(2)
65
+ totals = ::Hash.new(0)
66
+ pairs.each { |raw, count| totals[labels(raw)] += count.to_i }
67
+ totals.sort_by { |labels, _| labels.values }
68
+ end
69
+
70
+ private
71
+
72
+ def parse(payload)
73
+ ::JSON.parse(payload)
74
+ rescue ::JSON::ParserError
75
+ nil
76
+ end
77
+
78
+ def label(value)
79
+ value if value.is_a?(::String) && !value.empty?
80
+ end
81
+
82
+ def labels(raw)
83
+ queue, klass = parse(raw)
84
+ { 'queue' => label(queue) || UNKNOWN, 'class' => label(klass) || UNKNOWN }
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
@@ -6,11 +6,13 @@ require_relative '../keys'
6
6
  require_relative '../version'
7
7
  require_relative '../queue_consumers'
8
8
  require_relative 'process_counters'
9
+ require_relative 'deaths'
9
10
 
10
11
  module Wurk
11
12
  module Metrics
12
13
  # Prometheus text exposition (format 0.0.4) served by the health listener at
13
- # `GET /metrics`. Reads only keys Sidekiq already writes — no new Redis keys.
14
+ # `GET /metrics`. Reads keys Sidekiq already writes, plus Wurk's own death
15
+ # counter (`stat:deaths`, Metrics::Deaths); it writes none.
14
16
  #
15
17
  # Two families, and the difference matters when aggregating:
16
18
  # * cluster gauges/counters (`wurk_queue_*`, `wurk_processed_total`, …)
@@ -57,7 +59,7 @@ module Wurk
57
59
  # scheduler is behind.
58
60
  SET_HEADS = Scheduled::SETS.map { |set| ['ZRANGE', set, 0, 0, 'WITHSCORES'] }.freeze
59
61
  # Names come last: the detail pass is built from them.
60
- FIRST_PASS = [*SCALARS.values, *SET_HEADS, ['GET', Wurk::Leader::DEFAULT_KEY],
62
+ FIRST_PASS = [*SCALARS.values, *SET_HEADS, ['GET', Wurk::Leader::DEFAULT_KEY], ['HGETALL', Keys::STAT_DEATHS],
61
63
  ['SMEMBERS', Keys::QUEUES_SET], ['SMEMBERS', Keys::PROCESSES]].freeze
62
64
 
63
65
  QUEUE_GAUGES = [
@@ -98,7 +100,7 @@ module Wurk
98
100
  ProcessRow = Struct.new(:identity, :pid, :busy, :concurrency, :beat, :rss_kb, :quiet, :queues, :rtt_us,
99
101
  :oldest_run_at)
100
102
  Snapshot = Struct.new(:ok, :taken_at, :processed, :failed, :scheduled, :retries, :dead, :queues, :processes,
101
- :leader, :set_heads, keyword_init: true)
103
+ :leader, :set_heads, :deaths, keyword_init: true)
102
104
 
103
105
  def initialize(config, ttl: TTL, nonce: Component::PROCESS_NONCE, hostname: Component.hostname,
104
106
  clock: -> { ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) })
@@ -139,6 +141,7 @@ module Wurk
139
141
  ProcessFamilies.render(out, swarm: swarm)
140
142
  if snap.ok
141
143
  cluster(out, snap)
144
+ family(out, *Deaths::FAMILY, snap.deaths)
142
145
  local(out, snap, expected_children, fresh_window)
143
146
  end
144
147
  out
@@ -155,7 +158,7 @@ module Wurk
155
158
  queues, processes = names(first)
156
159
  rows = process_rows(processes, detail.drop(queues.size * 2), local_identities(processes))
157
160
  Snapshot.new(ok: true, taken_at: now, **scalars(first), leader: first[SCALARS.size + SET_HEADS.size],
158
- set_heads: heads_of_sets(first),
161
+ set_heads: heads_of_sets(first), deaths: Deaths.samples(first[SCALARS.size + SET_HEADS.size + 1]),
159
162
  queues: queue_rows(queues, detail, rows), processes: rows)
160
163
  rescue StandardError => e
161
164
  @config.logger&.warn { "Wurk::Metrics::Prometheus refresh failed: #{e.class}: #{e.message}" }
@@ -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
@@ -4,6 +4,7 @@ require_relative 'component'
4
4
  require_relative 'keys'
5
5
  require_relative 'lua'
6
6
  require_relative 'lua/loader'
7
+ require_relative 'metrics/deaths'
7
8
  require_relative 'client'
8
9
  require_relative 'process_set'
9
10
  require_relative 'timer_loop'
@@ -150,10 +151,12 @@ module Wurk
150
151
  def bury(jobstr, sset)
151
152
  # Two commands, no MULTI: a server that refuses the ZADD mid-transaction
152
153
  # (Dragonfly at maxmemory) still applies the ZREM, and the member is gone.
153
- # A crash between them costs one more trip through here.
154
+ # A crash between them costs one more trip through here. The count runs
155
+ # last and never raises, so a replay of the block cannot count twice.
154
156
  @config.redis(idempotent: true) do |conn|
155
157
  conn.call('ZADD', Keys::DEAD, real_time.to_s, jobstr)
156
158
  conn.call('ZREM', sset, jobstr)
159
+ Metrics::Deaths.record(conn, jobstr, config: @config)
157
160
  end
158
161
  rescue *TRANSIENT_ERRORS => e
159
162
  handle_exception(e, { context: 'scheduler_restore', set: sset })
@@ -238,8 +241,9 @@ module Wurk
238
241
  promoted = Wurk::Lua::Loader.eval_cached(
239
242
  conn,
240
243
  :reliable_schedule_promote,
241
- keys: [sset, Keys::QUEUES_SET, Keys::DEAD],
242
- argv: [real_time.to_s, Keys::QUEUE_PREFIX, real_ms.to_s, PROMOTE_BATCH.to_s]
244
+ keys: [sset, Keys::QUEUES_SET, Keys::DEAD, Keys::STAT_DEATHS],
245
+ argv: [real_time.to_s, Keys::QUEUE_PREFIX, real_ms.to_s, PROMOTE_BATCH.to_s,
246
+ Metrics::Deaths::MAX_SERIES.to_s, Metrics::Deaths::OVERFLOW]
243
247
  ).to_i
244
248
  Scheduled.record_promotions(sset, promoted)
245
249
  break if promoted < PROMOTE_BATCH || @done
@@ -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.19.0'
4
+ VERSION = '1.21.0'
5
5
  end
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.19.0",
3
- "timestamp": "2026-11-23T15:33:33.692Z"
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.19.0
4
+ version: 1.21.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - developerz.ai
@@ -332,6 +332,7 @@ files:
332
332
  - lib/wurk/lua/batch_push.lua
333
333
  - lib/wurk/lua/batch_remove_jobs.lua
334
334
  - lib/wurk/lua/batch_schedule.lua
335
+ - lib/wurk/lua/count_death.lua
335
336
  - lib/wurk/lua/debounce.lua
336
337
  - lib/wurk/lua/fast_delete.rb
337
338
  - lib/wurk/lua/fast_delete_window.lua
@@ -358,6 +359,7 @@ files:
358
359
  - lib/wurk/lua/refresh_slots.lua
359
360
  - lib/wurk/lua/status_write.lua
360
361
  - lib/wurk/lua/throttle_slot.lua
362
+ - lib/wurk/lua/unique_jobs_claim.lua
361
363
  - lib/wurk/lua/unique_jobs_delete.lua
362
364
  - lib/wurk/lua/unique_jobs_delete_by_digest.lua
363
365
  - lib/wurk/lua/unique_jobs_delete_job_by_digest.lua
@@ -370,6 +372,7 @@ files:
370
372
  - lib/wurk/metrics.rb
371
373
  - lib/wurk/metrics/accumulator.rb
372
374
  - lib/wurk/metrics/dashboard_series.rb
375
+ - lib/wurk/metrics/deaths.rb
373
376
  - lib/wurk/metrics/exposition.rb
374
377
  - lib/wurk/metrics/flusher.rb
375
378
  - lib/wurk/metrics/histogram.rb
@@ -485,6 +488,7 @@ files:
485
488
  - lib/wurk/unique_jobs/require/sidekiq-unique-jobs.rb
486
489
  - lib/wurk/unique_jobs/require/sidekiq_unique_jobs.rb
487
490
  - lib/wurk/unique_jobs/require/sidekiq_unique_jobs/web.rb
491
+ - lib/wurk/unique_jobs/run.rb
488
492
  - lib/wurk/unique_jobs/sidekiq_unique_jobs.rb
489
493
  - lib/wurk/unique_jobs/web.rb
490
494
  - lib/wurk/unique_jobs/web/views/_paging.erb