Skip to content

fix(uniqueness): bind until_executed keys after send so the reaper can heal orphans - #419

Merged
mhenrixon merged 4 commits into
mainfrom
fix/uniqueness-pending-orphan-reaper
Aug 22, 2026
Merged

mhenrixon merged 4 commits into
mainfrom
fix/uniqueness-pending-orphan-reaper

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

:until_executed uniqueness rows were inserted as queue_name: "pending", msg_id: 0 and never updated after send_message. The dispatcher reaper then probed pgmq.q_<prefix>_pending, which does not exist. Client#message_exists? rescued UndefinedTable as nil, and nil means "still here", so leaked keys discarded every later enqueue forever (on_conflict: :discard heartbeats stuck for hours/days with no matching PGMQ message).

Three cooperating fixes:

  1. Bind after send. Adapter and recurring scheduler acquire with the logical queue name, then UniquenessKey.bind! writes queue + msg_id after a successful produce. Bind errors are fail-soft. Retry re-enqueues (executions > 0) do not re-bind (issue Correctness: uniqueness default-key collapse, retry_on×until_executed, wildcard-worker adopts event queues #333).
  2. Reaper never queries the synthetic pending queue. Unbound rows (pending and/or msg_id=0) are scanned across live pgmq.q_* tables via Client#uniqueness_keys_present. In-flight jobs that still look like pending/0 are kept if any queue payload still carries the key. Age floor remains 2 * visibility_timeout.
  3. Release immediately after archive. The executor releases the lock right after archive (fail-soft), with the ensure DELETE as an idempotent backstop, so a kill during pgbus.job_completed cannot leak a lock whose message is already gone.

Bound message_exists? lookups on a logical name also check priority _pN sub-queues.

Do not bulk-delete pending/msg_id=0 rows on upgrade — in-flight jobs currently share that shape. After deploy, true orphans older than 2 * VT with no matching payload are reaped on the next dispatcher cleanup (default 5 minutes).

Closes #418

Test plan

  • RED first: bind, adapter, reaper, client scan, and executor-order specs failed before the matching code
  • bundle exec rspec spec/pgbus/ spec/generators/ — 3938 examples, 0 failures (line 90.71% / branch 78.6%)
  • PGBUS_DATABASE_URL=postgres:///pgbus_test bundle exec rspec spec/integration/dispatcher_reaper_spec.rb spec/integration/job_uniqueness_spec.rb spec/integration/recurring_scheduler_uniqueness_spec.rb spec/integration/uniqueness_retry_spec.rb — 20 examples, 0 failures, including:
    • aged pending/0 with no payload anywhere → reaped
    • aged pending/0 with a message on critical still holding the key → kept
    • recurring enqueue row has logical queue + positive msg_id
    • #333 retry_on × :until_executed still succeeds and cleans up the key
  • bundle exec rubocop on changed files — clean

Deviations & judgment calls

  • PG array bind: ANY($1::text[]) with a Ruby array is serialized as "[\"key\"]", which Postgres rejects (malformed array literal). The scan uses a bound IN ($1, $2, …) list instead.
  • No data migration / bulk DELETE of pending/0. That would unlock in-flight jobs whose message sits on a real queue. The reaper heals true orphans after 2 * VT.
  • No cross-connection transaction around produce + bind (PGMQ client and UniquenessKey/BusRecord may not share a transaction). Bind is fail-soft; leftover msg_id=0 rows are covered by the unbound scan.

Summary by cubic

Binds :until_executed uniqueness locks to real PGMQ messages after send so the reaper can release true orphans. Previously locks stayed pending/msg_id=0 and the reaper probed a non-existent pending table, so duplicates were discarded indefinitely.

  • Producer: acquire on the logical queue; after a successful send, bind queue+msg_id. Retries do not rebind. Bind is scoped to this enqueue’s unbound row (msg_id=0 and matching acquire created_at) to avoid retargeting a successor; failures warn and do not fail the enqueue. Clear the bind stamp if we don’t bind (e.g., concurrency :block) to avoid thread-local leaks.
  • Reaper/Client: never query a synthetic pending queue. For unbound rows (pending or msg_id=0) scan live pgmq.q_* tables for the key. For bound rows, check msg_id and also match the payload’s uniqueness key so a sub-queue msg_id collision can’t mask an orphan. message_exists? now accepts msg_id and/or uniqueness_key, searches all physical tables (including priority sub-queues), and returns true/false/nil; adds uniqueness_keys_present for scanning. Unknown results keep the lock; the age floor stays 2 × visibility_timeout.
  • Executor: release the uniqueness lock once, immediately after archive; remove the ensure backstop to avoid deleting a successor row. Release failures are logged and non-fatal.
  • Rollout: no migration. Do not bulk-delete pending/msg_id=0 rows; the reaper will heal true orphans after deploy.

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

Review in cubic

…n heal orphans

until_executed uniqueness rows were inserted as pending/msg_id=0 and never
updated after send_message. The dispatcher reaper then probed
pgmq.q_<prefix>_pending, which does not exist; message_exists? returned nil
and nil was treated as "still here", so leaked keys discarded every later
enqueue forever.

Acquire with the logical queue, bind queue+msg_id after a successful send
(adapter and recurring scheduler; retry re-enqueues do not re-bind). Unbound
rows are reaped by scanning live q_* tables, never the synthetic pending
queue. The executor releases the lock immediately after archive.

Refs #418
@cubic-dev-ai

cubic-dev-ai Bot commented Aug 22, 2026

Copy link
Copy Markdown

Running ultrareview automatically — This PR modifies critical uniqueness lock binding and reaping logic across the adapter, executor, and dispatcher. Subtle bugs in how locks are tracked or scanned across queues could lead to permanent job suppression or data integrity issues.. I'll post findings when complete.

@mhenrixon mhenrixon self-assigned this Aug 22, 2026
@mhenrixon mhenrixon added the bug Something isn't working label Aug 22, 2026

@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 23m 54s

All reported issues were addressed across 20 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/executor.rb Resolved
Comment thread lib/pgbus/uniqueness.rb Resolved
Comment thread lib/pgbus/process/dispatcher.rb Resolved
Comment thread lib/pgbus/client.rb Resolved
Comment thread lib/pgbus/uniqueness.rb Resolved
Comment thread lib/pgbus/process/dispatcher.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread CHANGELOG.md Resolved
Keep both Unreleased changelog entries (#418 this branch, #413 from
main). Adapter resolution: uniqueness_rejected? still takes queue: for
bind-after-send, plus main's uncount_batch_job / rollback_acquired_uniqueness_lock
and enqueue_all concurrency partition.
…r enqueue

A successful first release plus an ensure-backstop DELETE could remove a
new uniqueness row acquired in that window. Bind is now restricted to this
enqueue's unbound row (msg_id=0 and acquire created_at). Bound reaper
lookups also match the payload key so a priority sub-queue msg_id collision
cannot keep an orphan alive.

Refs #418

@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 11 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/executor.rb Resolved
Comment thread app/models/pgbus/uniqueness_key.rb Resolved
Comment thread spec/integration/job_uniqueness_spec.rb Resolved
A second DELETE in ensure is unsafe if the first already committed: a
successor can acquire the same key between the two calls. Release once
after archive. Drop the bind ownership stamp when enqueue returns
without bind (concurrency :block) so it does not leak on the producer
thread.

Refs #418

@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.

0 issues found across 5 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

Re-trigger cubic

@mhenrixon
mhenrixon merged commit 1d49f4a into main Aug 22, 2026
14 checks passed
@mhenrixon
mhenrixon deleted the fix/uniqueness-pending-orphan-reaper branch August 22, 2026 18:48
mhenrixon added a commit that referenced this pull request 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.
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

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

until_executed uniqueness keys stay pending/msg_id=0 so the orphan reaper never releases them

1 participant