Skip to content

feat(batches): execution-row completion tracking, stalled-batch sweep, on_failure rename - #420

Merged
mhenrixon merged 6 commits into
mainfrom
issue-414-batch-execution-rows
Aug 22, 2026
Merged

mhenrixon merged 6 commits into
mainfrom
issue-414-batch-execution-rows

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Batch completion is now execution-row tracking (pgbus_batch_executions), not completed + discarded == total. A worker crash between archive_from and the counter increment no longer stalls the batch forever.
  • Each batched job gets a row before send_message (identity = ActiveJob job_id); msg_id + queue_name are backfilled after send. The batch finishes when no rows remain (single-winner UPDATE … AND NOT EXISTS plus a fresh exists? re-check for Postgres READ COMMITTED).
  • Dispatcher sweep (config.batch_sweep_interval, default 5 minutes) repairs four crash windows: stale rows whose PGMQ message is gone; orphan msg_id NULL rows (enqueue crash — blocked concurrency jobs excluded); stalled pending batches; stalled processing batches with zero rows.
  • on_failure: / failed_jobs are canonical. on_discard: / discarded_jobs remain deprecated aliases until 1.0.
  • config.batch_retention (default 7 days, nil disables) replaces the hardcoded cleanup window.
  • Existing installs: rails generate pgbus:add_batch_executions (or pgbus:update). Unmigrated apps keep the counter path via Batch.executions_migrated?.

Closes #414

Test plan

  • bundle exec rspec spec/pgbus spec/generators — 3958 examples, 0 failures
  • PGBUS_DATABASE_URL=… bundle exec rspec spec/integration/batch_flow_spec.rb — 6 examples, 0 failures (including kill-window sweep)
  • bundle exec rubocop on changed files — clean
  • cd docs && bundle exec rake lint — clean
  • bun run lint:herb — clean
  • Existing install: run rails generate pgbus:add_batch_executions then db:migrate, confirm pgbus_batch_executions exists and on_discard_class / discarded_jobs are gone
  • Enqueue a batch, kill a worker after archive, wait one sweep interval, confirm the batch finishes and callbacks fire once

Perf

client_bench is the PGMQ send/read hot path and is unchanged (non-batched inject_batch_metadata still 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

  • Concurrency :block stores the payload in pgbus_blocked_executions with no PGMQ message, so an execution row inserted at inject_batch_metadata keeps msg_id NULL until promote_next. Sweep phase 2 would treat those as enqueue crashes. Exclude job_ids present in pgbus_blocked_executions, and backfill msg_id on 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".
  • Adapter rescue after send_message must not untrack: the message is live and the executor will delete the row. Untrack only when msg_id is still nil.
  • promote_next did not surface msg_id to the caller. Capture it and backfill.

Deviations

  • Stall threshold is a 5-minute constant (Batch::Sweep::STALL_THRESHOLD), not a new config key. The issue only specified batch_retention and batch_sweep_interval; this matches solid_queue's stalled_for: 5.minutes default.
  • message_in_queue? is a thin wrapper over existing message_exists?(msg_id:). message_archived? is new (pgmq.a_*). DLQ presence reuses message_in_queue? on config.dead_letter_queue_name.
  • Dashboard still emits discarded_jobs as an alias of failed_jobs so existing JSON/API consumers don't break; views and progress use failed_jobs.
  • on_discard: remains as a kwarg that warns and maps to on_failure:; empty-batch path still does not fire failure callbacks.

Judgment calls

  • Execution-row insert uses insert_all + unique job_id so a retry re-enqueue of the same ActiveJob id is a no-op rather than raising.
  • Callbacks fire after the finish transaction commits (same shape as today's 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_executions row per job before send and finishes when no rows remain. Also fixes DLQ suffix handling so _pN is stripped only when priority routing is enabled. Closes #414.

  • Rollout and migration

    • Required: run rails generate pgbus:add_batch_executions (or pgbus:update) and rails db:migrate; restart pgbus workers after migrating.
    • Migration creates pgbus_batch_executions, renames on_discard_class to on_failure_class, and folds discarded_jobs into failed_jobs.
    • on_failure: and failed_jobs are canonical; on_discard: and discarded_jobs remain deprecated aliases until 1.0.
    • Dispatcher sweep runs every config.batch_sweep_interval (default 5 minutes) and cleans finished batches using config.batch_retention (default 7 days; nil disables).
    • Unmigrated apps stay on the counter path. Pre-migration in‑flight batches increment counters when no execution row exists and finish only when completed + failed == total.
  • Reviewer notes

    • Execution rows are inserted before send (idempotent via ON CONFLICT DO NOTHING) and backfilled with msg_id and physical queue_name after send; the uniqueness lock is bound before backfill. Post-send uniqueness failures clear the thread-local without releasing the live lock.
    • Sweep repairs orphan rows (msg_id NULL, decrements total_jobs only after delete), missing queue/archive/DLQ rows (DLQ identified by payload job_id; priority sub-queues share the logical DLQ), stalled pending batches, and processing batches that already have terminal counters. DLQ _pN suffix is stripped only when priority levels are configured; otherwise a literal _pN suffix is preserved.

Written for commit a286cfc. Summary will update on new commits.

Review in cubic

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

cubic-dev-ai Bot commented Aug 22, 2026

Copy link
Copy Markdown

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.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread lib/pgbus/batch/sweep.rb Resolved
Comment thread lib/pgbus/batch/sweep.rb Resolved
Comment thread lib/pgbus/batch/sweep.rb Resolved
Comment thread lib/pgbus/batch.rb Resolved
Comment thread spec/pgbus/configuration_spec.rb Resolved
Comment thread spec/pgbus/batch_sweep_spec.rb Resolved
Comment thread spec/integration_helper.rb Resolved
Comment thread spec/pgbus/batch_execution_spec.rb Resolved
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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread lib/pgbus/batch/sweep.rb Resolved
Comment thread lib/pgbus/batch.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread lib/pgbus/client.rb Resolved
Comment thread config/locales/nb.yml Resolved
Comment thread config/locales/fi.yml Resolved
Comment thread config/locales/es.yml Resolved
Comment thread config/locales/pt.yml Resolved
Comment thread config/locales/pt.yml Resolved
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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread lib/pgbus/batch.rb Resolved
Comment thread lib/pgbus/client.rb Resolved
Comment thread spec/support/pgmq_doubles.rb Resolved
@mhenrixon mhenrixon self-assigned this Aug 22, 2026
@mhenrixon mhenrixon added the bug Something isn't working label Aug 22, 2026
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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread spec/support/pgmq_doubles.rb Resolved
Comment thread spec/pgbus/pgmq_doubles_spec.rb Resolved
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Batches v2: execution-row completion tracking, stalled-batch sweep, on_failure rename

1 participant