Skip to content

fix(batches): crashed empty batches finish; bulk enqueue honours priority routing - #421

Merged
mhenrixon merged 1 commit into
mainfrom
fix/batch-sweep-empty-and-bulk-priority
Aug 22, 2026
Merged

mhenrixon merged 1 commit into
mainfrom
fix/batch-sweep-empty-and-bulk-priority

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Two defects found while reviewing #417 / #419 / #420 against their issue
specifications (#413 / #414 / #418). Both were reproduced with a RED test
before being fixed.

1. A batch whose enqueue block crashed before enqueuing anything was immortal.

Sweep.start_stalled_pending moves a stalled pending batch to processing
with total_jobs set from its execution-row count — zero, when the block raised
before a single perform_later. But BatchEntry.finish_if_empty! required
total_jobs > 0, and Sweep#counters_terminal? required total_jobs.positive?.
Those guards exist so a pre-migration in-flight batch (zero execution rows,
counters short of total_jobs) is not closed empty — but they also made the
crashed batch unclosable. It sat in processing forever, cleanup_batches only
deletes finished rows so it accumulated, and on_finish never fired. That is
the same leak #414 set out to remove, relocated one status along.

Both guards now test completed_jobs + failed_jobs = total_jobs alone.
total_jobs = 0 with zero counters is terminal; a legacy in-flight batch still
has counters short of a positive total and is still left on the counter path.

2. ActiveJob.perform_all_later raised PG::UndefinedTable under priority routing.

Client#send_batch targeted config.queue_name(queue) — the bare
pgbus_<queue> table — while QueueFactory::PriorityStrategy only ever creates
_p0.._pN. Every bulk enqueue with priority_levels > 1 failed outright, and
had the table existed no worker would have read it (consumers poll the
sub-queues). Since #417 routed batch membership through that path, the failed
send also left pgbus_batch_executions rows behind until the sweep reaped them.

  • send_batch routes through the same strategy as send_message and accepts an
    optional priority:.
  • Adapter#enqueue_all groups bulk jobs by queue and priority, so a
    mixed-priority perform_all_later produces one produce_batch per level
    instead of silently collapsing to one.
  • Outbox::Poller#publish_queue_batch already grouped entries by priority and
    then discarded it; it now passes it through, and its single-send fallback does
    too, so both paths place messages identically.

Under the default single-queue strategy the resolved target is unchanged.

Review notes on #417 / #419 / #420

Everything else in the three PRs matches its issue's Decision section — the
enqueue_all partition and bulk metadata injection (#413), execution-row
tracking with the single-winner finish and READ COMMITTED re-check, the
four-phase sweep, the on_failure rename with deprecated aliases, configurable
retention and instrumentation (#414), and all four suggested uniqueness fixes
including the bind-ownership stamp (#418). The open review threads on those PRs
are either already fixed in a follow-up commit or carry a reasoned pushback I
agree with.

Two smaller observations, deliberately not changed here:

Test plan

  • RED first, then green:
    • spec/integration/batch_flow_spec.rb — a batch whose block raised finishes
      via the sweep and fires on_finish; a pre-migration in-flight batch (no
      rows, counters short of total) is still left alone
    • spec/integration/bulk_enqueue_priority_spec.rb — perform_all_later lands
      payloads on the _p0 / _p2 sub-queues workers actually read (raised
      PG::UndefinedTable before)
    • spec/pgbus/client_spec.rb — send_batch routes to the requested 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 — a zero-total processing batch is finished
  • bundle exec rspec spec/pgbus spec/generators — 4004 examples, 0 failures
  • PGBUS_DATABASE_URL=… bundle exec rspec spec/integration — 207 examples, 0 failures
  • bundle exec rubocop — clean on changed files

Deviations & judgment calls

  • Fixed Outbox::Poller too, though no issue asked for it. It is the only
    other send_batch caller and had the identical PG::UndefinedTable crash
    under priority routing. Leaving it would have meant shipping a client fix that
    half its callers still could not use. Passing through the priority the poller
    already groups by cannot regress anyone: under the default strategy the target
    is unchanged, and under priority routing the current behaviour is a crash.
  • Relaxed the guard rather than special-casing total_jobs = 0 in the sweep.
    A separate "finish empty crashed batch" branch would have been a third path to
    keep in sync with finish_if_empty!. Dropping total_jobs > 0 from the one
    predicate keeps a single definition of "terminal", and the legacy in-flight
    case is still excluded by the counter comparison itself.
  • Grouped bulk sends by priority even under the standard strategy. Adding a
    Client#priority_routing? predicate to avoid the extra grouping would have
    exposed strategy internals for a split that only costs anything when jobs in
    one perform_all_later carry different explicit priorities — rare, and each
    group is still a single produce_batch.

Summary by cubic

Finishes crashed empty batches and ensures bulk enqueues honor priority routing. Previously, a batch whose enqueue block crashed stayed in processing and never fired on_finish; now the sweep finishes it by treating total_jobs=0 as terminal. Previously, ActiveJob.perform_all_later targeted the base queue and failed under priority routing; now send_batch routes via the queue strategy with priority, so messages land on _pN sub-queues.

Written for commit ddf85ae. 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
@cubic-dev-ai

cubic-dev-ai Bot commented Aug 22, 2026

Copy link
Copy Markdown

Running ultrareview automatically — This PR modifies critical queue routing logic for bulk enqueues and relaxes batch lifecycle guards, which could lead to job routing failures or incorrect state transitions for in-flight batches.. 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 →

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.

1 participant