Repository navigation
fix(uniqueness): bind until_executed keys after send so the reaper can heal orphans - #419
Conversation
…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
|
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. |
There was a problem hiding this comment.
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
…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
There was a problem hiding this comment.
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
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
There was a problem hiding this comment.
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.
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.
…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
Summary
:until_executeduniqueness rows were inserted asqueue_name: "pending", msg_id: 0and never updated aftersend_message. The dispatcher reaper then probedpgmq.q_<prefix>_pending, which does not exist.Client#message_exists?rescuedUndefinedTableasnil, andnilmeans "still here", so leaked keys discarded every later enqueue forever (on_conflict: :discardheartbeats stuck for hours/days with no matching PGMQ message).Three cooperating fixes:
UniquenessKey.bind!writes queue +msg_idafter 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).pendingqueue. Unbound rows (pendingand/ormsg_id=0) are scanned across livepgmq.q_*tables viaClient#uniqueness_keys_present. In-flight jobs that still look likepending/0are kept if any queue payload still carries the key. Age floor remains2 * visibility_timeout.ensureDELETE as an idempotent backstop, so a kill duringpgbus.job_completedcannot leak a lock whose message is already gone.Bound
message_exists?lookups on a logical name also check priority_pNsub-queues.Do not bulk-delete
pending/msg_id=0rows on upgrade — in-flight jobs currently share that shape. After deploy, true orphans older than2 * VTwith no matching payload are reaped on the next dispatcher cleanup (default 5 minutes).Closes #418
Test plan
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:pending/0with no payload anywhere → reapedpending/0with a message oncriticalstill holding the key → keptmsg_id#333retry_on ×:until_executedstill succeeds and cleans up the keybundle exec rubocopon changed files — cleanDeviations & judgment calls
ANY($1::text[])with a Ruby array is serialized as"[\"key\"]", which Postgres rejects (malformed array literal). The scan uses a boundIN ($1, $2, …)list instead.pending/0. That would unlock in-flight jobs whose message sits on a real queue. The reaper heals true orphans after2 * VT.UniquenessKey/BusRecordmay not share a transaction). Bind is fail-soft; leftovermsg_id=0rows 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.
Written for commit 8291009. Summary will update on new commits.