wurk 1.17.0 → 1.17.1

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: 21ea6463167ebec27cef785cfba9e726c5cd162feb8c735f54b7e971a442fec5
4
- data.tar.gz: 8be078d35ac16e090f004c3975035bec8b8eb545627e2bec7da1c2e979bc260f
3
+ metadata.gz: 38e891f5c26931fc61deb3b165cc5a7c4e9c952ee7ed98e2ba121bc89c06476f
4
+ data.tar.gz: '09c9fb93ef3cbe927925d714138c98dd3795977c9bc775806b90338adcdf5d00'
5
5
  SHA512:
6
- metadata.gz: 1526cfaf774a77559de2aee1e82866c2be679fa2376ebd4f9d636a50a0947f64f4f100e69032c55fd3f10fc193f014c8f6b225cd17af738353a16edefbb9025b
7
- data.tar.gz: 2d6070c13fae762c34b2e868c51f31dc85985607fc4d533c311ba58ba22002a401344681e448b8548854bd053552ecf76ec97c02e74122eff0543e265ba93e9e
6
+ metadata.gz: dbbd540b3082626c6de579a8dfc841bf27e0c51344a023f9be30a7f411e5021647c5fb531147fe1fbeaee706bb8e6c8a174195ec3c2b741c70b47cbcb80487d6
7
+ data.tar.gz: b994abcc5dba5e22aeb892d46a4f619540eec963546ded5456f1d6dd3eca47d0232d5db41b7b31717c9a69ef9fc703579d31439f91814f03a961eadb41324d48
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.17.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.17.1", 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
 
@@ -23,9 +23,9 @@ module Wurk
23
23
  # The success ack runs outside the job's rescue: once `perform` returned,
24
24
  # nothing the batch bookkeeping raises may be mistaken for the job failing,
25
25
  # or a job that already did its work is retried and runs twice. The ack
26
- # itself is retried in-process and only raises (sending the job to retry,
27
- # at-least-once) when Redis stays unreachable — a jid left in the live set
28
- # would hold the batch open forever. The fire after it never raises: it is
26
+ # itself is retried in-process; when Redis stays unreachable it raises and
27
+ # the Processor hands the ack to FinishedJobCleanup, which sends it once
28
+ # Redis answers, without running the job again. The fire after it never raises: it is
29
29
  # re-driven in-process and then reported to the error handlers. Both wait
30
30
  # out a store that is not serving (Callbacks::STORE_OUTAGE_BUDGET): once
31
31
  # this job is ACKed nothing re-drives a fire that gave up.
@@ -170,6 +170,7 @@ module Wurk
170
170
  # `reraise: true` (used in tests / fail-fast boot). `oneshot: true`
171
171
  # clears the bucket after dispatch so the event can't fire twice.
172
172
  def fire_event(event, oneshot: true, reverse: false, reraise: false)
173
+ UniqueJobsCompat.install if event == :startup
173
174
  bucket = config[:lifecycle_events][event]
174
175
  return if bucket.nil? || bucket.empty?
175
176
 
@@ -4,19 +4,51 @@ require_relative '../keys'
4
4
 
5
5
  module Wurk
6
6
  class Fetcher
7
- # Reads the owner back out of a reliable-fetch private list key
8
- # (`queue:<public>|<host>|<pid>|<nonce>|<idx>`, see
9
- # Reliable.private_queue_name) for the Reaper's liveness check. Pure string
10
- # work, no Redis.
7
+ # Reads the owner back out of a reliable-fetch private list key for the
8
+ # Reaper's liveness check: Wurk's `queue:<public>|<host>|<pid>|<nonce>|<idx>`
9
+ # (Reliable.private_queue_name) or Sidekiq Pro's
10
+ # `queue:sq|<host>:<pid>:<nonce>|<public>` (SuperFetch#private_queue). Pure
11
+ # string work, no Redis.
11
12
  module PrivateListKey
12
13
  # The nonce shape Component::PROCESS_NONCE writes (`SecureRandom.hex(6)`).
13
14
  NONCE_PATTERN = /\A[0-9a-f]{12}\z/
14
15
 
16
+ PRO_PREFIX = "#{Keys::QUEUE_PREFIX}sq|".freeze
17
+ # Rebuilt byte for byte into the heartbeat key the liveness check reads,
18
+ # so a pid that would not round-trip through Integer is refused.
19
+ PRO_IDENTITY = /\A(.+):([1-9]\d*):([0-9a-f]{12})\z/
20
+ PRO_QUEUE = /\A[^|]+(?:\|[^|]+)*\z/
21
+
15
22
  module_function
16
23
 
