pgbus 0.27.2 → 1.1.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.
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
 
@@ -308,6 +308,21 @@ module Pgbus
308
308
  # marks only its queues unavailable.
309
309
  :web_queue_metrics_chunk_size
310
310
 
311
+ # Held jobs after which a Pgbus.coalesce scope (and the one Pgbus.batch
312
+ # opens for its block) sends what it holds before the block ends (issue
313
+ # #683), so a huge block stays bounded in memory. A built batch's scope
314
+ # holds past it while a transaction is open on the batch's connection.
315
+ attr_accessor :coalesce_chunk_size
316
+
317
+ # Whether a Pgbus.coalesce scope holds a job class that declares nothing
318
+ # (issue #689). true: every bulk-eligible job is held unless its class
319
+ # declares `pgbus_coalesce false`. false: only classes that declare
320
+ # `pgbus_coalesce true` are held; every other job is sent at its
321
+ # perform_later, so its caller sees the real outcome. A class that
322
+ # defines pgbus_coalesce? itself (the hook before #689) answers for
323
+ # itself whatever this says.
324
+ attr_accessor :coalesce_default
325
+
311
326
  # The MCP server's workflow write tools (issue #550): pgbus_workflow_resume,
312
327
  # _cancel, _skip_step, _resume_at, _run_now and _signal. Off by default, and
313
328
  # then they are never built, so tools/list cannot show them. Read once, when
@@ -510,6 +525,8 @@ module Pgbus
510
525
  @web_filter_parameters = nil # nil = auto-detect from Rails, then fall back to defaults
511
526
  @web_filter_sensitive = true
512
527
  @web_queue_metrics_chunk_size = 100
528
+ @coalesce_chunk_size = 1_000
529
+ @coalesce_default = true
513
530
  @deprecation_warned = Set.new
514
531
 
515
532
  # HTTP health endpoints — nil port disables the standalone server.
@@ -1133,6 +1150,11 @@ module Pgbus
1133
1150
  raise Pgbus::ConfigurationError, "web_queue_metrics_chunk_size must be a positive integer"
1134
1151
  end
1135
1152
 
1153
+ unless coalesce_chunk_size.is_a?(Integer) && coalesce_chunk_size.positive?
1154
+ raise Pgbus::ConfigurationError, "coalesce_chunk_size must be a positive integer"
1155
+ end
1156
+
1157
+ raise Pgbus::ConfigurationError, "coalesce_default must be true or false" unless [true, false].include?(coalesce_default)
1136
1158
  raise Pgbus::ConfigurationError, "require_primary must be true or false" unless [true, false].include?(require_primary)
1137
1159
  raise Pgbus::ConfigurationError, "mcp_write_tools must be true or false" unless [true, false].include?(mcp_write_tools)
1138
1160
 
data/lib/pgbus/engine.rb CHANGED
@@ -6,6 +6,14 @@ module Pgbus
6
6
  class Engine < ::Rails::Engine
7
7
  isolate_namespace Pgbus
8
8
 
9
+ # config.pgbus.* in the application (issue #682). coalesce_requests
10
+ # inserts Pgbus::ActiveJob::Coalesce::Middleware after
11
+ # ActionDispatch::Executor, with coalesce_requests_on_failure as its
12
+ # on_failure.
13
+ config.pgbus = ActiveSupport::OrderedOptions.new
14
+ config.pgbus.coalesce_requests = false
15
+ config.pgbus.coalesce_requests_on_failure = :raise
16
+
9
17
  # When pgbus was loaded before Rails, a separate Zeitwerk loader manages
10
18
  # app/models. Tear it down before Rails' autoloader claims the same paths.
11
19
  initializer "pgbus.release_models_loader", before: :set_autoload_paths do
@@ -95,6 +103,7 @@ module Pgbus
95
103
  include Pgbus::ActiveJob::DeployTaskRunId
96
104
  include Pgbus::ActiveJob::CurrentAttributes
97
105
  include Pgbus::VisibilityHeartbeat::JobMixin
106
+ include Pgbus::ActiveJob::Coalesce::JobMixin
98
107
  end
99
108
  end
100
109
 
@@ -168,6 +177,17 @@ module Pgbus
168
177
  app.middleware.use Pgbus::Signals::Middleware if Pgbus.configuration.streams_enabled
169
178
  end
170
179
 
180
+ # Opt-in (issue #682): each request's enqueues go out together before
181
+ # the response is returned.
182
+ # After the app's initializers, so the flag may be set there too.
183
+ initializer "pgbus.coalesce.middleware", after: :load_config_initializers do |app|
184
+ options = app.config.pgbus
185
+ if options.coalesce_requests
186
+ app.middleware.insert_after ActionDispatch::Executor, Pgbus::ActiveJob::Coalesce::Middleware,
187
+ on_failure: options.coalesce_requests_on_failure
188
+ end
189
+ end
190
+
171
191
  # Make the <pgbus-stream-source> element available to the host app's
172
192
  # asset pipeline (Propshaft or Sprockets). The importmap pin points at
173
193
  # the minified build (rake frontend:js). Propshaft rewrites its
@@ -102,6 +102,7 @@ module Pgbus
102
102
  add_processed_event_completion: "pgbus:add_processed_event_completion",
103
103
  add_batch_executions: "pgbus:add_batch_executions",
104
104
  add_batch_callback_jobs: "pgbus:add_batch_callback_jobs",
105
+ add_batch_owner: "pgbus:add_batch_owner",
105
106
  tune_autovacuum: "pgbus:tune_autovacuum",
106
107
  tune_fillfactor: "pgbus:tune_fillfactor",
107
108
  fold_queue_name_case: "pgbus:fold_queue_name_case"
@@ -130,6 +131,7 @@ module Pgbus
130
131
  add_processed_event_completion: "completed_at on pgbus_processed_events (two-phase idempotency claim)",
131
132
  add_batch_executions: "batch execution-row tracking (self-healing completion, on_failure rename)",
132
133
  add_batch_callback_jobs: "batch callback-job columns (configured ActiveJob instances as batch callbacks)",
134
+ add_batch_owner: "batch owner column (a batch built by a pgbus process; its perform_later calls sent together)",
133
135
  tune_autovacuum: "autovacuum tuning for PGMQ queue and archive tables",
134
136
  tune_fillfactor: "fillfactor=70 on PGMQ queue tables (reduces page density during update churn)",
135
137
  fold_queue_name_case: "lower-case spelling for queues created in mixed case (PGMQ's table names are lower case)"
@@ -169,6 +171,7 @@ module Pgbus
169
171
  *processed_event_completion_migrations,
170
172
  *batch_executions_migrations,
171
173
  *batch_callback_jobs_migrations,
174
+ *batch_owner_migrations,
172
175
  *autovacuum_migrations,
173
176
  *fillfactor_migrations
174
177
  ]
@@ -339,6 +342,15 @@ module Pgbus
339
342
  [:add_batch_callback_jobs]
340
343
  end
341
344
 
345
+ # The process that builds a batch (issue #683): without the column a
346
+ # batch is never built, and its members are sent one at a time.
347
+ def batch_owner_migrations
348
+ return [] unless table_exists?("pgbus_batches")
349
+ return [] if column_names("pgbus_batches").include?("owner_process_id")
350
+
351
+ [:add_batch_owner]
352
+ end
353
+
342
354
  # Autovacuum tuning: check if any PGMQ queue table already has
343
355
  # custom autovacuum settings applied. If not, queue the migration.
344
356
  def autovacuum_migrations