Repository navigation
feat(batches): execution-row completion tracking, stalled-batch sweep, on_failure rename - #420
Conversation
Batch finish is no longer completed+discarded==total, which stalled forever after a crash between archive and the counter increment. Each batched job now gets a pgbus_batch_executions row (ActiveJob job_id) inserted before send_message; the batch finishes when no rows remain. A dispatcher sweep repairs the crash windows. on_failure/failed_jobs are canonical; on_discard stays a deprecated alias until 1.0. Existing installs: rails generate pgbus:add_batch_executions (or pgbus:update). Unmigrated apps keep the counter path. Refs #414
|
Running ultrareview automatically — Introduces execution tracking as the source of truth for batch completion, with a new table, migration, sweeper, and finish semantics. A subtle bug here could break job-completion accounting for every batch — double-counting, missed terminal signals, or sweeper races — which is high-impact core.... I'll post findings when complete. |
There was a problem hiding this comment.
Ultrareview completed in 31m 3s
All reported issues were addressed across 38 files
Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.
Re-trigger cubic
Cubic ultrareview on PR #420: - Orphan sweep deletes only rows still at msg_id NULL and decrements total_jobs only after a successful delete. - Stalled processing batches finish only when counters are already terminal, so in-flight pre-migration batches are not closed empty. - DLQ lookup uses job_id in the payload; move_to_dead_letter assigns a new msg_id. - executions_migrated? caches only a true result so a pre-migration probe cannot pin a worker on the legacy path. - Delete + counter increment share a transaction; uniqueness lock rollback and untrack happen only when send did not return a msg_id. - Execution rows store the physical target queue; insert uses ON CONFLICT DO NOTHING instead of insert_all(unique_by:). - Migration is defensive when failed_jobs is missing, copies counters on down, and adds a partial orphan index. Restart workers after migrate. Refs #414
There was a problem hiding this comment.
All reported issues were addressed across 30 files (changes from recent commits).
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
Cubic re-review on PR #420: - Pre-migration in-flight batches increment counters when no execution row exists; finish_if_empty! requires completed+failed == total. - Post-send uniqueness failures clear the thread-local without releasing the live lock. - Promote-time backfill errors no longer report promotion failure (semaphore over-release). - Priority sub-queues strip _pN before appending _dlq. - Migration down zeros failed_jobs so a re-up does not double-count. - on_failure locale strings use failure wording, not discard. Refs #414
There was a problem hiding this comment.
1 issue found across 26 files (changes from recent commits).
Confidence score: 3/5
- In
lib/pgbus/batch.rb, a pre-migration batch with even one post-migration retry or enqueue can drop completion signals for other jobs lacking an execution row, causing those jobs to remain incomplete or batches to hang; handle legacy status per batch/job or persist a migration marker before merging.
Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/pgbus/batch.rb">
<violation number="1" location="lib/pgbus/batch.rb:147">
P1: When a pre-migration batch has even one post-migration retry or enqueue, this fallback drops completion signals for its other jobs that have no execution row. Handle legacy status per batch/job (or persist a migration marker) instead of treating any existing execution row as proof that all jobs are row-tracked.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
Resolve adapter_spec uniqueness after-hook (same cleanup as #419). Bind uniqueness lock before batch execution backfill so a live message is never left with an unbound pending/0 key if bookkeeping raises.
Priority sub-queues share the logical DLQ; a logical queue whose name ends in `_pN` with priority disabled must keep that suffix. The unit client double now applies `_pN` from config.priority_levels. Refs #414
There was a problem hiding this comment.
All reported issues were addressed across 4 files (changes from recent commits).
Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
A logical queue named orders_p0 was treated as a physical priority sub-queue and skipped the configured suffix. The already-physical shortcut now requires the configured queue prefix. Specs derive expected names from configuration instead of hardcoding pgbus_test. Refs #414
Summary
pgbus_batch_executions), notcompleted + discarded == total. A worker crash betweenarchive_fromand the counter increment no longer stalls the batch forever.send_message(identity = ActiveJobjob_id);msg_id+queue_nameare backfilled after send. The batch finishes when no rows remain (single-winnerUPDATE … AND NOT EXISTSplus a freshexists?re-check for Postgres READ COMMITTED).config.batch_sweep_interval, default 5 minutes) repairs four crash windows: stale rows whose PGMQ message is gone; orphanmsg_idNULL rows (enqueue crash — blocked concurrency jobs excluded); stalledpendingbatches; stalledprocessingbatches with zero rows.on_failure:/failed_jobsare canonical.on_discard:/discarded_jobsremain deprecated aliases until 1.0.config.batch_retention(default 7 days,nildisables) replaces the hardcoded cleanup window.rails generate pgbus:add_batch_executions(orpgbus:update). Unmigrated apps keep the counter path viaBatch.executions_migrated?.Closes #414
Test plan
bundle exec rspec spec/pgbus spec/generators— 3958 examples, 0 failuresPGBUS_DATABASE_URL=… bundle exec rspec spec/integration/batch_flow_spec.rb— 6 examples, 0 failures (including kill-window sweep)bundle exec rubocopon changed files — cleancd docs && bundle exec rake lint— cleanbun run lint:herb— cleanrails generate pgbus:add_batch_executionsthendb:migrate, confirmpgbus_batch_executionsexists andon_discard_class/discarded_jobsare gonePerf
client_benchis the PGMQ send/read hot path and is unchanged (non-batchedinject_batch_metadatastill early-returns on a nil thread-local). Batched enqueue gains two small AR writes (insert + msg_id backfill) per job; that cost is not on the client bench. Not claiming a speedup.Deviations & judgment calls
Discoveries
:blockstores the payload inpgbus_blocked_executionswith no PGMQ message, so an execution row inserted atinject_batch_metadatakeepsmsg_idNULL untilpromote_next. Sweep phase 2 would treat those as enqueue crashes. Exclude job_ids present inpgbus_blocked_executions, and backfillmsg_idon promote.uncount_batch_job(uniqueness/concurrency:discard, fix(active_job): perform_all_later no longer escapes batch tracking or concurrency limits #417) must also delete the execution row; otherwise a discarded job leaves a row the sweep later "completes".send_messagemust not untrack: the message is live and the executor will delete the row. Untrack only whenmsg_idis still nil.promote_nextdid not surfacemsg_idto the caller. Capture it and backfill.Deviations
Batch::Sweep::STALL_THRESHOLD), not a new config key. The issue only specifiedbatch_retentionandbatch_sweep_interval; this matches solid_queue'sstalled_for: 5.minutesdefault.message_in_queue?is a thin wrapper over existingmessage_exists?(msg_id:).message_archived?is new (pgmq.a_*). DLQ presence reusesmessage_in_queue?onconfig.dead_letter_queue_name.discarded_jobsas an alias offailed_jobsso existing JSON/API consumers don't break; views and progress usefailed_jobs.on_discard:remains as a kwarg that warns and maps toon_failure:; empty-batch path still does not fire failure callbacks.Judgment calls
insert_all+ uniquejob_idso a retry re-enqueue of the same ActiveJob id is a no-op rather than raising.update_counter), so a callback enqueue failure cannot roll back the finished status. Sweep phase 4 covers the inverse crash.Summary by cubic
Switches batch completion from counter math to execution-row tracking with a dispatcher sweep that self-heals crashes. Old behavior finished on completed + discarded == total; new behavior inserts one
pgbus_batch_executionsrow per job before send and finishes when no rows remain. Also fixes DLQ suffix handling so_pNis stripped only when priority routing is enabled. Closes #414.Rollout and migration
pgbus_batch_executions, renameson_discard_classtoon_failure_class, and foldsdiscarded_jobsintofailed_jobs.on_failure:andfailed_jobsare canonical;on_discard:anddiscarded_jobsremain deprecated aliases until 1.0.config.batch_sweep_interval(default 5 minutes) and cleans finished batches usingconfig.batch_retention(default 7 days; nil disables).Reviewer notes
msg_idand physicalqueue_nameafter send; the uniqueness lock is bound before backfill. Post-send uniqueness failures clear the thread-local without releasing the live lock.msg_idNULL, decrementstotal_jobsonly after delete), missing queue/archive/DLQ rows (DLQ identified by payloadjob_id; priority sub-queues share the logical DLQ), stalled pending batches, and processing batches that already have terminal counters. DLQ_pNsuffix is stripped only when priority levels are configured; otherwise a literal_pNsuffix is preserved.Written for commit a286cfc. Summary will update on new commits.