pgbus 0.27.2 → 1.0.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.
@@ -0,0 +1,305 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module ActiveJob
5
+ # A unit of work's enqueues, held at the adapter and sent together when
6
+ # the unit ends (issue #682): one send_batch per (queue, priority, delay) group
7
+ # instead of one send per perform_later. Opened by Pgbus.coalesce and the
8
+ # Rack Middleware.
9
+ #
10
+ # Only a bulk-eligible job is held (Adapter#enqueue / #enqueue_at
11
+ # decide), serialized at perform_later; a future one with its scheduled
12
+ # time, so its delay is what is left at the flush (issue #686). One with
13
+ # uniqueness or concurrency, a retry re-enqueue, a deploy task run's job,
14
+ # a batch member outside its own batch's scope or a Workflow::StepJob
15
+ # goes out at once, as it does outside a scope. Active Job's enqueue_after_transaction_commit runs before the
16
+ # adapter, so a job that defers reaches the buffer at commit, and a rolled
17
+ # back one never does.
18
+ #
19
+ # perform_later inside the scope returns the job with successfully_enqueued
20
+ # true and provider_job_id nil until the flush, the same optimistic answer
21
+ # Active Job gives a job deferred to after commit. The flush proves the
22
+ # delivery: Adapter#deliver_coalesced sends the buffer in bulk, retries
23
+ # every job it left unsent on its own, and what still fails goes to
24
+ # on_failure (:raise, :report, or a callable taking (jobs, error)).
25
+ #
26
+ # The scope is fiber-local (Thread.current, like the batch tag) and
27
+ # cleared before the flush starts, so a job enqueued on another thread or
28
+ # fiber, during the flush, or after the block, goes out at once. A nested
29
+ # scope joins the outer one, whose on_failure applies; only the outermost
30
+ # flushes.
31
+ #
32
+ # A batch scope (issue #683, opened by Pgbus.batch for a batch it builds,
33
+ # with +batch_id+ and +count_in+) holds only that batch's members and
34
+ # joins nothing: it replaces the current scope for the block, flushes
35
+ # when the block ends and puts the outer scope back. A plain scope opened
36
+ # inside it joins it. A batch scope counts each chunk in before sending
37
+ # it, with one call: count_in.call(payloads, final:). The final call
38
+ # (the block's end) also closes the batch's build, in the same
39
+ # transaction; see Batch#count_in. Before on_failure, a batch scope hands
40
+ # the jobs that were never sent to on_failed (Batch#record_enqueue_failures),
41
+ # so the batch counts them as failed. Every scope flushes early each
42
+ # config.coalesce_chunk_size held jobs, so a huge block stays bounded in
43
+ # memory (a batch scope only once no transaction is open on the batch's
44
+ # connection: until then it keeps holding); on_failure still runs once,
45
+ # at the end, for every chunk.
46
+ class Coalesce
47
+ KEY = :pgbus_coalesce
48
+ FAILURE_MODES = %i[raise report].freeze
49
+
50
+ Result = Data.define(:buffered, :sent, :retried, :failed, :error)
51
+
52
+ class << self
53
+ # The scope open on this thread or fiber, nil when there is none.
54
+ def current
55
+ Thread.current[KEY]
56
+ end
57
+
58
+ def open(on_failure: :raise, batch_id: nil, count_in: nil, on_failed: nil, &block)
59
+ raise ArgumentError, "Pgbus.coalesce needs a block" unless block
60
+
61
+ validate_on_failure!(on_failure)
62
+ return yield if current && batch_id.nil?
63
+
64
+ run(new(on_failure: on_failure, batch_id: batch_id, count_in: count_in, on_failed: on_failed), &block)
65
+ end
66
+
67
+ def validate_on_failure!(on_failure)
68
+ return if FAILURE_MODES.include?(on_failure) || on_failure.respond_to?(:call)
69
+
70
+ raise ArgumentError, "on_failure must be :raise, :report or a callable, got #{on_failure.inspect}"
71
+ end
72
+
73
+ private
74
+
75
+ def run(scope)
76
+ outer = current
77
+ Thread.current[KEY] = scope
78
+ error = nil
79
+ begin
80
+ yield
81
+ rescue Exception => e # rubocop:disable Lint/RescueException
82
+ error = e
83
+ raise
84
+ ensure
85
+ # No scope is current while this one flushes: an enqueue then
86
+ # goes out at once. The outer scope comes back afterwards.
87
+ Thread.current[KEY] = nil
88
+ begin
89
+ scope.finish!(block_error: error)
90
+ ensure
91
+ Thread.current[KEY] = outer
92
+ end
93
+ end
94
+ end
95
+ end
96
+
97
+ attr_reader :on_failure, :batch_id
98
+
99
+ def initialize(on_failure: :raise, batch_id: nil, count_in: nil, on_failed: nil,
100
+ chunk_size: Pgbus.configuration.coalesce_chunk_size)
101
+ @on_failure = on_failure
102
+ @batch_id = batch_id
103
+ @count_in = count_in
104
+ @on_failed = on_failed
105
+ @chunk_size = chunk_size
106
+ @mutex = Mutex.new
107
+ @entries = []
108
+ @totals = Result.new(buffered: 0, sent: 0, retried: 0, failed: [], error: nil)
109
+ @failed_entries = []
110
+ @closed = false
111
+ end
112
+
113
+ # Holds +job+ for +adapter+ with the +payload+ serialized at
114
+ # perform_later, and sends the buffer once it holds a chunk. Returns
115
+ # false once the flush has started: the caller sends it itself.
116
+ # +due_at+: the time a future job is due (enqueue_at, issue #686); the
117
+ # flush works its delay out from it.
118
+ def push(adapter, job, payload, due_at = nil) # rubocop:disable Naming/PredicateMethod -- holds; the result says whether
119
+ chunk = @mutex.synchronize do
120
+ return false if @closed
121
+
122
+ # A full chunk goes when the next job arrives, so a block of
123
+ # exactly chunk_size jobs is still one flush, at its end. A batch
124
+ # scope keeps holding while a transaction is open on the batch's
125
+ # connection: a chunk counted in there and sent on PGMQ's own
126
+ # connection would lose its count, not its messages, on a rollback.
127
+ full = drain if @entries.size >= @chunk_size && !hold_for_transaction?
128
+ @entries << [adapter, job, payload, due_at]
129
+ full
130
+ end
131
+ deliver_chunk(chunk) if chunk
132
+ true
133
+ end
134
+
135
+ # Closes the buffer, sends it, then applies on_failure to whatever could
136
+ # not be sent. With +block_error+ (the block raised) a callable still
137
+ # gets the jobs, but nothing raises: :raise becomes a report, and a
138
+ # callable that raises is reported, so the block's error propagates.
139
+ def finish!(block_error: nil)
140
+ started = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
141
+ deliver_chunk(close, final: true)
142
+ failed_entries, result = @mutex.synchronize { [@failed_entries, @totals] }
143
+ instrument(result, started) if result.buffered.positive?
144
+ if result.failed.any?
145
+ @on_failed&.call(result.failed)
146
+ handle_failure(result, failed_entries, block_error)
147
+ end
148
+ result
149
+ rescue StandardError => e
150
+ # The block's error is the one that propagates: anything the flush
151
+ # raises after it (a notification subscriber, say) is reported.
152
+ raise unless block_error
153
+
154
+ ErrorReporter.report(e, { pgbus_coalesce: :finish })
155
+ result
156
+ end
157
+
158
+ private
159
+
160
+ def close
161
+ @mutex.synchronize do
162
+ @closed = true
163
+ drain
164
+ end
165
+ end
166
+
167
+ # Takes the buffer; the caller holds the mutex.
168
+ def drain
169
+ entries = @entries
170
+ @entries = []
171
+ entries
172
+ end
173
+
174
+ # Sends +entries+ now and keeps their result for finish!. A batch
175
+ # scope counts them in first (count_in); the final chunk also closes
176
+ # the batch's build, so it runs even when the chunk is empty.
177
+ def deliver_chunk(entries, final: false)
178
+ counted = count_chunk_in(entries, final)
179
+ return if entries.empty?
180
+
181
+ results = entries.group_by(&:first).map do |adapter, group|
182
+ adapter.deliver_coalesced(group.map { |_, job, payload, due_at| [job, payload, due_at] }, counted: counted)
183
+ end
184
+ result = combine(entries.size, results)
185
+ failed = result.failed.to_set(&:object_id)
186
+ # Only the counts and the failed jobs are kept: a sent chunk's jobs
187
+ # and payloads go, so chunking bounds memory.
188
+ @mutex.synchronize do
189
+ @totals = combine(@totals.buffered + result.buffered, [@totals, result])
190
+ @failed_entries.concat(entries.select { |_, job, _| failed.include?(job.object_id) })
191
+ end
192
+ end
193
+
194
+ def hold_for_transaction?
195
+ return false unless @count_in
196
+
197
+ connection = Pgbus::BatchEntry.connection_pool.active_connection?
198
+ connection ? connection.transaction_open? : false
199
+ rescue StandardError => e
200
+ # Unknown is treated as open: holding a chunk to the block's end is
201
+ # safe, counting it inside a transaction that rolls back is not.
202
+ Pgbus.logger.debug { "[Pgbus] Coalesce could not read the batch connection's transaction (#{e.class}); holding the chunk" }
203
+ true
204
+ end
205
+
206
+ # True when the chunk was counted in. A count that fails (a batch the
207
+ # sweep reaped, a database error) sends nothing: every job of the chunk
208
+ # fails, with that error, through on_failure.
209
+ def count_chunk_in(entries, final)
210
+ return false unless @count_in
211
+
212
+ @count_in.call(entries.map { |_, _, payload, _| payload }, final: final)
213
+ true
214
+ rescue StandardError => e
215
+ raise if entries.empty?
216
+
217
+ jobs = entries.map { |_, job, _| job }
218
+ jobs.each { |job| job.successfully_enqueued = false }
219
+ @mutex.synchronize do
220
+ failed = Result.new(buffered: entries.size, sent: 0, retried: 0, failed: jobs, error: e)
221
+ @totals = combine(@totals.buffered + entries.size, [@totals, failed])
222
+ @failed_entries.concat(entries)
223
+ end
224
+ entries.clear
225
+ false
226
+ end
227
+
228
+ # The held jobs this scope still references, waiting for the flush or
229
+ # failed in it.
230
+ def retained_entries
231
+ @mutex.synchronize { @entries + @failed_entries }
232
+ end
233
+
234
+ def combine(buffered, results)
235
+ Result.new(
236
+ buffered: buffered,
237
+ sent: results.sum(&:sent), retried: results.sum(&:retried),
238
+ failed: results.flat_map(&:failed), error: results.filter_map(&:error).last
239
+ )
240
+ end
241
+
242
+ # A subscriber that raises is reported: the flush's outcome, and the
243
+ # failed jobs on_failure must still see, do not depend on it.
244
+ def instrument(result, started)
245
+ duration = (::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - started) * 1000.0
246
+ Instrumentation.instrument(
247
+ "pgbus.coalesce",
248
+ buffered: result.buffered, sent: result.sent, retried: result.retried,
249
+ failed: result.failed.size, duration: duration
250
+ )
251
+ rescue StandardError => e
252
+ ErrorReporter.report(e, { pgbus_coalesce: :instrument })
253
+ end
254
+
255
+ def handle_failure(result, entries, block_error)
256
+ error = failure_error(result)
257
+ payloads = failed_payloads(result.failed, entries)
258
+ case on_failure
259
+ when :raise then block_error ? report(payloads, error) : raise(error)
260
+ when :report then report(payloads, error)
261
+ else call_on_failure(result.failed, payloads, error, block_error)
262
+ end
263
+ end
264
+
265
+ def call_on_failure(jobs, payloads, error, block_error)
266
+ on_failure.call(jobs, error)
267
+ rescue StandardError => e
268
+ raise unless block_error
269
+
270
+ report(payloads, error)
271
+ ErrorReporter.report(e, { pgbus_coalesce_on_failure: on_failure.to_s })
272
+ end
273
+
274
+ # The payloads serialized at perform_later: a job that failed is never
275
+ # serialized again here.
276
+ def failed_payloads(jobs, entries)
277
+ failed = jobs.to_set(&:object_id)
278
+ entries.filter_map { |_, job, payload| payload if failed.include?(job.object_id) }
279
+ end
280
+
281
+ def failure_error(result)
282
+ names = result.failed.map { |job| "#{job.class.name} (#{job.job_id})" }
283
+ message = "Pgbus.coalesce could not enqueue #{names.size} job(s): #{names.join(", ")}"
284
+ message += " — #{result.error.class}: #{result.error.message}" if result.error
285
+ # Raised and rescued here so the error carries a backtrace and the
286
+ # send's own error as its cause.
287
+ begin
288
+ raise EnqueueError, message, cause: result.error
289
+ rescue EnqueueError => e
290
+ e
291
+ end
292
+ end
293
+
294
+ def report(payloads, error)
295
+ context = { pgbus_coalesce: payloads }
296
+ if defined?(::Rails) && ::Rails.respond_to?(:error)
297
+ Pgbus.logger.error { "[Pgbus] #{error.message}" }
298
+ ::Rails.error.report(error, context: context)
299
+ else
300
+ ErrorReporter.report(error, context)
301
+ end
302
+ end
303
+ end
304
+ end
305
+ end
@@ -43,7 +43,7 @@ module Pgbus
43
43
 