17
- # `queue:<public>|<host>|<pid>|<nonce>|<idx>` → [public_q, host, pid,
18
- # nonce], parsed from the right so a `|` inside the queue name is
19
- # tolerated. nil when the key isn't a well-formed private list.
24
+ # [public_q, host, pid, nonce], or nil when the key isn't a well-formed
25
+ # private list.
26
+ #
27
+ # A key that reads as both Pro's and Wurk's is refused: the two name
28
+ # different owners, and judging the wrong one dead would drain a live
29
+ # owner's list. It stays put and the Reaper reports it.
30
+ def parse_full(key)
31
+ return unless key.valid_encoding?
32
+
33
+ pro = parse_pro(key)
34
+ wurk = parse_wurk(key)
35
+ pro && wurk ? nil : pro || wurk
36
+ end
37
+
38
+ # `queue:sq|<identity>|<public>`. Everything after the identity is the
39
+ # queue, so a `|` inside its name is kept.
40
+ def parse_pro(key)
41
+ return unless key.start_with?(PRO_PREFIX)
42
+
43
+ identity, queue = key.delete_prefix(PRO_PREFIX).split('|', 2)
44
+ owner = PRO_IDENTITY.match(identity.to_s)
45
+ return unless owner && queue&.match?(PRO_QUEUE)
46
+
47
+ ["#{Keys::QUEUE_PREFIX}#{queue}", owner[1], owner[2].to_i, owner[3]]
48
+ end
49
+
50
+ # `queue:<public>|<host>|<pid>|<nonce>|<idx>`, parsed from the right so a
51
+ # `|` inside the queue name is tolerated.
20
52
  #
21
53
  # With no known prefix to split on, both owner shapes are tried in
22
54
  # preference order and the first one leaving a real public queue behind
@@ -27,7 +59,7 @@ module Wurk
27
59
  # pipe and puts the real pid in the nonce slot (pipe-bearing queue).
28
60
  # Both misreads are refused: the leftover must be a real queue name and
29
61
  # the pseudo-nonce must be nonce-shaped (see wide_tail).
30
- def parse_full(key)
62
+ def parse_wurk(key)
31
63
  parts = key.split('|')
32
64
  owner_tails(parts).each do |host, pid, nonce, width|
33
65
  public_q = parts[0...-width].join('|')
@@ -229,9 +229,9 @@ module Wurk
229
229
  end
230
230
 
231
231
  # Yields private_list_key, [public_q, host, pid, nonce] for every list.
232
- # MATCH `queue:*|*` matches only private lists (public queue
233
- # keys carry no `|`); PrivateListKey.parse_full drops anything that isn't a
234
- # well-formed `queue:<public>|<host>|<pid>|<nonce>|<idx>`.
232
+ # MATCH `queue:*|*` also matches a public queue with `|` in its name
233
+ # (#public_queue?); PrivateListKey.parse_full drops anything that is not
234
+ # a well-formed Wurk or Sidekiq Pro private list.
235
235
  def each_private_list
236
236
  cursor = '0'
237
237
  loop do
@@ -275,11 +275,19 @@ module Wurk
275
275
  @grace.forget(key)
276
276
  return false
277
277
  end
278
- return false if @grace.recent?(key, owner)
278
+ return false if public_queue?(key) || @grace.recent?(key, owner)
279
279
 
280
280
  owner_gone?(host, pid, nonce)
281
281
  end
282
282
 
283
+ # A public queue's own name can read as a private list. It has no owner to
284
+ # be dead, and draining it would move its waiting jobs to another queue.
285
+ def public_queue?(key)
286
+ redis(idempotent: true) do |c|
287
+ c.call('SISMEMBER', Keys::QUEUES_SET, key.delete_prefix(Keys::QUEUE_PREFIX))
288
+ end == 1
289
+ end
290
+
283
291
  def owner_key(host, pid, nonce)
284
292
  nonce ? "#{host}:#{pid}:#{nonce}" : "#{host}:#{pid}"
285
293
  end
@@ -7,12 +7,10 @@ module Wurk
7
7
  # The Reaper's report on a `queue:*|*` key that is not a private list it
8
8
  # can read the owner of — a list whose owner tail does not parse, say
9
9
  # `queue:<queue>|<host>|not-a-pid|<index>`, left behind by a producer that
10
- # is not Wurk. Sidekiq Pro's four-part shape
11
- # (`queue:<queue>|<host>|<pid>|<index>`) parses as the pre-nonce tail and
12
- # is reclaimed, so Pro's lists are not reported. Nothing will ever reclaim
13
- # the jobs of an unparseable list, so it is said once per key per process
14
- # (WARN, with the list's length) rather than skipped in silence on every
15
- # sweep.
10
+ # is not Wurk, or a key that reads as both a Wurk and a Sidekiq Pro list
11
+ # (PrivateListKey.parse_full). Nothing will ever reclaim the jobs of an
12
+ # unparseable list, so it is said once per key per process (WARN, with the
13
+ # list's length) rather than skipped in silence on every sweep.
16
14
  #
17
15
  # The dedup memory is an in-memory ::Set in THIS process only: one
