Repository navigation
fix(concurrency): make on_conflict: :block durable and never over-admit - #460
Conversation
Audit of limits_concurrency against the solid_queue fixes for the same bug class (rails/solid_queue#712 enqueue/unblock race, #761 lock leaks that duplicate execution, #783 orphan blocked rows). Four defects applied: - A parked job was deleted by the sweep once older than `duration`, and release_next! refused to promote it. Blocked rows no longer expire; the only way out of pgbus_blocked_executions is promotion. - The semaphore expired under a still-running holder and the next parked job was promoted beside it without taking a slot. The visibility heartbeat now re-arms the semaphore (Semaphore.touch), and every promotion takes its slot through the guarded upsert, so a key can never exceed `to:`. - The enqueue checked the semaphore and parked as two autocommit statements, so a holder finishing in between stranded the row. The adapter now checks and parks in one transaction under the semaphore row lock, and Semaphore.signal decrements under that lock before promoting. - A duplicate delivery (heartbeat lapse) released the slot twice. pgmq.archive returning false is the exact-once claim: the executor returns :duplicate and skips every completion signal. Underneath, BlockedExecution.insert handed the jsonb column a serialized string, so every parked payload was a jsonb string: the job-class lookup, scheduled_at, batch backfill and the batch sweep's payload->>'job_id' all misread it. Rows are stored as objects now; the sweep repairs old rows in place and release_next! reads both shapes. No migration. Bench: executor plain path within noise of main, identical allocations.
|
Running ultrareview automatically — This PR rewrites the core concurrency/blocking subsystem — semaphore transactions, sweep promotion, heartbeat-driven semaphore touches, and a data-repair migration for double-encoded payloads — where subtle race or transaction bugs could cause lost jobs, duplicate execution, or limit overruns.... I'll post findings when complete. |
There was a problem hiding this comment.
Ultrareview completed in 12m 17s
All reported issues were addressed across 18 files
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
Six narrower holes in the same invariant, each with a regression spec: - A scheduled job's slot lease now covers its delay; the heartbeat that renews a lease only starts at dequeue. The residual (a queue backed up longer than duration) is documented rather than papered over. - duration is floored at twice the heartbeat interval so a lease can never lapse before the beat that would have renewed it. - The enqueue sends the message AFTER the slot transaction commits. The PGMQ connection can never join the AR transaction, so a commit failure after a send left the message live with the slot rolled back. Now the only crash window under-admits until the sweep reclaims the lease. A send that raises hands the slot back immediately. - The batch backfill after a promotion runs in its own savepoint so a database error there cannot poison Semaphore.signal's transaction and undo a promotion whose message is already live. - archive_from distinguishes :ambiguous (false after our own retry) from :already_archived, and claims the former. A genuine duplicate releases its own :while_executing lock conditioned on msg_id. - The sweep scans only keys that could take a slot now, so held keys cannot starve a key behind them whose holder died. An unresolved job class promotes against the semaphore row's recorded max_value. Both vacuous specs flagged in review now assert the real invariant.
There was a problem hiding this comment.
All reported issues were addressed across 16 files (changes from recent commits).
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
…lease by queue Second review pass on the :block guarantee: - An ambiguous send (the failure reached the database, so the produce may have committed with its reply lost) now keeps the slot, the uniqueness lock and the batch count; only a failure raised before the wire hands the slot straight back. Undoing bookkeeping for a message that is in fact live is the unrecoverable direction. - UniquenessKey.release_if_bound! matches on (lock_key, queue_name, msg_id): PGMQ ids are per-queue sequences, so msg_id alone could delete a successor on another queue. - Semaphore.touch applies the duration floor itself, so a renewal can never be shorter than the gap to the next beat. - A promoted scheduled job's lease covers its remaining delay, matching the direct-enqueue path. - The docs name the one window a lease cannot cover, including a produce that stalls past the lease, with sizing guidance. - The starvation unit example is renamed to what it pins; the SQL is pinned by the integration spec.
…to end A batch of three children under limits_concurrency to: 1 driven by the real executor: two park at enqueue and stay counted, the stall sweep leaves them alone, each finish promotes exactly one more, execution rows are backfilled on promotion, and the batch finishes after the last one. The sweep half is the regression the double-encoded parked payload used to trip once the stall threshold passed.
There was a problem hiding this comment.
All reported issues were addressed across 12 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
…ase after checkout Third review pass: - The adapter's rescue read any database-shaped error as an ambiguous send, so a PG::Error from the slot upsert or from parking the job skipped the uniqueness rollback and batch uncount. A `sending` flag set immediately before each produce keeps the reprieve to the produce itself; everything before it still rolls back. - Semaphore.touch reads Time.current inside with_connection, so waiting on a busy pool is no longer charged against the renewal. - CHANGELOG names each recovery path (concurrency sweep, unbound-lock reaper, batch orphan pass) instead of implying the lease expiry reclaims all three, and states the one deliberate over-approximation in the classifier.
… MCP (#463) * feat(web): surface concurrency keys on the Locks page, in metrics and MCP ## Summary `limits_concurrency … on_conflict: :block` became durable in #460, but nothing showed it: `pgbus_semaphores` and `pgbus_blocked_executions` appeared on no page, in no gauge and in no MCP tool, so an operator whose per-record pipeline looked stuck had no way to see that the key's slot was held or how many jobs were parked behind it, short of SQL. One new read, `Web::DataSource#concurrency_stats`, feeds four consumers: - A **Concurrency** section on the Locks page: four summary cards plus a row per key (value / limit, lease state, parked count, oldest wait), in its own auto-refreshing turbo-frame served by `GET /locks?frame=concurrency`. The uniqueness table moves into its own partial and keeps its bulk-select state by staying out of a frame. - A **Parked jobs** card on the dashboard home, linking to the Locks page. - Three unlabelled gauges on `/pgbus/api/metrics` and the AppSignal probe: `pgbus_concurrency_blocked_executions`, `pgbus_concurrency_blocked_oldest_age_seconds`, `pgbus_concurrency_slots_held`. No per-key labels — keys are per-record and would be an unbounded series. - A read-only `pgbus_concurrency` MCP tool. The key rows come from a FULL OUTER JOIN, not a LEFT one: a key can have parked jobs and no semaphore (its holder died and the sweep removed the row) or a semaphore and nothing parked, and both matter. The four aggregates are memoized per instance and merged into `summary_stats`, so the home card, the serializer and the probe add no second query. Two guarded per-key actions: - **Release** deletes the semaphore row then promotes through `Concurrency::BlockedExecution.promote_next`, so every promoted job takes a real slot through the guarded upsert and the release cannot reintroduce the over-admission #460 closed. When the lease is still fresh the confirm says so. - **Discard parked** drops one key's parked jobs under `FOR UPDATE SKIP LOCKED` and resolves what those jobs never will: a parked batch child is marked failed (#413) and an `:until_executed` uniqueness lock is released (#423). The confirm names the exact count; the button only renders when something is parked. No cross-key bulk discard — not losing work is the point of `:block`. Nothing is added to the enqueue or execute path. ## Test Coverage - data_source_spec: `#concurrency_stats` shape, lease_fresh from bool and "t", zeros fallback, summary merge, one query per instance; `release_concurrency_key` promote loop, cap, blank key; `discard_parked_jobs` batch/uniqueness/plain payloads, double-encoded legacy row, instrumentation per row - dashboard_concurrency_spec (integration, real tables): the join's row shape, parked-without-semaphore, release promotes one and leaves the key at 1/1, discard marks a batch child failed and frees a real uniqueness row - locks_controller_spec: both sections, `?frame=concurrency`, both POSTs, blank key - locks_spec (system): cards, rows, the two confirm texts, both submits - dashboard_spec (system): the Parked jobs card - metrics_serializer_spec, api/metrics_controller_spec, probe_spec, dashboard_spec (AppSignal JSON), mcp/tools_spec ## Verification - [x] bundle exec rubocop app benchmarks config gemfiles lib spec Gemfile Rakefile pgbus.gemspec — no offenses - [x] bundle exec rspec spec/pgbus/ spec/generators/ — 4395 examples, 0 failures (91.21% line / 79.06% branch) - [x] bundle exec rspec (bare) — 4918 examples, 0 failures - [x] PGBUS_DATABASE_URL=… rspec the three concurrency/locks integration specs — 33 examples, 0 failures - [x] bun run lint:herb — clean - [x] rake frontend:css — artifact rebuilt and committed, git clean - [x] cd docs && rake lint && rspec — clean, 71 examples Refs #461 Claude-Session: https://claude.ai/code/session_014bwX3ZhFrobXyMYhEKpkqP * fix(web): address review findings on the concurrency section Correctness (P1): - Discarding a parked job released its uniqueness lock by key alone. If the unbound-lock reaper had already removed that row and a successor took the same key and was actually sent, the discard dropped the SUCCESSOR's lock and admitted a duplicate beside the running job. A parked job's lock is unbound (it never got a msg_id) while a sent job's is bound, so the new UniquenessKey.release_if_unbound! scopes the delete to msg_id = 0 — the mirror of release_if_bound!, for the side of the lifecycle with no message to match on. - release_key and discard_parked stripped the key before the lookup. Keys come from a user-supplied proc and may legitimately carry surrounding whitespace, so stripping addressed a different key or none. The raw value now goes through; strip is used only for the blank check. Correctness (P2): - Releasing a key DELETED the semaphore row, which is where the key's limit is recorded. When a parked payload's job class no longer resolves, promotion has no limit of its own and Semaphore.acquire! falls back to 1 on a fresh row — so a `to: 3` key was silently demoted to 1. The release now zeroes `value` and leaves the row for the dispatcher's expired-semaphore sweep. - lease_fresh reported a live lease for a semaphore emptied to value = 0, labelling a key with no holder "Live". It now requires a held slot. - The Parked jobs card sits inside the dashboard-stats turbo-frame, so clicking it asked Turbo to render /locks into a frame that page does not have and the user stayed on the dashboard. Added turbo_frame: "_top", plus a system spec that clicks the card (verified failing without the fix). - Each metrics scrape called summary_stats twice — it is not memoized, so that repeated the queue/health/process queries and advanced the throughput snapshot a second time within one scrape. One read is now shared. Pre-existing bug found while reviewing the new memo: - Web::DataSource memoizes for the life of the instance, which is right for the dashboard (one instance per request) but wrong for the two consumers that hold one instance for the life of the process: the AppSignal Probe::Runner and the MCP server context. Both replayed their first read forever — queue depth in AppSignal never moved after the first minute, and every MCP tool returned the same snapshot. DataSource#reset_cache! drops the memos; the probe calls it per iteration and BaseTool.data_source_from per tool call. Docs and i18n (P3): - "a growing backlog means a holder died" now distinguishes a fresh lease (demand above the limit) from a stale one (dead holder). - The Locks table is capped at 100 rows; say so, and that the cards carry the true totals. - Name the dashboard-home Parked jobs card as the entry point operators see first ("four places", not three). - keys_at_limit has no gauge — say it is Locks/MCP only rather than implying the three gauges carry all four totals. - it/nl page titles matched neither locale's own nav label: "Lock" -> "Blocchi", "Locks" -> "Vergrendelingen". - Finnish partitive agreement: "pysäköityä %{count} työtä". - Spanish hint reworded to describe the longest wait. - The uniqueness empty-state row spanned 5 columns while the header renders 4. - StubDataSource#release_concurrency_key returned parked_total; the real method returns jobs PROMOTED. It now has its own promoted_count. Not changed, with reasoning left on the thread: the claim that cleanup after the delete commit should be made retryable. Running it inside the transaction swaps a recoverable failure (an orphan row) for the unrecoverable one this codebase already rejected in Concurrency::BlockedExecution#backfill — a batch callback fired for a batch that then rolls back. The residual is now named in a comment instead. ## Verification - [x] rubocop (CI's target list) — no offenses - [x] rspec spec/pgbus/ spec/generators/ — 4398 examples, 0 failures (91.20% line / 79.09% branch) - [x] rspec (bare, full) — 4924 examples, 0 failures - [x] 4 integration specs incl. batch_flow — 47 examples, 0 failures - [x] bun run lint:herb — clean - [x] cd docs && rake lint && rspec — clean, 71 examples Refs #461 Claude-Session: https://claude.ai/code/session_0198toomhaXPGeLaf5QtVa1U * fix(web): tie the parked-lock release to row ownership, expire released keys Two findings from the re-review of the previous commit. - `release_if_unbound!` deleted ANY unbound lock for the key, so a successor that had re-acquired the key and was itself PARKED (also unbound, so msg_id could not separate them) lost its lock to the older row's discard. The lock is acquired immediately before the row is parked, so a lock created after the parked row cannot belong to it: the delete now takes an `acquired_before:` ceiling and the caller passes the discarded row's `created_at`. - Releasing a key left the row at `value = 0` with its original `expires_at`, but the dispatcher's `Concurrency::Semaphore.expire_stale` matches on `expires_at` ALONE — only the unused `Semaphore.expired` model scope also matches `value <= 0`. A released key therefore sat on the Locks page as a phantom 0/N row for up to its whole `duration`. The release now marks the emptied row expired, guarded on `value = 0` so a row a promotion just filled is never expired out from under its holder. The integration spec now asserts against `expire_stale` rather than the model scope, which is what let the gap through in the first place. Both new specs were verified to fail without their fix. ## Verification - [x] rubocop (CI's target list) — no offenses - [x] rspec spec/pgbus/ spec/generators/ — 4399 examples, 0 failures (91.26% line / 79.18% branch) - [x] rspec (bare, full) — 4926 examples, 0 failures - [x] 3 concurrency/locks integration specs — 36 examples, 0 failures Refs #461 Claude-Session: https://claude.ai/code/session_0198toomhaXPGeLaf5QtVa1U
Summary
solid_queue recently closed a class of
limits_concurrencybugs that produced duplicate execution and stranded jobs (rails/solid_queue#712, #761, plus #783). This audits pgbus'slimits_concurrency … on_conflict: :blockagainst the same failure modes and fixes the four that applied — the goal being that:blockconstrains a job without ever losing it, and never runs more thanto:at once. Uniqueness cannot serve that purpose: everyensures_uniquenessconflict rejects, discards or logs; there is no:block, and:while_executingduplicates burnread_cton every visibility lapse until they dead-letter.The four defects
delete_all-ed blocked rows pastexpires_at;release_next!refused to promote them. A park outlivingdurationwas silently gone.pgbus_blocked_executionsis promotion.expires_atorders the sweep, nothing more.durationcapped run time. Past it, the sweep deleted the semaphore and promoted the next parked job beside the still-running holder — and that promotion took no slot, so a further enqueue created a fresh semaphore and ran too.Semaphore.touch), sodurationbounds heartbeat silence. Every promotion (completion-time or sweep) takes its slot through the samevalue < max_valueupsert an enqueue uses.:blocked(verified empirically: a concurrentUPDATEblocked 2.5 s until the parking transaction committed). The completion signal decrements under that lock before looking for parked rows.to: 1key ran 2, then 3.pgmq.archivereturningfalseis the exact-once claim: that execution returns:duplicateand skips concurrency, batch and uniqueness signals.Found underneath: the parked payload was double-encoded
BlockedExecution.inserthanded the jsonb column an already-serialized string, so every row was a jsonb string, not an object (jsonb_typeof(payload) = 'string'in the test DB). Promotion worked only becauseClient#send_messagepasses a String body through untouched. Everything that read the column as a document was silently wrong: the job-class lookup,scheduled_at(a parkedperform_later(wait:)promoted immediately),Batch.backfill_execution, and the batch sweep'spayload->>'job_id'(a parked batch job looked orphaned and was un-counted, undoing #423). Rows are now stored as objects; the sweep rewrites pre-existing rows in place (repair_double_encoded!, idempotent);release_next!reads both shapes. No migration.API changes
Concurrency::Semaphore.signal(key, client:)— release + promote in one transaction; replaces the executor's promote-then-release pair.Concurrency::Semaphore.touch(key, duration)— heartbeat-driven expiry extension.Concurrency::BlockedExecution.promote_pending(client:)— the sweep;expire_staleon blocked executions is gone.Concurrency.config_for(job_class)/DEFAULT_DURATION— limit/duration for promotion; a class that no longer resolves promotes with the defaults and dead-letters in the executor (no maintenance crash loop, cf. solid_queue#783).Executor#executereturns:duplicatefor an already-archived message.Not changed (called out for review)
send_messageinside the promote transaction runs on pgmq's own connection, as before. The AR transaction still guards the DELETE + slot; a failed send rolls both back.durationof heartbeat silence; the sweep then promotes. Making archive + signal atomic is a possible follow-up.ensures_uniqueness :while_executingstill burnsread_ctfor duplicates waiting on a long holder.Performance
Executor hot path (
rake bench:one[executor_bench], mocked PGMQ, heartbeat on, same machine, interleaved A/B, two runs each):Method-level, within noise. The plain-job path gains one hash lookup (
extract_key) and one nil kwarg; a first cut carried two extraEntrymembers and pushed the struct into the next slot size (+384 B/job) — collapsed into one member to get back to baseline. Concurrency jobs pay one transaction around the signal where release + promote were already two round-trips; system-level cost is the database, as before.Test plan
spec/integration/concurrency_block_durability_spec.rb) and 12 unit examples failed for the intended reasons before the fix.bundle exec rspec(bare) green.rake lint+rspecgreen.to: 1, on_conflict: :blockjob with a run longer thandurationno longer sees a second run start beside it; a park older thandurationstill promotes.Summary by cubic
Makes
limits_concurrency … on_conflict: :blockdurable: a parked job is never dropped, and a key never runs more thanto:at once. This closes the same bug class solid_queue fixed in rails/solid_queue#712, #761, and #783.Bug fixes
pgbus_blocked_executions.durationbounds heartbeat silence, not run time; the heartbeat re-arms the semaphore, the lease is floored at twice the heartbeat interval (at acquire and again at each renewal, each renewal clocked from when the connection is in hand), and a scheduled job's lease covers its delay.:while_executinglock is released only while still bound to that message on that queue.:blockkey stay counted while parked and promote one at a time.Migration
Concurrency::BlockedExecution.expire_staleis removed; the dispatcher sweep is nowpromote_pending(client:).Written for commit 529220b. Summary will update on new commits.