Skip to content

fix(active_job): perform_all_later no longer escapes batch tracking or concurrency limits - #417

Merged
mhenrixon merged 3 commits into
mainfrom
issue-413-bulk-enqueue-batch-concurrency
Aug 22, 2026
Merged

mhenrixon merged 3 commits into
mainfrom
issue-413-bulk-enqueue-batch-concurrency

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adapter#enqueue_all's bulk path (enqueue_immediate in lib/pgbus/active_job/adapter.rb) now maps every payload through inject_batch_metadata, so jobs bulk-enqueued via ActiveJob.perform_all_later inside a Pgbus::Batch#enqueue block are tagged with pgbus_batch_id and counted into total_jobs. Before, they escaped the batch entirely — the batch could finish and fire on_finish/on_success before the bulk jobs ever ran.
  • Jobs whose class declares pgbus_concurrency are partitioned out of the bulk path into the individual enqueue/enqueue_at path, mirroring the existing uniqueness partition and for the same reason: per-job semaphore acquisition cannot happen in a bulk send_batch. Before, their concurrency limits were silently ignored.
  • Plain jobs keep the fast send_batch path unchanged.

Closes #413 (first sub-issue of #416).

Test plan

  • Unit (RED first): bulk payloads tagged + thread-local count incremented inside a batch context; concurrency jobs routed through the individual path with semaphore acquire and conflict handling; plain jobs still bulk (spec/pgbus/active_job/adapter_spec.rb)
  • Integration: perform_all_later inside a batch yields total_jobs == 2, tagged payloads on the work queue, and the callback fires only after both jobs complete (spec/integration/batch_flow_spec.rb) — verified RED against the unfixed adapter (total_jobs was 0)
  • bundle exec rubocop — no offenses
  • Full bundle exec rspec — 4323 examples, only the 2 known-baseline i18n failures
  • Integration batch_flow suite green against real PGMQ

Deviations & judgment calls

None — the plan held. (One addition beyond the issue's spec list: a second enqueue_all concurrency test covering the on_conflict path, so the partition is proven for both the acquire and conflict branches.)


Summary by cubic

ActiveJob.perform_all_later bulk enqueues now participate in batch tracking and enforce concurrency limits. Previously, bulk jobs inside a batch were untagged/uncounted and concurrency was bypassed; now they are tagged, counted, and limits apply. We also release :until_executed uniqueness locks when a concurrency :discard drops the job to avoid orphaned locks.

  • In enqueue_all, jobs with uniqueness or concurrency use the individual path; only plain jobs stay on the bulk path, which now injects batch metadata before send_batch.
  • Enqueue-time discards (uniqueness duplicate or concurrency: :discard) are not counted into the batch; blocked concurrency stays counted and runs later. On concurrency :discard, we release the acquired :until_executed lock.
  • Batch.update_total re-checks completion after publishing total_jobs so early completions can finish the batch; no migration or config changes.

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

Review in cubic

…r concurrency limits

## Summary
Adapter#enqueue_all's bulk path (enqueue_immediate) skipped the metadata
injection the individual enqueue paths run: bulk jobs inside a
Pgbus::Batch#enqueue block were untagged and uncounted (callbacks could
fire before they ran), and pgbus_concurrency jobs bypassed their
semaphore entirely. Bulk payloads now pass through inject_batch_metadata,
and concurrency-configured jobs are partitioned into the individual
enqueue path, mirroring the existing uniqueness partition.

## Test Coverage
- adapter_spec: bulk payloads tagged with batch id + thread-local count
- adapter_spec: concurrency jobs routed individually (acquire + conflict)
- batch_flow integration: perform_all_later jobs counted into total_jobs,
  payloads tagged, batch finishes only after both complete (verified RED
  against the unfixed adapter)

## Verification
- [x] bundle exec rubocop passes
- [x] bundle exec rspec passes (baseline: 2 known i18n failures only)
- [x] integration batch_flow_spec green against real PGMQ

Refs #413
@cubic-dev-ai

cubic-dev-ai Bot commented Aug 22, 2026

Copy link
Copy Markdown

Running ultrareview automatically — This PR modifies core job dispatching logic to fix critical bugs where bulk-enqueued jobs bypassed concurrency limits and batch tracking, risking race conditions and premature batch completion callbacks.. 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 7m 49s

All reported issues were addressed across 4 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/active_job/adapter.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread spec/pgbus/active_job/adapter_spec.rb Resolved
Comment thread spec/pgbus/active_job/adapter_spec.rb Resolved
…ck completion after total publish

Review pass on PR #417:

- A job discarded at enqueue time (uniqueness duplicate or concurrency
  on_conflict: :discard) is no longer counted into its batch — a
  counted-but-never-sent job can never signal completion and left the
  batch processing forever. Blocked jobs stay counted: their stored
  payload keeps the batch tag and runs when the semaphore frees.
- Batch#update_total now re-checks completion after publishing
  total_jobs: completion signals that arrived while the enqueue block
  was still open saw total_jobs == 0 and could not finish the batch
  (BatchEntry.check_finished!, row-locked and idempotent).
- Spec cleanup: shared concurrency fixtures hoisted to describe level,
  misleading example name corrected.

Both behavior fixes verified RED first (unit for the discard paths,
integration for the total-publish race).

@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 5 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread lib/pgbus/active_job/adapter.rb Resolved
A job that acquired an :until_executed uniqueness lock and then hit a
concurrency on_conflict: :discard never sent a message, so no executor
could release the lock. Later equivalent jobs were blocked until the
pgbus_uniqueness_keys row was deleted by hand.

The uniqueness-duplicate discard path is unchanged: that lock belongs
to the in-flight job. :block conflicts still keep the lock because
BlockedExecution stores the tagged payload.

Verified RED first.

Refs #413
@mhenrixon
mhenrixon merged commit 41ed7a9 into main Aug 22, 2026
13 checks passed
@mhenrixon
mhenrixon deleted the issue-413-bulk-enqueue-batch-concurrency branch August 22, 2026 08:56
mhenrixon added a commit that referenced this pull request Aug 23, 2026
…ep, while_executing release (#425)

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(active_job): perform_all_later bypasses batch and concurrency metadata

1 participant