18
16
  # UnparseableKeys per Reaper, one Reaper per Launcher, one Launcher per
@@ -43,9 +41,10 @@ module Wurk
43
41
  @reported.clear if @reported.size >= MEMORY
44
42
  @reported << key
45
43
  @config.logger.warn do
46
- "reaper: #{key.inspect} looks like a reliable-fetch private list but matches neither " \
47
- 'queue:<queue>|<host>|<pid>|<nonce>|<index> nor the pre-nonce ' \
48
- "queue:<queue>|<host>|<pid>|<index>; its #{size} job(s) will not be recovered " \
44
+ "reaper: #{key.inspect} looks like a reliable-fetch private list but does not read as " \
45
+ 'exactly one of queue:<queue>|<host>|<pid>|<nonce>|<index>, the pre-nonce ' \
46
+ 'queue:<queue>|<host>|<pid>|<index> or Sidekiq Pro\'s queue:sq|<identity>|<queue>; ' \
47
+ "its #{size} job(s) will not be recovered " \
49
48
  'automatically. Inspect it and LMOVE them back onto their queue by hand ' \
50
49
  'if they belong to a dead process. ' \
51
50
  'Reported once per process: every worker that sees the key logs it for itself, ' \
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wurk
4
+ # What a job still owes Redis after its `perform` returned and the bookkeeping
5
+ # behind it failed: a sidekiq-unique-jobs lock and a batch's success ack.
6
+ #
7
+ # The job is finished and is never run again for this, since a second run of a
8
+ # bank login or an email is the harm. So the owed writes wait here, in this
9
+ # process, and every Processor retries them before its next fetch. That costs
10
+ # no thread and no sleep during the outage, and they land as soon as Redis
11
+ # answers. A process that exits first says which locks it left (#give_up): the
12
+ # gem's reaper or the lock's TTL clears them.
13
+ class FinishedJobCleanup
14
+ # Names the job, with the Redis error as its `cause`.
15
+ class BookkeepingFailed < ::StandardError; end
16
+
17
+ STORE_ERRORS = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError].freeze
18
+ # Past this many owed jobs the oldest is reported and dropped.
19
+ MEMORY = 10_000
20
+ RETRY_EVERY = 1.0
21
+ RUN_SUFFIX = ':RUN'
22
+ # This lock type is meant to outlive the job, until its TTL.
23
+ KEEPS_LOCK = 'until_expired'
24
+
25
+ Entry = Struct.new(:job, :pool, :config)
26
+
27
+ @entries = []
28
+ @lock = ::Mutex.new
29
+ @draining = ::Mutex.new
30
+ @next_try = 0.0
31
+
32
+ class << self
33
+ def store_error?(error) = STORE_ERRORS.any? { |klass| error.is_a?(klass) }
34
+
35
+ # Reports the failure, tries the owed writes once, keeps what did not land.
36
+ def settle(job, error, pool:, config:)
37
+ report(job, error, config)
38
+ entry = Entry.new(job, pool, config)
39
+ return unless owes_anything?(job)
40
+ return if attempt?(entry)
41
+
42
+ remember(entry)
43
+ config.logger.error { "#{describe(job)}: waiting for Redis to finish its cleanup" }
44
+ end
45
+
46
+ # Hot path: one empty check per fetch while nothing is owed.
47
+ def drain
48
+ return if @entries.empty? || monotonic < @next_try
49
+ return unless @draining.try_lock
50
+
51
+ begin
52
+ drain_entries
53
+ ensure
54
+ @draining.unlock
55
+ end
56
+ end
57
+
58
+ # The process is stopping: one last try, then say what is left.
59
+ def give_up
60
+ return if @entries.empty?
61
+
62
+ @next_try = 0.0
63
+ drain
64
+ @lock.synchronize { @entries.slice!(0..) }.each { |entry| warn_left(entry) }
65
+ end
66
+
67
+ def pending = @lock.synchronize { @entries.size }
68
+
69
+ def reset!
70
+ @lock.synchronize { @entries.clear }
71
+ @next_try = 0.0
72
+ end
73
+
74
+ private
75
+
76
+ def drain_entries
77
+ while (entry = @lock.synchronize { @entries.first })
78
+ unless attempt?(entry)
79
+ @next_try = monotonic + RETRY_EVERY
80
+ return
81
+ end
82
+ @lock.synchronize { @entries.delete_at(@entries.index { |held| held.equal?(entry) } || @entries.size) }
83
+ entry.config.logger.info { "#{describe(entry.job)}: cleanup finished after the Redis failure" }
84
+ end
85
+ end
86
+
87
+ # true when nothing more can be done for this entry. Idempotent, so an
88
+ # entry half done by an earlier try is safe to run again.
89
+ def attempt?(entry)
90
+ release_unique_locks(entry.job)
91
+ ack_batch(entry.job, entry.pool)
92
+ true
93
+ rescue StandardError => e
94
+ return false if store_error?(e)
95
+
96
+ entry.config.handle_exception(e, { context: "#{describe(entry.job)}: cleanup failed", job: entry.job })
97
+ true
98
+ end
99
+
100
+ # Locksmith#unlock only drops a lock this jid holds. Both digests: an
101
+ # until_and_while_executing job takes its base lock back when an error
102
+ # crosses it, on top of the `:RUN` lock it may still hold.
103
+ def release_unique_locks(job)
104
+ digests(job).each { |digest| ::SidekiqUniqueJobs::Locksmith.new(job.merge('lock_digest' => digest)).unlock }
105
+ end
106
+
107
+ def digests(job)
108
+ digest = job['lock_digest']
109
+ return [] unless digest && job['lock'].to_s != KEEPS_LOCK && defined?(::SidekiqUniqueJobs::Locksmith)
110
+
111
+ base = digest.delete_suffix(RUN_SUFFIX)
112
+ [base, "#{base}#{RUN_SUFFIX}"]
113
+ end
114
+
115
+ # A replayed ack removes nothing, and the callback markers absorb a second
116
+ # fire (Batch::ServerMiddleware#ack_success).
117
+ def ack_batch(job, pool)
118
+ bid = job['bid']
119
+ return unless bid
120
+
121
+ _removed, pending, live, kids = pool.with { |conn| Batch.ack_success(conn, bid, job['jid']) }
122
+ Batch::Callbacks.maybe_fire(bid, pending: pending, live: live, kids: kids)
123
+ end
124
+
125
+ def owes_anything?(job) = job['bid'] || digests(job).any?
126
+
127
+ def remember(entry)
128
+ dropped = @lock.synchronize do
129
+ @entries << entry
130
+ @entries.shift if @entries.size > MEMORY
131
+ end
132
+ warn_left(dropped) if dropped
133
+ end
134
+
135
+ def warn_left(entry)
136
+ entry.config.logger.error do
137
+ "#{describe(entry.job)}: cleanup never reached Redis. Locks left: #{digests(entry.job).join(', ')}; " \
138
+ 'the sidekiq-unique-jobs reaper or the lock TTL clears them. Batch: ' \
139
+ "#{entry.job['bid'] || 'none'}"
140
+ end
141
+ end
142
+
143
+ def report(job, error, config)
144
+ raise BookkeepingFailed, "#{describe(job)}: Redis failed after perform returned, not running it again " \
145
+ "(#{error.class}: #{error.message}). Locks: #{digests(job).join(', ')}", cause: error
146
+ rescue BookkeepingFailed => e
147
+ config.handle_exception(e, { context: 'Bookkeeping failed after perform', job: job })
148
+ end
149
+
150
+ def describe(job) = "#{job['class']} JID-#{job['jid']}"
151
+
152
+ def monotonic = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
153
+ end
154
+ end
155
+ end
@@ -38,14 +38,6 @@ module Wurk
38
38
  # short-circuits processing (e.g. interrupt-handler re-pushed the job).
