Skip to content

feat(web): surface concurrency keys on the Locks page, in metrics and MCP - #463

Merged
mhenrixon merged 3 commits into
mainfrom
issue-461-concurrency-visibility
Sep 10, 2026
Merged

mhenrixon merged 3 commits into
mainfrom
issue-461-concurrency-visibility

Conversation

@mhenrixon

@mhenrixon mhenrixon commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

limits_concurrency … on_conflict: :block became durable in #460 — a parked job is never dropped and a key never runs past to: — but nothing showed it. pgbus_semaphores and pgbus_blocked_executions appeared on no page, in no gauge, 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, how many jobs were parked behind it, or how long the oldest had waited, short of SQL.

One new read, Web::DataSource#concurrency_stats, feeds four consumers:

  • A Concurrency section on the Locks page (app/views/pgbus/locks/_concurrency.html.erb) — four summary cards (parked jobs, oldest wait, slots held, keys at limit) plus a row per key with value / limit, lease state, parked count and oldest wait, in its own turbo-frame served by GET /locks?frame=concurrency. The uniqueness table moves into _uniqueness.html.erb and deliberately stays out of a frame so its bulk-select state survives.
  • A Parked jobs card on the dashboard home (_stats_cards.html.erb, now lg:grid-cols-7), the whole card linking to the Locks page.
  • Three unlabelled gauges on /pgbus/api/metrics (lib/pgbus/web/metrics_serializer.rb) and the AppSignal probe (lib/pgbus/integrations/appsignal/probe.rb): pgbus_concurrency_blocked_executions, pgbus_concurrency_blocked_oldest_age_seconds, pgbus_concurrency_slots_held, plus a "Concurrency" visual in dashboard.json.
  • A read-only pgbus_concurrency MCP tool (lib/pgbus/mcp/tools/concurrency_tool.rb).

The key rows come from a FULL OUTER JOIN, not a LEFT one: a key can have parked rows and no semaphore (its holder died and the sweep removed the row) or a semaphore and nothing parked, and an operator needs to see both. The four aggregates come from their own single statement, memoized per DataSource instance and merged into summary_stats, so the home card, the serializer and the probe add no second query.

The two guarded actions

Nothing is added to the enqueue or execute path, so there is no hot-path before/after to report — this change cannot move the executor bench, and no number is claimed.