44
44
  def on_failure(job = nil, &) = set_callback(:on_failure, job, &)
45
45
 
46
- # Deprecated alias of #on_complete until 1.0.
46
+ # Deprecated alias of #on_complete, kept past 1.0; removed in 2.0.
47
47
  def on_finish(job = nil, &)
48
48
  Batch.warn_on_finish_deprecated
49
49
  set_callback(:on_complete, job, &)
@@ -14,8 +14,9 @@ module Pgbus
14
14
  return unless Batch.executions_migrated?
15
15
 
16
16
  payload = { stale_executions: 0, orphan_rows: 0, started_batches: 0, finished_batches: 0,
17
- stalled_for: stalled_for }
17
+ abandoned_builds: 0, stalled_for: stalled_for }
18
18
  Instrumentation.instrument("pgbus.batch_sweep", payload) do |p|
19
+ p[:abandoned_builds] = reap_abandoned_builds(batch_size: batch_size)
19
20
  p[:stale_executions] = sweep_stale_executions(batch_size: batch_size, client: client, stalled_for: stalled_for)
20
21
  p[:orphan_rows] = sweep_orphan_rows(stalled_for: stalled_for, batch_size: batch_size, client: client)
21
22
  p[:started_batches] = start_stalled_pending(stalled_for: stalled_for, batch_size: batch_size)
