Repository navigation
feat(web): surface concurrency keys on the Locks page, in metrics and MCP - #463
Conversation
… 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
|
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. |
There was a problem hiding this comment.
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
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
There was a problem hiding this comment.
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
…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
Summary
limits_concurrency … on_conflict: :blockbecame durable in #460 — a parked job is never dropped and a key never runs pastto:— but nothing showed it.pgbus_semaphoresandpgbus_blocked_executionsappeared 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: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 ownturbo-frameserved byGET /locks?frame=concurrency. The uniqueness table moves into_uniqueness.html.erband deliberately stays out of a frame so its bulk-select state survives._stats_cards.html.erb, nowlg:grid-cols-7), the whole card linking to the Locks page./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 indashboard.json.pgbus_concurrencyMCP 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
release_concurrency_key) deletes the semaphore row, then promotes throughConcurrency::BlockedExecution.promote_nextin a capped loop, so every promoted job takes a real slot through the same guarded upsert an enqueue uses. Re-sending the parked payloads directly would reintroduce exactly the over-admission fix(concurrency): make on_conflict: :block durable and never over-admit #460 closed. When the lease is still fresh the confirm says so — a job is then probably still running, and releasing lets another start beside it.discard_parked_jobs) reads one key's rowsFOR UPDATE SKIP LOCKEDso it cannot race a concurrent promote, deletes them, and resolves the bookkeeping those jobs will never resolve themselves: a parked batch child is marked failed so its batch stops waiting andon_failurefires (fix(active_job): perform_all_later bypasses batch and concurrency metadata #413), and an:until_executeduniqueness lock is released rather than orphaned (Batches v2 follow-up: per-job accounting, sweep correctness, while_executing release, review fixes for #417–#422 #423). Each row logs a warning naming the job and emitspgbus.blocked_execution_discarded. The confirm names the exact count and the button only renders when something is parked. There is no cross-key bulk discard: not losing work is the whole point of:block.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% branchbundle exec rspec(bare, full) — 4918 examples, 0 failuresPGBUS_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 offensesbun run lint:herb— cleanbundle exec rake frontend:cssleavesgit statusclean (artifact committed)cd docs && bundle exec rake lint && bundle exec rspec— clean, 71 examplesCloses #461
Deviations & judgment calls
connection, notSemaphore.connection.exec_query. The issue's step 1 suggested stubbingPgbus::Semaphore.connection.exec_query; the implementation uses the privateconnectionhelper (Pgbus::BusRecord.connection) withselect_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.parked_totalhas to be the true total while the key list is capped at 100, so one statement cannot serve both. The page runs two statements; thesummary_stats/ serializer / probe path runs one (memoized).lib/pgbus/mcp.rb's require list as well as inServer::TOOLS— the issue only named server.rb.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_releasedhas nozero: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_discardedwas added to the event list inlib/pgbus/instrumentation.rb, which enumerates every emitted event — the issue didn't mention that file.spec/system/locks_spec.rbassertedh1text "Uniqueness Keys" (the h1 is now "Locks", with that text as the sectionh2), and its single-lock-discard example scopedwithin("tbody"), which is ambiguous with two tables — now scoped to[data-bulk-scope="locks"] tbody.spec/pgbus/integrations/appsignal/dashboard_spec.rbfails 3 examples when run alone (itsbe_inmatcher needs ActiveSupport'sObject#in?, loaded by a sibling spec). Verified by stashing this branch and reproducing onmain. 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: :blockmade durable in #460: a pipeline at its limit previously looked stalled, withpgbus_semaphoresandpgbus_blocked_executionson 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/metricsand the AppSignal probe, and a read-onlypgbus_concurrencyMCP tool.Guarded per-key actions
value— deleting the row lost the key's limit and demotedto: 3keys to 1 — marks the emptied row expired so it can't linger as a phantom 0/N row, then promotes throughConcurrency::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.FOR UPDATE SKIP LOCKEDand 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'screated_at, so neither a sent nor a parked successor's lock is ever dropped.key:proc may produce surrounding whitespace, and stripping would address a different key or none.Observability details
DataSourceinstance and merged intosummary_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.turbo_frame: "_top"so clicking it leaves the stats frame and reaches the Locks page.Written for commit f0bd0cd. Summary will update on new commits.