Repository navigation
fix(batches): crashed empty batches finish; bulk enqueue honours priority routing - #421
Merged
Merged
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
|
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. |
|
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:
|
5 of 6 tasks
This was referenced Aug 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
enqueueblock crashed before enqueuing anything was immortal.Sweep.start_stalled_pendingmoves a stalledpendingbatch toprocessingwith
total_jobsset from its execution-row count — zero, when the block raisedbefore a single
perform_later. ButBatchEntry.finish_if_empty!requiredtotal_jobs > 0, andSweep#counters_terminal?requiredtotal_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 thecrashed batch unclosable. It sat in
processingforever,cleanup_batchesonlydeletes
finishedrows so it accumulated, andon_finishnever fired. That isthe same leak #414 set out to remove, relocated one status along.
Both guards now test
completed_jobs + failed_jobs = total_jobsalone.total_jobs = 0with zero counters is terminal; a legacy in-flight batch stillhas counters short of a positive total and is still left on the counter path.
2.
ActiveJob.perform_all_laterraisedPG::UndefinedTableunder priority routing.Client#send_batchtargetedconfig.queue_name(queue)— the barepgbus_<queue>table — whileQueueFactory::PriorityStrategyonly ever creates_p0.._pN. Every bulk enqueue withpriority_levels > 1failed outright, andhad 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_executionsrows behind until the sweep reaped them.send_batchroutes through the same strategy assend_messageand accepts anoptional
priority:.Adapter#enqueue_allgroups bulk jobs by queue and priority, so amixed-priority
perform_all_laterproduces oneproduce_batchper levelinstead of silently collapsing to one.
Outbox::Poller#publish_queue_batchalready grouped entries by priority andthen 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_allpartition and bulk metadata injection (#413), execution-rowtracking with the single-winner finish and READ COMMITTED re-check, the
four-phase sweep, the
on_failurerename with deprecated aliases, configurableretention 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:
BatchEntry.increment_total_jobs!is still unused. That is intentionalgroundwork for Batches v2: open batches, batch accessor on jobs/callbacks, configured callback instances #415 (open batches), which wires it up.
client_benchrun. PRfeat(batches): execution-row completion tracking, stalled-batch sweep, on_failure rename #420 stated the hot path was unchanged but captured no numbers.
send_batchnow resolves through the queue strategy — one extra method call on a path that
is dominated by the PGMQ round trip — so the benchmark belongs with the Batches v2: open batches, batch accessor on jobs/callbacks, configured callback instances #415
PR, where batched enqueue actually gains work.
Test plan
spec/integration/batch_flow_spec.rb— a batch whose block raised finishesvia the sweep and fires
on_finish; a pre-migration in-flight batch (norows, counters short of total) is still left alone
spec/integration/bulk_enqueue_priority_spec.rb—perform_all_laterlandspayloads on the
_p0/_p2sub-queues workers actually read (raisedPG::UndefinedTablebefore)spec/pgbus/client_spec.rb—send_batchroutes to the requested level andfalls back to
default_priorityspec/pgbus/active_job/adapter_spec.rb— one batch per priority levelspec/pgbus/batch_sweep_spec.rb— a zero-totalprocessingbatch is finishedbundle exec rspec spec/pgbus spec/generators— 4004 examples, 0 failuresPGBUS_DATABASE_URL=… bundle exec rspec spec/integration— 207 examples, 0 failuresbundle exec rubocop— clean on changed filesDeviations & judgment calls
Outbox::Pollertoo, though no issue asked for it. It is the onlyother
send_batchcaller and had the identicalPG::UndefinedTablecrashunder 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.
total_jobs = 0in the sweep.A separate "finish empty crashed batch" branch would have been a third path to
keep in sync with
finish_if_empty!. Droppingtotal_jobs > 0from the onepredicate keeps a single definition of "terminal", and the legacy in-flight
case is still excluded by the counter comparison itself.
Client#priority_routing?predicate to avoid the extra grouping would haveexposed strategy internals for a split that only costs anything when jobs in
one
perform_all_latercarry different explicit priorities — rare, and eachgroup 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_latertargeted the base queue and failed under priority routing; nowsend_batchroutes via the queue strategy withpriority, so messages land on_pNsub-queues.total_jobs > 0guard and finish when completed + failed equals total_jobs; legacy in-flight batches (counters short of a positive total) remain untouched. Aligns with issue Batches v2: execution-row completion tracking, stalled-batch sweep, on_failure rename #414.Client#send_batch(priority:),Adapter#enqueue_allgroups by queue and priority, andOutbox::Pollercarries priority for both batch and fallback paths. Default single-queue behavior is unchanged. Aligns with issue fix(active_job): perform_all_later bypasses batch and concurrency metadata #413.Written for commit ddf85ae. Summary will update on new commits.