Repository navigation
feat(batches): open batches, batch accessor on jobs, configured callback instances - #422
Conversation
…rity routing Two defects found reviewing #417/#419/#420 against issues #413/#414/#418, each reproduced with a RED test before the fix. 1. A batch whose `enqueue` block crashed before enqueuing anything was immortal. `Sweep.start_stalled_pending` moved it pending -> processing with `total_jobs = 0`, but `finish_if_empty!` required `total_jobs > 0` and `Sweep#counters_terminal?` required `total_jobs.positive?` — guards meant to protect pre-migration in-flight batches. Nothing could close it: it sat in `processing` forever, `cleanup_batches` only deletes `finished`, and `on_finish` never fired. Both guards now test `completed_jobs + failed_jobs = total_jobs` alone; a legacy in-flight batch still has counters short of a positive total and stays on the counter path. 2. `Client#send_batch` targeted the bare `pgbus_<queue>` table, which the priority strategy never creates, so `ActiveJob.perform_all_later` raised `PG::UndefinedTable` whenever `priority_levels > 1` — and would have written to a queue no worker reads. `send_batch` now routes through the QueueFactory strategy and takes `priority:`; `enqueue_all` groups bulk jobs by queue AND priority; `Outbox::Poller` passes through the priority it already grouped by (its single-send fallback too, so both paths place messages identically). ## Test Coverage - spec/integration/batch_flow_spec.rb: crashed enqueue block finishes via sweep and fires on_finish; pre-migration in-flight batch still left alone - spec/integration/bulk_enqueue_priority_spec.rb: perform_all_later lands on the _pN sub-queues workers actually read - spec/pgbus/client_spec.rb: send_batch routes to the requested priority level and falls back to default_priority - spec/pgbus/active_job/adapter_spec.rb: one batch per priority level - spec/pgbus/batch_sweep_spec.rb: zero-total processing batch is finished ## Verification - [x] bundle exec rubocop passes - [x] bundle exec rspec spec/pgbus spec/generators — 4004 examples, 0 failures - [x] integration suite — 207 examples, 0 failures
…ack instances Closes #415. ## Summary **Open batches.** `Batch#enqueue` is re-callable while the batch is unfinished. Later calls add to the existing group via the guarded `BatchEntry.increment_total_jobs!` instead of hitting the unique index on `batch_id`; adding to a finished batch raises `Batch::AlreadyFinished`. Execution rows are inserted as the block enqueues, before `total_jobs` is bumped, so the single-winner finish always sees outstanding work; a `check_finished!` after the bump covers a block whose jobs all completed while it was still open. `Batch.find` now returns a rehydrated `Pgbus::Batch` handle (BREAKING pre-1.0: it used to return the attributes Hash) with `status`, `total_jobs`, `completed_jobs`, `failed_jobs`, `pending_jobs`, `progress_percentage`, `finished?`, `description` and `properties`. **`batch` accessor.** New `Pgbus::ActiveJob::BatchId` mixin, included on `ActiveJob::Base` from the engine alongside `Concurrency` and `Uniqueness`: `batch_id` / `callback_batch_id` accessors, both round-tripping through serialize/deserialize and both omitted when unset so unbatched payloads do not grow, plus a memoized `batch` reader. The executor assigns `batch_id` from the payload's `pgbus_batch_id` before `perform`, so a running job can call `batch.enqueue` to add siblings. **Configured callback instances.** `on_finish:`/`on_success:`/`on_failure:` accept an ActiveJob instance as well as a class. `.set` options resolve at batch-creation time into new `on_finish_job`/`on_success_job`/`on_failure_job` jsonb columns. At fire time the job is deserialized, given `callback_batch_id`, has its own `batch_id` cleared, and is enqueued on its configured queue and `scheduled_at`. Legacy class-name callbacks keep `perform_later(properties)`. The dashboard shows a configured callback's `job_class`. Migration ships in the install template and as `rails generate pgbus:add_batch_callback_jobs` (wired into `pgbus:update`). ## Test Coverage - spec/pgbus/active_job/batch_id_spec.rb: serialize/deserialize round-trip, omitted keys when unset, memoized batch reader, callback_batch_id precedence - spec/integration/batch_open_spec.rb: re-callable enqueue, empty re-open no-op, AlreadyFinished, batch stays open for stage-two jobs, find returns a usable handle, batch accessor inside a job, configured callback queue + callback_batch_id + nil batch_id, legacy class callback still gets properties - spec/pgbus/batch_spec.rb: find returns a handle with delegated readers; configured instance serialized at creation; bare class keeps the legacy column - spec/pgbus/active_job/executor_spec.rb: batch_id assigned before perform - spec/pgbus/engine_spec.rb: mixin included by the active_job initializer - spec/pgbus/generators + spec/generators: new migration detected and generated - spec/pgbus/web/batches_data_source_spec.rb: configured callback job_class shown ## Verification - [x] bundle exec rubocop passes - [x] bundle exec rspec spec/pgbus spec/generators — 4026 examples, 0 failures - [x] integration suite — 215 examples, 0 failures - [x] cd docs && bundle exec rake lint + rspec — clean
…batch is measurable client_bench's read section aborted with `undefined method 'run_guarded' for nil` — BenchStubs.build_mock_client never set @connection_health, which Client#guarded_read (and therefore every read_batch) goes through. The documented dequeue hot path had no working benchmark on any branch. Harness only; no gem code changed.
|
Running ultrareview automatically — This PR reworks core batch semantics with re-callable enqueue, race-sensitive finish guards, a breaking Batch.find return-type change, and a schema migration adding jsonb callback columns that deserialize stored ActiveJob instances at fire time — subtle bugs here could corrupt batch accounting,.... I'll post findings when complete. |
|
I can't run this ultrareview because your workspace has reached its monthly review limit. cubic has reviewed 102,664 of the 80,000 allowed lines of code this month. Reviews resume on 10 September 2026 (in 19 days). Enable flex capacity to cover overages automatically and resume reviews now. Learn how flex capacity works. To help optimise your usage, you can tune cubic to get the most out of your usage limits:
|
…ep, while_executing release (#425) Closes #423. Refs #416. ## Summary Second-pass review fixes for #417–#422. **Accounting (F1–F3).** Every batched enqueue now runs `BatchEntry.increment_total_jobs!` (guarded on an unfinished row) and the execution-row insert in ONE transaction, before `send_message`; a bulk `perform_all_later` increments once by N. `AlreadyFinished` raises at `perform_later` before anything is sent. The invariant `total_jobs == outstanding rows + completed + failed` holds at every commit point, so: the first block only flips pending→processing (guarded) and re-checks; a re-opened block never bumps at the end (a block that raises mid-way stays consistent); the empty batch finishes through the same single-winner path; the stalled-pending sweep never recomputes totals (it discarded counters → immortal batches). `Thread.current[:pgbus_batch_job_count]` removed. Legacy counter path only auto-finishes a processing batch. **Sweep (F4, F8).** Orphan phase probes the queue and DLQ by job_id before un-counting a msg_id-less row (a live message whose backfill failed was being un-counted → early on_success). Rows store the logical queue at insert. `Client#message_with_job_id?` expands `_pN` sub-queues for logical names. Stalled-pending needs no execution row within the threshold (activity guard); new `config.batch_stall_threshold` (default 300) replaces the constant. **:while_executing (F5).** Lock bound to the executing msg_id; released in the failure path; `acquire!(reacquire_same_message: true)` re-acquires a row left by a crashed attempt of the same message. Before: a failed attempt's row made every retry `:skipped` until DLQ. **Also:** configured callback instance on an unmigrated schema degrades to its class + WARN instead of being dropped (F6); blocked-job promotion keeps priority (F7); #419 CHANGELOG entry corrected — no `ensure` release exists (F9). ## Test Coverage - spec/pgbus/batch_spec.rb, batch_entry_spec.rb, batch_execution_spec.rb, active_job/adapter_spec.rb: RED-first for the accounting model - spec/integration/batch_flow_spec.rb: F1 (RED: total_jobs reset to 1), F4 live/DLQ/nowhere orphan classification, activity guard - spec/integration/batch_open_spec.rb: stale-handle AlreadyFinished sends nothing; reopen crash keeps totals; bulk counts with one UPDATE - spec/integration/while_executing_retry_spec.rb (new): F5 RED against main - spec/pgbus/batch_sweep_spec.rb, client_spec.rb, uniqueness_spec.rb, concurrency/blocked_execution_spec.rb, executor_spec.rb, configuration_spec.rb ## Verification - [x] bundle exec rubocop — 583 files, no offenses - [x] bundle exec rspec spec/pgbus spec/generators — 4058 examples, 0 failures - [x] integration suite — 225 examples, 0 failures - [x] cd docs && rake lint && rspec — clean
Summary
Closes #415. Stacked on #421 — review that one first; this branch contains its commit.
1. Open batches
Batch#enqueueis re-callable while the batch is unfinished. Later calls add tothe existing group through the guarded
BatchEntry.increment_total_jobs!instead of hitting the unique index on
batch_id; adding to a finished batchraises
Pgbus::Batch::AlreadyFinished.Pgbus::Batch.find(batch_id)returns a rehydratedPgbus::Batchhandle withdescription,properties,status,total_jobs,completed_jobs,failed_jobs,pending_jobs(execution-row count),progress_percentageandfinished?. Membership stays explicit: only jobs enqueued inside anenqueueblock join the batch.
2.
batchaccessor on jobs and callbacksNew
Pgbus::ActiveJob::BatchIdmixin, included onActiveJob::Basefrom theengine alongside
ConcurrencyandUniqueness:batch_id/callback_batch_idaccessors, both round-tripping throughserialize/deserialize, plus a memoizedbatchreader. The executor assignsbatch_idfrom the payload'spgbus_batch_idbeforeperform, so a runningjob can add siblings to its own batch:
3. Configured callback instances
on_finish:/on_success:/on_failure:accept an ActiveJob instance aswell as a class.
.setoptions resolve at batch-creation time (matchingsolid_queue) into new
on_finish_job/on_success_job/on_failure_jobjsonb columns. At fire time the job is deserialized, given
callback_batch_id,has its own
batch_idcleared, and is enqueued on its configured queue andscheduled_at.Legacy class-name callbacks keep the
perform_later(properties)signature. Thedashboard shows a configured callback's
job_class. Migration ships in theinstall template and as
rails generate pgbus:add_batch_callback_jobs, wiredinto
pgbus:update.Pgbus::Batch.findreturned the raw attributes Hash and now returns aPgbus::Batch. Read the values off the handle, or queryPgbus::BatchEntryfor a row. The dashboard
DataSourcereadsBatchEntrydirectly and isunaffected.
Race safety
finish_if_empty!requires bothNOT EXISTS(execution rows)andcompleted_jobs + failed_jobs = total_jobs. That pair is what makes adding to alive batch safe:
total_jobsisbumped, so the first predicate blocks a concurrent finish.
completed > totaland thesecond predicate blocks it.
check_finished!runs after the bump, so a block whose jobs all finishedwhile it was still open still closes the batch.
enqueue's guard and the bump, the guardedupdate_allmatches zero rows and raisesAlreadyFinished— the added jobsstill run, they just report into an already-closed batch.
Perf
Per
.claude/rules/performance.md, before/after on the same machine(
rake bench:one[...], main worktree vs this branch):send_messagesmallsend_messagelargesend_batch(10)send_batch(100)read_batch(5)read_batch(25)Executor#executeExecutor#executeallocationsNot claiming a speedup. The
send_batchdeltas are cross-process variance,not a real gain — this branch adds a strategy dispatch to that path, it does not
remove work. The noise floor on this machine is large:
serialization_bench,which measures untouched
JSON.generate, moved −21% between the same two runs.The signal worth reporting is the byte-identical executor allocation profile:
the added
payload[METADATA_KEY]lookup andbatch_id=assignment allocatenothing, and non-batched enqueue still early-returns on a nil thread-local.
This also fixes the benchmark harness:
client_bench's read section abortedwith
undefined method 'run_guarded' for nilon every branch, becauseBenchStubs.build_mock_clientnever set@connection_health. The documenteddequeue hot path had no working benchmark until this PR. Baseline
read_batchnumbers above come from the fixed harness applied to a
mainworktree.Test plan
spec/pgbus/active_job/batch_id_spec.rb(new) — serialize/deserializeround-trip, keys omitted when unset, memoized
batch,callback_batch_idprecedence
spec/integration/batch_open_spec.rb(new) — re-callable enqueue, emptyre-open is a no-op,
AlreadyFinished, the batch stays open for stage-twojobs,
findreturns a usable handle, thebatchaccessor inside a job,configured callback lands on its configured queue with
callback_batch_idset and
batch_idnil, legacy class callback still receives propertiesspec/pgbus/batch_spec.rb—findreturns a handle with delegated readers;a configured instance is serialized at creation; a bare class still uses the
legacy column
spec/pgbus/active_job/executor_spec.rb—batch_idassigned before performspec/pgbus/engine_spec.rb— the mixin is included by the initializerspec/pgbus/generators/migration_detector_spec.rb+spec/generators/pgbus/add_batch_callback_jobs_generator_spec.rbspec/pgbus/web/batches_data_source_spec.rb— configured callback shownbundle exec rspec spec/pgbus spec/generators— 4026 examples, 0 failuresPGBUS_DATABASE_URL=… bundle exec rspec spec/integration— 215 examples, 0 failuresbundle exec rubocop— 582 files, no offensescd docs && bundle exec rake lint+bundle exec rspec— clean.erbtouched, solint:herbis not in playDeviations & judgment calls
enqueueblock keeps its absoluteupdate_total; only re-openedblocks increment. Making the first block incremental too would have unified
the two paths, but at the cost of a third AR write per batched job on the
common closed-batch case.
"increment-before-row-insert" as the race-safe ordering. Either is safe here,
because
finish_if_empty!tests both predicates (see Race safety above),and insert-first lets the block run unchanged and bump once instead of issuing
an UPDATE per job.
serializeomitsbatch_id/callback_batch_idwhen unset.solid_queue's mixin always writes both keys. Omitting them keeps an unbatched
job's payload byte-for-byte what it was before the mixin existed, so an app
that never uses batches pays nothing.
The issue asked for a guard "so it only activates when the pgbus adapter is in
use", but
config.active_job.queue_adapteris not reliably resolvable aton_load(:active_job)time — which is why the two mixins already in that hook(
Concurrency,Uniqueness) are unguarded too. The mixin is inert without abatch id.
*_classcolumn. The issuedoes not say what happens when a row has both, which is only reachable
mid-upgrade. Preferring the richer form is the conservative read.
batch_detail, not the view.on_finish_classnow falls back to the serialized job's
job_class, so no.erbchanged.client_benchharness (see Perf). Reporting a before/after for ahot-path change is required by the repo's performance rules, and the dequeue
bench did not run at all. Benchmarks only — no gem code.
Known, out of scope
A
retry_onre-enqueue does not carrypgbus_batch_id, so the retried messagenever signals its batch. Nothing stalls — the original message already signalled
completion when
retry_onreturned — but the batch counts a job as done at themoment it is scheduled for retry. Pre-existing; changing it would change
membership semantics, which #415 explicitly keeps explicit.
Summary by cubic
Open batches, a batch accessor on ActiveJob, and configured callback instances. Previously Batch#enqueue could not add to an existing batch and Batch.find returned a Hash; now enqueue is re-callable until finish (adding to a finished batch raises AlreadyFinished), find returns a Pgbus::Batch handle, the executor assigns batch_id so jobs can call batch.enqueue, and callbacks may be serialized ActiveJob instances.
Written for commit 016ab28. Summary will update on new commits.