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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c71d931a9535fbd5de255faea22fec90d0b39b156e91bf43dcbce1b5741947d9
4
- data.tar.gz: 3d5603ca4af7d362fc79a4e9da056deb727beea997102c5ab5ad4bca68790891
3
+ metadata.gz: 9b4a4d3841816d583e3e1f7099c28b94644f0eb1a7fd10f2ef18ea4a2a668b2b
4
+ data.tar.gz: 57e6a90e66111b1c8c3b529c7e7703f6c01f9521fd640122013b3a1b20e82d75
5
5
  SHA512:
6
- metadata.gz: 85600c2edcff67e30302f53cf06fa0e31acc411700213f5324a3254c85b06c0d8694ed4d29cb0b24a3f49a15e1f488a2af4176dd7f0a6e444c27370edec53db7
7
- data.tar.gz: c055469e1e4d110b5f64d84d4591c618c5e057d2c2ca901683fc514823d8ff21ac7d0dd9160c17d0be0792f7e806bfb73230a9480342cf3735416f00a81052a0
6
+ metadata.gz: 90af08c73871898b31f9f689603b8c0311d2a6c6302d9f457275b74710b21f3e73c6b81cf4116c27027cbb88342750d2ef0f815af77e41083b03f534b9408059
7
+ data.tar.gz: f4c799bf12d564dcbe39d66664e65266d1ca131836f817629227930020abc2eec5d9f6c4ee0e541d0eae39cfbef7decb76fc41c5ea2bddb415f3f34d5047e206
data/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ### Added
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
+
3
37
  ## [0.27.2] - 2026-11-21
4
38
 
5
39
  ### Fixed
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
@@ -5,11 +5,22 @@ require "active_job"
5
5
  module Pgbus
6
6
  module ActiveJob
7
7
  class Adapter
8
+ # Inside Pgbus.coalesce a bulk-eligible job is serialized now and held,
9
+ # then sent with the rest when the scope ends (issue #682); everything
10
+ # else is sent now. With no scope open this costs one fiber-local read.
8
11
  def enqueue(active_job)
12
+ scope = Coalesce.current
13
+ return active_job if scope && coalesce(scope, active_job)
14
+
9
15
  enqueue_job(active_job)
10
16
  end
11
17
 
18
+ # A future job is held too inside Pgbus.coalesce (issue #686); its delay
19
+ # is worked out at the flush, from +timestamp+.
12
20
  def enqueue_at(active_job, timestamp)
21
+ scope = Coalesce.current
22
+ return active_job if scope && coalesce(scope, active_job, due_at: timestamp)
23
+
13
24
  enqueue_job(active_job, delay: delay_until(timestamp))
14
25
  end
15
26
 
@@ -30,19 +41,133 @@ module Pgbus
30
41
  individual.each { |j| enqueue_one_of_all(j) }
31
42
 
32
43
  # Group by priority too: send_batch routes through the queue strategy,
33
- # so a mixed-priority bulk send needs one produce_batch per level.
34
- bulk.group_by { |j| [j.queue_name || Pgbus.configuration.default_queue, j.try(:priority)] }
35
- .each do |(queue, priority), jobs|
36
- immediate, scheduled = jobs.partition { |j| !scheduled_in_future?(j) }
37
- enqueue_immediate(queue, immediate, priority: priority)
38
- scheduled.each { |j| enqueue_one_of_all(j) }
44
+ # so a mixed-priority bulk send needs one produce_batch per level. And
45
+ # by delay (issue #686): PGMQ's batch send takes one delay, so jobs
46
+ # scheduled for the same second go out together, a staggered fan-out
47
+ # as one send per slice.
48
+ bulk.group_by { |j| [j.queue_name || Pgbus.configuration.default_queue, j.try(:priority), job_delay(j)] }
49
+ .each do |(queue, priority, delay), jobs|
50
+ enqueue_immediate(queue, jobs, priority: priority, delay: delay)
39
51
  end
40
52
 
41
53
  active_jobs.count(&:successfully_enqueued?)
42
54
  end
43
55
 