39
39
  class Skip < Handled; end
40
40
 
41
- # Raised by Processor when Redis stopped answering after `perform` had
42
- # returned: the job did its work and only the bookkeeping behind it (a
43
- # batch ack, a status row) failed. Counted as a failure it would be retried
44
- # with a stale count or, on a last attempt, killed, and a batch would mark
45
- # itself dead over a job that succeeded. Both guards let it through to the
46
- # Processor, which puts the job back to run again. `cause` is the Redis error.
47
- class StoreUnavailableAfterPerform < ::StandardError; end
48
-
49
41
  def initialize(capsule)
50
42
  @capsule = capsule
51
43
  @config = capsule
@@ -58,7 +50,7 @@ module Wurk
58
50
  # bubbles up so the swarm can drain.
59
51
  def global(jobstr, queue)
60
52
  yield
61
- rescue Handled, Wurk::Shutdown, StoreUnavailableAfterPerform
53
+ rescue Handled, Wurk::Shutdown
62
54
  raise
63
55
  rescue Exception => e # rubocop:disable Lint/RescueException
64
56
  raise Wurk::Shutdown if exception_caused_by_shutdown?(e)
@@ -79,7 +71,7 @@ module Wurk
79
71
  # circuit `global`'s rescue.
80
72
  def local(jobinst, jobstr, queue)
81
73
  yield
82
- rescue Handled, Wurk::Shutdown, StoreUnavailableAfterPerform
74
+ rescue Handled, Wurk::Shutdown
83
75
  raise
84
76
  rescue Exception => e # rubocop:disable Lint/RescueException
85
77
  raise Wurk::Shutdown if exception_caused_by_shutdown?(e)
@@ -3,6 +3,7 @@
3
3
  require_relative 'component'
