pgbus 0.27.1 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6b6f949cf25759a3498971f5c00a1ba4c3beee0bdcadac41c6bd978af96ba392
4
- data.tar.gz: 0cd2f5abd43c6f5b380f2439b40553dd707ec0283dc42fbe696d6dd2f0a0172e
3
+ metadata.gz: 9b4a4d3841816d583e3e1f7099c28b94644f0eb1a7fd10f2ef18ea4a2a668b2b
4
+ data.tar.gz: 57e6a90e66111b1c8c3b529c7e7703f6c01f9521fd640122013b3a1b20e82d75
5
5
  SHA512:
6
- metadata.gz: 2d9fa8de5bcae929a3546fba35c7734e83ca9794aa582adc69cb9fee0aadbd397061324cea4e00fa5fcb77bc79e11e39909ff96fd4c27e83d8f94c7acca46a42
7
- data.tar.gz: 7fba6d23df3a93fa218b2f23cb59b6a942a45ebdd8aadd57cf00f01d3f110adb7eb406086aed7922b0b54931bb937cfe366fef5230bb01fc517dd50d3bb64c0a
6
+ metadata.gz: 90af08c73871898b31f9f689603b8c0311d2a6c6302d9f457275b74710b21f3e73c6b81cf4116c27027cbb88342750d2ef0f815af77e41083b03f534b9408059
7
+ data.tar.gz: f4c799bf12d564dcbe39d66664e65266d1ca131836f817629227930020abc2eec5d9f6c4ee0e541d0eae39cfbef7decb76fc41c5ea2bddb415f3f34d5047e206
data/CHANGELOG.md CHANGED
@@ -2,6 +2,61 @@
2
2
 
3
3
  ### Added
4
4
 