56
+ # Sends what a Coalesce scope held, as [job, payload, due_at] entries
57
+ # with the payload serialized at perform_later (issue #682): one
58
+ # send_batch per (queue, priority, delay) group (issue #686), through
59
+ # the bulk path enqueue_all uses, then
60
+ # each job left unsent on its own. Queue and priority are the payload's,
61
+ # so a job changed after perform_later goes where it was sent. Never
62
+ # raises: what still fails is the result's +failed+, for on_failure.
63
+ # +counted+: a batch scope already counted the entries into their batch
64
+ # (issue #683), so the send does not count them again.
65
+ def deliver_coalesced(entries, counted: false)
66
+ jobs = entries.map(&:first)
67
+ jobs.each do |job|
68
+ job.successfully_enqueued = false
69
+ job.enqueue_error = nil
70
+ end
71
+ error = nil
72
+ standing = {}.compare_by_identity
73
+ entries.each { |job, payload, _| standing[job] = true if payload[Batch::METADATA_KEY] } if counted
74
+ groups = entries.group_by do |_, payload, due_at|
75
+ [payload["queue_name"] || Pgbus.configuration.default_queue, payload["priority"], due_delay(due_at)]
76
+ end
77
+ groups.each do |(queue, priority, delay), group|
78
+ enqueue_immediate(queue, group.map(&:first), priority: priority, delay: delay, payloads: group.map { _1[1] },
79
+ counted: standing, tracked: counted)
80
+ rescue StandardError => e
81
+ error = e
82
+ end
83
+ sent = jobs.count(&:successfully_enqueued?)
84
+ unsent = entries.reject { |job, *| job.successfully_enqueued? }
85
+ retried, failed, error = retry_coalesced(unsent, standing, error)
86
+ Coalesce::Result.new(buffered: entries.size, sent: sent, retried: retried, failed: failed, error: error)
87
+ end
88
+
44
89
  private
45
90
 
91
+ # Holds +active_job+ in +scope+, serialized now, when the bulk path can
92
+ # send it, a future one included (+due_at+, its scheduled time: the delay is
93
+ # what is left at the flush, issue #686). Sent at once instead:
94
+ # uniqueness and concurrency (their lock or slot, and its lease over the
95
+ # delay, is taken at enqueue), a retry re-enqueue (#424) and a deploy task run's job (#660), which need the
96
+ # single path's bookkeeping, a batch member outside its own batch's
97
+ # scope (Pgbus.batch opens one for its block, issue #683; an outer
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).
101
+ # Serializing now raises an unserializable argument here, as outside a
102
+ # scope, and keeps a later change to the job or its arguments out of
103
+ # the message.
104
+ def coalesce(scope, active_job, due_at: nil)
105
+ return false if Uniqueness.uniqueness_config(active_job) || concurrency_config(active_job)
106
+ return false if active_job.executions.to_i.positive?
107
+ return false if active_job.is_a?(DeployTaskRunId) && active_job.deploy_task_run_id
108
+ 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?
110
+
111
+ payload = tag_bulk_member(FairShare.inject_metadata(active_job, Serializer.serialize_job_hash(active_job)), active_job)
112
+ scope.push(self, active_job, payload, due_at)
113
+ end
114
+
115
+ # Whole seconds until +job+ is due, 0 for a job due now.
116
+ def job_delay(job)
117
+ scheduled_in_future?(job) ? delay_until(job.scheduled_at.to_f) : 0
118
+ end
119
+
120
+ # Whole seconds until +due_at+ (a scheduled time held by a coalesce
121
+ # scope), counted from now, the flush: 0 for none or a time past.
122
+ def due_delay(due_at)
123
+ due_at ? delay_until(due_at.to_f) : 0
124
+ end
125
+
126
+ # Each held job the bulk left unsent, on its own: for a job coalesce
127
+ # admitted, the single path is the plain send, plus a batch member's
128
+ # count and backfill. Returns [retried count, failed jobs, the last error].
129
+ def retry_coalesced(entries, counted, error)
130
+ retried = 0
131
+ failed = []
132
+ entries.each do |job, payload, due_at|
133
+ if resend_coalesced(job, payload, counted: counted.key?(job), delay: due_delay(due_at))
134
+ retried += 1
135
+ else
136
+ failed << job
137
+ end
138
+ rescue StandardError => e
139
+ error = e
140
+ failed << job
141
+ end
142
+ [retried, failed, error]
143
+ end
144
+
145
+ # A batch member not +counted+ is counted in first, as a single
146
+ # enqueue is, and uncounted when its send fails before any message can
147
+ # exist; one the bulk counted keeps that count (its send's outcome is
148
+ # unknown) and is only sent.
149
+ def resend_coalesced(job, payload, counted:, delay: 0) # rubocop:disable Naming/PredicateMethod -- sends; the result says whether
150
+ queue = payload["queue_name"] || Pgbus.configuration.default_queue
151
+ priority = payload["priority"]
152
+ member = payload[Batch::METADATA_KEY]
153
+ Batch.track_enqueue(payload) if member && !counted
154
+ begin
155
+ msg_id = Pgbus.client.send_message(queue, payload, delay: delay, priority: priority)
156
+ rescue StandardError => e
157
+ Batch.untrack_enqueue(payload) if member && !counted && !ambiguous_delivery?(e)
158
+ raise
159
+ end
160
+ unless msg_id
161
+ Batch.untrack_enqueue(payload) if member && !counted
162
+ return false
163
+ end
164
+
165
+ job.provider_job_id = msg_id
166
+ job.successfully_enqueued = true
167
+ Batch.backfill_executions([payload], [msg_id], physical_queue(queue, priority)) if member
168
+ true
169
+ end
170
+
46
171
  # One job of an enqueue_all that cannot take the bulk path.