4
4
  require_relative 'context'
5
5
  require_relative 'dead_set'
6
+ require_relative 'finished_job_cleanup'
6
7
  require_relative 'job_logger'
7
8
  require_relative 'job_retry'
8
9
  require_relative 'profiler'
@@ -41,40 +42,9 @@ module Wurk
41
42
  # escaping the retry layer comes from the payload itself (a `retry_count`
42
43
  # that is not a number, args that cannot be re-serialized into a retry) and
43
44
  # will fail the same way every time.
44
- TRANSIENT_FAILURES = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError,
45
- JobRetry::StoreUnavailableAfterPerform].freeze
45
+ TRANSIENT_FAILURES = [RedisClient::Error, ConnectionPool::Error, ConnectionPool::TimeoutError].freeze
46
46
  private_constant :TRANSIENT_FAILURES
47
47
 
48
- # Redis not answering, or answering that it is not serving yet. Narrower than
49
- # TRANSIENT_FAILURES on purpose: a refusal on the merits (WRONGTYPE, OOM)
50
- # after `perform` would refuse the re-run's bookkeeping too, so requeueing it
51
- # would re-run `perform` every REQUEUE_PAUSE for good.
52
- STORE_UNAVAILABLE = [RedisClient::ConnectionError, ConnectionPool::TimeoutError].freeze
53
- private_constant :STORE_UNAVAILABLE
54
- STORE_NOT_SERVING = /\A(?:LOADING|BUSY|TRYAGAIN|CLUSTERDOWN)\b/
55
- private_constant :STORE_NOT_SERVING
56
-
57
- # How many times one process puts a job back for an outage after `perform`
58
- # before the error goes to the retry policy after all. Unbounded, a write
59
- # that keeps failing while the requeue lands (a second Redis a middleware
60
- # talks to, a pool that stays exhausted) re-runs `perform` every
61
- # REQUEUE_PAUSE for good. Process-local: the payload carries no counter.
62
- STORE_REQUEUE_LIMIT = 3
63
- STORE_REQUEUE_JIDS = 10_000
64
- private_constant :STORE_REQUEUE_LIMIT, :STORE_REQUEUE_JIDS
65
- @store_requeues = {}
66
- @store_requeues_lock = ::Mutex.new
67
-
68
- # True while `jid` has requeues left; counts this one.
69
- def self.store_requeue?(jid)
70
- @store_requeues_lock.synchronize do
71
- count = @store_requeues.delete(jid).to_i + 1
72
- @store_requeues.shift while @store_requeues.size >= STORE_REQUEUE_JIDS
73
- @store_requeues[jid] = count
74
- count <= STORE_REQUEUE_LIMIT
75
- end
76
- end
77
-
78
48
  # Pause after putting a job back on an internal failure. The job goes to the
79
49
  # tail, which is the next fetch, so without one a failure that persists
80
50
  # re-runs `perform` as fast as the thread can loop.
@@ -143,6 +113,7 @@ module Wurk
143
113
  # Single iteration: fetch one UoW, process it. Public so tests can drive
144
114
  # the loop step-by-step without spawning a thread.
145
115
  def process_one
116
+ FinishedJobCleanup.drain
146
117
  @job = fetch
147
118
  process(@job) if @job
148
119
  @job = nil
@@ -276,6 +247,7 @@ module Wurk
276
247
  # `respond_to?` because a config[:fetch_class] fetcher need not defer, and
277
248
  # the capsule has no fetcher at all if the launcher died before prepare!.
278
249
  def flush_acks
250
+ FinishedJobCleanup.give_up
279
251
  fetcher = @capsule.fetcher
280
252
  fetcher.flush_pending_acks if fetcher.respond_to?(:flush_pending_acks)
281
253
  rescue StandardError => e
@@ -414,11 +386,7 @@ module Wurk
414
386
  # slot and simply ACKs — the counter then ages out on its 72h TTL.
415
387
  uow.jid = job_hash['jid'] if uow.respond_to?(:jid=)
416
388
 
417
- dispatch(job_hash, queue, jobstr) do |instance|
418
- Thread.handle_interrupt(ALLOW_SHUTDOWN_INTERRUPTS) do
419
- execute_job(instance, job_hash, queue)
420
- end
421
- end
389
+ dispatch(job_hash, queue, jobstr) { |instance| execute_job(instance, job_hash, queue) }
422
390
  end
423
391
 
424
392
  # Reported, never raised: this runs inside #process's ensure on the shutdown
@@ -483,23 +451,34 @@ module Wurk
483
451
  instance
484
452
  end
485
453
 
454
+ # Once `perform` has returned the job is done, whatever its unwind runs
455
+ # into. A Redis failure or a hard shutdown there must not run it again, at
456
+ # any retry setting: the job returns normally, so it is ACKed, and what it
457
+ # still owes Redis goes to FinishedJobCleanup. The rescues sit outside the
458
+ # interruptible scope, so a Shutdown cannot land between them and the ACK.
486
459
  def execute_job(instance, job_hash, queue)