@@ -23,6 +24,46 @@ module Pgbus
23
24
  end
24
25
  end
25
26
 
27
+ # A building batch (issue #683) is reaped only when the process that
28
+ # builds it is dead: its pgbus_processes row is gone or has not
29
+ # heartbeat within Process::Heartbeat::ALIVE_THRESHOLD. A live
30
+ # owner's build is never touched, however long its block runs. One
31
+ # guarded statement per batch (status = 'building'), so the reaper
32
+ # and a block closing its build cannot both win.
33
+ #
34
+ # The abandoned build counts as one failed job (total_jobs and
35
+ # failed_jobs both + 1): whatever its block held was never sent, so
36
+ # the batch must not report success. It moves to processing; the
37
+ # members it did send still resolve, and the batch then finishes
38
+ # through the usual single-winner path, firing on_complete and
39
+ # on_failure, never on_success.
40
+ def reap_abandoned_builds(batch_size: 500, now: Time.current)
41
+ return 0 unless Batch.owner_migrated?
42
+
43
+ alive_since = now - Process::Heartbeat::ALIVE_THRESHOLD
44
+ reaped = BatchEntry.connection_pool.with_connection do |conn|
45
+ conn.exec_query(<<~SQL.squish, "Pgbus Batch Reap Build", [alive_since, batch_size]).rows.flatten
46
+ UPDATE #{BatchEntry.table_name} b
47
+ SET status = 'processing', total_jobs = b.total_jobs + 1, failed_jobs = b.failed_jobs + 1
48
+ WHERE b.id IN (
49
+ SELECT c.id FROM #{BatchEntry.table_name} c
50
+ WHERE c.status = 'building'
51
+ AND NOT EXISTS (
52
+ SELECT 1 FROM #{ProcessEntry.table_name} p
53
+ WHERE p.id = c.owner_process_id AND p.last_heartbeat_at >= $1
54
+ )
55
+ LIMIT $2
56
+ ) AND b.status = 'building'
57
+ RETURNING b.batch_id
58
+ SQL
59
+ end
60
+ reaped.each do |batch_id|
61
+ Pgbus.logger.warn { "[Pgbus] Batch #{batch_id} was being built by a process that stopped heartbeating; reaped" }
62
+ Batch.send(:finish_if_needed, Batch.try_finish!(batch_id))
63
+ end
64
+ reaped.size
65
+ end
66
+
26
67
  private
