Skip to content

fix(concurrency): make on_conflict: :block durable and never over-admit - #460

Merged
mhenrixon merged 5 commits into
mainfrom
fix/concurrency-block-durability
Sep 10, 2026
Merged

mhenrixon merged 5 commits into
mainfrom
fix/concurrency-block-durability

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

solid_queue recently closed a class of limits_concurrency bugs that produced duplicate execution and stranded jobs (rails/solid_queue#712, #761, plus #783). This audits pgbus's limits_concurrency … on_conflict: :block against the same failure modes and fixes the four that applied — the goal being that :block constrains a job without ever losing it, and never runs more than to: at once. Uniqueness cannot serve that purpose: every ensures_uniqueness conflict rejects, discards or logs; there is no :block, and :while_executing duplicates burn read_ct on every visibility lapse until they dead-letter.

The four defects

Before After
Parked job aged out Dispatcher delete_all-ed blocked rows past expires_at; release_next! refused to promote them. A park outliving duration was silently gone. Blocked rows never expire. The only way out of pgbus_blocked_executions is promotion. expires_at orders the sweep, nothing more.
Semaphore expired under a running job duration capped 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. The visibility heartbeat re-arms the semaphore alongside the message (Semaphore.touch), so duration bounds heartbeat silence. Every promotion (completion-time or sweep) takes its slot through the same value < max_value upsert an enqueue uses.
Enqueue / unblock race (#712) Semaphore check and blocked-row insert were two autocommit statements. A holder finishing in between found no parked row, released, and nobody promoted the row it had just missed. Adapter checks and parks in one transaction — the upsert holds the semaphore row lock until commit even when it returns :blocked (verified empirically: a concurrent UPDATE blocked 2.5 s until the parking transaction committed). The completion signal decrements under that lock before looking for parked rows.
Duplicate delivery released twice (#761) A worker whose heartbeat lapsed had its message redelivered; both copies finished, both signalled, and a to: 1 key ran 2, then 3. pgmq.archive returning false is the exact-once claim: that execution returns :duplicate and skips concurrency, batch and uniqueness signals.

Found underneath: the parked payload was double-encoded

BlockedExecution.insert handed 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 because Client#send_message passes a String body through untouched. Everything that read the column as a document was silently wrong: the job-class lookup, scheduled_at (a parked perform_later(wait:) promoted immediately), Batch.backfill_execution, and the batch sweep's payload->>'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_stale on 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#execute returns :duplicate for an already-archived message.

Not changed (called out for review)

  • On the default dedicated-connection client path, send_message inside 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.
  • A crash between archive and signal still leaks a slot until duration of heartbeat silence; the sweep then promotes. Making archive + signal atomic is a possible follow-up.
  • ensures_uniqueness :while_executing still burns read_ct for 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):

main this branch
execute (small job) 51.6k / 52.4k i/s 49.0k (±11%) / 51.8k (±2%) i/s
allocated per job 6824 B, 81 objects 6824 B, 81 objects
retained per job 0 0

Method-level, within noise. The plain-job path gains one hash lookup (extract_key) and one nil kwarg; a first cut carried two extra Entry members 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

  • RED first: 7 new integration examples (spec/integration/concurrency_block_durability_spec.rb) and 12 unit examples failed for the intended reasons before the fix.
  • bundle exec rspec (bare) green.
  • Integration suite (non-streams) green against local PG 18 + pgmq.
  • Docs site rake lint + rspec green.
  • RuboCop clean on touched files.
  • Consumer: a to: 1, on_conflict: :block job with a run longer than duration no longer sees a second run start beside it; a park older than duration still promotes.

Summary by cubic

Makes limits_concurrency … on_conflict: :block durable: a parked job is never dropped, and a key never runs more than to: at once. This closes the same bug class solid_queue fixed in rails/solid_queue#712, #761, and #783.

Bug fixes

  • Blocked rows no longer expire; only promotion removes them from pgbus_blocked_executions.
  • duration bounds 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.
  • The enqueue checks and parks in one transaction under the semaphore row lock, then sends the message only after commit; a send failure raised before the wire returns the slot immediately, while an ambiguous outcome keeps the slot, uniqueness lock and batch count until lease expiry reclaims them.
  • A duplicate delivery skips concurrency, batch, and uniqueness signals; archiving is the exact-once claim, an ambiguous archive retry is claimed rather than treated as a duplicate, and a :while_executing lock is released only while still bound to that message on that queue.
  • Parked payloads were double-encoded as jsonb strings; rows now store objects, are repaired in place, and new integration coverage verifies batches whose children share a :block key stay counted while parked and promote one at a time.
  • The sweep promotes only keys that can take a slot right now, and a job whose class no longer resolves promotes against the limit the semaphore row already records.

Migration

  • Concurrency::BlockedExecution.expire_stale is removed; the dispatcher sweep is now promote_pending(client:).
  • No DB migration needed.

Written for commit 529220b. Summary will update on new commits.

Review in cubic

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

cubic-dev-ai Bot commented Sep 10, 2026

Copy link
Copy Markdown

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.

@mhenrixon mhenrixon self-assigned this Sep 10, 2026
@mhenrixon mhenrixon added enhancement New feature or request stability Crash safety, recovery and resilience under failure (applied by judgment) labels Sep 10, 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 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

Comment thread lib/pgbus/concurrency/semaphore.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread lib/pgbus/active_job/executor.rb Resolved
Comment thread lib/pgbus/active_job/executor.rb Resolved
Comment thread lib/pgbus/concurrency.rb Resolved
Comment thread spec/pgbus/visibility_heartbeat_spec.rb Resolved
Comment thread lib/pgbus/active_job/executor.rb Resolved
Comment thread spec/pgbus/process/dispatcher_spec.rb Resolved
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.

@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 16 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/active_job/adapter.rb Resolved
Comment thread app/models/pgbus/uniqueness_key.rb Resolved
Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread lib/pgbus/concurrency.rb Resolved
Comment thread CHANGELOG.md Resolved
…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.

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

Comment thread lib/pgbus/active_job/adapter.rb Resolved
Comment thread lib/pgbus/concurrency/semaphore.rb Resolved
Comment thread CHANGELOG.md Resolved
Comment thread CHANGELOG.md Resolved
…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.

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

Re-trigger cubic

@mhenrixon
mhenrixon merged commit d7249fa into main Sep 10, 2026
14 checks passed
@mhenrixon
mhenrixon deleted the fix/concurrency-block-durability branch September 10, 2026 10:00
mhenrixon added a commit that referenced this pull request Sep 10, 2026
… 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request stability Crash safety, recovery and resilience under failure (applied by judgment)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant