Skip to content

feat(batches): open batches, batch accessor on jobs, configured callback instances - #422

Merged
mhenrixon merged 3 commits into
mainfrom
issue-415-batches-v2-open-batches
Aug 22, 2026
Merged

mhenrixon merged 3 commits into
mainfrom
issue-415-batches-v2-open-batches

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #415. Stacked on #421 — review that one first; this branch contains its commit.

1. Open batches

Batch#enqueue is re-callable while the batch is unfinished. Later calls add to
the existing group through the guarded BatchEntry.increment_total_jobs!
instead of hitting the unique index on batch_id; adding to a finished batch
raises Pgbus::Batch::AlreadyFinished.

Pgbus::Batch.find(batch_id) returns a rehydrated Pgbus::Batch handle with
description, properties, status, total_jobs, completed_jobs,
failed_jobs, pending_jobs (execution-row count), progress_percentage and
finished?. Membership stays explicit: only jobs enqueued inside an enqueue
block join the batch.

batch = Pgbus::Batch.new(on_finish: BatchFinishedJob)
batch.enqueue { ExtractJob.perform_later }
batch.enqueue { TransformJob.perform_later }  # same batch, total_jobs == 2

2. batch accessor on jobs and callbacks

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, plus a memoized batch reader. The executor assigns
batch_id from the payload's pgbus_batch_id before perform, so a running
job can add siblings to its own batch:

class ExtractJob < ApplicationJob
  def perform
    rows = extract
    batch.enqueue { rows.each { |row| TransformJob.perform_later(row.id) } }
  end
end

3. 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 (matching
solid_queue) 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.

Pgbus::Batch.new(on_finish: ReportJob.new.set(queue: :critical, wait: 5.minutes))

Legacy class-name callbacks keep the perform_later(properties) signature. 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.

⚠️ Breaking (pre-1.0)

Pgbus::Batch.find returned the raw attributes Hash and now returns a
Pgbus::Batch. Read the values off the handle, or query Pgbus::BatchEntry
for a row. The dashboard DataSource reads BatchEntry directly and is
unaffected.

Race safety

finish_if_empty! requires both NOT EXISTS(execution rows) and
completed_jobs + failed_jobs = total_jobs. That pair is what makes adding to a
live batch safe:

  • A job added mid-block has its execution row inserted before total_jobs is
    bumped, so the first predicate blocks a concurrent finish.
  • If that job also completes before the bump, completed > total and the
    second predicate blocks it.
  • check_finished! runs after the bump, so a block whose jobs all finished
    while it was still open still closes the batch.
  • If the batch finishes between enqueue's guard and the bump, the guarded
    update_all matches zero rows and raises AlreadyFinished — the added jobs
    still 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):

Bench main branch
send_message small 756.6k i/s 812.0k i/s
send_message large 421.3k i/s 401.8k i/s
send_batch (10) 238.0k i/s 274.0k i/s
send_batch (100) 36.7k i/s 43.5k i/s
read_batch(5) 1.177M i/s 1.189M i/s
read_batch(25) 1.177M i/s 1.186M i/s
Executor#execute 62.1k i/s 62.9k i/s
Executor#execute allocations 6504 B / 77 obj per job, 0 retained identical

Not claiming a speedup. The send_batch deltas 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 and batch_id= assignment allocate
nothing, and non-batched enqueue still early-returns on a nil thread-local.

This also fixes the benchmark harness: client_bench's read section aborted
with undefined method 'run_guarded' for nil on every branch, because
BenchStubs.build_mock_client never set @connection_health. The documented
dequeue hot path had no working benchmark until this PR. Baseline read_batch
numbers above come from the fixed harness applied to a main worktree.

Test plan

  • RED first, then green:
    • spec/pgbus/active_job/batch_id_spec.rb (new) — serialize/deserialize
      round-trip, keys omitted when unset, memoized batch, callback_batch_id
      precedence
    • spec/integration/batch_open_spec.rb (new) — re-callable enqueue, empty
      re-open is a no-op, AlreadyFinished, the batch stays open for stage-two
      jobs, find returns a usable handle, the batch accessor inside a job,
      configured callback lands on its configured queue with callback_batch_id
      set and batch_id nil, legacy class callback still receives properties
    • spec/pgbus/batch_spec.rb — find returns 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_id assigned before perform
    • spec/pgbus/engine_spec.rb — the mixin is included by the initializer
    • spec/pgbus/generators/migration_detector_spec.rb +
      spec/generators/pgbus/add_batch_callback_jobs_generator_spec.rb
    • spec/pgbus/web/batches_data_source_spec.rb — configured callback shown
  • bundle exec rspec spec/pgbus spec/generators — 4026 examples, 0 failures
  • PGBUS_DATABASE_URL=… bundle exec rspec spec/integration — 215 examples, 0 failures
  • bundle exec rubocop — 582 files, no offenses
  • cd docs && bundle exec rake lint + bundle exec rspec — clean
  • No .erb touched, so lint:herb is not in play

Deviations & judgment calls

  • The first enqueue block keeps its absolute update_total; only re-opened
    blocks 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.
  • Row-insert-then-increment, not increment-then-insert. The issue names
    "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.
  • serialize omits batch_id / callback_batch_id when 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 mixin is included unconditionally rather than guarded on the adapter.
    The issue asked for a guard "so it only activates when the pgbus adapter is in
    use", but config.active_job.queue_adapter is not reliably resolvable at
    on_load(:active_job) time — which is why the two mixins already in that hook
    (Concurrency, Uniqueness) are unguarded too. The mixin is inert without a
    batch id.
  • A configured instance wins over the legacy *_class column. The issue
    does not say what happens when a row has both, which is only reachable
    mid-upgrade. Preferring the richer form is the conservative read.
  • The dashboard change is in batch_detail, not the view. on_finish_class
    now falls back to the serialized job's job_class, so no .erb changed.
  • Fixed the client_bench harness (see Perf). Reporting a before/after for a
    hot-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_on re-enqueue does not carry pgbus_batch_id, so the retried message
never signals its batch. Nothing stalls — the original message already signalled
completion when retry_on returned — but the batch counts a job as done at the
moment 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.

  • Rollout
    • Run: rails generate pgbus:add_batch_callback_jobs && rails db:migrate; restart workers.
    • Breaking (pre-1.0): Pgbus::Batch.find now returns a Pgbus::Batch. Update callers to read status, totals, and properties from the handle or query Pgbus::BatchEntry.

Written for commit 016ab28. Summary will update on new commits.

Review in cubic

…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.
@cubic-dev-ai

cubic-dev-ai Bot commented Aug 22, 2026

Copy link
Copy Markdown

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.

@cubic-dev-ai

cubic-dev-ai Bot commented Aug 22, 2026

Copy link
Copy Markdown

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:

Learn more →

Base automatically changed from fix/batch-sweep-empty-and-bulk-priority to main August 22, 2026 22:51
@mhenrixon
mhenrixon merged commit 62fd56d into main Aug 22, 2026
14 checks passed
@mhenrixon
mhenrixon deleted the issue-415-batches-v2-open-batches branch August 22, 2026 22:52
mhenrixon added a commit that referenced this pull request Aug 23, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Batches v2: open batches, batch accessor on jobs/callbacks, configured callback instances

1 participant