27
68
 
28
69
  def sweep_stale_executions(batch_size:, client:, stalled_for:)
data/lib/pgbus/batch.rb CHANGED
@@ -22,7 +22,7 @@ module Pgbus
22
22
  VALID_CONFLICTS = %i[reject discard log].freeze
23
23
 
24
24
  # The callback slots, each mapped to the prefix of its pgbus_batches
25
- # columns. on_complete keeps the on_finish_* columns until the 1.0 schema
25
+ # columns. on_complete keeps the on_finish_* columns until the 2.0 schema
26
26
  # cleanup, so rows written before the rename still fire.
27
27
  CALLBACK_COLUMNS = { on_complete: "on_finish", on_success: "on_success", on_failure: "on_failure" }.freeze
28
28
 
@@ -30,17 +30,15 @@ module Pgbus
30
30
  :on_complete, :on_success, :on_failure,
31
31
  :uniqueness_key, :on_conflict
32
32
 
33
- # Deprecated alias of #on_complete until 1.0.
33
+ # Deprecated alias of #on_complete, kept past 1.0 for the callers that
34
+ # still pass it; removed in 2.0.
34
35
  def on_finish = on_complete
35
36
 
36
- def on_discard
37
- on_failure
38
- end
39
-
40
37
  # Open a batch, yield a Pgbus::Batch::Builder, and start the batch when
