pgbus 0.26.1 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/README.md +30 -1
  4. data/Rakefile +7 -1
  5. data/app/views/pgbus/dashboard/_queues_table.html.erb +9 -5
  6. data/app/views/pgbus/queues/_queues_list.html.erb +10 -6
  7. data/config/locales/da.yml +1 -0
  8. data/config/locales/de.yml +1 -0
  9. data/config/locales/en.yml +1 -0
  10. data/config/locales/es.yml +1 -0
  11. data/config/locales/fi.yml +1 -0
  12. data/config/locales/fr.yml +1 -0
  13. data/config/locales/it.yml +1 -0
  14. data/config/locales/ja.yml +1 -0
  15. data/config/locales/nb.yml +1 -0
  16. data/config/locales/nl.yml +1 -0
  17. data/config/locales/pt.yml +1 -0
  18. data/config/locales/sv.yml +1 -0
  19. data/lib/pgbus/client/notify_stream.rb +16 -0
  20. data/lib/pgbus/configuration.rb +11 -1
  21. data/lib/pgbus/dedicated_connection.rb +20 -7
  22. data/lib/pgbus/engine.rb +8 -0
  23. data/lib/pgbus/integrations/appsignal/probe.rb +20 -1
  24. data/lib/pgbus/mcp/health_analyzer.rb +32 -2
  25. data/lib/pgbus/mcp/tools/dlq_detail_tool.rb +11 -2
  26. data/lib/pgbus/mcp/tools/queues_tool.rb +3 -0
  27. data/lib/pgbus/open_transaction.rb +96 -0
  28. data/lib/pgbus/signals/middleware.rb +23 -0
  29. data/lib/pgbus/signals.rb +282 -0
  30. data/lib/pgbus/streams.rb +3 -39
  31. data/lib/pgbus/testing/minitest.rb +1 -0
  32. data/lib/pgbus/testing.rb +36 -0
  33. data/lib/pgbus/version.rb +1 -1
  34. data/lib/pgbus/web/data_source/dead_letter.rb +35 -16
  35. data/lib/pgbus/web/data_source/job_list.rb +1 -1
  36. data/lib/pgbus/web/data_source/queue_summary.rb +1 -1
  37. data/lib/pgbus/web/data_source.rb +176 -56
  38. data/lib/pgbus/web/metrics_serializer.rb +34 -5
  39. data/lib/pgbus/web/queue_summary.rb +6 -1
  40. data/lib/pgbus/web/streamer/failover_listener.rb +132 -27
  41. data/lib/pgbus/web/streamer/hub_client.rb +46 -15
  42. data/lib/pgbus/web/streamer/hub_protocol.rb +6 -0
  43. data/lib/pgbus/web/streamer/instance.rb +37 -2
  44. data/lib/pgbus/web/streamer/listener.rb +113 -24
  45. data/lib/pgbus/web/streamer/master_hub.rb +87 -2
  46. data/lib/pgbus/web/streamer/signal_delivery.rb +136 -0
  47. data/lib/pgbus/web/streamer.rb +10 -0
  48. data/lib/pgbus.rb +21 -0
  49. data/sig/pgbus/client.rbs +1 -0
  50. data/sig/pgbus/configuration.rbs +2 -0
  51. data/sig/pgbus.rbs +13 -0
  52. metadata +5 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8b69998354e78e47fc483f2c03b2fd2d4856031ad0a1e2db00d4ba7da7f40547
4
- data.tar.gz: 3bfad5779917d58b0afd88da6b6cb680c3086f879a76de66aa139c318476bbcc
3
+ metadata.gz: 6b6f949cf25759a3498971f5c00a1ba4c3beee0bdcadac41c6bd978af96ba392
4
+ data.tar.gz: 0cd2f5abd43c6f5b380f2439b40553dd707ec0283dc42fbe696d6dd2f0a0172e
5
5
  SHA512:
6
- metadata.gz: 48fffb0b444afea7ba76f4d53e65426cbfe9cea96af16f1aa674586dc1141106e246f51b117da7d533ad153185a3189d3d6b730521eed7c21ce5acec3d3c3df9
7
- data.tar.gz: 7e580515d3b53981e973556c1fd440dfe91700a30f554b650cc82c4843d7286161a1f7ff07c73799a7988303e04bf6d433e88bd37951ef47d1e1ae5d7b42c417
6
+ metadata.gz: 2d9fa8de5bcae929a3546fba35c7734e83ca9794aa582adc69cb9fee0aadbd397061324cea4e00fa5fcb77bc79e11e39909ff96fd4c27e83d8f94c7acca46a42
7
+ data.tar.gz: 7fba6d23df3a93fa218b2f23cb59b6a942a45ebdd8aadd57cf00f01d3f110adb7eb406086aed7922b0b54931bb937cfe366fef5230bb01fc517dd50d3bb64c0a
data/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ### Added
4
+
5
+ - **Process signals: `Pgbus.on_signal(name) { |payload| ... }` runs a block in every web process when any process calls `Pgbus.signal(name, payload = nil)` (issue #674).** This covers a per-process in-memory cache that every Puma worker must drop when its data changes, which had no supported route: the event bus delivers an event to one competing consumer in a worker process, and the streamer only woke SSE connections.
6
+
7
+ - **Sending.** A signal is a `NOTIFY` on `<queue_prefix>_signal_<name>`, sent through `Pgbus.client` (new `Client#notify_signal`). Inside an open ActiveRecord transaction it is sent at `COMMIT` and never on rollback. A `transaction(joinable: false)` block sends at once: the fixture transaction of an app's transactional tests is one, so an `after_commit { Pgbus.signal(...) }` still sends there. The payload is an optional String under NOTIFY's 7999-byte cap; an empty String arrives as `nil`. A name may use lowercase letters, digits and underscores, and its channel must fit the queue-name budget; anything else raises `ArgumentError`.
8
+ - **Transport.** The streamer's LISTEN connection carries the signal: each worker's `Listener` under `streams_listen_scope :process`, the `MasterHub`'s under `:master`. The hub fans it out over the hub socket with new frames: `ssub`/`sack`, refcounted per channel like a stream, and `signal`/`gap`, never dropped by the backpressure policy; a worker evicted for not draining fails over and reports a gap. No worker opens a LISTEN connection of its own. A worker whose master predates signals gets no `sack` and fails over to its own listener. A signal NOTIFY never enters the stream dispatch queue and is never dropped at `streams_dispatch_queue_limit`.
9
+ - **Running the blocks.** Subscribers run on a new per-process `SignalDelivery` thread, started by the first signal for a registered name, each inside `Rails.application.executor.wrap`. A block that raises is reported through `error_reporters` and the others still run. With 1 000 signals waiting behind a slow block, a further one is dropped and reported as a gap.
10
+ - **Eager start.** With at least one subscriber, a process's first request starts its streamer on a background thread (new `Pgbus::Signals::Middleware`, which the engine installs when `streams_enabled`). A process that never served an SSE connection still receives signals, and no request waits on the LISTEN connect. A failed start is reported and retried by a request 30 s later. The middleware adds about 100 ns to a request (65 ns once started; 1M calls, this machine). Without a subscriber nothing changes: no connection, no thread.
11
+ - **Gaps.** Delivery is at most once. Every `on_gap:` callable runs once, once the LISTEN is in place (gaps that arrive before it runs coalesce), after each gap: the process's first LISTEN (nothing sent before it reached the process), a listener reconnect, a worker failover from the master hub, or the hub's own listener reconnecting.
12
+ - **Failover retry.** A worker whose hub died and whose own listener cannot be built now retries the build every 5 s in the background, for streams too (it used to stay degraded until it recycled), then replays every subscription and runs `on_gap`; a retry in flight never holds up the worker's shutdown. The streamer's dedicated LISTEN connection (per worker, and the master hub's) now also opens with `connect_timeout=10`, beside the #664 keepalives (a keyword the connection options already set wins, and so does `PGCONNECT_TIMEOUT`; on libpq < 12, where #664 adds no keepalive keyword, `connect_timeout` is still added), so a connect to an unreachable streams host fails in 10 s instead of waiting out the OS's TCP retries.
13
+ - **Testing.** `Pgbus::Testing.fake!` records signals in `Pgbus::Testing.signals` (a `SignalRecord` with `name` and `payload`; `clear_signals!` empties it) without a NOTIFY. `inline!` also runs the blocks synchronously on the caller's thread, without the Rails executor, so `Current` attributes survive. Both record at the commit of a `transaction do … end` block, never on its rollback.
14
+ - **Scope.** Web processes only: pgbus worker processes are not subscribed.
15
+ - **Internals.** The open-transaction probe `Streams::Stream` used is now `Pgbus::OpenTransaction.current`, unchanged. On Rails 7.1, whose transactions have no `after_commit`, deferral goes through a transaction record.
16
+
17
+ Refs #674.
18
+
3
19
  ### Changed
4
20
 
5
21
  - **A member-keyed presence `touch` no longer probes `information_schema` on a table without the seat columns, and a forced re-check no longer restarts the backoff (issue #666).** On a `pgbus_presence_members` table where `rails g pgbus:add_presence_seats` has not run, every member-keyed `touch`, `leave` and `sweep!` re-probed a cached "no seats" answer before it ran and restarted the #665 backoff at 30 s. The streamer touches once per connection per heartbeat, so a process with N member-keyed connections sent N catalog queries every `streams_heartbeat_interval` (15 s by default), and its backoff never took effect. A member-keyed `touch` now uses the cached answer and re-checks only on the backoff's schedule: three touches after a reset send one probe instead of four, and none while a "no" is cached. Assumed: on a table migrated under a running process, such a `touch` can also refresh that member's seat rows until the next re-check (at most 10 minutes, `SCHEMA_RECHECK_MAX_SECONDS`); it is an `UPDATE` of `last_seen_at`, so nothing is deleted. A member-keyed `leave` and `sweep!` still re-check a cached "no" before they delete, so they never delete seat rows on a migrated table (#515), now with one probe instead of up to two, answered from that probe. That re-check leaves the backoff alone: over a fresh "no" it changes neither the step nor the schedule however many disconnects force one, and over a "no" already due it is the timed re-check, one step. `reset_schema_cache!` still re-probes at once and starts again from 30 s. Refs #666.
@@ -8,6 +24,15 @@
8
24
 
9
25
  ### Fixed
10
26
 
27
+ - **`Web::DataSource#queues_with_metrics` reads 1 000 queues in a tenth of the time, and a metrics query that fails or times out no longer reads as "no queues" (issue #677).** The read was one statement with nine scalar subqueries per queue (eight scans of each queue table plus one sequence read), so its cost grew with the queue count until `statement_timeout` cancelled it, and the rescue returned `[]`: the dashboard, the dead-letter views, `pgbus_health`, the Prometheus scrape and the AppSignal probe all read a timeout as an empty, healthy system. Inside a caller's transaction the cancelled statement also aborted it.
28
+
29
+ - **One scan per queue, in chunks.** Each queue's metrics are one aggregate over its table, and the queues are read `web_queue_metrics_chunk_size` (new, default 100) per statement, each statement in its own savepoint. Same machine, one message per queue: 100 queues 57.7 ms → 37.4 ms, 1 000 queues 3 711 ms → 373 ms, 5 000 queues 126 s → 1.9 s (`rake bench:queue_metrics`, new). A healthy queue's hash is unchanged.
30
+ - **A failed chunk is visible.** Its queues stay in the list with `metrics_unavailable: true` and `nil` counts; the other chunks still report, and an enclosing transaction stays usable. After 3 chunks that timed out (a cancelled statement, a lock wait, a deadlock, a connection that cannot be established) the rest are not read and come back unavailable at once, so a database where every chunk times out costs a few `statement_timeout`s, not one per chunk; a chunk that fails at once (a queue whose table is gone) never stops the others. Totals (`summary_stats` `total_depth` / `dlq_depth`, the `pgbus_dlq_depth` and AppSignal summary gauges) leave an unmeasured queue out rather than guess, so they read low while the verdict is DEGRADED. New `DataSource#queue_metrics_errors` returns `[]` or `[{ queues: [...], error: "Class: message" }]` (`queues: []` when `pgmq.meta` itself could not be read). `pgbus_health` / `/readyz` report `DEGRADED` with a reason naming the queues; the dashboard queue tables say "Metrics unavailable" in place of the counts; the AppSignal probe skips the queue's gauges and increments `pgbus_queue_metrics_unavailable`; the Prometheus scrape writes no count for it and adds the `pgbus_queue_metrics_unavailable` gauge; the MCP `pgbus_queues` tool carries the flag per row; the dead-letter total counts the rows of a DLQ whose metrics are unavailable (in a savepoint) rather than reading it as 0. An unreadable queue list increments the AppSignal counter untagged, writes one unlabelled Prometheus sample and leaves `pgbus_dlq_depth` out of the scrape; a failure after the queue list was read keeps every queue, flagged.
31
+ - **Names without metrics.** New `DataSource#queue_names` reads `pgmq.meta` only (memoized, cleared by `reset_cache!`). The job list, `dlq_messages`, `dlq_message_detail`, discard-all, priority siblings and the MCP `pgbus_dlq_detail` scan use it and run no metrics statement (the dead-letter page's counts, `dlq_total_count` and `dlq_counts_by_queue`, still read the metrics).
32
+ - **Throughput.** `summary_stats[:throughput_rate]` was always 0.0: `compute_throughput` called `Process.clock_gettime` inside `Pgbus::Web`, where `Process` is `Pgbus::Process`, and rescued the `NoMethodError`. It now reads the clock, never reports a negative rate (a dropped queue lowers the total), and keeps its last complete snapshot while any queue's metrics are unavailable.
33
+
34
+ Refs #677.
35
+
11
36
  - **A pooled connection in `connection_guc_mode = :session` keeps its database.yml `variables` when it is reset (issue #671).** In `:session` mode the `variables` (`statement_timeout`, `lock_timeout` and the like) are applied with `SET` after connect, and `PG::Connection#reset` opens a new backend without them. pgmq-ruby's checkout health check resets an unhealthy pooled connection (`finished?` or `CONNECTION_BAD` since #332, and an intermediate state such as `CONNECTION_STARTED` since pgmq-ruby 0.9.0), so that connection went on serving the job or streams pool with the server's defaults. Each connection the `:session` connect lambda opens now re-applies its `SET`s when it is reset, whoever resets it. A connection whose `SET`s do not all complete, after a connect or a reset, is closed before the error reaches the caller, so it is never pooled without them; with pg 1.5.9 or later the next checkout resets it and applies the `SET`s again (an older pg cannot reset a closed connection, so it is replaced when the pool is reloaded before the last stale-connection retry; the call itself is retried only for a stale-connection error, so a `SET` that always fails, such as an invalid value, fails each time). The completion pipeline's own reset (#619) no longer applies the `SET`s itself (they ran twice), and a `SET` that fails there is now logged as `Resetting the connection or re-applying its session variables failed` and leaves the connection closed, where before the session carried on without its `variables`. `:options` mode, a String URL and the shared ActiveRecord connection are unaffected. Refs #671.
12
37
 
13
38
  ## [0.25.1] - 2026-11-15
data/README.md CHANGED
@@ -47,6 +47,7 @@ PostgreSQL-native job processing and event bus for Rails, built on [PGMQ](https:
47
47
  - [Health endpoints (liveness / readiness)](#health-endpoints-liveness--readiness)
48
48
  - [Boot diagnostics banner](#boot-diagnostics-banner)
49
49
  - [Real-time broadcasts](#real-time-broadcasts-turbo-streams-replacement)
50
+ - [Process signals](#process-signals)
50
51
  - [Testing](#testing)
51
52
  - [RSpec setup](#rspec-setup)
52
53
  - [Minitest / TestUnit setup](#minitest--testunit-setup)
@@ -1024,7 +1025,7 @@ When the `appsignal` gem is loaded in your app, Pgbus auto-installs a subscriber
1024
1025
 
1025
1026
  - **Background-job transactions** for every ActiveJob run and every event-bus handler invocation. Action names follow the AppSignal convention: `MyJob#perform`, `MyHandler#handle`. Tags include `queue`, `job_class`/`handler`, `routing_key`, `attempts`, and the `active_job_id` / `provider_job_id`. `enqueued_at` becomes the AppSignal `queue_start` timestamp so "time on queue" shows up correctly in the timeline. The transaction is current for the whole execution (deserialize, `perform`/`handle`, archive), so `Appsignal.add_tags`, `Appsignal.set_error` and `Appsignal.instrument` called from job or handler code attach to it, and the error an execution raised is reported on it, also when it was raised before `perform` (an unknown job class, arguments that cannot be deserialized).
1026
1027
  - **Custom counters and distributions** for sends, reads, broadcasts, outbox publishes, recurring scheduling, and worker recycles. All metric names are prefixed `pgbus_`.
1027
- - **A minutely probe** that gauges queue depth (visible vs total), oldest message age per queue, DLQ depth, failed events count, dead-tuple totals, MVCC horizon age, active processes, and stream connection estimates.
1028
+ - **A minutely probe** that gauges queue depth (visible vs total), oldest message age per queue, DLQ depth, failed events count, dead-tuple totals, MVCC horizon age, active processes, and stream connection estimates. A queue whose metrics could not be read (its metrics query failed or hit `statement_timeout`) gets no gauges that minute; it increments the `pgbus_queue_metrics_unavailable` counter, tagged by queue, instead (untagged when the queue list itself could not be read).
1028
1029
 
1029
1030
  There is nothing to wire up — load the appsignal gem and the integration installs itself in a Rails initializer. To opt out:
1030
1031
 
@@ -1204,6 +1205,7 @@ When `config.metrics_enabled = true` (default), the dashboard exposes Prometheus
1204
1205
  | Metric | Description |
1205
1206
  |--------|-------------|
1206
1207
  | `pgbus_queue_oldest_claimable_age_seconds` | Age of the oldest message eligible for pickup (visibility timeout elapsed) — safe to alert on: scheduled/backoff-parked messages don't count until due; the series is omitted entirely when no claimable backlog exists (while the raw `pgbus_queue_oldest_message_age_seconds` gauge may still report a parked message's age) |
1208
+ | `pgbus_queue_metrics_unavailable` | 1 when the queue's metrics could not be read this scrape (its metrics query failed or hit `statement_timeout`), else 0; such a queue has no depth or age samples, rather than a false 0. One unlabelled `1` sample when the queue list itself could not be read |
1207
1209
  | `pgbus_table_dead_tuples` | Dead tuple count per PGMQ table |
1208
1210
  | `pgbus_table_live_tuples` | Live tuple count per PGMQ table |
1209
1211
  | `pgbus_table_bloat_ratio` | Dead / (dead + live) per table |
@@ -1987,6 +1989,29 @@ The Insights tab gains a "Real-time Streams" section with counts of broadcasts /
1987
1989
 
1988
1990
  Overhead on a real Puma + PGMQ setup (`bundle exec rake bench:streams`): the most visible cost is an INSERT per connect/disconnect pair, which shows up under thundering-herd connect scenarios (K=50 concurrent connects: ~+20% per-connect latency). Steady-state broadcast and fanout numbers stay in the run-to-run noise band. Enable it if Insights is useful; leave it off if the write traffic worries you.
1989
1991
 
1992
+ ### Process signals
1993
+
1994
+ Run a block in every web process when any process sends a signal: the way to tell every Puma worker "drop your in-memory cache now" when the data behind it changes.
1995
+
1996
+ ```ruby
1997
+ # config/initializers/widgets.rb
1998
+ WIDGETS = Concurrent::Map.new
1999
+
2000
+ Pgbus.on_signal(:widgets_changed, on_gap: -> { WIDGETS.clear }) { |_payload| WIDGETS.clear }
2001
+
2002
+ class Widget < ApplicationRecord
2003
+ after_commit { Pgbus.signal(:widgets_changed) }
2004
+ end
2005
+ ```
2006
+
2007
+ - `Pgbus.signal(name, payload = nil)` sends a `NOTIFY` on `<queue_prefix>_signal_<name>`. Inside an open ActiveRecord transaction it is sent at `COMMIT`, and never on rollback. The exception is a `transaction(joinable: false)` block (the kind transactional tests open around each example): there it is sent at once. The payload is an optional String under NOTIFY's 7999-byte cap; an empty String arrives as `nil`.
2008
+ - `Pgbus.on_signal(name) { |payload| ... }` registers a block in this process (register in an initializer, like `Pgbus::Streams.filters`). Names are lowercase letters, digits and underscores, and the channel must fit the queue-name budget.
2009
+ - The signal rides the streamer's LISTEN connection: one per web process under `streams_listen_scope :process`, the master hub's under `:master` (fanned out to every worker, so no worker opens a LISTEN connection of its own). With at least one subscriber, a process's first request starts that listener on a background thread (`Pgbus::Signals::Middleware`, installed by the engine; no request waits on the connect), so a process that never served an SSE connection still receives signals. A failed start is reported and retried by a request 30 s later. Without a subscriber nothing changes: no connection, no thread. Under `:master`, a worker that starts before the master hub has bound its socket uses a LISTEN connection of its own until it recycles, as an SSE-started worker does.
2010
+ - Blocks run on a dedicated thread (not the LISTEN thread, not the stream dispatcher), each inside the Rails executor. A block that raises is reported through `error_reporters` and the other blocks still run. When 1 000 signals are waiting behind a slow block, a further one is dropped and reported as a gap.
2011
+ - Delivery is at most once, within about a second. A signal sent while a process was not listening is lost: before its first LISTEN (whatever it cached at boot, or before a fork under `preload_app!`), while its LISTEN connection reconnected, or while a worker failed over from the master hub. After each such gap, the first LISTEN included, every `on_gap` runs once the LISTEN is in place (gaps that arrive while one is still waiting to run share that run), so it can assume it missed signals. A subscriber whose state can go stale needs an `on_gap`: no request waits for the first LISTEN, so a signal sent between a process's first request and its LISTEN reaches it only as that first gap. A worker whose hub died and whose own listener cannot connect retries every 5 s and runs `on_gap` when it succeeds.
2012
+ - Web processes only: pgbus worker processes do not receive signals. Signals need `streams_enabled` (the default) and a dedicated streams connection, as SSE does: pgbus builds it from `database_url`, a `connection_params` Hash, or the ActiveRecord database configuration, never from a Proc.
2013
+ - In tests, `Pgbus::Testing.fake!` records signals in `Pgbus::Testing.signals` without sending them, and `Pgbus::Testing.inline!` also runs the blocks synchronously on the calling thread, without the Rails executor, so `Current` attributes survive. Both record when the NOTIFY would be sent: at the commit of a `transaction do ... end` block, never on its rollback (the fixture transaction of transactional tests is not waited for). Set a mode in your suite (`config.before { Pgbus::Testing.fake! }`, as for SSE): with `Pgbus::Testing.disabled!` and an `on_signal` registered, the first request spec starts a real streamer, with a LISTEN connection and threads outside the test transaction.
2014
+
1990
2015
  ## Testing
1991
2016
 
1992
2017
  Pgbus ships opt-in test helpers for both RSpec and Minitest. The testing module is **never autoloaded** by Zeitwerk -- you must `require` it explicitly, so it cannot leak into production.
@@ -2022,6 +2047,7 @@ RSpec.configure do |config|
2022
2047
  config.append_after do
2023
2048
  Pgbus::Testing.disabled!
2024
2049
  Pgbus::Testing.store.clear!
2050
+ Pgbus::Testing.clear_signals!
2025
2051
  end
2026
2052
  end
2027
2053
  ```
@@ -2034,6 +2060,7 @@ RSpec.configure do |config|
2034
2060
  config.append_after(:each, :pgbus) do
2035
2061
  Pgbus::Testing.disabled!
2036
2062
  Pgbus::Testing.store.clear!
2063
+ Pgbus::Testing.clear_signals!
2037
2064
  end
2038
2065
  end
2039
2066
 
@@ -2162,6 +2189,8 @@ Pgbus::Testing.disabled? # => true/false
2162
2189
 
2163
2190
  The `:inline` mode skips delayed publishes (`delay: > 0`) -- those are captured in the store but not dispatched. Use `Pgbus::Testing.store.drain!` to manually dispatch all captured events including delayed ones.
2164
2191
 
2192
+ `Pgbus.signal` follows the same modes: `:fake` records `Pgbus::Testing::SignalRecord`s (`name`, `payload`) in `Pgbus::Testing.signals` (`Pgbus::Testing.clear_signals!` empties it), `:inline` records them and runs the process's `on_signal` blocks synchronously, and `:disabled` sends the NOTIFY. See [Process signals](#process-signals).
2193
+
2165
2194
  ### SSE streams in tests
2166
2195
 
2167
2196
  When using `use_transactional_fixtures = true` (the default in Rails), pgbus SSE streams are incompatible with transactional test isolation. The `rack.hijack` mechanism spawns background threads that acquire their own database connections outside the test transaction, which causes:
data/Rakefile CHANGED
@@ -26,7 +26,8 @@ namespace :bench do
26
26
  db_benches = %w[connection_pool_bench integration_bench streams_bench streams_read_pool_bench
27
27
  execution_modes_bench pool_swap_bench pool_autoscale_bench job_burst_bench
28
28
  notify_wake_bench notify_chaos_bench streams_hub_bench fair_read_bench
29
- worker_profile_bench workflow_insights_bench streams_scale_bench stat_flush_bench].freeze
29
+ worker_profile_bench workflow_insights_bench streams_scale_bench stat_flush_bench
30
+ queue_metrics_bench].freeze
30
31
  # The unit suite is every *_bench.rb that doesn't need a database, derived
31
32
  # from the directory so a new unit bench is picked up automatically (kept in
32
33
  # sync with bench:one, which globs the same files).
@@ -78,6 +79,11 @@ namespace :bench do
78
79
  ruby "benchmarks/workflow_insights_bench.rb"
79
80
  end
80
81
 
82
+ desc "Time queues_with_metrics at 100 / 1 000 / 5 000 queues (requires PGBUS_DATABASE_URL)"
83
+ task :queue_metrics do
84
+ ruby "benchmarks/queue_metrics_bench.rb"
85
+ end
86
+
81
87
  desc "Run fair share read benchmark (requires PGBUS_DATABASE_URL)"
82
88
  task :fair_read do
83
89
  ruby "benchmarks/fair_read_bench.rb"
@@ -26,11 +26,15 @@
26
26
  <%= pgbus_queue_badge(q[:name]) %>
27
27
  </td>
28
28
  <td data-label="<%= t("pgbus.dashboard.queues_table.headers.status") %>" class="px-4 py-3 text-sm"><%= pgbus_queue_status(@queue_lines[q[:name]]) %></td>
29
- <td data-label="<%= t("pgbus.dashboard.queues_table.headers.depth") %>" class="px-4 py-3 text-sm text-right text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_length]) %></td>
30
- <td data-label="<%= t("pgbus.dashboard.queues_table.headers.visible") %>" class="px-4 py-3 text-sm text-right text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_visible_length]) %></td>
31
- <td data-label="<%= t("pgbus.dashboard.queues_table.headers.parked") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:parked_length]) %></td>
32
- <td data-label="<%= t("pgbus.dashboard.queues_table.headers.oldest_claimable") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_duration(q[:oldest_claimable_age_sec]) %></td>
33
- <td data-label="<%= t("pgbus.dashboard.queues_table.headers.total") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:total_messages]) %></td>
29
+ <% if q[:metrics_unavailable] %>
30
+ <td colspan="5" data-label="<%= t("pgbus.dashboard.queues_table.headers.depth") %>" class="px-4 py-3 text-sm text-right text-yellow-800 dark:text-yellow-200"><%= t("pgbus.queues.show.summary.metrics_unavailable_html") %></td>
31
+ <% else %>
32
+ <td data-label="<%= t("pgbus.dashboard.queues_table.headers.depth") %>" class="px-4 py-3 text-sm text-right text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_length]) %></td>
33
+ <td data-label="<%= t("pgbus.dashboard.queues_table.headers.visible") %>" class="px-4 py-3 text-sm text-right text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_visible_length]) %></td>
34
+ <td data-label="<%= t("pgbus.dashboard.queues_table.headers.parked") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:parked_length]) %></td>
35
+ <td data-label="<%= t("pgbus.dashboard.queues_table.headers.oldest_claimable") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_duration(q[:oldest_claimable_age_sec]) %></td>
36
+ <td data-label="<%= t("pgbus.dashboard.queues_table.headers.total") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:total_messages]) %></td>
37
+ <% end %>
34
38
  </tr>
35
39
  <% end %>
36
40
  <% if @queues.empty? %>
@@ -23,12 +23,16 @@
23
23
  <%= pgbus_paused_badge(q[:paused]) %>
24
24
  <% end %>
25
25
  </td>
26
- <td data-label="<%= t("pgbus.queues.queues_list.headers.depth") %>" class="px-4 py-3 text-sm text-right font-mono text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_length]) %></td>
27
- <td data-label="<%= t("pgbus.queues.queues_list.headers.visible") %>" class="px-4 py-3 text-sm text-right font-mono text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_visible_length]) %></td>
28
- <td data-label="<%= t("pgbus.queues.queues_list.headers.parked") %>" class="px-4 py-3 text-sm text-right font-mono text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:parked_length]) %></td>
29
- <td data-label="<%= t("pgbus.queues.queues_list.headers.oldest_claimable") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_duration(q[:oldest_claimable_age_sec]) %></td>
30
- <td data-label="<%= t("pgbus.queues.queues_list.headers.newest") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_duration(q[:newest_msg_age_sec]) %></td>
31
- <td data-label="<%= t("pgbus.queues.queues_list.headers.total_ever") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:total_messages]) %></td>
26
+ <% if q[:metrics_unavailable] %>
27
+ <td colspan="6" data-label="<%= t("pgbus.queues.queues_list.headers.depth") %>" class="px-4 py-3 text-sm text-right text-yellow-800 dark:text-yellow-200"><%= t("pgbus.queues.show.summary.metrics_unavailable_html") %></td>
28
+ <% else %>
29
+ <td data-label="<%= t("pgbus.queues.queues_list.headers.depth") %>" class="px-4 py-3 text-sm text-right font-mono text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_length]) %></td>
30
+ <td data-label="<%= t("pgbus.queues.queues_list.headers.visible") %>" class="px-4 py-3 text-sm text-right font-mono text-gray-700 dark:text-gray-200"><%= pgbus_number(q[:queue_visible_length]) %></td>
31
+ <td data-label="<%= t("pgbus.queues.queues_list.headers.parked") %>" class="px-4 py-3 text-sm text-right font-mono text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:parked_length]) %></td>
32
+ <td data-label="<%= t("pgbus.queues.queues_list.headers.oldest_claimable") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_duration(q[:oldest_claimable_age_sec]) %></td>
33
+ <td data-label="<%= t("pgbus.queues.queues_list.headers.newest") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_duration(q[:newest_msg_age_sec]) %></td>
34
+ <td data-label="<%= t("pgbus.queues.queues_list.headers.total_ever") %>" class="px-4 py-3 text-sm text-right text-gray-500 dark:text-gray-400"><%= pgbus_number(q[:total_messages]) %></td>
35
+ <% end %>
32
36
  <td data-label="<%= t("pgbus.queues.queues_list.headers.actions") %>" class="px-4 py-3 text-sm text-right space-x-2">
33
37
  <% if q[:paused] %>
34
38
  <%= pgbus_button_to t("pgbus.queues.queues_list.resume"), pgbus.resume_queue_path(name: q[:name]),
@@ -973,6 +973,7 @@ da:
973
973
  other: Tømmes af en wildcard-worker-kapsel (%{count} sunde workers)
974
974
  empty_html: Intet venter
975
975
  handler_html: Event handler-kø — tømmes af consumers (%{count} sunde)
976
+ metrics_unavailable_html: 'Metrikker utilgængelige: metrikforespørgslen fejlede eller fik timeout'
976
977
  no_consumers_html:
977
978
  one: Event handler-kø uden sund consumer — %{count} event venter
978
979
  other: Event handler-kø uden sund consumer — %{count} events venter
@@ -973,6 +973,7 @@ de:
973
973
  other: Abgearbeitet von einer Wildcard-Worker-Kapsel (%{count} gesunde Worker)
974
974
  empty_html: Nichts wartet
975
975
  handler_html: Event-Handler-Queue — von Consumern abgearbeitet (%{count} gesund)
976
+ metrics_unavailable_html: 'Metriken nicht verfügbar: Die Metrikabfrage ist fehlgeschlagen oder hat das Zeitlimit überschritten'
976
977
  no_consumers_html:
977
978
  one: Event-Handler-Queue ohne gesunden Consumer — %{count} Event wartet
978
979
  other: Event-Handler-Queue ohne gesunden Consumer — %{count} Events warten
@@ -973,6 +973,7 @@ en:
973
973
  other: Drained by a wildcard worker capsule (%{count} healthy workers)
974
974
  empty_html: Nothing waiting
975
975
  handler_html: Event handler queue — drained by consumers (%{count} healthy)
976
+ metrics_unavailable_html: 'Metrics unavailable: the metrics query failed or timed out'
976
977
  no_consumers_html:
977
978
  one: Event handler queue with no healthy consumer — %{count} event waits
978
979
  other: Event handler queue with no healthy consumer — %{count} events wait
@@ -973,6 +973,7 @@ es:
973
973
  other: La vacía una cápsula de workers comodín (%{count} workers sanos)
974
974
  empty_html: Nada en espera
975
975
  handler_html: Cola de manejador de eventos — la vacían los consumidores (%{count} sanos)
976
+ metrics_unavailable_html: 'Métricas no disponibles: la consulta de métricas falló o agotó el tiempo de espera'
976
977
  no_consumers_html:
977
978
  one: Cola de manejador de eventos sin consumidor sano — %{count} evento espera
978
979
  other: Cola de manejador de eventos sin consumidor sano — %{count} eventos esperan
@@ -973,6 +973,7 @@ fi:
973
973
  other: Tyhjentää jokerimerkki-worker-kapseli (%{count} tervettä workeria)
974
974
  empty_html: Mitään ei odota
975
975
  handler_html: Tapahtumankäsittelijän jono — consumerit tyhjentävät (%{count} tervettä)
976
+ metrics_unavailable_html: 'Mittarit eivät ole saatavilla: mittarikysely epäonnistui tai aikakatkaistiin'
976
977
  no_consumers_html:
977
978
  one: Tapahtumankäsittelijän jono ilman tervettä consumeria — %{count} tapahtuma odottaa
978
979
  other: Tapahtumankäsittelijän jono ilman tervettä consumeria — %{count} tapahtumaa odottaa
@@ -973,6 +973,7 @@ fr:
973
973
  other: Vidée par une capsule de workers joker (%{count} workers sains)
974
974
  empty_html: Rien en attente
975
975
  handler_html: File de gestionnaire d'événements — vidée par les consommateurs (%{count} sains)
976
+ metrics_unavailable_html: 'Métriques indisponibles : la requête des métriques a échoué ou a expiré'
976
977
  no_consumers_html:
977
978
  one: File de gestionnaire d'événements sans consommateur sain — %{count} événement attend
978
979
  other: File de gestionnaire d'événements sans consommateur sain — %{count} événements attendent
@@ -973,6 +973,7 @@ it:
973
973
  other: Svuotata da una capsula di worker jolly (%{count} worker sani)
974
974
  empty_html: Niente in attesa
975
975
  handler_html: Coda del gestore di eventi — svuotata dai consumer (%{count} sani)
976
+ metrics_unavailable_html: 'Metriche non disponibili: la query delle metriche non è riuscita o è scaduta'
976
977
  no_consumers_html:
977
978
  one: Coda del gestore di eventi senza consumer sano — %{count} evento in attesa
978
979
  other: Coda del gestore di eventi senza consumer sano — %{count} eventi in attesa
@@ -973,6 +973,7 @@ ja:
973
973
  other: ワイルドカードのワーカーカプセルが処理(正常なワーカー %{count})
974
974
  empty_html: 待機中のものはありません
975
975
  handler_html: イベントハンドラーキュー — コンシューマーが処理(正常 %{count})
976
+ metrics_unavailable_html: 'メトリクスを取得できません: メトリクスのクエリが失敗したかタイムアウトしました'
976
977
  no_consumers_html:
977
978
  one: 正常なコンシューマーがいないイベントハンドラーキュー — %{count} 件のイベントが待機中
978
979
  other: 正常なコンシューマーがいないイベントハンドラーキュー — %{count} 件のイベントが待機中
@@ -973,6 +973,7 @@ nb:
973
973
  other: Tømmes av en jokertegn-worker-kapsel (%{count} friske workers)
974
974
  empty_html: Ingenting venter
975
975
  handler_html: Hendelsesbehandler-kø — tømmes av consumers (%{count} friske)
976
+ metrics_unavailable_html: 'Metrikker utilgjengelige: metrikkspørringen feilet eller fikk tidsavbrudd'
976
977
  no_consumers_html:
977
978
  one: Hendelsesbehandler-kø uten frisk consumer — %{count} hendelse venter
978
979
  other: Hendelsesbehandler-kø uten frisk consumer — %{count} hendelser venter
@@ -973,6 +973,7 @@ nl:
973
973
  other: Leeggemaakt door een wildcard-workercapsule (%{count} gezonde workers)
974
974
  empty_html: Niets in de wacht
975
975
  handler_html: Event-handlerwachtrij — leeggemaakt door consumers (%{count} gezond)
976
+ metrics_unavailable_html: 'Metrieken niet beschikbaar: de metriekenquery is mislukt of verlopen'
976
977
  no_consumers_html:
977
978
  one: Event-handlerwachtrij zonder gezonde consumer — %{count} event wacht
978
979
  other: Event-handlerwachtrij zonder gezonde consumer — %{count} events wachten
@@ -973,6 +973,7 @@ pt:
973
973
  other: Esvaziada por uma cápsula de workers curinga (%{count} workers saudáveis)
974
974
  empty_html: Nada à espera
975
975
  handler_html: Fila de handler de eventos — esvaziada pelos consumidores (%{count} saudáveis)
976
+ metrics_unavailable_html: 'Métricas indisponíveis: a consulta de métricas falhou ou expirou'
976
977
  no_consumers_html:
977
978
  one: Fila de handler de eventos sem consumidor saudável — %{count} evento espera
978
979
  other: Fila de handler de eventos sem consumidor saudável — %{count} eventos esperam
@@ -973,6 +973,7 @@ sv:
973
973
  other: Töms av en jokertecken-worker-kapsel (%{count} friska workers)
974
974
  empty_html: Inget väntar
975
975
  handler_html: Händelsehanterarkö — töms av consumers (%{count} friska)
976
+ metrics_unavailable_html: 'Mätvärden otillgängliga: mätvärdesfrågan misslyckades eller överskred tidsgränsen'
976
977
  no_consumers_html:
977
978
  one: Händelsehanterarkö utan frisk consumer — %{count} händelse väntar
978
979
  other: Händelsehanterarkö utan frisk consumer — %{count} händelser väntar
@@ -44,6 +44,22 @@ module Pgbus
44
44
  end
45
45
  end
46
46
 
47
+ # Fire-and-forget NOTIFY for a process signal (issue #674) on its channel,
48
+ # `<queue_prefix>_signal_<name>` (Pgbus::Signals validates the name and
49
+ # the payload: a String within the cap, or nil for none).
50
+ def notify_signal(name, payload = nil)
51
+ channel = config.queue_name("signal_#{name}")
52
+ Instrumentation.instrument("pgbus.signal.notify", signal: name.to_s, bytes: payload.to_s.bytesize) do
53
+ with_stale_connection_retry do
54
+ synchronized do
55
+ @pgmq.__send__(:with_connection) do |conn|
56
+ conn.exec_params("SELECT pg_notify($1, $2)", [channel, payload])
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+
47
63
  private
48
64
 
49
65
  def validate_notify_payload_size!(stream_name, json)
@@ -301,7 +301,12 @@ module Pgbus
301
301
  attr_accessor :web_auth, :web_refresh_interval, :web_per_page, :web_live_updates, :web_data_source,
302
302
  :insights_default_minutes, :base_controller_class, :return_to_app_url, :web_actor,
303
303
  :metrics_enabled,
304
- :web_filter_parameters, :web_filter_sensitive
304
+ :web_filter_parameters, :web_filter_sensitive,
305
+ # Queues per statement when Web::DataSource#queues_with_metrics
306
+ # reads every queue's metrics (issue #677): each chunk is its
307
+ # own statement in its own savepoint, so a cancelled chunk
308
+ # marks only its queues unavailable.
309
+ :web_queue_metrics_chunk_size
305
310
 
306
311
  # The MCP server's workflow write tools (issue #550): pgbus_workflow_resume,
307
312
  # _cancel, _skip_step, _resume_at, _run_now and _signal. Off by default, and
@@ -504,6 +509,7 @@ module Pgbus
504
509
  @metrics_enabled = true
505
510
  @web_filter_parameters = nil # nil = auto-detect from Rails, then fall back to defaults
506
511
  @web_filter_sensitive = true
512
+ @web_queue_metrics_chunk_size = 100
507
513
  @deprecation_warned = Set.new
508
514
 
509
515
  # HTTP health endpoints — nil port disables the standalone server.
@@ -1123,6 +1129,10 @@ module Pgbus
1123
1129
  raise Pgbus::ConfigurationError, "insights_default_minutes must be a positive integer"
1124
1130
  end
1125
1131
 
1132
+ unless web_queue_metrics_chunk_size.is_a?(Integer) && web_queue_metrics_chunk_size.positive?
1133
+ raise Pgbus::ConfigurationError, "web_queue_metrics_chunk_size must be a positive integer"
1134
+ end
1135
+
1126
1136
  raise Pgbus::ConfigurationError, "require_primary must be true or false" unless [true, false].include?(require_primary)
1127
1137
  raise Pgbus::ConfigurationError, "mcp_write_tools must be true or false" unless [true, false].include?(mcp_write_tools)
1128
1138
 
@@ -27,14 +27,18 @@ module Pgbus
27
27
  # probing starts after 5 idle seconds, every 2 s, 3 times, so a dead
28
28
  # socket errors within ~11 s even between the listener's own keepalive
29
29
  # queries; tcp_user_timeout bounds data the peer never acknowledges by
30
- # the same 11 s. Client-side keywords: never in the startup packet, so a
31
- # pooler cannot reject them.
30
+ # the same 11 s. connect_timeout bounds the connect itself (issue #674:
31
+ # a streamer starting for process signals, and a hub worker rebuilding
32
+ # its own listener, otherwise wait on an unreachable host as long as the
33
+ # OS lets the TCP handshake retry). Client-side keywords: never in the
34
+ # startup packet, so a pooler cannot reject them.
32
35
  LISTEN_KEEPALIVES = {
33
36
  keepalives: 1,
34
37
  keepalives_idle: 5,
35
38
  keepalives_interval: 2,
36
39
  keepalives_count: 3,
37
- tcp_user_timeout: 11_000
40
+ tcp_user_timeout: 11_000,
41
+ connect_timeout: 10
38
42
  }.freeze
39
43
 
40
44
  def connect(opts)
@@ -76,20 +80,29 @@ module Pgbus
76
80
  defined?(::PG) && ::PG.respond_to?(:library_version) && ::PG.library_version >= 120_000
77
81
  end
78
82
 
83
+ # LISTEN_KEEPALIVES, without connect_timeout when PGCONNECT_TIMEOUT is set:
84
+ # a conninfo keyword beats the environment, and the operator's value wins.
85
+ def listen_keywords
86
+ keywords = libpq_supports_socket_bounds? ? LISTEN_KEEPALIVES : LISTEN_KEEPALIVES.slice(:connect_timeout)
87
+ return keywords if ENV.fetch("PGCONNECT_TIMEOUT", nil).to_s.empty?
88
+
89
+ keywords.except(:connect_timeout)
90
+ end
91
+
79
92
  # Fill in the LISTEN_KEEPALIVES keywords the options do not already set.
80
- # Unchanged on libpq < 12 (see libpq_supports_socket_bounds?), and for a
93
+ # Only connect_timeout on libpq < 12 (see libpq_supports_socket_bounds?;
94
+ # connect_timeout is older than that), and nothing for a
81
95
  # connection that names a service (service=, or PGSERVICE): libpq applies
82
96
  # the service file only to keywords the conninfo leaves unset, so an added
83
97
  # keyword would override the service's own.
84
98
  def with_keepalives(opts)
85
- return opts unless libpq_supports_socket_bounds?
86
99
  return opts if ENV.fetch("PGSERVICE", nil).to_s != ""
87
100
 
88
101
  case opts
89
102
  when Hash
90
103
  return opts if opts.key?(:service) || opts.key?("service")
91
104
 
92
- missing = LISTEN_KEEPALIVES.reject { |key, _| opts.key?(key) || opts.key?(key.to_s) }
105
+ missing = listen_keywords.reject { |key, _| opts.key?(key) || opts.key?(key.to_s) }
93
106
  opts.merge(missing)
94
107
  when String then append_keepalives(opts)
95
108
  else opts
@@ -105,7 +118,7 @@ module Pgbus
105
118
  set = conninfo_keywords(conninfo)
106
119
  return conninfo if set.nil? || set.include?("service")
107
120
 
108
- missing = LISTEN_KEEPALIVES.reject { |key, _| set.include?(key.to_s) }
121
+ missing = listen_keywords.reject { |key, _| set.include?(key.to_s) }
109
122
  return conninfo if missing.empty?
110
123
 
111
124
  if url?(conninfo)
data/lib/pgbus/engine.rb CHANGED
@@ -160,6 +160,14 @@ module Pgbus
160
160
  app.middleware.use Pgbus::Streams::WatermarkCacheMiddleware if Pgbus.configuration.streams_enabled
161
161
  end
162
162
 
163
+ # Process signals (issue #674): start the streamer's LISTEN before a
164
+ # process's first request when a signal is registered. Installed whenever
165
+ # streams are enabled, since on_signal usually runs in an initializer after
166
+ # this one; with no subscriber it does nothing.
167
+ initializer "pgbus.signals.middleware" do |app|
168
+ app.middleware.use Pgbus::Signals::Middleware if Pgbus.configuration.streams_enabled
169
+ end
170
+
163
171
  # Make the <pgbus-stream-source> element available to the host app's
164
172
  # asset pipeline (Propshaft or Sprockets). The importmap pin points at
165
173
  # the minified build (rake frontend:js). Propshaft rewrites its
@@ -92,8 +92,17 @@ module Pgbus
92
92
  end
93
93
 
94
94
  def track_queues
95
- data_source.queues_with_metrics.each do |q|
95
+ queues = data_source.queues_with_metrics
96
+ # The queue list itself could not be read: count it once, untagged,
97
+ # rather than emit nothing (an empty list reads as a quiet fleet).
98
+ counter("queue_metrics_unavailable", 1) if queues.empty? && queue_list_unavailable?
99
+
100
+ queues.each do |q|
96
101
  tags = { queue: q[:name] }
102
+ # Issue #677: an unmeasured queue reports no gauge (a missing
103
+ # point, not a false 0) and counts as unavailable instead.
104
+ next counter("queue_metrics_unavailable", 1, tags) if q[:metrics_unavailable]
105
+
97
106
  gauge "queue_depth", q[:queue_length], tags
98
107
  gauge "queue_visible_depth", q[:queue_visible_length], tags
99
108
  gauge "queue_paused", q[:paused] ? 1 : 0, tags
@@ -175,6 +184,16 @@ module Pgbus
175
184
  ::Appsignal.set_gauge("#{METRIC_PREFIX}#{key}", value, tags)
176
185
  end
177
186
 
187
+ def queue_list_unavailable?
188
+ return false unless data_source.respond_to?(:queue_metrics_errors)
189
+
190
+ data_source.queue_metrics_errors.any? { |e| Array(e[:queues]).empty? }
191
+ end
192
+
193
+ def counter(key, value, tags = {})
194
+ ::Appsignal.increment_counter("#{METRIC_PREFIX}#{key}", value, tags)
195
+ end
196
+
178
197
  def log_failure(label, error)
179
198
  Pgbus.logger.debug do
180
199
  "[Pgbus::AppSignal::Probe] #{label} failed: #{error.class}: #{error.message}"
@@ -13,8 +13,9 @@ module Pgbus
13
13
  # but its claim loop has stopped advancing (status :stalled),
14
14
  # OR backlog with live-but-idle workers and zero claim progress.
15
15
  # DEGRADED — something is wrong but not the wedge: stale processes, a
16
- # paused queue holding a backlog, growing DLQ, or MVCC horizon
17
- # pinned by a long-running transaction.
16
+ # paused queue holding a backlog, growing DLQ, MVCC horizon
17
+ # pinned by a long-running transaction, or queue metrics that
18
+ # could not be read (issue #677).
18
19
  # OK — draining normally / nothing actionable.
19
20
  class HealthAnalyzer
20
21
  # A worker is considered to have idle capacity unless its metadata
@@ -161,6 +162,9 @@ module Pgbus
161
162
 
162
163
  reasons << "queue health stats unavailable: #{health_error.class}: #{health_error.message}" if health_error
163
164
 
165
+ metrics_reason = metrics_unavailable_reason(queues)
166
+ reasons << metrics_reason if metrics_reason
167
+
164
168
  stale = processes.select { |p| p[:status].to_s == "stale" }
165
169
  reasons << "#{stale.size} process(es) stale (no recent heartbeat)" if stale.any?
166
170
 
@@ -189,6 +193,32 @@ module Pgbus
189
193
  reasons
190
194
  end
191
195
 
196
+ # Issue #677: a queue whose metrics could not be read (its chunk failed or
197
+ # hit statement_timeout) has nil counts, so it can never look backed up
198
+ # or wedged. Without this reason a fleet too large to measure would read
199
+ # OK. queue_metrics_errors also covers a pgmq.meta read that failed, when
200
+ # there are no rows to flag; a custom data source without it still
201
+ # reports its flagged rows.
202
+ def metrics_unavailable_reason(queues)
203
+ unavailable = queues.select { |q| q[:metrics_unavailable] }
204
+ errors = queue_metrics_errors
205
+ return if unavailable.empty? && errors.empty?
206
+
207
+ # First line only: a database error carries a multi-line SQL excerpt.
208
+ cause = errors.first && " (#{errors.first[:error].to_s.lines.first.to_s.strip})"
209
+ if unavailable.any?
210
+ "queue metrics unavailable for #{unavailable.size} queue(s)#{cause}: #{backlog_names(unavailable)}"
211
+ else
212
+ "queue metrics unavailable#{cause}: the queue list could not be read"
213
+ end
214
+ end
215
+
216
+ def queue_metrics_errors
217
+ return [] unless @data_source.respond_to?(:queue_metrics_errors)
218
+
219
+ Array(@data_source.queue_metrics_errors)
220
+ end
221
+
192
222
  # Issue #366: fingerprint-matched streams excluded from the wedge signal
193
223
  # still need the registry for orphan sweep bookkeeping and durable
194
224
  # wildcard safety. Surface a DEGRADED hint so operators run the backfill.
@@ -57,10 +57,13 @@ module Pgbus
57
57
  # refuse to guess if more than one matches. Returns an error response
58
58
  # on ambiguity, nil otherwise (so the caller proceeds with the normal
59
59
  # first-match lookup).
60
+ # Names only (issue #677): finding a message runs no metrics statement.
61
+ # A custom web_data_source without queue_names falls back to the names
62
+ # of its queues_with_metrics.
60
63
  def self.ambiguity_check(data_source, msg_id)
61
64
  dlq_suffix = Pgbus::DEAD_LETTER_SUFFIX
62
- dlqs = data_source.queues_with_metrics.select { |q| q[:name].to_s.end_with?(dlq_suffix) }
63
- matches = dlqs.map { |q| q[:name] }.select { |name| data_source.job_detail(name, msg_id) }
65
+ dlqs = queue_names_of(data_source).select { |name| name.to_s.end_with?(dlq_suffix) }
66
+ matches = dlqs.select { |name| data_source.job_detail(name, msg_id) }
64
67
  return nil if matches.size <= 1
65
68
 
66
69
  error_response(
@@ -68,6 +71,12 @@ module Pgbus
68
71
  "(#{matches.join(", ")}). Pass `queue:` to disambiguate."
69
72
  )
70
73
  end
74
+
75
+ def self.queue_names_of(data_source)
76
+ return data_source.queue_names if data_source.respond_to?(:queue_names)
77
+
78
+ data_source.queues_with_metrics.map { |q| q[:name] }
79
+ end
71
80
  end
72
81
  end
73
82
  end
@@ -20,6 +20,9 @@ module Pgbus
20
20
  with a future visibility timeout. A queue whose oldest_msg_age_sec
21
21
  keeps growing while oldest_claimable_age_sec stays nil has no
22
22
  starving backlog — nothing is waiting for a worker.
23
+ A queue with metrics_unavailable: true could not be measured (its
24
+ metrics query failed or timed out): its counts and ages are null,
25
+ meaning unknown, not zero; pgbus_health reports it as DEGRADED.
23
26
  DESC
24
27
 
25
28
  input_schema(properties: {}, required: [])