47
172
  # enqueue_with_concurrency marks it once it is live, as enqueue_immediate
48
173
  # marks the bulk; on perform_later the adapter never sets
@@ -465,16 +590,30 @@ module Pgbus
465
590
  batch_id ? payload_hash.merge(Batch::METADATA_KEY => batch_id) : payload_hash
466
591
  end
467
592
 
468
- def enqueue_immediate(queue, jobs, priority: nil)
593
+ # +payloads+: already built (a Coalesce scope serialized them at push).
594
+ # +counted+ (deliver_coalesced) collects the batch members whose count
595
+ # stands after a failure, so their retry does not count them twice.
596
+ # The bookkeeping around the send is one statement per group (issue
597
+ # #683): track_bulk's insert, the backfill, or the untrack on a failure.
598
+ # +tracked+: the payloads are already counted into their batch.
599
+ # +delay+: whole seconds every job of the group waits (issue #686).
600
+ def enqueue_immediate(queue, jobs, priority: nil, delay: 0, payloads: nil, counted: nil, tracked: false)
469
601
  return if jobs.empty?
470
602
 
471
- payloads = jobs.map do |j|
603
+ payloads ||= jobs.map do |j|
472
604
  tag_bulk_member(FairShare.inject_metadata(j, Serializer.serialize_job_hash(j)), j)
473
605
  end
474
- track_bulk(payloads)
606
+ track_bulk(payloads) unless tracked
607
+ tracked = true
475
608
  physical = physical_queue(queue, priority)
476
609
  msg_ids = nil
477
- msg_ids = Pgbus.client.send_batch(queue, payloads, priority: priority)
610
+ sending = true
611
+ msg_ids = if delay.positive?
612
+ Pgbus.client.send_batch(queue, payloads, delay: delay, priority: priority)
613
+ else
614
+ Pgbus.client.send_batch(queue, payloads, priority: priority)
615
+ end
616
+ sent = true
478
617
 
479
618
  unless msg_ids.is_a?(Array) && msg_ids.size == jobs.size
480
619
  raise Pgbus::EnqueueError, "Pgbus batch enqueue failed: expected #{jobs.size} ids, got #{msg_ids&.size || 0}"
@@ -484,19 +623,48 @@ module Pgbus
484
623
  job.provider_job_id = id
485
624
  job.successfully_enqueued = true
486
625
  end
487
- payloads.zip(msg_ids).each { |payload, id| Batch.backfill_execution(payload, id, physical) }
626
+ Batch.backfill_executions(payloads, msg_ids, physical)
488
627
  rescue Pgbus::EnqueueError
489
- Array(payloads).each_with_index do |payload, index|
490
- Batch.untrack_enqueue(payload) if msg_ids.nil? || msg_ids[index].nil?
491
- end
628
+ unsent = Array(payloads).each_index.select { |index| msg_ids.nil? || msg_ids[index].nil? }
629
+ # Noted before the untrack, which can raise: a member with an id keeps
630
+ # its count either way.
631
+ note_counted(counted, jobs, payloads, Array(payloads).each_index.to_a - unsent)
632
+ # The unsent ones are uncounted here: their retry counts them again.
633
+ unsent.each { |index| counted&.delete(jobs[index]) }
634
+ Batch.untrack_enqueue_all(payloads.values_at(*unsent))
492
635
  raise