41
38
  # the block returns. Every job the block enqueues (through +b.add+ or a
42
- # plain +perform_later+) joins the batch, which stays pending, and so
43
- # cannot finish, until the block is done. Keywords go to Batch.new.
39
+ # plain +perform_later+) joins the batch, which stays building (in a
40
+ # pgbus process, issue #683) or pending, and so cannot finish, until the
41
+ # block is done. Keywords go to Batch.new.
44
42
  # Membership is the block's own thread or fiber (the tag lives in
45
43
  # Thread.current): b.add raises anywhere else, and a plain perform_later
46
44
  # from a thread or fiber the block spawns does not join the batch.
@@ -81,29 +79,31 @@ module Pgbus
81
79
  # this key may exist; see #enqueue for what happens to the next one
82
80
  # @param on_conflict [Symbol] :reject (raise AlreadyRunning), :discard
83
81
  # (skip the block silently) or :log (skip the block, warn)
84
- def initialize(on_complete: nil, on_finish: nil, on_success: nil, on_discard: nil, on_failure: nil,
85
- description: nil, properties: {}, uniqueness_key: nil, on_conflict: :reject)
86
- raise ArgumentError, "pass on_failure: only — on_discard: is a deprecated alias" if on_discard && on_failure
82
+ # @param on_enqueue_failure [Symbol, #call] what happens to a member the
83
+ # block's coalesce scope (issue #683) could not send: :raise (default,
84
+ # Pgbus::EnqueueError), :report, or a callable taking (jobs, error).
85
+ # Distinct from on_failure:, the callback fired when a member fails.
86
+ def initialize(on_complete: nil, on_finish: nil, on_success: nil, on_failure: nil,
87
+ description: nil, properties: {}, uniqueness_key: nil, on_conflict: :reject,
88
+ on_enqueue_failure: :raise)
87
89
  raise ArgumentError, "pass on_complete: only — on_finish: is a deprecated alias" if on_finish && on_complete
