Skip to content

fix(batches): per-job increment-before-insert accounting, probing sweep, while_executing release - #425

Merged
mhenrixon merged 1 commit into
mainfrom
issue-423-batch-per-job-accounting
Aug 23, 2026
Merged

mhenrixon merged 1 commit into
mainfrom
issue-423-batch-per-job-accounting

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

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! (guarded WHERE status IN ('pending','processing')) and the execution-row insert inside one BatchEntry.transaction, before send_message. A perform_all_later increments 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:

Before After
Add to a finished batch every job sent, then AlreadyFinished (checked on a stale memoized row) raises at perform_later, nothing sent — even through a stale Batch.find handle
Re-opened block raises mid-way rows inserted, total never bumped → completed > total → immortal every inserted job already counted; batch finishes normally
Crashed pending block with early completions sweep set total_jobs = COUNT(rows), discarding completed_jobs → immortal sweep never touches totals; just flips pending → processing and re-checks

The invariant total_jobs == outstanding rows + completed_jobs + failed_jobs now holds at every commit point. Consequences: the first block only flips status (guarded — the sweep may have flipped it first) and calls check_finished!; reopen re-reads before its early exit and never bumps; the empty batch finishes through the same try_finish! path (and now emits pgbus.batch_finished) — fire_empty_batch_callbacks is gone; uncount decrements + deletes in one transaction; the legacy counter path only auto-finishes a processing batch (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 NULL row 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 _pN sub-queues for logical names (tri-state like message_exists?). Stalled-pending requires no execution row within the threshold (activity guard), so a long-running live block is not closed under the caller. New config.batch_stall_threshold (default 5.minutes) replaces the hardcoded constant.

:while_executing (F5 — pre-existing, found while reviewing #419)

The lock was acquired with msg_id = 0 and released only on success/DLQ. A failed attempt's row made the retry of the same message conflict with itself → :skipped every read until DLQ. Now: bound to the executing msg_id, released in the failure path (:until_executed untouched), and UniquenessKey.acquire!(reacquire_same_message: true) re-acquires a row pointing at the same msg_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

  • F6 configured callback instance on an unmigrated DB degrades to its class + one WARN per process instead of being silently dropped.
  • F7 BlockedExecution.release_next! returns priority; promote_next passes it to send_message and the backfill target — promoted jobs no longer fall to the default sub-queue.
  • F9 fix(uniqueness): bind until_executed keys after send so the reaper can heal orphans #419 CHANGELOG entry rewritten: there is deliberately no ensure release; it said there was.

Perf

Same machine, main worktree vs branch.

Bench main branch
send_message small / large 728k / 384k i/s 782k / 385k i/s
send_batch 10 / 100 220k / 34k i/s 253k / 41k i/s
read_batch(5) / (25) 1.047M / 1.043M i/s 1.102M / 1.128M i/s
Executor#execute 58.6k i/s 56.2k i/s
Executor allocations 6504 B / 77 obj per job, 0 retained identical

All 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:

main branch
individual perform_later ×1000 0.51–0.80 s 0.80–1.09 s (+≈50%, one extra UPDATE pgbus_batches per job)
perform_all_later ×1000 0.33–0.39 s 0.26–0.30 s (one increment per bulk — within noise of plain)
plain, no batch ×1000 0.24–0.30 s 0.24–0.30 s (unchanged)

Method-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

  • RED first, unit: batch_spec (flip-only first block, reopen re-read + no bump, track_enqueue order/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_spec
  • RED first, integration against main: F1 (total_jobs reset to 1), F5 (lock held / :skipped)
  • Integration: stale-handle AlreadyFinished sends nothing; reopen crash keeps total_jobs == 2; bulk counts with exactly one total_jobs = total_jobs + UPDATE; orphan live → kept, DLQ → failed_jobs, nowhere → un-counted; activity guard
  • bundle exec rspec spec/pgbus spec/generators — 4058 examples, 0 failures
  • PGBUS_DATABASE_URL=… bundle exec rspec spec/integration — 225 examples, 0 failures
  • bundle exec rubocop — 583 files, no offenses
  • cd docs && bundle exec rake lint && bundle exec rspec — clean (config-drift spec includes batch_stall_threshold)
  • No .erb touched

Deviations & judgment calls

  • F5 RED was captured against main before the fix (the repo rule): after a failed :while_executing attempt UniquenessKey.locked? stayed true, and a row left by a crashed attempt of the same msg_id made the retry return :skipped.
  • Integration specs for the accounting change went green immediately — the RED step for that change was the unit layer (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 default stalled_for: now reads config.batch_stall_threshold. Sweep::STALL_THRESHOLD is kept (300) for anyone referencing it but is no longer the source of truth.
  • Uniqueness.acquire_execution_lock keeps its 2-arg form working (falls back to the msg_id: 0 placeholder), 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.
  • No archive-table probe in the orphan phase (as planned): the double-crash case it would disambiguate still finishes the batch, with counters off by one, logged.
  • Perf: the batched individual-enqueue cost is reported honestly as +≈50% wall-clock at 1 000 jobs; bulk is unchanged/better. Not claiming any speedup elsewhere — the unit-bench deltas are noise.

Summary by cubic

Fixes batch accounting, sweep, and uniqueness so batches cannot go immortal and :while_executing retries no longer lock themselves out. Before: execution rows inserted during the block and total_jobs bumped at the end; the sweep un-counted live jobs; and failed :while_executing attempts kept the lock. Now: each job increments total_jobs and 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.

  • AlreadyFinished now raises at perform_later before sending, even through a stale Batch.find. Empty batches finish via the same single-winner path and emit pgbus.batch_finished. Promoted blocked jobs keep their priority. A configured callback instance on an unmigrated DB degrades to its class and logs a WARN once per process.
  • The orphan sweep stores the logical queue at insert and probes it by job_id; only rows whose message exists nowhere are un-counted. Stalled-pending requires no execution row within config.batch_stall_threshold (new; default 5 minutes).
  • :while_executing: the uniqueness row is bound to the executing msg_id; failures release; retries of the same message re-acquire; retries with a different message still :skip.

Bolded sections:

  • Review focus
  • Rollout notes

Written for commit 80ddddc. Summary will update on new commits.

Review in cubic

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

cubic-dev-ai Bot commented Aug 23, 2026

Copy link
Copy Markdown

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.

@cubic-dev-ai

cubic-dev-ai Bot commented Aug 23, 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 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:

Learn more →

@mhenrixon mhenrixon self-assigned this Aug 23, 2026
@mhenrixon mhenrixon added bug Something isn't working stability Crash safety, recovery and resilience under failure (applied by judgment) labels Aug 23, 2026
@mhenrixon
mhenrixon merged commit 64988dc into main Aug 23, 2026
14 checks passed
@mhenrixon
mhenrixon deleted the issue-423-batch-per-job-accounting branch August 23, 2026 10:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working stability Crash safety, recovery and resilience under failure (applied by judgment)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Batches v2 follow-up: per-job accounting, sweep correctness, while_executing release, review fixes for #417–#422

1 participant