487
460
  performed = false
488
- @capsule.server_middleware.invoke(instance, job_hash, queue) do
489
- result = instance.perform(*job_hash['args'])
490
- performed = true
491
- result
461
+ Thread.handle_interrupt(ALLOW_SHUTDOWN_INTERRUPTS) do
462
+ @capsule.server_middleware.invoke(instance, job_hash, queue) do
463
+ RedisPool.job_performing!
464
+ result = instance.perform(*job_hash['args'])
465
+ performed = true
466
+ result
467
+ end
492
468
  end
469
+ rescue Wurk::Shutdown => e
470
+ raise unless performed
471
+
472
+ settle_finished_job(job_hash, e)
493
473
  rescue StandardError => e
494
- raise unless performed && store_unavailable?(e) && self.class.store_requeue?(job_hash['jid'])
474
+ raise unless performed && FinishedJobCleanup.store_error?(e)
495
475
 
496
- raise JobRetry::StoreUnavailableAfterPerform, "Redis unavailable after perform returned: #{e.class}: #{e.message}"
476
+ settle_finished_job(job_hash, e)
497
477
  end
498
478
 
499
- def store_unavailable?(error)
500
- return true if STORE_UNAVAILABLE.any? { |klass| error.is_a?(klass) }
501
-
502
- error.is_a?(RedisClient::CommandError) && STORE_NOT_SERVING.match?(error.message.to_s)
479
+ def settle_finished_job(job_hash, error)
480
+ FinishedJobCleanup.settle(job_hash, error, pool: @capsule.redis_pool, config: @capsule.config)
481
+ nil
503
482
  end
504
483
 
505
484
  # Bookkeeping wrapper. Publishes the in-flight job to WORK_STATE so the
@@ -114,9 +114,19 @@ module Wurk
114
114
  # this — Sidekiq reaps on its 10s heartbeat.
115
115
  REAP_MAX_INTERVAL = 10.0
116
116
 
117
+ # Thread variable the Processor bumps as it enters `perform`. A middleware
118
+ # can run `perform` inside a checkout (sidekiq-unique-jobs does), and a
119
+ # replay of that block would run the job again, so it is never replayed.
120
+ PERFORM_COUNT = :wurk_perform_count
121
+
117
122
  attr_reader :size, :url, :name, :pool_timeout, :client_config, :redis_idle_timeout
118
123
 
119
124
  class << self
125
+ def job_performing!
126
+ thread = ::Thread.current
127
+ thread.thread_variable_set(PERFORM_COUNT, thread.thread_variable_get(PERFORM_COUNT).to_i + 1)
128
+ end
129
+
120
130
  # A redis-client middleware every pool built from now on carries, after
121
131
  # any the host configured. Set only by the boot of a command that must not
122
132
  # write Redis (Preflight::RedisGuard); nil everywhere else.
@@ -342,13 +352,16 @@ module Wurk
342
352
  # Runs the block on the checked-out `conn`, retrying transient RedisClient
343
353
  # errors in place: the same slot is reused across retries (redis-client
344
354
  # redials a closed socket lazily), so a busy fetcher can't leak checkouts.
345
- def run(conn, idempotent)
355
+ def run(conn, idempotent) # rubocop:disable Metrics/AbcSize
346
356
  attempts = 0
347
357
  odometer = conn.round_trips
358
+ performs = performs_on_this_thread
348
359
  begin
349
360
  attempts += 1
350
361
  yield conn
351
362
  rescue RedisClient::Error => e
363
+ raise if performs_on_this_thread != performs
364
+
352
365
  plan = retry_plan(e, attempts, idempotent, conn.round_trips != odometer)
353
366
  raise if plan == :propagate
354
367
 
@@ -363,6 +376,8 @@ module Wurk
363
376
  end
364
377
  end
365
378
 
379
+ def performs_on_this_thread = ::Thread.current.thread_variable_get(PERFORM_COUNT)
380
+
366
381
  # Pure classification of a RedisClient error against the attempt count, the
367
382
  # caller's apply-safety claim, and whether this attempt already completed a