88
90
  unless VALID_CONFLICTS.include?(on_conflict)
89
91
  raise ArgumentError, "on_conflict must be one of #{VALID_CONFLICTS.join(", ")}, got #{on_conflict.inspect}"
90
92
  end
91
93
 
92
- if on_discard
93
- Pgbus.logger.warn do
94
- "[Pgbus] Batch on_discard: is deprecated and will be removed in 1.0 — use on_failure: instead"
95
- end
96
- end
94
+ Pgbus::ActiveJob::Coalesce.validate_on_failure!(on_enqueue_failure)
95
+
97
96
  self.class.warn_on_finish_deprecated if on_finish
98
97
 
99
98
  @batch_id = SecureRandom.uuid
100
99
  @on_complete = on_complete || on_finish
101
100
  @on_success = on_success
102
- @on_failure = on_failure || on_discard
101
+ @on_failure = on_failure
103
102
  @description = description
104
103
  @properties = properties
105
104
  @uniqueness_key = uniqueness_key&.to_s
106
105
  @on_conflict = on_conflict
106
+ @on_enqueue_failure = on_enqueue_failure
107
107
  @discarded = false
108
108
  @started = false
109
109
  end
@@ -130,13 +130,25 @@ module Pgbus
130
130
  return self unless acquire_lock!
131
131
 
132
132
  begin
133
+ @owner = self.class.building_owner
133
134
  create_record
134
135
  rescue StandardError
135
136
  self.class.release_lock(batch_id)
136
137
  raise
137
138
  end
138
139
  @started = true
139
- count_jobs(&)
140
+ if @owner
141
+ # Built (issue #683): the block runs with the batch "building", so no
142
+ # sweep and no finish can touch it, and its perform_later calls are
143
+ # held in a scope of the batch's own and counted in per chunk. The
144
+ # last count closes the build (count_in), before anything is sent.
145
+ count_jobs do
146
+ Pgbus::ActiveJob::Coalesce.open(on_failure: @on_enqueue_failure, batch_id: batch_id,
147
+ count_in: method(:count_in), on_failed: method(:record_enqueue_failures), &)
148
+ end
149
+ else
150
+ count_jobs(&)
151
+ end
140
152
  self.class.send(:after_transactions_commit) { start_processing }
141
153
  self
142
154
  end
@@ -296,7 +308,7 @@ module Pgbus
296
308
  return unless first
297
309
 
298
310
  Pgbus.logger.warn do
299
- "[Pgbus] Batch on_finish is deprecated and will be removed in 1.0 — use on_complete instead"
311
+ "[Pgbus] Batch on_finish is deprecated and will be removed in 2.0 — use on_complete instead"
300
312
  end
301
313
  end
302
314
 
@@ -327,6 +339,7 @@ module Pgbus
327
339
  @schema_lock.synchronize do
328
340
  @executions_migrated = nil
329
341
  @callback_jobs_migrated = nil
342
+ @owner_migrated = nil
330
343
  @warned_callback_jobs_unmigrated = nil
331
344
  @warned_on_finish = nil
332
345
  end
@@ -347,6 +360,31 @@ module Pgbus
347
360
  result
348
361
  end
349
362
 