Test plan

  • bundle exec rspec spec/pgbus/ spec/generators/ (CI's unit job) — 4395 examples, 0 failures, 91.21% line / 79.06% branch
  • bundle exec rspec (bare, full) — 4918 examples, 0 failures
  • PGBUS_DATABASE_URL=… bundle exec rspec spec/integration/dashboard_concurrency_spec.rb spec/integration/dashboard_discard_locks_spec.rb spec/integration/concurrency_block_durability_spec.rb — 33 examples, 0 failures (the last one proves the release path still cannot over-admit)
  • bundle exec rubocop app benchmarks config gemfiles lib spec Gemfile Rakefile pgbus.gemspec — no offenses
  • bun run lint:herb — clean
  • bundle exec rake frontend:css leaves git status clean (artifact committed)
  • cd docs && bundle exec rake lint && bundle exec rspec — clean, 71 examples
  • Manually: on a key with a stale lease and a parked backlog, Release promotes and the key settles at its limit; on a key with a fresh lease, the confirm warns before anything happens

Closes #461

Deviations & judgment calls

  • Reads go through the DataSource's own connection, not Semaphore.connection.exec_query. The issue's step 1 suggested stubbing Pgbus::Semaphore.connection.exec_query; the implementation uses the private connection helper (Pgbus::BusRecord.connection) with select_all, matching every other raw-SQL read in the file (fetch_all_table_stats, release_locks_for_failed_events). The unit spec stubs that same connection double.
  • The aggregates are a separate statement from the key join. parked_total has to be the true total while the key list is capped at 100, so one statement cannot serve both. The page runs two statements; the summary_stats / serializer / probe path runs one (memoized).
  • MCP tools are not autoloaded. A new tool needs an entry in lib/pgbus/mcp.rb's require list as well as in Server::TOOLS — the issue only named server.rb.
  • The home Parked jobs card is one big link_to. The Recurring card links via a small inner link; a card whose only action is "go look at the Locks page" reads better as a single target.
  • key_released has no zero: plural form. A release that promoted nothing reads "Released X and promoted 0 jobs." Honest, and one fewer key in each of the 12 locales.
  • pgbus.blocked_execution_discarded was added to the event list in lib/pgbus/instrumentation.rb, which enumerates every emitted event — the issue didn't mention that file.
  • Two existing specs needed adjusting, both because the page now has two tables. spec/system/locks_spec.rb asserted h1 text "Uniqueness Keys" (the h1 is now "Locks", with that text as the section h2), and its single-lock-discard example scoped within("tbody"), which is ambiguous with two tables — now scoped to [data-bulk-scope="locks"] tbody.
  • Pre-existing, not introduced here: spec/pgbus/integrations/appsignal/dashboard_spec.rb fails 3 examples when run alone (its be_in matcher needs ActiveSupport's Object#in?, loaded by a sibling spec). Verified by stashing this branch and reproducing on main. Green as part of the directory or suite run, which is how CI runs it.

https://claude.ai/code/session_014bwX3ZhFrobXyMYhEKpkqP


Summary by cubic

Surfaces the concurrency state limits_concurrency … on_conflict: :block made durable in #460: a pipeline at its limit previously looked stalled, with pgbus_semaphores and pgbus_blocked_executions on no page, gauge, or MCP tool. Adds a Concurrency section to the Locks page, a Parked jobs card to the dashboard home, three gauges to /pgbus/api/metrics and the AppSignal probe, and a read-only pgbus_concurrency MCP tool.

Guarded per-key actions

  • Release zeroes the semaphore's value — deleting the row lost the key's limit and demoted to: 3 keys to 1 — marks the emptied row expired so it can't linger as a phantom 0/N row, then promotes through Concurrency::BlockedExecution.promote_next, so the limit still holds and fix(concurrency): make on_conflict: :block durable and never over-admit #460's over-admission can't return.
  • Discard parked drops one key's parked jobs under FOR UPDATE SKIP LOCKED and resolves what they never will: a parked batch child is marked failed (fix(active_job): perform_all_later bypasses batch and concurrency metadata #413) and its uniqueness lock is released only while still unbound (msg_id = 0) and acquired before the parked row's created_at, so neither a sent nor a parked successor's lock is ever dropped.
  • Keys pass through verbatim — a key: proc may produce surrounding whitespace, and stripping would address a different key or none.

Observability details

  • Key rows come from a FULL OUTER JOIN: a key can have parked jobs without a semaphore (holder died) or a semaphore with nothing parked, and both matter.
  • The four aggregates are memoized per DataSource instance and merged into summary_stats; reset_cache! stops the AppSignal probe and MCP server — which hold one instance for the process's life — from replaying their first read forever.
  • Gauges are unlabelled because concurrency keys are per-record and would be an unbounded series.
  • The dashboard card uses turbo_frame: "_top" so clicking it leaves the stats frame and reaches the Locks page.
  • Nothing is added to the enqueue or execute path.

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

Review in cubic

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

cubic-dev-ai Bot commented Sep 10, 2026

Copy link
Copy Markdown

Running ultrareview automatically — This adds concurrency-sensitive data surgery to a job queue: a guarded release loop that promotes parked jobs through slot upserts (risk of over-admission), a FOR UPDATE SKIP LOCKED discard path that deletes jobs and resolves batch/uniqueness bookkeeping, plus new routes, metrics, and SQL joins.... 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 12m 41s

All reported issues were addressed across 41 files

Tip: instead of fixing issues one by one fix them all with cubic

Re-trigger cubic

Comment thread lib/pgbus/web/data_source.rb Resolved
Comment thread lib/pgbus/web/data_source.rb Resolved
Comment thread lib/pgbus/web/data_source.rb Resolved
Comment thread lib/pgbus/web/data_source.rb Resolved
Comment thread config/locales/it.yml Resolved
Comment thread spec/support/pgbus/stub_data_source.rb Resolved
@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) observability Metrics, instrumentation, logging and error reporting labels Sep 10, 2026
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

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

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

Fix all with cubic | Re-trigger cubic

Comment thread app/models/pgbus/uniqueness_key.rb Resolved
Comment thread lib/pgbus/web/data_source.rb Resolved
…ed 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

@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 4 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 e4aa888 into main Sep 10, 2026
14 checks passed
@mhenrixon
mhenrixon deleted the issue-461-concurrency-visibility branch September 10, 2026 15:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request observability Metrics, instrumentation, logging and error reporting stability Crash safety, recovery and resilience under failure (applied by judgment)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(web): Concurrency section on the Locks page, three gauges, home card and MCP tool

1 participant