368
383
  # round trip (`dirty`):
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require_relative '../keys'
5
+
6
+ module Wurk
7
+ module UniqueJobsCompat
8
+ # One read of every private list: the lock digests of the jobs in them.
9
+ #
10
+ # Any Redis error propagates, so a caller deciding what to delete deletes
11
+ # nothing. A list longer than a page is read in overlapping pages, because
12
+ # an ACK removing an entry shifts the rest toward the head: the overlap
13
+ # proves no entry slid past the read position, and ListMoved says it did.
14
+ class PrivateListDigests
15
+ class ListMoved < ::StandardError; end
16
+
17
+ Result = Struct.new(:digests, :unreadable)
18
+
19
+ MATCH = "#{Keys::QUEUE_PREFIX}*|*".freeze
20
+ SCAN_COUNT = 1000
21
+ PAGE = 1000
22
+ OVERLAP = 100
23
+ PIPELINE = 100
24
+ RUN_SUFFIX = ':RUN'
25
+ DIGEST_FIELDS = %w[lock_digest unique_digest].freeze
26
+
27
+ def initialize(page: PAGE, overlap: OVERLAP)
28
+ @page = page
29
+ @overlap = overlap
30
+ @result = Result.new(::Set.new, 0)
31
+ end
32
+
33
+ def call
34
+ private_lists.each_slice(PIPELINE) do |lists|
35
+ first_pages = Wurk.redis do |conn|
36
+ conn.pipelined { |pipe| lists.each { |list| pipe.call('LRANGE', list, 0, @page - 1) } }
37
+ end
38
+ lists.zip(first_pages) { |list, page| read_list(list, page) }
39
+ end
40
+ @result
41
+ end
42
+
43
+ private
44
+
45
+ def read_list(list, first_page)
46
+ collect(first_page)
47
+ previous = first_page
48
+ start = @page - @overlap
49
+ while previous.size == @page
50
+ page = read_page(list, start)
51
+ unless page.first(@overlap).intersect?(previous.last(@overlap))
52
+ raise ListMoved,
53
+ "#{list} moved past the read position"
54
+ end
55
+
56
+ collect(page)
57
+ previous = page
58
+ start += @page - @overlap
59
+ end
60
+ end
61
+
62
+ def read_page(list, start)
63
+ Wurk.redis { |conn| conn.call('LRANGE', list, start, start + @page - 1) }
64
+ end
65
+
66
+ def collect(payloads)
67
+ payloads.each { |payload| collect_payload(payload) }
68
+ end
69
+
70
+ def collect_payload(payload)
71
+ job = parse(payload)
72
+ return collect_unreadable(payload) unless job.is_a?(::Hash)
73
+
74
+ DIGEST_FIELDS.each { |field| add(job[field]) if job[field].is_a?(::String) }
75
+ end
76
+
77
+ # No way to tell which lock it holds, so every quoted string in it counts.
78
+ def collect_unreadable(payload)
79
+ @result.unreadable += 1
80
+ payload.b.split('"').each { |token| add(token) }
81
+ end
82
+
83
+ def add(digest)
84
+ @result.digests << digest.delete_suffix(RUN_SUFFIX)
85
+ end
86
+
87
+ def parse(payload)
88
+ Wurk.load_json(payload)
89
+ rescue ::JSON::ParserError, ::EncodingError
90
+ nil
91
+ end
92
+
93
+ def private_lists
94
+ public_queues = Wurk.redis { |conn| conn.call('SMEMBERS', Keys::QUEUES_SET) }.to_set
95
+ scan_lists.select { |key| private_list?(key, public_queues) }
96
+ end
97
+
98
+ # Parsed by each reading on its own: a key that reads as both is one the
99
+ # fetcher refuses to reclaim, and the job in it is real.
100
+ def private_list?(key, public_queues)
101
+ return false unless key.valid_encoding?
102
+ return false if public_queues.include?(key.delete_prefix(Keys::QUEUE_PREFIX))
103
+
104
+ !(Fetcher::PrivateListKey.parse_pro(key) || Fetcher::PrivateListKey.parse_wurk(key)).nil?
105
+ end
106
+
107
+ def scan_lists
108
+ cursor = '0'
109
+ keys = []
110
+ loop do
111
+ cursor, batch = Wurk.redis do |conn|
112
+ conn.call('SCAN', cursor, 'MATCH', MATCH, 'COUNT', SCAN_COUNT, 'TYPE', 'list')
113
+ end
114
+ keys.concat(batch)
115
+ break if cursor == '0'
116
+ end
117
+ keys.uniq
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'keys'
4
+ require_relative 'unique_jobs_compat/private_list_digests'
5
+
6
+ module Wurk
7
+ # Two corrections to sidekiq-unique-jobs, applied when a server boots with the
8
+ # gem loaded. The gem cannot see what only the reliable fetcher knows.
9
+ module UniqueJobsCompat
10
+ RUN_SUFFIX = ':RUN'
11
+ OOM = /\AOOM\b|\bout of memory\b/i
12
+ VERSION_KEY = 'uniquejobs:live'
13
+
14
+ # RubyReaper reads public queues, the retry and schedule sets and live
15
+ # workers. A job in a dead worker's private list is in none of them until it
16
+ # is reclaimed, so its lock read as orphaned and was deleted, and a duplicate
17
+ # ran beside the recovery.
18
+ #
19
+ # The lists are read once before the gem classifies its digests and once
20
+ # after, so a run costs O(digests + jobs). Both reads are needed: a job
21
+ # fetched after the gem looked at its public queue is only in the second, and
22
+ # one reclaimed back to its queue after that look is only in the first. A
23
+ # failed read raises here, ahead of the gem's delete.
24
+ module PrivateListsAreLive
25
+ def orphans
26
+ before = PrivateListDigests.new.call
27
+ candidates = super
28
+ after = PrivateListDigests.new.call
29
+ UniqueJobsCompat.report_unreadable([before.unreadable, after.unreadable].max)
30
+ candidates.reject do |digest|
31
+ base = digest.delete_suffix(RUN_SUFFIX)
32
+ before.digests.include?(base) || after.digests.include?(base)
33
+ end
34
+ end
35
+ end
36
+
37
+ # The gem writes its version at boot, for upgrades it has not built yet, and
38
+ # a refusal there stops the worker. At `maxmemory` that is a crash loop with
39
+ # nothing draining the queues. Only this write is forgiven: a lock write
40
+ # refused by OOM still raises.
41
+ module VersionWriteIsOptional
42
+ def call
43
+ super
44
+ rescue StandardError => e # the gem wraps a script's error in its own class
45
+ raise unless OOM.match?(e.message.to_s)
46
+
47
+ Wurk.logger.error do
48
+ "sidekiq-unique-jobs: Redis is at maxmemory, so #{VERSION_KEY} was not set to " \
49
+ "#{UniqueJobsCompat.gem_version}. Booting anyway; locks are unaffected. (#{e.message})"
50
+ end
51
+ false
52
+ end
53
+ end
54
+
55
+ class << self
56
+ def install
57
+ return unless defined?(::SidekiqUniqueJobs::Orphans::RubyReaper) && defined?(::SidekiqUniqueJobs::UpdateVersion)
58
+
59
+ guard_reaper(::SidekiqUniqueJobs::Orphans::RubyReaper)
60
+ ::SidekiqUniqueJobs::UpdateVersion.singleton_class.prepend(VersionWriteIsOptional)
61
+ true
62
+ end
63
+
64
+ def guard_reaper(reaper)
65
+ return reaper.prepend(PrivateListsAreLive) if reaper.method_defined?(:orphans)
66
+
67
+ Wurk.logger.error do
68
+ "sidekiq-unique-jobs #{gem_version} has no RubyReaper#orphans, so its reaper can delete the lock of a " \
69
+ 'job in a private list. Set `config.reaper = :none` or use a supported version.'
70
+ end
71
+ end
72
+
73
+ def report_unreadable(count)
74
+ return unless count.positive?
75
+
76
+ Wurk.logger.warn do
77
+ "sidekiq-unique-jobs reaper: #{count} unreadable payload(s) in private lists; " \
78
+ 'every lock they name was kept.'
79
+ end
80
+ end
81
+
82
+ def gem_version
83
+ defined?(::SidekiqUniqueJobs::VERSION) ? ::SidekiqUniqueJobs::VERSION : 'unknown'
84
+ end
85
+ end
86
+ end
87
+ end
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.17.0'
4
+ VERSION = '1.17.1'
5
5
  end