363
+ # True once pgbus_batches.owner_process_id exists (issue #683,
364
+ # pgbus:add_batch_owner): a batch can then be built (status "building")
365
+ # by a process the sweep can watch.
366
+ def self.owner_migrated?
367
+ return true if @schema_lock.synchronize { @owner_migrated }
368
+
369
+ result = begin
370
+ BatchEntry.column_names.include?("owner_process_id")
371
+ rescue StandardError
372
+ false
373
+ end
374
+ @schema_lock.synchronize { @owner_migrated = true } if result
375
+ result
376
+ end
377
+
378
+ # The process that builds a batch opened now, or nil when the batch is
379
+ # not built (issue #683): the pgbus_processes row this process
380
+ # heartbeats under. A process without one (a web server, a console, a
381
+ # rake task) has nothing whose death the sweep can see, so its batches
382
+ # take the pending path and enqueue their members one at a time.
383
+ def self.building_owner
384
+ owner = Process::Heartbeat.current_process_id
385
+ owner if owner && executions_migrated? && owner_migrated?
386
+ end
387
+
350
388
  # Count tagged payloads into their batch and insert their execution rows,
351
389
  # in ONE transaction, BEFORE any message is sent (issue #423). Every
352
390
  # commit point keeps the invariant
@@ -354,7 +392,7 @@ module Pgbus
354
392
  # which is what lets a finish never race an add: the guarded increment
355
393
  # raises AlreadyFinished here — at perform_later, before send — when the
356
394
  # batch has already finished. Pass an Array to count a bulk send once.
357
- def self.track_enqueue(payloads)
395
+ def self.track_enqueue(payloads, statuses: BatchEntry::UNFINISHED)
358
396
  payloads = payloads.is_a?(Hash) ? [payloads] : Array(payloads)
359
397
  batch_id = payloads.first&.fetch(METADATA_KEY, nil)
360
398
  return if payloads.empty? || batch_id.nil?
@@ -364,15 +402,12 @@ module Pgbus
364
402
  # list through the connection.
365
403
  migrated = executions_migrated?
366
404
  BatchEntry.transaction do
367
- BatchEntry.increment_total_jobs!(batch_id, payloads.size)
405
+ BatchEntry.increment_total_jobs!(batch_id, payloads.size, statuses: statuses)
368
406
  next unless migrated
369
407
 
370
- payloads.each do |payload|
371
- job_id = payload["job_id"]
372
- next unless job_id
373
-
374
- BatchExecution.insert_for!(batch_id: batch_id, job_id: job_id, queue_name: payload["queue_name"])
375
- end
408
+ # One multi-row INSERT for the whole bulk (issue #683).
409
+ rows = payloads.filter_map { |payload| [payload["job_id"], payload["queue_name"]] if payload["job_id"] }
410
+ BatchExecution.insert_all_for!(batch_id: batch_id, rows: rows)
376
411
  end
377
412
  end
378
413
  end
@@ -436,6 +471,38 @@ module Pgbus
436
471
  end
437
472
  end
438
473
 
474
+ # untrack_enqueue for every payload of a failed bulk send (issue #683):
475
+ # per batch, one decrement by the count and one DELETE.
476
+ def self.untrack_enqueue_all(payloads)
477
+ payloads.select { |payload| payload[METADATA_KEY] }.group_by { |payload| payload[METADATA_KEY] }
478
+ .each do |batch_id, members|
479
+ BatchEntry.connection_pool.with_connection do
480
+ migrated = executions_migrated?
481
+ BatchEntry.transaction do
482
+ BatchEntry.decrement_total_jobs!(batch_id, members.size)
483
+ BatchExecution.delete_all_for!(members.filter_map { |payload| payload["job_id"] }) if migrated
484
+ end
485
+ end
486
+ end
487
+ end
488
+
489
+ # backfill_execution for a whole send group, in one UPDATE (issue #683).
490
+ # The messages are live, so a failure is logged, never raised: the rows
491
+ # keep their logical queue_name, which is what the stalled-execution sweep
492
+ # probes before the msg_id lands.
493
+ def self.backfill_executions(payloads, msg_ids, queue_name)
494
+ rows = payloads.zip(msg_ids).filter_map do |payload, msg_id|
495
+ [payload["job_id"], msg_id, queue_name] if payload[METADATA_KEY] && payload["job_id"] && msg_id
496
+ end
497
+ return if rows.empty?
498
+ return unless execution_rows_migrated_softly?
499
+
500
+ BatchExecution.backfill_all!(rows)
501
+ rescue StandardError => e
502
+ Pgbus.logger.warn { "[Pgbus] Batch execution backfill failed for #{rows&.size} job(s): #{e.class}: #{e.message}" }
503
+ nil
504
+ end
505
+
439
506
  def self.backfill_execution(payload, msg_id, queue_name)
