pgbus 1.0.0 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9b4a4d3841816d583e3e1f7099c28b94644f0eb1a7fd10f2ef18ea4a2a668b2b
4
- data.tar.gz: 57e6a90e66111b1c8c3b529c7e7703f6c01f9521fd640122013b3a1b20e82d75
3
+ metadata.gz: a8a1d130e080a9c5b98771d9aa49f42b9799a815916c8fb1d50269723e4e2878
4
+ data.tar.gz: cf3201146bd227f7ff8a6a114ebd6d8e1e9fc349cf9e58f1ead0daa05b58c769
5
5
  SHA512:
6
- metadata.gz: 90af08c73871898b31f9f689603b8c0311d2a6c6302d9f457275b74710b21f3e73c6b81cf4116c27027cbb88342750d2ef0f815af77e41083b03f534b9408059
7
- data.tar.gz: f4c799bf12d564dcbe39d66664e65266d1ca131836f817629227930020abc2eec5d9f6c4ee0e541d0eae39cfbef7decb76fc41c5ea2bddb415f3f34d5047e206
6
+ metadata.gz: 7e776479ba3bab58e293c13c7a37b37120c82b94eb3778242ea85a767e81ac13a1e210ef562237dad5652b34a75d5fbb0377ee3c4e5b7b3f5155922757898ccf
7
+ data.tar.gz: 470c5e5fa425ab0d040e1502268e9c7eb7cea583f1db530cef0f5af1ace4eecc9eff1da6b21601471969d4cd0737b887094910564eead713de7ce08e0ad5290a
data/CHANGELOG.md CHANGED
@@ -8,6 +8,16 @@
8
8
 
9
9
  ### Security
10
10
 