data/lib/wurk.rb CHANGED
@@ -56,6 +56,7 @@ require_relative 'wurk/batch/status'
56
56
  require_relative 'wurk/batch_set'
57
57
  require_relative 'wurk/limiter'
58
58
  require_relative 'wurk/unique'
59
+ require_relative 'wurk/unique_jobs_compat'
59
60
  require_relative 'wurk/debounce'
60
61
  require_relative 'wurk/throttle'
61
62
  require_relative 'wurk/queue_slot'
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.17.0",
3
- "timestamp": "2026-11-19T18:03:18.925Z"
2
+ "version": "1.17.1",
3
+ "timestamp": "2026-11-22T05:17:51.045Z"
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.17.0
4
+ version: 1.17.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - developerz.ai
@@ -277,6 +277,7 @@ files:
277
277
  - lib/wurk/fetcher/self_reconcile.rb
278
278
  - lib/wurk/fetcher/unit_of_work.rb
279
279
  - lib/wurk/fetcher/unparseable_keys.rb
280
+ - lib/wurk/finished_job_cleanup.rb
280
281
  - lib/wurk/flow.rb
281
282
  - lib/wurk/flow/builder.rb
282
283
  - lib/wurk/flow/chain.rb
@@ -444,6 +445,8 @@ files:
444
445
  - lib/wurk/topology.rb
445
446
  - lib/wurk/transaction_aware_client.rb
446
447
  - lib/wurk/unique.rb
448
+ - lib/wurk/unique_jobs_compat.rb
449
+ - lib/wurk/unique_jobs_compat/private_list_digests.rb
447
450
  - lib/wurk/version.rb
448
451
  - lib/wurk/watchdog.rb
449
452
  - lib/wurk/web.rb