440
507
  return unless payload && msg_id
441
508
  # Only batch members have an execution row: without this, every plain
@@ -708,13 +775,65 @@ module Pgbus
708
775
  self
709
776
  end
710
777
 
778
+ # The batch scope's count (issue #683): each chunk of held members is
779
+ # counted in before it is sent; the last one, at the block's end, also
780
+ # closes the build, building -> pending, in the same transaction, so the
781
+ # batch can finish only once every held member is counted. Raises
782
+ # AlreadyFinished when the build is no longer open (the sweep reaped it
783
+ # because its process stopped heartbeating).
784
+ #
785
+ # A chunk before the last counts only into a batch still building: one
786
+ # the sweep reaped (its owner looked dead) takes no more members. When
787
+ # the closing transaction fails, the build is closed on its own: the
788
+ # chunk was neither counted nor sent, so the counts stay right, and a
789
+ # pending batch is one the sweep can start, where a building one would
790
+ # wait for its owner to die.
791
+ def count_in(payloads, final:)
792
+ return self.class.track_enqueue(payloads, statuses: %w[building]) unless final
793
+
794
+ begin
795
+ BatchEntry.connection_pool.with_connection do
796
+ BatchEntry.transaction do
797
+ BatchEntry.close_build!(batch_id)
798
+ self.class.track_enqueue(payloads) if payloads.any?
799
+ end
800
+ end
801
+ rescue AlreadyFinished
802
+ raise
803
+ rescue StandardError
804
+ close_build_alone
805
+ raise
806
+ end
807
+ end
808
+
809
+ # Members of this batch's block that were never sent (issue #683) count
810
+ # as failed jobs, total and failed alike, so the invariant holds and the
811
+ # batch cannot report success: on_failure fires, on_success cannot,
812
+ # whatever on_enqueue_failure does with the jobs. Reported, not raised,
813
+ # when it cannot be written: on_enqueue_failure still runs.
814
+ def record_enqueue_failures(jobs)
815
+ BatchEntry.connection_pool.with_connection do
816
+ BatchEntry.where(batch_id: batch_id, status: BatchEntry::UNFINISHED)
817
+ .update_all(["total_jobs = total_jobs + ?, failed_jobs = failed_jobs + ?", jobs.size, jobs.size])
818
+ end
819
+ rescue StandardError => e
820
+ ErrorReporter.report(e, { pgbus_batch_enqueue_failures: batch_id })
821
+ end
822
+
823
+ def close_build_alone
824
+ BatchEntry.connection_pool.with_connection { BatchEntry.close_build!(batch_id) }
825
+ rescue StandardError => e
826
+ ErrorReporter.report(e, { pgbus_batch_close_build: batch_id })
827
+ end
828
+
711
829
  def create_record
712
830
  attrs = {
713
831
  batch_id: batch_id,
714
832
  description: description,
715
833
  properties: JSON.generate(properties),
716
- status: "pending"
834
+ status: @owner ? "building" : "pending"
717
835
  }
836
+ attrs[:owner_process_id] = @owner if @owner
718
837
  CALLBACK_COLUMNS.each_key { |slot| attrs.merge!(callback_attributes(slot, public_send(slot))) }
719
838
  @record = BatchEntry.create!(attrs)
720
839
  end
@@ -723,7 +842,7 @@ module Pgbus
723
842
  # builder's setters, inside the Pgbus.batch block, while the row is
724
843
  # still pending and so cannot fire its callbacks).
725
844
  def write_callback(slot, callback)
726
- updated = BatchEntry.where(batch_id: batch_id, status: %w[pending processing])
845
+ updated = BatchEntry.where(batch_id: batch_id, status: BatchEntry::UNFINISHED)
727
846
  .update_all(callback_attributes(slot, callback))
728
847
  raise AlreadyFinished, "Can't change the callbacks of an already finished batch" if updated.zero?
729
848