11
+ ## [1.1.0] - 2026-11-24
12
+
13
+ ### Added
14
+
15
+ - **`pgbus_coalesce false/true` and `config.coalesce_default`** (#689). A job class declares `pgbus_coalesce false` to be sent at its `perform_later` inside `Pgbus.coalesce` and the request middleware, so a caller that reads `successfully_enqueued?` or rescues the send sees the real outcome. `config.coalesce_default = false` holds only classes that declare `pgbus_coalesce true`, in a batch's own scope too. The setting is inherited by subclasses. `Workflow::StepJob` declares `pgbus_coalesce false` and defines its `pgbus_coalesce?` reader on itself, so an application's base-class hook cannot shadow it; a class that still defines `pgbus_coalesce?` itself keeps working, and that override wins over the macro and the config for it and its subclasses, so remove it when adopting them.
16
+
17
+ ### Changed
18
+
19
+ - **PGMQ: vendored schema v1.13.2 (issue #676).** `pgmq.create()` on an existing queue no longer waits for the queue's open transactions: it ran `CREATE INDEX IF NOT EXISTS` on the queue and archive tables, which takes a `SHARE` lock before it checks for the index, so a process ensuring its queues at boot waited for every open transaction that had sent to one of them, and later sends queued behind it. The index DDL now runs only when `to_regclass()` finds the index missing, and the `pg_monitor` grants only when it lacks them. The fix covers `pgmq.create()` only: other DDL a starting process runs on a queue still waits for its open writers, among it re-arming a NOTIFY trigger (one missing or out of date, and a stream queue's on every cold start) and the `group_mode` FIFO and `fair_share` indexes. Under the default configuration, a job queue whose trigger is in place no longer waits. Fresh embedded installs get 1.13.2. Existing *embedded* installs: `rake pgbus:pgmq:status`, then `rails generate pgbus:upgrade_pgmq` + `rails db:migrate` (`rails db:migrate:pgbus` on a separate-database install); the hop changes functions only, so it carries no fixup. An `:extension` install gets 1.13.2 from `ALTER EXTENSION pgmq UPDATE`. Refs #676.
20
+
11
21
  ## [1.0.0] - 2026-11-21
12
22
 
13
23
  **pgbus 1.0.** This release stabilises the API that 0.x settled into, and makes enqueueing many jobs cost a constant number of round trips instead of one or more per job.
data/README.md CHANGED
@@ -848,6 +848,13 @@ config.middleware.insert_after ActionDispatch::Executor, Pgbus::ActiveJob::Coale
848
848
  - **What `perform_later` returns.** The job, with `successfully_enqueued?` true and `provider_job_id` nil until the flush, the same optimistic answer Rails gives a job deferred to after commit. The flush is where delivery is proved.
849
849
  - **The flush.** At the end of the block, before its value returns: one `send_batch` per (queue, priority, delay), then each job left unsent is retried on its own. A send whose outcome is unknown (a connection lost mid-statement) may have written its messages, so the retry can deliver a job twice; jobs must be idempotent, as they already must be for at-least-once delivery. What still fails goes to `on_failure`: `:raise` (default) raises `Pgbus::EnqueueError` naming each job's class and id, `:report` sends it to `Rails.error.report` with the serialized jobs (`Pgbus::ErrorReporter`, and so `config.error_reporters`, only without Rails), and a callable receives `(jobs, error)`. If the block itself raised, the buffer is still sent, a callable still gets the failed jobs, nothing in the flush raises (`:raise` becomes a report), and the block's error propagates.
850
850
  - **Nesting and batches.** A nested `Pgbus.coalesce` joins the outer scope, whose `on_failure` applies; only the outermost sends. A `Pgbus.batch` built in a pgbus process opens a scope of its own (see Batches): it holds only that batch's members and sends them by the batch block's end, never in an outer scope's flush. Any other batch member (a batch opened outside a pgbus process, an open-batch `batch.add`, a deferred member reaching the adapter at commit) is sent at once and counted in as usual.
851
+ - **Jobs whose caller reads the enqueue outcome.** A caller that checks `successfully_enqueued?` or rescues around `perform_later` to undo its own state needs the job sent at the call. Declare `pgbus_coalesce false` on its class: it is sent at its `perform_later` inside any scope, with its `provider_job_id`, and a send error raises there. This bypasses pgbus's scope only: a job Rails defers to after commit (`enqueue_after_transaction_commit`, Rails 7.2+) still reaches the adapter at commit, so inside a transaction its caller sees Rails' deferred answer, not the send. Subclasses inherit the setting, and `pgbus_coalesce true` turns it back on. When most jobs are like that, set `Pgbus.configure { |c| c.coalesce_default = false }` (default `true`; it is a `Pgbus.configuration` setting, not a `config.pgbus` one): only classes that declare `pgbus_coalesce true` are held, in a `Pgbus.batch` block's own scope too, so declare it on each member class whose jobs should go out in one bulk send. A class that defines `pgbus_coalesce?` itself (the hook before this setting) answers for itself whatever `coalesce_default` says. Already sent at once whatever the setting: the jobs listed under "What is held".
852
+
853
+ ```ruby
854
+ class ProcessItemJob < ApplicationJob
855
+ pgbus_coalesce false
856
+ end
857
+ ```
851
858
  - **When not to use it.** With `:raise`, a job that cannot be sent fails the request after its transaction has committed, and from right after `ActionDispatch::Executor` the error surfaces above `ActionDispatch::ShowExceptions`, so the client gets the server's bare 500. An endpoint that must not answer 500 after committing its writes should pass `on_failure: :report` or a callable that does not raise.
852
859
 
853
860
  The scope emits `pgbus.coalesce` with `buffered`, `sent`, `retried`, `failed` and `duration` (ms).
@@ -865,7 +872,7 @@ batch = Pgbus.batch(description: "Import users", properties: { initiated_by: cur
865
872
  end
866
873
  ```
867
874
 
868
- `b.add` takes job instances (each keeps its own `.set(wait:, queue:)`) and sends them in one bulk enqueue. A plain `perform_later` inside the block is coalesced the same way when the batch is opened in a pgbus process (a worker, consumer, dispatcher or scheduler: one with a `pgbus_processes` heartbeat). The batch is then created as `building`, with that process as its owner. While it is `building` the stalled-batch sweep leaves it alone, it cannot finish and no callback fires, whatever its block does. The block's members are held, serialized at the call, counted in with one statement per `config.coalesce_chunk_size` jobs (default 1 000), sent with one `send_batch` per (queue, priority, delay) and backfilled with one more, whatever their number. When the block returns, the last chunk is counted in and the batch moves to `pending` in one transaction, before anything of that chunk is sent, so the batch can finish only once every member is counted. If the owner process dies (its heartbeat row is gone or older than five minutes), the sweep reaps the build: the batch moves to `processing` and the abandoned build counts as one failed job, so `on_complete` and `on_failure` fire once the members that were sent resolve, and `on_success` never does. A batch opened anywhere else (a web request, a console, a rake task) has no heartbeat the sweep could watch: it is created `pending` and its plain `perform_later` members are sent and counted one at a time, as before (`b.add` stays one bulk send everywhere). A held member that cannot be sent is retried on its own, counted as a failed job of the batch, then handed to `on_enqueue_failure:` (`:raise` by default, `:report`, or a callable taking `(jobs, error)`; `on_failure:` stays the callback for a member that fails). Uniqueness and concurrency members keep the single enqueue path; future members are held and sent with their delay. The batch row exists before the block runs and stays `building` or `pending` until it returns. A `building` batch cannot finish before its block returns; a `pending` one cannot either, unless the stalled-batch sweep starts it first (below). A built batch keeps a full chunk while a transaction is open on the batch's connection and counts it in once the transaction is gone (or at the block's end), so a rollback never strands a sent member without its count. If the database stays unreachable through both attempts to close a build (the closing transaction and a bare retry), the batch stays `building` until its owner process exits, when the sweep reaps it. Set callbacks first: if the block raises after an `add`, the added jobs still run and the batch finishes later with only the callbacks set by then. A `pending` batch whose block goes `config.batch_stall_threshold` (default 5 minutes) without adding a job is started by the stalled-batch sweep, so keep slow work outside it; a `building` batch is never started that way. Callbacks are job classes or configured instances, never blocks: they are stored on the batch row.
875
+ `b.add` takes job instances (each keeps its own `.set(wait:, queue:)`) and sends them in one bulk enqueue. A plain `perform_later` inside the block is coalesced the same way when the batch is opened in a pgbus process (a worker, consumer, dispatcher or scheduler: one with a `pgbus_processes` heartbeat). The batch is then created as `building`, with that process as its owner. While it is `building` the stalled-batch sweep leaves it alone, it cannot finish and no callback fires, whatever its block does. The block's members are held (unless their class may not be held: `pgbus_coalesce false`, or no `pgbus_coalesce true` under `config.coalesce_default = false`; those are sent and counted one at a time), serialized at the call, counted in with one statement per `config.coalesce_chunk_size` jobs (default 1 000), sent with one `send_batch` per (queue, priority, delay) and backfilled with one more, whatever their number. When the block returns, the last chunk is counted in and the batch moves to `pending` in one transaction, before anything of that chunk is sent, so the batch can finish only once every member is counted. If the owner process dies (its heartbeat row is gone or older than five minutes), the sweep reaps the build: the batch moves to `processing` and the abandoned build counts as one failed job, so `on_complete` and `on_failure` fire once the members that were sent resolve, and `on_success` never does. A batch opened anywhere else (a web request, a console, a rake task) has no heartbeat the sweep could watch: it is created `pending` and its plain `perform_later` members are sent and counted one at a time, as before (`b.add` stays one bulk send everywhere). A held member that cannot be sent is retried on its own, counted as a failed job of the batch, then handed to `on_enqueue_failure:` (`:raise` by default, `:report`, or a callable taking `(jobs, error)`; `on_failure:` stays the callback for a member that fails). Uniqueness and concurrency members keep the single enqueue path; future members are held and sent with their delay. The batch row exists before the block runs and stays `building` or `pending` until it returns. A `building` batch cannot finish before its block returns; a `pending` one cannot either, unless the stalled-batch sweep starts it first (below). A built batch keeps a full chunk while a transaction is open on the batch's connection and counts it in once the transaction is gone (or at the block's end), so a rollback never strands a sent member without its count. If the database stays unreachable through both attempts to close a build (the closing transaction and a bare retry), the batch stays `building` until its owner process exits, when the sweep reaps it. Set callbacks first: if the block raises after an `add`, the added jobs still run and the batch finishes later with only the callbacks set by then. A `pending` batch whose block goes `config.batch_stall_threshold` (default 5 minutes) without adding a job is started by the stalled-batch sweep, so keep slow work outside it; a `building` batch is never started that way. Callbacks are job classes or configured instances, never blocks: they are stored on the batch row.
869
876
 
870
877
  Inside a job, `batch { |b| ... }` opens a new batch the same way, and a job that is already a member adds siblings with `batch.add(NextJob.new(id))`. `Pgbus::Batch.new(on_complete: ...)` plus `batch.enqueue { ... }` remains the lower-level form.
871
878
 
@@ -96,8 +96,10 @@ module Pgbus
96
96
  # single path's bookkeeping, a batch member outside its own batch's
97
97
  # scope (Pgbus.batch opens one for its block, issue #683; an outer
98
98
  # scope's flush could come after the sweep reads the batch as stalled),
99
- # and a pgbus class that opts out (Workflow::StepJob, whose enqueue failure
100
- # is reported and swept, never raised; pgbus_coalesce? is internal).
99
+ # and a class the scope may not hold: one that declares
100
+ # `pgbus_coalesce false` (Workflow::StepJob, whose enqueue failure is
101
+ # reported and swept, never raised), or, with config.coalesce_default
102
+ # false, one that does not declare `pgbus_coalesce true` (issue #689).
101
103
  # Serializing now raises an unserializable argument here, as outside a
102
104
  # scope, and keeps a later change to the job or its arguments out of
103
105
  # the message.
@@ -106,12 +108,20 @@ module Pgbus
106
108
  return false if active_job.executions.to_i.positive?
107
109
  return false if active_job.is_a?(DeployTaskRunId) && active_job.deploy_task_run_id
108
110
  return false if member_batch_id(active_job) != scope.batch_id
109
- return false if active_job.class.respond_to?(:pgbus_coalesce?) && !active_job.class.pgbus_coalesce?
111
+ return false unless coalesce_class?(active_job.class)
110
112
 
111
113
  payload = tag_bulk_member(FairShare.inject_metadata(active_job, Serializer.serialize_job_hash(active_job)), active_job)
112
114
  scope.push(self, active_job, payload, due_at)
113
115
  end
114
116
 
117
+ # A class with pgbus_coalesce? (Coalesce::JobMixin's, or an app's own
118
+ # hook from before #689, which then wins over the macro and the config)
119
+ # answers for itself; a class without it follows config.coalesce_default,
120
+ # like one that declares nothing.
121
+ def coalesce_class?(klass)
122
+ klass.respond_to?(:pgbus_coalesce?) ? klass.pgbus_coalesce? : Pgbus.configuration.coalesce_default
123
+ end
124
+
115
125
  # Whole seconds until +job+ is due, 0 for a job due now.
116
126
  def job_delay(job)
117
127
  scheduled_in_future?(job) ? delay_until(job.scheduled_at.to_f) : 0
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module ActiveJob
5
+ class Coalesce
6
+ # Whether a Pgbus.coalesce scope (the request middleware's, a batch's)
7
+ # may hold a job class (issue #689). Included on ActiveJob::Base by the
8
+ # engine:
9
+ #
10
+ # class ProcessItemJob < ApplicationJob
11
+ # pgbus_coalesce false # sent at its perform_later, inside a scope too
12
+ # end
13
+ #
14
+ # A class that declares nothing follows config.coalesce_default (true:
15
+ # held). With the default false, only classes that declare
16
+ # `pgbus_coalesce true` are held. Subclasses inherit the setting.
17
+ module JobMixin
18
+ extend ActiveSupport::Concern
19
+
20
+ included do
21
+ # A per-class setting the job's own class body writes at load
22
+ # (`pgbus_coalesce false`); the adapter only reads it at enqueue.
23
+ class_attribute :pgbus_coalesce_enabled, instance_writer: false, default: nil # rubocop:disable ThreadSafety/ClassAndModuleAttributes
24
+ end
25
+
26
+ class_methods do
27
+ def pgbus_coalesce(enabled = true) # rubocop:disable Style/OptionalBooleanParameter
28
+ self.pgbus_coalesce_enabled = enabled ? true : false
29
+ end
30
+
31
+ # The adapter's check: the class's own setting, else the configured default.
32
+ def pgbus_coalesce?
33
+ enabled = pgbus_coalesce_enabled
34
+ enabled.nil? ? Pgbus.configuration.coalesce_default : enabled
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -11,7 +11,9 @@ module Pgbus
11
11
  # decide), serialized at perform_later; a future one with its scheduled
12
12
  # time, so its delay is what is left at the flush (issue #686). One with
13
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
14
+ # a batch member outside its own batch's scope, a Workflow::StepJob or a
15
+ # class the scope may not hold (`pgbus_coalesce false`, or no
16
+ # `pgbus_coalesce true` under config.coalesce_default false, issue #689)
15
17
  # goes out at once, as it does outside a scope. Active Job's enqueue_after_transaction_commit runs before the
16
18
  # adapter, so a job that defers reaches the buffer at commit, and a rolled
17
19
  # back one never does.
@@ -314,6 +314,15 @@ module Pgbus
314
314
  # holds past it while a transaction is open on the batch's connection.
315
315
  attr_accessor :coalesce_chunk_size
316
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
+
317
326
  # The MCP server's workflow write tools (issue #550): pgbus_workflow_resume,
318
327
  # _cancel, _skip_step, _resume_at, _run_now and _signal. Off by default, and
319
328
  # then they are never built, so tools/list cannot show them. Read once, when
@@ -517,6 +526,7 @@ module Pgbus
517
526
  @web_filter_sensitive = true
518
527
  @web_queue_metrics_chunk_size = 100
519
528
  @coalesce_chunk_size = 1_000
529
+ @coalesce_default = true
520
530
  @deprecation_warned = Set.new
521
531
 
522
532
  # HTTP health endpoints — nil port disables the standalone server.
@@ -1144,6 +1154,7 @@ module Pgbus
1144
1154
  raise Pgbus::ConfigurationError, "coalesce_chunk_size must be a positive integer"
1145
1155
  end
1146
1156
 
1157
+ raise Pgbus::ConfigurationError, "coalesce_default must be true or false" unless [true, false].include?(coalesce_default)
1147
1158
  raise Pgbus::ConfigurationError, "require_primary must be true or false" unless [true, false].include?(require_primary)
1148
1159
  raise Pgbus::ConfigurationError, "mcp_write_tools must be true or false" unless [true, false].include?(mcp_write_tools)
1149
1160
 
data/lib/pgbus/engine.rb CHANGED
@@ -103,6 +103,7 @@ module Pgbus
103
103
  include Pgbus::ActiveJob::DeployTaskRunId
104
104
  include Pgbus::ActiveJob::CurrentAttributes
105
105
  include Pgbus::VisibilityHeartbeat::JobMixin
106
+ include Pgbus::ActiveJob::Coalesce::JobMixin
106
107
  end
107
108
  end
108
109