Repository navigation
fix(batches): per-job increment-before-insert accounting, probing sweep, while_executing release - #425
Conversation
…ep, while_executing release 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
|
Running ultrareview automatically — This PR rewrites batched-enqueue accounting (per-job increment-before-insert), stalled/orphan sweep classification, and :while_executing uniqueness-lock semantics — concurrency- and data-integrity-sensitive changes where a missed bug could corrupt batch totals, finish batches early, or lock.... 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 18 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:
|
Summary
Second-pass review fixes for #417 / #419 / #420 / #421 / #422, per #423. Closes #423. Refs #416 (EPIC stays open until this merges).
Accounting — per-job increment-before-insert (F1, F2, F3)
Every batched enqueue — individual, bulk, and blocked-promote — now runs
BatchEntry.increment_total_jobs!(guardedWHERE status IN ('pending','processing')) and the execution-row insert inside oneBatchEntry.transaction, beforesend_message. Aperform_all_laterincrements once by N. This is solid_queue's model and what #415 specified; #422 had kept "insert during the block, bump once at the end", which is the single root cause of three bugs:AlreadyFinished(checked on a stale memoized row)perform_later, nothing sent — even through a staleBatch.findhandlecompleted > total→ immortalpendingblock with early completionstotal_jobs = COUNT(rows), discardingcompleted_jobs→ immortalpending → processingand re-checksThe invariant
total_jobs == outstanding rows + completed_jobs + failed_jobsnow holds at every commit point. Consequences: the first block only flips status (guarded — the sweep may have flipped it first) and callscheck_finished!;reopenre-reads before its early exit and never bumps; the empty batch finishes through the sametry_finish!path (and now emitspgbus.batch_finished) —fire_empty_batch_callbacksis gone;uncountdecrements + deletes in one transaction; the legacy counter path only auto-finishes aprocessingbatch (totals now grow mid-block).Thread.current[:pgbus_batch_job_count]is removed — nothing reads it.Sweep (F4, F8)
Orphan phase classifies a
msg_id IS NULLrow before touching it: message on its queue → keep (a send that landed whose backfill failed); probe inconclusive → keep; in the DLQ →job_discarded; nowhere → orphan as before. Rows store the logical queue at insert for this.Client#message_with_job_id?now expands_pNsub-queues for logical names (tri-state likemessage_exists?). Stalled-pending requires no execution row within the threshold (activity guard), so a long-running live block is not closed under the caller. Newconfig.batch_stall_threshold(default5.minutes) replaces the hardcoded constant.:while_executing(F5 — pre-existing, found while reviewing #419)The lock was acquired with
msg_id = 0and released only on success/DLQ. A failed attempt's row made the retry of the same message conflict with itself →:skippedevery read until DLQ. Now: bound to the executingmsg_id, released in the failure path (:until_executeduntouched), andUniquenessKey.acquire!(reacquire_same_message: true)re-acquires a row pointing at the samemsg_id(a crashed attempt of this message — PGMQ's VT guarantees nobody else holds it). RED first against main —spec/integration/while_executing_retry_spec.rb:locked?stayed true after the failure; a leftover same-msg_id row produced:skipped.Smaller
BlockedExecution.release_next!returnspriority;promote_nextpasses it tosend_messageand the backfill target — promoted jobs no longer fall to the default sub-queue.ensurerelease; it said there was.Perf
Same machine,
mainworktree vs branch.send_messagesmall / largesend_batch10 / 100read_batch(5)/(25)Executor#executeAll within cross-process noise (same run-to-run spread as #422's numbers); none of these benches enter a batch context. The real cost is on the batched path, measured with a real database, 1 000 jobs inside one batch, 3 runs each:
perform_later×1000UPDATE pgbus_batchesper job)perform_all_later×1000Method-level overhead on batched individual enqueue only; that is the price of the guarantee (solid_queue pays the same). Bulk is the cheap path for large batches.
Test plan
batch_spec(flip-only first block, reopen re-read + no bump,track_enqueueorder/bulk/legacy/AlreadyFinished,untrack, F6 degrade),batch_entry_spec(decrement_total_jobs!, legacy pending guard),adapter_spec(count before send, raise before send, bulk once),batch_sweep_spec(flip-only + activity guard; orphan live/unknown/DLQ/nowhere),client_spec(message_with_job_id?expansion),uniqueness_spec,blocked_execution_spec,executor_spec,configuration_spectotal_jobsreset to 1), F5 (lock held /:skipped)AlreadyFinishedsends nothing; reopen crash keepstotal_jobs == 2; bulk counts with exactly onetotal_jobs = total_jobs +UPDATE; orphan live → kept, DLQ →failed_jobs, nowhere → un-counted; activity guardbundle exec rspec spec/pgbus spec/generators— 4058 examples, 0 failuresPGBUS_DATABASE_URL=… bundle exec rspec spec/integration— 225 examples, 0 failuresbundle exec rubocop— 583 files, no offensescd docs && bundle exec rake lint && bundle exec rspec— clean (config-drift spec includesbatch_stall_threshold).erbtouchedDeviations & judgment calls
:while_executingattemptUniquenessKey.locked?stayed true, and a row left by a crashed attempt of the samemsg_idmade the retry return:skipped.batch_spec,adapter_spec,batch_entry_spec); the integration specs (reopen crash, stale-handle raise, bulk single-UPDATE) were written after GREEN as end-to-end proof. F1, F4, F5 integration specs were RED first.Sweep.run's defaultstalled_for:now readsconfig.batch_stall_threshold.Sweep::STALL_THRESHOLDis kept (300) for anyone referencing it but is no longer the source of truth.Uniqueness.acquire_execution_lockkeeps its 2-arg form working (falls back to themsg_id: 0placeholder), so an external caller is unaffected; only the executor passes the message.Thread.current[:pgbus_batch_job_count]removed outright rather than left as dead state — once jobs count themselves nothing reads it. Called out in the CHANGELOG for apps whose specs stubbed it.Summary by cubic
Fixes batch accounting, sweep, and uniqueness so batches cannot go immortal and
:while_executingretries no longer lock themselves out. Before: execution rows inserted during the block andtotal_jobsbumped at the end; the sweep un-counted live jobs; and failed:while_executingattempts kept the lock. Now: each job incrementstotal_jobsand inserts its execution row in one transaction before send (bulk increments once by N), the sweep probes the queue/DLQ before un-counting, and the lock binds to the executing message, releases on failure, and re-acquires for the same message after a crash.AlreadyFinishednow raises atperform_laterbefore sending, even through a staleBatch.find. Empty batches finish via the same single-winner path and emitpgbus.batch_finished. Promoted blocked jobs keep theirpriority. A configured callback instance on an unmigrated DB degrades to its class and logs a WARN once per process.job_id; only rows whose message exists nowhere are un-counted. Stalled-pending requires no execution row withinconfig.batch_stall_threshold(new; default 5 minutes).:while_executing: the uniqueness row is bound to the executingmsg_id; failures release; retries of the same message re-acquire; retries with a different message still:skip.Bolded sections:
Written for commit 80ddddc. Summary will update on new commits.