493
- rescue Pgbus::SchemaNotReady => e
494
- Pgbus.logger.error { "[Pgbus] #{e.message}" }
636
+ rescue StandardError => e
637
+ Pgbus.logger.error { "[Pgbus] #{e.message}" } if e.is_a?(Pgbus::SchemaNotReady)
638
+ # After the send returned, its messages are live: the counts stand.
639
+ settle_counted(counted, jobs, payloads, ambiguous: sent || (sending && ambiguous_delivery?(e))) if tracked
495
640
  raise
496
641
  ensure
497
642
  jobs.each { |j| forget_enqueue_batch_id(j) }
498
643
  end
499
644
 
645
+ # A coalesce delivery's members after a failed send (+counted+ set):
646
+ # when the send may have committed, their counts stand and the retry
647
+ # does not count them again; when no message can exist, they are
648
+ # uncounted now and the retry counts each again, so a member that
649
+ # fails twice leaves no row behind. Without +counted+ (enqueue_all) the
650
+ # counts stand, as they always did.
651
+ def settle_counted(counted, jobs, payloads, ambiguous:)
652
+ return unless counted
653
+ return note_counted(counted, jobs, payloads, Array(payloads).each_index.to_a) if ambiguous
654
+
655
+ jobs.each { |job| counted.delete(job) }
656
+ Batch.untrack_enqueue_all(payloads)
657
+ end
658
+
659
+ # The members at +indexes+ stay counted in their batch (their send's
660
+ # outcome is unknown, or it returned their id): a retry sends them
661
+ # without counting them again.
662
+ def note_counted(counted, jobs, payloads, indexes)
663
+ return unless counted
664
+
665
+ indexes.each { |index| counted[jobs[index]] = true if payloads[index][Batch::METADATA_KEY] }
666
+ end
667
+
500
668
  # One guarded increment per batch for the whole bulk, not one per job.
501
669
  # When a later batch refuses (finished), the batches already counted are
502
670
  # uncounted before the error goes up: nothing has been sent yet.
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module ActiveJob
5
+ class Coalesce
6
+ # Coalesces a request's enqueues (issue #682): the request runs inside
7
+ # Pgbus.coalesce, and the buffer is sent before the response tuple is
8
+ # returned, never after the response (rack.response_finished), so a
9
+ # crash once the client has its answer cannot lose a job. A job
10
+ # enqueued while a streaming body is iterated goes out at once.
11
+ #
12
+ # Opt-in: insert it after ActionDispatch::Executor, or set
13
+ # config.pgbus.coalesce_requests = true (Pgbus::Engine does the insert).
14
+ # With on_failure: :raise (the default) a job that cannot be sent fails
15
+ # the request; an endpoint that must not answer 500 after committing its
16
+ # writes passes :report or a callable. Inserted after the Executor, the
17
+ # error surfaces above ActionDispatch::ShowExceptions, so the client
18
+ # gets the server's bare 500, not the app's error page.
19
+ class Middleware
20
+ def initialize(app, on_failure: :raise)
21
+ Coalesce.validate_on_failure!(on_failure)
22
+ @app = app
23
+ @on_failure = on_failure
24
+ end
25
+
26
+ # A flush that raises (on_failure: :raise, or a callable that raises)
27
+ # closes the body first, as Rack requires of a response it will never
28
+ # send.
29
+ def call(env)
30
+ response = nil
31
+ Pgbus.coalesce(on_failure: @on_failure) { response = @app.call(env) }
32
+ rescue Exception # rubocop:disable Lint/RescueException -- closes, then re-raises
33
+ close_body(response&.at(2))
34
+ raise
35
+ end
36
+
37
+ private
38
+
39
+ # A body whose close raises must not hide the error being raised.
40
+ def close_body(body)
41
+ body.close if body.respond_to?(:close)
42
+ rescue StandardError => e
43
+ Pgbus.logger.warn { "[Pgbus] Closing the response body failed: #{e.class}: #{e.message}" }
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end