5
+ ### Changed
6
+
7
+ ### Fixed
8
+
9
+ ### Security
10
+
11
+ ## [1.0.0] - 2026-11-21
12
+
13
+ **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.
14
+
15
+ - **Coalesced enqueues.** `Pgbus.coalesce { }` holds a unit of work's jobs and sends them together: one `send_batch` per queue, priority and delay. `config.pgbus.coalesce_requests` turns on an opt-in Rack middleware that does the same for every request. At 5 ms per database round trip, 1 000 `perform_later` calls take about 75 ms instead of 6.9 s.
16
+ - **Building batches.** A `Pgbus.batch` opened in a pgbus process is created `building`, owned by that process's heartbeat row. While it is building, no sweep or finish can touch it. Its block's `perform_later` calls are held and counted in once per chunk (`config.coalesce_chunk_size`). If the owner process dies, the sweep reaps the build. Existing installs add `owner_process_id` with `rails generate pgbus:add_batch_owner` (or `pgbus:update`).
17
+ - **Bulk batch bookkeeping.** A batch's execution rows are inserted, backfilled and uncounted with one statement per group, not one per job. At 5 ms per round trip, 1 000 members through `b.add` take about 0.36 s instead of 15.5 s, and 1 000 `perform_later` calls in a built batch take about 0.36 s instead of 41.6 s.
18
+ - **Bulk scheduled sends.** Jobs with `set(wait:)` go out as one `send_batch` per delay, so a staggered fan-out costs one send per slice.
19
+ - **Breaking:** `Batch.new(on_discard:)` and `Batch#on_discard` are removed; use `on_failure:`. `on_finish` stays until 2.0. The 1.0 table in the upgrade guide lists every change.
20
+
21
+ ### Breaking Changes
22
+
23
+ - **`Pgbus::Batch.new(on_discard:)` and `Batch#on_discard` are removed**, as their deprecation warning announced for 1.0 (this release). Pass `on_failure:` and read `#on_failure`. `on_discard:` now raises `ArgumentError` (unknown keyword).
24
+
25
+ ### Changed
26
+
27
+ - **`on_finish` stays one more major version.** The `on_finish:` keyword and the builder's `b.on_finish` are still accepted and still warn once per process (`Batch#on_finish` stays as a plain reader alias); the warning now says they are removed in 2.0. Callers in the wild still use them. The `BatchEntry#discarded_jobs` alias, for installs that have not run `pgbus:add_batch_executions`, is also kept until 2.0: the legacy-schema path still reads it. The `on_finish_class` / `on_finish_job` columns, which were to be renamed at 1.0, stay until 2.0 too.
28
+
29
+ ### Added
30
+
31
+ - **Scheduled jobs go out in bulk (issue #686).** `enqueue_all` (`perform_all_later`, `b.add`), a `Pgbus.coalesce` scope and a built batch's block group bulk-eligible jobs by queue, priority and delay (whole seconds), and send each group with one `send_batch` carrying that delay; they used to send every future job on its own. A staggered fan-out (slice i scheduled i × delay ahead) costs one send per slice, and 50 jobs that share a `wait:` one send. A coalesce scope now holds future jobs (`enqueue_at`) as well, and works their delay out at the flush, from the scheduled time, so time spent in the scope is not added to it. A batch's scheduled members are counted and backfilled in bulk with the rest. Uniqueness and concurrency jobs keep the single path, their lock and slot leases covering the delay. Refs #686.
32
+
33
+ - **A batch's bookkeeping takes a constant number of statements, and `Pgbus.batch` coalesces its block (issue #683).** `Batch.track_enqueue` inserts every execution row of a bulk in one `INSERT … SELECT FROM unnest(…) ON CONFLICT (job_id) DO NOTHING` (new `BatchExecution.insert_all_for!`), still in the same transaction as the guarded increment and still before any send. The bulk send backfills each group's `msg_id`s with one `UPDATE … FROM unnest(…)` (`BatchExecution.backfill_all!`); a backfill that fails is logged and never fails an enqueue whose messages are live. A failed bulk send uncounts its group with one `DELETE … WHERE job_id = ANY($1)` and one decrement by the count (`Batch.untrack_enqueue_all`). **A batch opened in a pgbus process is built:** with the new `owner_process_id` column (`rails generate pgbus:add_batch_owner`; fresh installs have it) and a process heartbeat row (a worker, consumer, dispatcher or scheduler), `Pgbus.batch` creates the batch as `building` with that row as its owner. While `building`, the stalled-batch sweep ignores it, no finish can close it (a member sent at once that completes still counts) and no callback fires. Its block runs in a `Pgbus.coalesce` scope of the batch's own: plain `perform_later` calls are held, serialized at the call, counted in once per `config.coalesce_chunk_size` jobs (new, default 1 000; every coalesce scope uses it) and sent with that bookkeeping; the scope never joins an outer one, and an outer scope's flush never sends a batch's members. The block's end counts the last chunk and moves the batch `building` → `pending` in one transaction, then sends it; the usual start re-checks finish. The sweep reaps a build only once its owner's row is gone or its heartbeat is older than `Process::Heartbeat::ALIVE_THRESHOLD`: the batch moves to `processing` with the abandoned build counted as one failed job, so `on_complete` and `on_failure` fire and `on_success` cannot. A batch opened anywhere else (a web request, a console, a rake task; or before the migration) is `pending` and sends its members one at a time, as before. A closing transaction that fails is followed by a bare guarded close, so the batch is `pending`; only a database unreachable through both leaves it `building` until its owner exits. New `Pgbus.batch(on_enqueue_failure:)` (`:raise` default, `:report`, or a callable); `on_failure:` remains the failed-member callback. Batch of N bulk-eligible jobs: about 2N + 4 round trips (`b.add`) or 6N (`perform_later`) before, after a constant number per `coalesce_chunk_size` chunk and per (queue, priority) group, whatever N is within them. **Changed for existing callers:** inside a built batch's block, `perform_later` now returns the job with `provider_job_id` nil until its chunk is sent (at the next chunk or the block's end), a held member that is never sent counts as a failed job of the batch (`on_failure` fires, `on_success` cannot), `AlreadyFinished` surfaces at the block's end, and a member that cannot be sent raises `Pgbus::EnqueueError` when the block ends (or goes to `on_enqueue_failure:`), not at the call; during a rolling deploy a pre-0.28 process rejects an open-batch `batch.add` into a `building` batch with `AlreadyFinished`, and a pre-0.28 dispatcher's orphan-row sweep can remove a `building` batch's unsent row without its count, leaving that batch unfinished; **downgrading** below this release leaves any `building` batch to nobody: move them on first with `UPDATE pgbus_batches SET status = 'pending' WHERE status = 'building'`; a bulk backfill that fails no longer raises out of `enqueue_all`. An empty `Pgbus.coalesce` scope emits no `pgbus.coalesce` event. Refs #683.
34
+
35
+ - **`Pgbus.coalesce { }` and an opt-in Rack middleware send a unit of work's enqueues together: one `send_batch` per (queue, priority) group instead of one send per `perform_later` (issue #682).** Inside the scope the adapter serializes every bulk-eligible job at `perform_later`, holds it, and returns it with `successfully_enqueued?` true and `provider_job_id` nil, as Rails does for a job deferred to after commit. At the end of the block the held payloads go out in bulk; each job left unsent is retried on its own, and what still fails goes to `on_failure:` (`:raise`, the default, raises `Pgbus::EnqueueError` naming each job; `:report` reports it with the serialized jobs; a callable receives `(jobs, error)`). The buffer is also sent when the block raises, and the block's error propagates. Jobs with uniqueness or concurrency, `retry_on` re-enqueues, deploy task runs, batch members, workflow steps, and jobs enqueued on another thread or fiber or after the flush has started go out at once. A nested scope joins the outer one. `Pgbus::ActiveJob::Coalesce::Middleware` sends before it returns the response, never in `rack.response_finished`; `config.pgbus.coalesce_requests = true` (default false) inserts it after `ActionDispatch::Executor`, with `config.pgbus.coalesce_requests_on_failure` (default `:raise`). New `pgbus.coalesce` notification with `buffered`, `sent`, `retried`, `failed` and `duration`. Refs #682.
36
+
37
+ ## [0.27.2] - 2026-11-21
38
+
39
+ ### Fixed
40
+
41
+ - **`ActiveJob.perform_all_later` now reads each job's outcome from the job: the adapter's `enqueue_all` sets `successfully_enqueued` (issue #679).** Rails documents that an adapter reports per-job status on the instances, and Rails' own fallback and Solid Queue do; pgbus set only `provider_job_id`, so `successfully_enqueued?` stayed falsy for every job, sent or not. `enqueue_all` now resets `successfully_enqueued = false` and `enqueue_error = nil` on every job first, then marks a job `true` when it was sent (bulk `send_batch` or the individual path) or parked behind its concurrency limit as a blocked execution; a job a uniqueness or concurrency `on_conflict` dropped stays `false`. Errors still raise, as before. A job whose send or park was not confirmed stays `false` (`JobNotUnique` under `:reject`, `ConcurrencyLimitExceeded`, a send error, or a short `send_batch`, which still raises `Pgbus::EnqueueError` and leaves that bulk without ids), and so does every job not yet reached; after a short `send_batch` or a connection error during the send, its message may still be live. A job already sent or parked stays `true`, including one whose bookkeeping afterwards (batch backfill, retry notes) raised. The return value, which ActiveJob reports as the `enqueue_all.active_job` notification's `enqueued_count`, is now the number of jobs marked enqueued, not the number passed in, so a dropped job no longer counts. Rails' `enqueue_all` log line therefore now reports a job dropped on purpose (`on_conflict: :discard` or `:log`) under "Failed enqueuing N jobs". When `enqueue_all` raises, ActiveJob still publishes no `enqueued_count`, so its failed count is the whole batch: after a raise partway through a batch of 3, the log line now reads "Enqueued 1 job … Failed enqueuing 3 jobs". The jobs it lists as enqueued are the ones sent or parked. `perform_later` is unchanged: `enqueue` and `enqueue_at` never set the flag, ActiveJob does. Refs #679.
42
+
43
+ ## [0.27.1] - 2026-11-20
44
+
45
+ ### Fixed
46
+
47
+ - **`Web::DataSource#queues_with_metrics` reads 1 000 queues in a tenth of the time, and a metrics query that fails or times out no longer reads as "no queues" (issue #677).** The read was one statement with nine scalar subqueries per queue (eight scans of each queue table plus one sequence read), so its cost grew with the queue count until `statement_timeout` cancelled it, and the rescue returned `[]`: the dashboard, the dead-letter views, `pgbus_health`, the Prometheus scrape and the AppSignal probe all read a timeout as an empty, healthy system. Inside a caller's transaction the cancelled statement also aborted it.
48
+
49
+ - **One scan per queue, in chunks.** Each queue's metrics are one aggregate over its table, and the queues are read `web_queue_metrics_chunk_size` (new, default 100) per statement, each statement in its own savepoint. Same machine, one message per queue: 100 queues 57.7 ms → 37.4 ms, 1 000 queues 3 711 ms → 373 ms, 5 000 queues 126 s → 1.9 s (`rake bench:queue_metrics`, new). A healthy queue's hash is unchanged.
50
+ - **A failed chunk is visible.** Its queues stay in the list with `metrics_unavailable: true` and `nil` counts; the other chunks still report, and an enclosing transaction stays usable. After 3 chunks that timed out (a cancelled statement, a lock wait, a deadlock, a connection that cannot be established) the rest are not read and come back unavailable at once, so a database where every chunk times out costs a few `statement_timeout`s, not one per chunk; a chunk that fails at once (a queue whose table is gone) never stops the others. Totals (`summary_stats` `total_depth` / `dlq_depth`, the `pgbus_dlq_depth` and AppSignal summary gauges) leave an unmeasured queue out rather than guess, so they read low while the verdict is DEGRADED. New `DataSource#queue_metrics_errors` returns `[]` or `[{ queues: [...], error: "Class: message" }]` (`queues: []` when `pgmq.meta` itself could not be read). `pgbus_health` / `/readyz` report `DEGRADED` with a reason naming the queues; the dashboard queue tables say "Metrics unavailable" in place of the counts; the AppSignal probe skips the queue's gauges and increments `pgbus_queue_metrics_unavailable`; the Prometheus scrape writes no count for it and adds the `pgbus_queue_metrics_unavailable` gauge; the MCP `pgbus_queues` tool carries the flag per row; the dead-letter total counts the rows of a DLQ whose metrics are unavailable (in a savepoint) rather than reading it as 0. An unreadable queue list increments the AppSignal counter untagged, writes one unlabelled Prometheus sample and leaves `pgbus_dlq_depth` out of the scrape; a failure after the queue list was read keeps every queue, flagged.
51
+ - **Names without metrics.** New `DataSource#queue_names` reads `pgmq.meta` only (memoized, cleared by `reset_cache!`). The job list, `dlq_messages`, `dlq_message_detail`, discard-all, priority siblings and the MCP `pgbus_dlq_detail` scan use it and run no metrics statement (the dead-letter page's counts, `dlq_total_count` and `dlq_counts_by_queue`, still read the metrics).
52
+ - **Throughput.** `summary_stats[:throughput_rate]` was always 0.0: `compute_throughput` called `Process.clock_gettime` inside `Pgbus::Web`, where `Process` is `Pgbus::Process`, and rescued the `NoMethodError`. It now reads the clock, never reports a negative rate (a dropped queue lowers the total), and keeps its last complete snapshot while any queue's metrics are unavailable.
53
+
54
+ Refs #677.
55
+
56
+ ## [0.27.0] - 2026-11-18
57
+
58
+ ### Added
59
+
5
60
  - **Process signals: `Pgbus.on_signal(name) { |payload| ... }` runs a block in every web process when any process calls `Pgbus.signal(name, payload = nil)` (issue #674).** This covers a per-process in-memory cache that every Puma worker must drop when its data changes, which had no supported route: the event bus delivers an event to one competing consumer in a worker process, and the streamer only woke SSE connections.
6
61
 
7
62
  - **Sending.** A signal is a `NOTIFY` on `<queue_prefix>_signal_<name>`, sent through `Pgbus.client` (new `Client#notify_signal`). Inside an open ActiveRecord transaction it is sent at `COMMIT` and never on rollback. A `transaction(joinable: false)` block sends at once: the fixture transaction of an app's transactional tests is one, so an `after_commit { Pgbus.signal(...) }` still sends there. The payload is an optional String under NOTIFY's 7999-byte cap; an empty String arrives as `nil`. A name may use lowercase letters, digits and underscores, and its channel must fit the queue-name budget; anything else raises `ArgumentError`.
@@ -16,24 +71,19 @@
16
71
 
17
72
  Refs #674.
18
73
 
19
- ### Changed
20
-
21
- - **A member-keyed presence `touch` no longer probes `information_schema` on a table without the seat columns, and a forced re-check no longer restarts the backoff (issue #666).** On a `pgbus_presence_members` table where `rails g pgbus:add_presence_seats` has not run, every member-keyed `touch`, `leave` and `sweep!` re-probed a cached "no seats" answer before it ran and restarted the #665 backoff at 30 s. The streamer touches once per connection per heartbeat, so a process with N member-keyed connections sent N catalog queries every `streams_heartbeat_interval` (15 s by default), and its backoff never took effect. A member-keyed `touch` now uses the cached answer and re-checks only on the backoff's schedule: three touches after a reset send one probe instead of four, and none while a "no" is cached. Assumed: on a table migrated under a running process, such a `touch` can also refresh that member's seat rows until the next re-check (at most 10 minutes, `SCHEMA_RECHECK_MAX_SECONDS`); it is an `UPDATE` of `last_seen_at`, so nothing is deleted. A member-keyed `leave` and `sweep!` still re-check a cached "no" before they delete, so they never delete seat rows on a migrated table (#515), now with one probe instead of up to two, answered from that probe. That re-check leaves the backoff alone: over a fresh "no" it changes neither the step nor the schedule however many disconnects force one, and over a "no" already due it is the timed re-check, one step. `reset_schema_cache!` still re-probes at once and starts again from 30 s. Refs #666.
22
-
23
- - **pgmq-ruby 0.9.0 (was 0.8.2); the gemspec now requires `~> 0.9.0` (issue #656).** What reaches pgbus users is the connection pool: pgmq-ruby's checkout health check now resets a pooled connection in any state other than `CONNECTION_OK`, so a connection a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`) is recovered on the next checkout. Before, the checkout handed it out again, libpq refused every send (`no connection to the server`), and pgbus's stale-connection retry only recovered it on its last attempt by dropping both pools (#645): now the call succeeds on the first attempt, with no retry, no pool reload and no warning. pgmq-ruby also resets a connection whose call raised `PG::ConnectionBad` or `PG::UnableToSend` before it goes back to the pool (not a connection pgbus hands it through a callable, which it neither resets nor closes: the shared ActiveRecord connection, and dedicated connections in `connection_guc_mode = :session` with database.yml `variables`); native statements re-prepare on the new backend as on any reconnect. pgbus keeps its reload before the last stale retry for a connection that still fails after the health check passed it. A checkout reset of a connection in `connection_guc_mode = :session` with `variables` applies its `SET`s again (#671). `produce_topic` and `produce_batch_topic` now raise `PGMQ::Errors::MessageInvalidError` for a message that is not a String or headers that are neither a String nor nil, as `produce` has since 0.8.0. `Client#publish_to_topic` (what `Pgbus.publish` and the outbox poller call; `Pgbus::Testing`'s fake and inline modes never reach PGMQ) serializes the payload and headers to JSON Strings first, so it is unaffected; `headers: false`, which pgmq-ruby dropped before with an integer delay (and stored as JSON `false` with a fractional one) and now rejects, is passed as nil, so it is dropped at any delay. `spec/integration/connection_failure_spec.rb` now asserts the mid-reset connection is recovered at checkout (it failed on 0.8.2), in place of the two examples that pinned the old last-retry recovery. Refs #656.
74
+ ## [0.26.1] - 2026-11-15
24
75
 
25
76
  ### Fixed
26
77
 
27
- - **`Web::DataSource#queues_with_metrics` reads 1 000 queues in a tenth of the time, and a metrics query that fails or times out no longer reads as "no queues" (issue #677).** The read was one statement with nine scalar subqueries per queue (eight scans of each queue table plus one sequence read), so its cost grew with the queue count until `statement_timeout` cancelled it, and the rescue returned `[]`: the dashboard, the dead-letter views, `pgbus_health`, the Prometheus scrape and the AppSignal probe all read a timeout as an empty, healthy system. Inside a caller's transaction the cancelled statement also aborted it.
78
+ - **A pooled connection in `connection_guc_mode = :session` keeps its database.yml `variables` when it is reset (issue #671).** In `:session` mode the `variables` (`statement_timeout`, `lock_timeout` and the like) are applied with `SET` after connect, and `PG::Connection#reset` opens a new backend without them. pgmq-ruby's checkout health check resets an unhealthy pooled connection (`finished?` or `CONNECTION_BAD` since #332, and an intermediate state such as `CONNECTION_STARTED` since pgmq-ruby 0.9.0), so that connection went on serving the job or streams pool with the server's defaults. Each connection the `:session` connect lambda opens now re-applies its `SET`s when it is reset, whoever resets it. A connection whose `SET`s do not all complete, after a connect or a reset, is closed before the error reaches the caller, so it is never pooled without them; with pg 1.5.9 or later the next checkout resets it and applies the `SET`s again (an older pg cannot reset a closed connection, so it is replaced when the pool is reloaded before the last stale-connection retry; the call itself is retried only for a stale-connection error, so a `SET` that always fails, such as an invalid value, fails each time). The completion pipeline's own reset (#619) no longer applies the `SET`s itself (they ran twice), and a `SET` that fails there is now logged as `Resetting the connection or re-applying its session variables failed` and leaves the connection closed, where before the session carried on without its `variables`. `:options` mode, a String URL and the shared ActiveRecord connection are unaffected. Refs #671.
28
79
 
29
- - **One scan per queue, in chunks.** Each queue's metrics are one aggregate over its table, and the queues are read `web_queue_metrics_chunk_size` (new, default 100) per statement, each statement in its own savepoint. Same machine, one message per queue: 100 queues 57.7 ms → 37.4 ms, 1 000 queues 3 711 ms → 373 ms, 5 000 queues 126 s → 1.9 s (`rake bench:queue_metrics`, new). A healthy queue's hash is unchanged.
30
- - **A failed chunk is visible.** Its queues stay in the list with `metrics_unavailable: true` and `nil` counts; the other chunks still report, and an enclosing transaction stays usable. After 3 chunks that timed out (a cancelled statement, a lock wait, a deadlock, a connection that cannot be established) the rest are not read and come back unavailable at once, so a database where every chunk times out costs a few `statement_timeout`s, not one per chunk; a chunk that fails at once (a queue whose table is gone) never stops the others. Totals (`summary_stats` `total_depth` / `dlq_depth`, the `pgbus_dlq_depth` and AppSignal summary gauges) leave an unmeasured queue out rather than guess, so they read low while the verdict is DEGRADED. New `DataSource#queue_metrics_errors` returns `[]` or `[{ queues: [...], error: "Class: message" }]` (`queues: []` when `pgmq.meta` itself could not be read). `pgbus_health` / `/readyz` report `DEGRADED` with a reason naming the queues; the dashboard queue tables say "Metrics unavailable" in place of the counts; the AppSignal probe skips the queue's gauges and increments `pgbus_queue_metrics_unavailable`; the Prometheus scrape writes no count for it and adds the `pgbus_queue_metrics_unavailable` gauge; the MCP `pgbus_queues` tool carries the flag per row; the dead-letter total counts the rows of a DLQ whose metrics are unavailable (in a savepoint) rather than reading it as 0. An unreadable queue list increments the AppSignal counter untagged, writes one unlabelled Prometheus sample and leaves `pgbus_dlq_depth` out of the scrape; a failure after the queue list was read keeps every queue, flagged.
31
- - **Names without metrics.** New `DataSource#queue_names` reads `pgmq.meta` only (memoized, cleared by `reset_cache!`). The job list, `dlq_messages`, `dlq_message_detail`, discard-all, priority siblings and the MCP `pgbus_dlq_detail` scan use it and run no metrics statement (the dead-letter page's counts, `dlq_total_count` and `dlq_counts_by_queue`, still read the metrics).
32
- - **Throughput.** `summary_stats[:throughput_rate]` was always 0.0: `compute_throughput` called `Process.clock_gettime` inside `Pgbus::Web`, where `Process` is `Pgbus::Process`, and rescued the `NoMethodError`. It now reads the clock, never reports a negative rate (a dropped queue lowers the total), and keeps its last complete snapshot while any queue's metrics are unavailable.
80
+ ## [0.26.0] - 2026-11-15
33
81
 
34
- Refs #677.
82
+ ### Changed
35
83
 
36
- - **A pooled connection in `connection_guc_mode = :session` keeps its database.yml `variables` when it is reset (issue #671).** In `:session` mode the `variables` (`statement_timeout`, `lock_timeout` and the like) are applied with `SET` after connect, and `PG::Connection#reset` opens a new backend without them. pgmq-ruby's checkout health check resets an unhealthy pooled connection (`finished?` or `CONNECTION_BAD` since #332, and an intermediate state such as `CONNECTION_STARTED` since pgmq-ruby 0.9.0), so that connection went on serving the job or streams pool with the server's defaults. Each connection the `:session` connect lambda opens now re-applies its `SET`s when it is reset, whoever resets it. A connection whose `SET`s do not all complete, after a connect or a reset, is closed before the error reaches the caller, so it is never pooled without them; with pg 1.5.9 or later the next checkout resets it and applies the `SET`s again (an older pg cannot reset a closed connection, so it is replaced when the pool is reloaded before the last stale-connection retry; the call itself is retried only for a stale-connection error, so a `SET` that always fails, such as an invalid value, fails each time). The completion pipeline's own reset (#619) no longer applies the `SET`s itself (they ran twice), and a `SET` that fails there is now logged as `Resetting the connection or re-applying its session variables failed` and leaves the connection closed, where before the session carried on without its `variables`. `:options` mode, a String URL and the shared ActiveRecord connection are unaffected. Refs #671.
84
+ - **A member-keyed presence `touch` no longer probes `information_schema` on a table without the seat columns, and a forced re-check no longer restarts the backoff (issue #666).** On a `pgbus_presence_members` table where `rails g pgbus:add_presence_seats` has not run, every member-keyed `touch`, `leave` and `sweep!` re-probed a cached "no seats" answer before it ran and restarted the #665 backoff at 30 s. The streamer touches once per connection per heartbeat, so a process with N member-keyed connections sent N catalog queries every `streams_heartbeat_interval` (15 s by default), and its backoff never took effect. A member-keyed `touch` now uses the cached answer and re-checks only on the backoff's schedule: three touches after a reset send one probe instead of four, and none while a "no" is cached. Assumed: on a table migrated under a running process, such a `touch` can also refresh that member's seat rows until the next re-check (at most 10 minutes, `SCHEMA_RECHECK_MAX_SECONDS`); it is an `UPDATE` of `last_seen_at`, so nothing is deleted. A member-keyed `leave` and `sweep!` still re-check a cached "no" before they delete, so they never delete seat rows on a migrated table (#515), now with one probe instead of up to two, answered from that probe. That re-check leaves the backoff alone: over a fresh "no" it changes neither the step nor the schedule however many disconnects force one, and over a "no" already due it is the timed re-check, one step. `reset_schema_cache!` still re-probes at once and starts again from 30 s. Refs #666.
85
+
86
+ - **pgmq-ruby 0.9.0 (was 0.8.2); the gemspec now requires `~> 0.9.0` (issue #656).** What reaches pgbus users is the connection pool: pgmq-ruby's checkout health check now resets a pooled connection in any state other than `CONNECTION_OK`, so a connection a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`) is recovered on the next checkout. Before, the checkout handed it out again, libpq refused every send (`no connection to the server`), and pgbus's stale-connection retry only recovered it on its last attempt by dropping both pools (#645): now the call succeeds on the first attempt, with no retry, no pool reload and no warning. pgmq-ruby also resets a connection whose call raised `PG::ConnectionBad` or `PG::UnableToSend` before it goes back to the pool (not a connection pgbus hands it through a callable, which it neither resets nor closes: the shared ActiveRecord connection, and dedicated connections in `connection_guc_mode = :session` with database.yml `variables`); native statements re-prepare on the new backend as on any reconnect. pgbus keeps its reload before the last stale retry for a connection that still fails after the health check passed it. A checkout reset of a connection in `connection_guc_mode = :session` with `variables` applies its `SET`s again (#671). `produce_topic` and `produce_batch_topic` now raise `PGMQ::Errors::MessageInvalidError` for a message that is not a String or headers that are neither a String nor nil, as `produce` has since 0.8.0. `Client#publish_to_topic` (what `Pgbus.publish` and the outbox poller call; `Pgbus::Testing`'s fake and inline modes never reach PGMQ) serializes the payload and headers to JSON Strings first, so it is unaffected; `headers: false`, which pgmq-ruby dropped before with an integer delay (and stored as JSON `false` with a fractional one) and now rejects, is passed as nil, so it is dropped at any delay. `spec/integration/connection_failure_spec.rb` now asserts the mid-reset connection is recovered at checkout (it failed on 0.8.2), in place of the two examples that pinned the old last-retry recovery. Refs #656.
37
87
 
38
88
  ## [0.25.1] - 2026-11-15
39
89
 
data/README.md CHANGED
@@ -820,6 +820,38 @@ Uses PostgreSQL session-level advisory locks (`pg_try_advisory_lock`). The lock
820
820
 
821
821
  How Pgbus integrates with your application's transactions and tracks groups of related work: outbox for atomic publish, batches for fan-out coordination, archive compaction for keeping the queue tables small.
822
822
 
823
+ ### Coalescing enqueues
824
+
825
+ Every `perform_later` is one send, so one database round trip. A unit of work that enqueues several jobs (a request that records a few events, a job that fans out follow-ups) can send them together instead:
826
+
827
+ ```ruby
828
+ Pgbus.coalesce do
829
+ EventJob.perform_later("a")
830
+ EventJob.perform_later("b")
831
+ EventJob.perform_later("c")
832
+ end # one send_batch here, per (queue, priority, delay)
833
+ ```
834
+
835
+ Or for every request, through an opt-in Rack middleware that runs the request inside the scope and sends before it returns the response, never after it (a crash once the client has its answer cannot lose a job):
836
+
837
+ ```ruby
838
+ # config/application.rb
839
+ config.pgbus.coalesce_requests = true # inserted after ActionDispatch::Executor (application.rb or an initializer)
840
+ config.pgbus.coalesce_requests_on_failure = :raise # the default; :report or a callable
841
+
842
+ # or by hand
843
+ config.middleware.insert_after ActionDispatch::Executor, Pgbus::ActiveJob::Coalesce::Middleware, on_failure: :report
844
+ ```
845
+
846
+ - **What is held.** A job that the bulk path can send, serialized at `perform_later` (an argument that cannot be serialized raises there, as outside a scope, and a later change to the job or its arguments is not sent). These go out at once, as they do outside a scope: jobs with `ensures_uniqueness` or `limits_concurrency` (the single enqueue path takes or checks their lock or slot), `retry_on` re-enqueues, deploy task runs, batch members (outside their own batch's block), workflow steps, jobs enqueued on another thread or fiber, and jobs enqueued after the flush has started (for example while a streaming body is iterated). On Rails 7.2+ a job that Rails defers to after commit (`enqueue_after_transaction_commit`) reaches the scope at commit, and a rolled-back one never does; a job that does not defer is held like any other; Rails 7.1 has no deferral, so there a job enqueued inside a transaction is held, and sent, whatever the transaction does, as it is sent without a scope.
847
+ - **Future jobs.** A bulk-eligible `set(wait:)` / `set(wait_until:)` job is held too and sent at the flush with the delay left then (never the time it waited in the scope), one `send_batch` per (queue, priority, delay), so a staggered fan-out costs one send per slice (per chunk, past `config.coalesce_chunk_size`). `perform_all_later` and `b.add` group future jobs the same way. A scheduled job with uniqueness or a concurrency limit still takes the single path, so its lock and slot lease cover the wait.
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
+ - **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
+ - **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
+ - **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
+
853
+ The scope emits `pgbus.coalesce` with `buffered`, `sent`, `retried`, `failed` and `duration` (ms).
854
+
823
855
  ### Batches
824
856
 
825
857
  Coordinate groups of jobs with callbacks when all complete:
@@ -833,7 +865,7 @@ batch = Pgbus.batch(description: "Import users", properties: { initiated_by: cur
833
865
  end
834
866
  ```
835
867
 
836
- `b.add` takes job instances (each keeps its own `.set(wait:, queue:)`) and sends them in one bulk enqueue. The batch row exists before the block runs and stays pending until it returns, so a job that finishes while the block is still adding cannot finish the batch early. 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 block that 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. Callbacks are job classes or configured instances, never blocks: they are stored on the batch row.
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.
837
869
 
838
870
  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.
839
871
 
@@ -841,9 +873,9 @@ Inside a job, `batch { |b| ... }` opens a new batch the same way, and a job that
841
873
 
842
874
  | Callback | Fired when |
843
875
  |----------|------------|
844
- | `on_complete` | All jobs completed (success or failure). `on_finish` is a deprecated alias until 1.0 |
876
+ | `on_complete` | All jobs completed (success or failure). `on_finish` is a deprecated alias, removed in 2.0 |
845
877
  | `on_success` | All jobs completed successfully (zero failed) |
846
- | `on_failure` | At least one job was dead-lettered. `on_discard` is a deprecated alias until 1.0 |
878
+ | `on_failure` | At least one job failed (dead-lettered, or never sent) |
847
879
 
848
880
  Callback jobs given as a bare class receive the batch `properties` hash as their argument:
849
881
 
@@ -871,8 +903,8 @@ The lock is taken at the top of the block (or at `enqueue`) and held until the b
871
903
 
872
904
  #### How batches work
873
905
 
874
- 1. The top of the `Pgbus.batch` block (or the first `batch.enqueue`) creates a tracking row in `pgbus_batches` with `status: "pending"`
875
- 2. Each job enqueued in the block is tagged with the `pgbus_batch_id` in its payload
906
+ 1. The top of the `Pgbus.batch` block (or the first `batch.enqueue`) creates a tracking row in `pgbus_batches`: `status: "building"` with its owner process when opened in a pgbus process (`rails generate pgbus:add_batch_owner` on an existing install), else `status: "pending"`; a built batch moves to `pending` when its block returns
907
+ 2. Each job enqueued in the block is tagged with the `pgbus_batch_id` in its payload and counted in before it is sent: `total_jobs` goes up and one `pgbus_batch_executions` row per job is inserted, in one statement for a whole bulk or chunk
876
908
  3. After each job completes or is dead-lettered, the executor atomically updates the batch counters
877
909
  4. When `completed_jobs + discarded_jobs == total_jobs`, the batch status flips to `"finished"` and callback jobs are enqueued
878
910
  5. The dispatcher cleans up finished batches older than 7 days
@@ -11,11 +11,20 @@ module Pgbus
11
11
 
12
12
  scope :finished, -> { where(status: "finished") }
13
13
  scope :stale, ->(before:) { finished.where("finished_at < ?", before) }
14
+ # building (issue #683): the batch's block is still open in the process
15
+ # owner_process_id names; no sweep changes its status and no finish
16
+ # closes it (counters still move) until the block closes the build
17
+ # (close_build!) or the owner stops heartbeating.
18
+ UNFINISHED = %w[building pending processing].freeze
19
+
20
+ scope :building, -> { where(status: "building") }
14
21
  scope :pending, -> { where(status: "pending") }
15
22
  scope :processing, -> { where(status: "processing") }
16
23
  scope :without_executions, -> { where.not(batch_id: BatchExecution.select(:batch_id)) }
17
24
 
18
- # Deprecated alias until 1.0: after the column is dropped this reads failed_jobs.
25
+ # Deprecated alias, removed in 2.0, kept for installs that have not run
26
+ # pgbus:add_batch_executions: after the column is dropped this reads
27
+ # failed_jobs.
19
28
  def discarded_jobs
20
29
  has_attribute?(:discarded_jobs) ? self[:discarded_jobs] : failed_jobs
21
30
  end
@@ -23,8 +32,10 @@ module Pgbus
23
32
  # Atomically add n to total_jobs on an unfinished batch. Returns true.
24
33
  # Raises Batch::AlreadyFinished when the row is already finished (0 rows
25
34
  # updated) — the adder-before-insert contract open batches (#415) rely on.
26
- def self.increment_total_jobs!(batch_id, count) # rubocop:disable Naming/PredicateMethod
27
- updated = where(batch_id: batch_id, status: %w[pending processing])
35
+ # +statuses+: a batch scope counts a chunk into a batch still building
36
+ # only, never into one the sweep reaped (issue #683).
37
+ def self.increment_total_jobs!(batch_id, count, statuses: UNFINISHED) # rubocop:disable Naming/PredicateMethod
38
+ updated = where(batch_id: batch_id, status: statuses)
28
39
  .update_all(["total_jobs = total_jobs + ?", count])
29
40
  raise Batch::AlreadyFinished, "Can't add jobs into an already finished batch" if updated.zero?
30
41
 
@@ -33,9 +44,19 @@ module Pgbus
33
44
 
34
45
  # Reverse of increment_total_jobs! for a job that will never run. Floored
35
46
  # at zero; a finished row is left alone.
36
- def self.decrement_total_jobs!(batch_id)
37
- where(batch_id: batch_id, status: %w[pending processing])
38
- .update_all(["total_jobs = GREATEST(total_jobs - 1, 0)"])
47
+ def self.decrement_total_jobs!(batch_id, count = 1)
48
+ where(batch_id: batch_id, status: UNFINISHED)
49
+ .update_all(["total_jobs = GREATEST(total_jobs - ?, 0)", count])
50
+ end
51
+
52
+ # The block that builds the batch returned: building -> pending, guarded
53
+ # so the block and the sweep's reaping (Sweep.reap_abandoned_builds)
54
+ # cannot both win. Raises AlreadyFinished when the build was reaped.
55
+ def self.close_build!(batch_id)
56
+ closed = where(batch_id: batch_id, status: "building").update_all(status: "pending")
57
+ raise Batch::AlreadyFinished, "Can't close the build of batch #{batch_id}: the sweep reaped it" if closed.zero?
58
+
59
+ closed
39
60
  end
40
61
 
41
62
  # Resolve a batch member and count it, in one statement and no
@@ -23,8 +23,63 @@ module Pgbus
23
23
  end
24
24
  end
25
25
 
26
+ # insert_for! for many members of one batch, in one statement (issue
27
+ # #683): +rows+ are [job_id, queue_name] pairs, bound as two arrays so
28
+ # the statement keeps three parameters whatever the count.
29
+ def self.insert_all_for!(batch_id:, rows:)
30
+ return if rows.empty?
31
+
32
+ job_ids, queue_names = rows.transpose
33
+ connection_pool.with_connection do |conn|
34
+ conn.exec_query(
35
+ "INSERT INTO #{table_name} (batch_id, job_id, queue_name, created_at) " \
36
+ "SELECT $1, r.job_id, r.queue_name, $4 FROM unnest($2::varchar[], $3::varchar[]) AS r(job_id, queue_name) " \
37
+ "ON CONFLICT (job_id) DO NOTHING",
38
+ "BatchExecution Insert All",
39
+ [batch_id, encode_array(job_ids), encode_array(queue_names), Time.current]
40
+ )
41
+ end
42
+ end
43
+
26
44
  def self.backfill!(job_id, msg_id:, queue_name:)
27
45
  where(job_id: job_id).update_all(msg_id: msg_id, queue_name: queue_name)
28
46
  end
47
+
48
+ # backfill! for a whole send group in one statement (issue #683): +rows+
49
+ # are [job_id, msg_id, queue_name] triples.
50
+ def self.backfill_all!(rows)
51
+ return if rows.empty?
52
+
53
+ job_ids, msg_ids, queue_names = rows.transpose
54
+ connection_pool.with_connection do |conn|
55
+ conn.exec_query(
56
+ "UPDATE #{table_name} AS e SET msg_id = v.msg_id, queue_name = v.queue_name " \
57
+ "FROM unnest($1::varchar[], $2::bigint[], $3::varchar[]) AS v(job_id, msg_id, queue_name) " \
58
+ "WHERE e.job_id = v.job_id",
59
+ "BatchExecution Backfill All",
60
+ [encode_array(job_ids), encode_array(msg_ids), encode_array(queue_names)]
61
+ )
62
+ end
63
+ end
64
+
65
+ # Deletes the rows of +job_ids+ in one statement; returns how many went.
66
+ def self.delete_all_for!(job_ids)
67
+ return 0 if job_ids.empty?
68
+
69
+ connection_pool.with_connection do |conn|
70
+ conn.exec_delete(
71
+ "DELETE FROM #{table_name} WHERE job_id = ANY($1::varchar[])",
72
+ "BatchExecution Delete All",
73
+ [encode_array(job_ids)]
74
+ )
75
+ end
76
+ end
77
+
78
+ # A Postgres array literal, so an array binds as one text parameter the
79
+ # same way on every Rails version.
80
+ def self.encode_array(values)
81
+ PG::TextEncoder::Array.new.encode(values.map { |v| v&.to_s })
82
+ end
83
+ private_class_method :encode_array
29
84
  end
30
85
  end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/active_record"
5
+ require_relative "migration_path"
6
+
7
+ module Pgbus
8
+ module Generators
9
+ class AddBatchOwnerGenerator < Rails::Generators::Base
10
+ include ActiveRecord::Generators::Migration
11
+ include MigrationPath
12
+
13
+ source_root File.expand_path("templates", __dir__)
14
+
15
+ desc "Add owner_process_id to pgbus_batches, so a batch can be built by a watched process (issue #683)"
16
+
17
+ class_option :database,
18
+ type: :string,
19
+ default: nil,
20
+ desc: "Use a separate database for pgbus tables (e.g. --database=pgbus)"
21
+
22
+ def create_migration_file
23
+ migration_template "add_batch_owner.rb.erb",
24
+ File.join(pgbus_migrate_path, "add_pgbus_batch_owner.rb")
25
+ end
26
+
27
+ def display_post_install
28
+ say ""
29
+ say "Pgbus batch owner column installed!", :green
30
+ say ""
31
+ say "Next steps:"
32
+ say " 1. Run: rails db:migrate#{migrate_command_suffix}"
33
+ say " 2. Restart pgbus: bin/pgbus start"
34
+ say ""
35
+ say "A Pgbus.batch opened in a pgbus process (a worker, consumer, dispatcher or"
36
+ say "scheduler) is now built: its perform_later calls are held and sent together"
37
+ say "when the block returns."
38
+ say ""
39
+ end
40
+
41
+ private
42
+
43
+ def migration_version
44
+ "[#{ActiveRecord::Migration.current_version}]"
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,13 @@
1
+ class AddPgbusBatchOwner < ActiveRecord::Migration<%= migration_version %>
2
+ # The pgbus_processes row of the process that builds a batch (issue #683):
3
+ # the stalled-batch sweep reaps a build only once that process stops
4
+ # heartbeating. No index: the sweep reads it only for batches in
5
+ # status "building", which idx_pgbus_batches_status narrows.
6
+ def up
7
+ add_column :pgbus_batches, :owner_process_id, :bigint unless column_exists?(:pgbus_batches, :owner_process_id)
8
+ end
9
+
10
+ def down
11
+ remove_column :pgbus_batches, :owner_process_id if column_exists?(:pgbus_batches, :owner_process_id)
12
+ end
13
+ end
@@ -116,6 +116,7 @@ class CreatePgbusTables < ActiveRecord::Migration<%= migration_version %>
116
116
  t.integer :completed_jobs, null: false, default: 0
117
117
  t.integer :failed_jobs, null: false, default: 0
118
118
  t.string :status, null: false, default: "pending"
119
+ t.bigint :owner_process_id
119
120
  t.datetime :created_at, null: false, default: -> { "CURRENT_TIMESTAMP" }
120
121
  t.datetime :finished_at
121
122
  end