Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(pgapi): add a Locks page that shows who waited for whom (#102743)

Nick Best20e67f114005
diff --git a/docs/internal/pgapi.md b/docs/internal/pgapi.md
index 0e02a6b11a01..e058ab7905a2 100644
--- a/docs/internal/pgapi.md
+++ b/docs/internal/pgapi.md
@@ -8,12 +8,12 @@ contract.
## Surfaces
-| path | what | auth |
-| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
-| `/api/v1/*` | JSON API: servers, overview, queries, query tags, activity, tables, indexes, vacuum, events, logs, system, schema, settings, collector health, guarded raw SQL | identity required |
-| `/mcp` | MCP streamable HTTP, 18 read-only tools over the same query layer | identity required |
-| `/` | embedded UI over `/api/v1` | identity required |
-| `/healthz`, `/readyz`, `/metrics` | probes and Prometheus | none |
+| path | what | auth |
+| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
+| `/api/v1/*` | JSON API: servers, overview, queries, query tags, activity, locks, sessions, tables, indexes, vacuum, events, logs, system, schema, settings, collector health, guarded raw SQL | identity required |
+| `/mcp` | MCP streamable HTTP, 19 read-only tools over the same query layer | identity required |
+| `/` | embedded UI over `/api/v1` | identity required |
+| `/healthz`, `/readyz`, `/metrics` | probes and Prometheus | none |
## Query tags
@@ -33,6 +33,18 @@ endpoint accepts `since` or absolute `from`/`to`, which is how a range dragged o
chart is fetched. `GET /servers/{id}/events?exclude=pgss_dealloc,log_cancel,log_lock%`
leaves out routine kinds before the limit, so event markers show the rare kinds.
+## Lock waits
+
+`GET /servers/{id}/locks` (MCP `lock_waits`) answers "who waited for whom" over a
+range from the 10 s blocking-graph samples: sessions waiting per bucket by lock type,
+(blocker statement, waiter statement) pairs with waiter-seconds and how often the
+blocker sat idle in transaction, blocking episodes (consecutive samples of one waiter
+and blocker pair) with the blocker's transaction age, and deadlocks from the log.
+`GET /servers/{id}/sessions/{pid}?instance=writer&from=&to=&backend_start=` returns one
+backend's long-session samples, which the Locks page uses to show what a blocker ran before
+it went idle. `backend_start` tells a reused pid apart; without it the backend sampled
+nearest to `at` is returned.
+
## Identity and authorization
The app runs no OAuth flow. Identity is established at the edge and read from
diff --git a/rust/pgapi/README.md b/rust/pgapi/README.md
index 80ba6d3a1219..a6f83f2914cf 100644
--- a/rust/pgapi/README.md
+++ b/rust/pgapi/README.md
@@ -16,8 +16,8 @@ curl "localhost:3400/api/v1/servers/<id>/load?since=1h&bucket=1m" # a
```
MCP client config (Claude Code / Desktop): `{"type": "http", "url": "http://localhost:3400/mcp"}`.
-18 tools: `list_servers`, `server_overview`, `top_queries`, `query_detail`,
-`query_tags`, `wait_events`, `current_activity`, `table_stats`, `index_stats`,
+19 tools: `list_servers`, `server_overview`, `top_queries`, `query_detail`,
+`query_tags`, `wait_events`, `lock_waits`, `current_activity`, `table_stats`, `index_stats`,
`vacuum_status`, `events`, `settings`, `schema`, `log_errors`, `system_stats`,
`collector_health`, `describe_stats_schema`, `query_stats_db` (guarded raw SQL).
diff --git a/rust/pgapi/src/api.rs b/rust/pgapi/src/api.rs
index d557e458dfc4..8298d8edca97 100644
--- a/rust/pgapi/src/api.rs
+++ b/rust/pgapi/src/api.rs
@@ -12,6 +12,7 @@ use axum::{
routing::get,
Router,
};
+use chrono::{DateTime, Utc};
use serde::Deserialize;
use std::sync::Arc;
@@ -54,6 +55,8 @@ pub fn router() -> Router<Arc<AppState>> {
.route("/servers/:server/queries/:queryid", get(query_detail))
.route("/servers/:server/tags", get(tags))
.route("/servers/:server/waits", get(waits))
+ .route("/servers/:server/locks", get(locks))
+ .route("/servers/:server/sessions/:pid", get(session_history))
.route("/servers/:server/activity", get(activity))
.route("/servers/:server/tables", get(tables))
.route("/servers/:server/indexes", get(indexes))
@@ -182,6 +185,57 @@ async fn waits(State(s): S, Path(server): Path<String>, Query(p): Query<BucketQ>
let (f, t) = p.range.resolve()?;
Ok(Json(q::wait_events(&s.db, &server, f, t, &p.bucket).await?))
}
+#[derive(Deserialize)]
+struct LocksQ {
+ #[serde(flatten)]
+ range: Range,
+ #[serde(default = "d_bucket")]
+ bucket: String,
+ #[serde(default = "d_limit")]
+ limit: i64,
+}
+async fn locks(State(s): S, Path(server): Path<String>, Query(p): Query<LocksQ>) -> R {
+ let (f, t) = p.range.resolve()?;
+ Ok(Json(
+ q::lock_waits(&s.db, &server, f, t, &p.bucket, p.limit.clamp(1, 500)).await?,
+ ))
+}
+#[derive(Deserialize)]
+struct SessionQ {
+ #[serde(flatten)]
+ range: Range,
+ #[serde(default = "d_instance")]
+ instance: String,
+ /// The backend's start time, which tells a reused pid apart from the one asked about.
+ backend_start: Option<DateTime<Utc>>,
+ /// Without `backend_start`, the backend sampled nearest to this time is the one returned.
+ at: Option<DateTime<Utc>>,
+}
+fn d_instance() -> String {
+ "writer".into()
+}
+async fn session_history(
+ State(s): S,
+ Path((server, pid)): Path<(String, i64)>,
+ Query(p): Query<SessionQ>,
+) -> R {
+ let (f, t) = p.range.resolve()?;
+ Ok(Json(
+ q::session_history(
+ &s.db,
+ &server,
+ &p.instance,
+ pid,
+ q::SessionWindow {
+ from: f,
+ to: t,
+ backend_start: p.backend_start,
+ at: p.at,
+ },
+ )
+ .await?,
+ ))
+}
async fn activity(State(s): S, Path(server): Path<String>) -> R {
Ok(Json(q::current_activity(&s.db, &server).await?))
}
diff --git a/rust/pgapi/src/mcp.rs b/rust/pgapi/src/mcp.rs
index b279cb79d079..f8a2cf09ffc5 100644
--- a/rust/pgapi/src/mcp.rs
+++ b/rust/pgapi/src/mcp.rs
@@ -106,6 +106,13 @@ pub struct EventsArg {
pub limit: Option<i64>,
}
#[derive(Deserialize, schemars::JsonSchema)]
+pub struct LocksArg {
+ pub server: String,
+ pub since: Option<String>,
+ /// Rows per list (pairs and episodes), default 50.
+ pub limit: Option<i64>,
+}
+#[derive(Deserialize, schemars::JsonSchema)]
pub struct SchemaArg {
pub server: String,
pub datname: String,
@@ -229,6 +236,25 @@ impl PgMcp {
.await
.map_err(err)?)
}
+ #[tool(
+ description = "Who waited for whom over a window: sessions waiting on locks per bucket by lock type, (blocker statement, waiter statement) pairs with waiter-seconds and how often the blocker was idle in transaction, blocking episodes with start/end and the blocker's transaction age, and deadlocks from the log."
+ )]
+ async fn lock_waits(
+ &self,
+ Parameters(a): Parameters<LocksArg>,
+ ) -> Result<CallToolResult, McpError> {
+ let (f, t) = range(&a.since)?;
+ ok(q::lock_waits(
+ &self.state.db,
+ &a.server,
+ f,
+ t,
+ "1m",
+ a.limit.unwrap_or(50).clamp(1, 500),
+ )
+ .await
+ .map_err(err)?)
+ }
#[tool(
description = "What is happening right now: connection counts by state, long-running / lock-waiting / idle-in-transaction sessions, blocking graph, memory-hungry backends."
)]
@@ -383,7 +409,7 @@ impl ServerHandler for PgMcp {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::from_build_env())
- .with_instructions("Read-only access to PostHog's Postgres telemetry (pgcollector). Start with list_servers, then server_overview; drill into top_queries / query_detail for performance, query_tags for load per code path, current_activity for live issues, vacuum_status and events for maintenance. query_stats_db runs arbitrary read-only SQL against the stats database.")
+ .with_instructions("Read-only access to PostHog's Postgres telemetry (pgcollector). Start with list_servers, then server_overview; drill into top_queries / query_detail for performance, query_tags for load per code path, lock_waits for who blocked whom, current_activity for live issues, vacuum_status and events for maintenance. query_stats_db runs arbitrary read-only SQL against the stats database.")
}
}
diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rs
index 818da45001bf..110a89baf5c4 100644
--- a/rust/pgapi/src/queries.rs
+++ b/rust/pgapi/src/queries.rs
@@ -602,6 +602,96 @@ pub async fn db_load(db: &Db, server: &str, from: Ts, to: Ts, bucket: &str) -> R
Ok(json!({ "bucket": bucket_interval(bucket), "series": series, "host": host }))
}
+pub async fn lock_waits(
+ db: &Db,
+ server: &str,
+ from: Ts,
+ to: Ts,
+ bucket: &str,
+ limit: i64,
+) -> Result<Value> {
+ let b = bucket_expr("collected_at", bucket_interval(bucket));
+ let series = opt(db, &format!(
+ "WITH samples AS (
+ SELECT {b} AS bucket, instance, count(DISTINCT collected_at) AS n
+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2),
+ waiting AS (
+ SELECT {b} AS bucket, instance, coalesce(wait_event, 'other') AS locktype, sum(backends) AS backends
+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND wait_event_type = 'Lock' GROUP BY 1, 2, 3)
+ SELECT w.bucket, w.locktype, round(sum(w.backends::float8 / s.n)::numeric, 2)::float8 AS avg_waiting_sessions
+ FROM waiting w JOIN samples s USING (bucket, instance) GROUP BY 1, 2 ORDER BY 1, 2"), &[&server, &from, &to]).await?;
+ // One row per blocked backend per 10 s sample, so summing the interval gives waiter-seconds.
+ let pairs = opt(db, "SELECT blocker_query, waiter_query, locktype, relation, wanted_mode,
+ count(*)::bigint AS samples, round(sum(interval_seconds)::numeric, 0)::float8 AS waited_s,
+ count(DISTINCT (instance, waiter_pid))::bigint AS waiters, count(DISTINCT (instance, blocker_pid))::bigint AS blockers,
+ max(waiting_s)::float8 AS max_waiting_s, max(blocker_xact_age_s)::float8 AS max_blocker_xact_age_s,
+ round(100.0 * sum(CASE WHEN blocker_state = 'idle in transaction' THEN 1 ELSE 0 END) / count(*), 0)::float8 AS blocker_idle_pct,
+ max(usename) AS usename, max(application_name) AS application_name,
+ max(blocker_usename) AS blocker_usename, max(blocker_application_name) AS blocker_application_name,
+ max(collected_at) AS last_seen
+ FROM ts_lock_waits WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3
+ GROUP BY 1, 2, 3, 4, 5 ORDER BY waited_s DESC LIMIT $4", &[&server, &from, &to, &limit]).await?;
+ // Consecutive samples of one (waiter, blocker) pair are one episode; a gap over 30 s (three
+ // missed samples) starts a new one, which is what a waiter that timed out and retried looks like.
+ // A backend is its pid plus backend_start. The backend_start columns arrive with a newer collector
+ // and pgapi can deploy first, so they are read through to_jsonb, which parses without them.
+ let episodes = opt(db, "WITH w AS (
+ SELECT l.*, (to_jsonb(l) ->> 'waiter_backend_start') AS waiter_backend_start, (to_jsonb(l) ->> 'blocker_backend_start') AS blocker_backend_start,
+ CASE WHEN lag(collected_at) OVER pair IS NULL OR collected_at - lag(collected_at) OVER pair > interval '30 seconds'
+ OR blocker_xact_age_s < lag(blocker_xact_age_s) OVER pair OR waiting_s < lag(waiting_s) OVER pair THEN 1 ELSE 0 END AS starts
+ FROM ts_lock_waits l WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3
+ WINDOW pair AS (PARTITION BY instance, waiter_pid, (to_jsonb(l) ->> 'waiter_backend_start'), blocker_pid, (to_jsonb(l) ->> 'blocker_backend_start') ORDER BY collected_at)),
+ e AS (SELECT *, sum(starts) OVER (PARTITION BY instance, waiter_pid, waiter_backend_start, blocker_pid, blocker_backend_start ORDER BY collected_at) AS episode FROM w)
+ SELECT instance, datname, waiter_pid, waiter_backend_start, blocker_pid, blocker_backend_start, min(collected_at) AS first_seen, max(collected_at) AS last_seen,
+ count(*)::bigint AS samples, round(sum(interval_seconds)::numeric, 0)::float8 AS waited_s, max(waiting_s)::float8 AS max_waiting_s,
+ max(blocker_xact_age_s)::float8 AS blocker_xact_age_s, min(blocker_xact_age_s)::float8 AS blocker_xact_age_at_start_s,
+ (array_agg(blocker_state ORDER BY collected_at DESC))[1] AS blocker_state,
+ (array_agg(locktype ORDER BY collected_at DESC))[1] AS locktype, (array_agg(relation ORDER BY collected_at DESC))[1] AS relation,
+ (array_agg(wanted_mode ORDER BY collected_at DESC))[1] AS wanted_mode,
+ (array_agg(waiter_query ORDER BY collected_at DESC))[1] AS waiter_query, (array_agg(blocker_query ORDER BY collected_at DESC))[1] AS blocker_query,
+ max(usename) AS usename, max(application_name) AS application_name,
+ max(blocker_usename) AS blocker_usename, max(blocker_application_name) AS blocker_application_name
+ FROM e GROUP BY instance, datname, waiter_pid, waiter_backend_start, blocker_pid, blocker_backend_start, episode ORDER BY first_seen DESC LIMIT $4", &[&server, &from, &to, &limit]).await?;
+ let deadlocks = opt(db, "SELECT id, at, instance, datname, subject, after FROM events WHERE server_id = $1 AND at >= $2 AND at < $3 AND kind = 'log_deadlock' ORDER BY at DESC LIMIT 50", &[&server, &from, &to]).await?;
+ Ok(
+ json!({ "bucket": bucket_interval(bucket), "series": series, "pairs": pairs, "episodes": episodes, "deadlocks": deadlocks }),
+ )
+}
+
+/// Backends are only sampled once active for 5 s or idle in transaction for 60 s, so a short
+/// transaction leaves no rows. Without `backend_start`, the backend sampled nearest to `at` is used.
+pub struct SessionWindow {
+ pub from: Ts,
+ pub to: Ts,
+ pub backend_start: Option<Ts>,
+ pub at: Option<Ts>,
+}
+
+pub async fn session_history(
+ db: &Db,
+ server: &str,
+ instance: &str,
+ pid: i64,
+ w: SessionWindow,
+) -> Result<Value> {
+ let SessionWindow {
+ from,
+ to,
+ backend_start,
+ at,
+ } = w;
+ let at = at.unwrap_or(to);
+ Ok(json!(opt(db, "WITH rows AS (
+ SELECT collected_at, datname, usename, application_name, client_addr, backend_start, state, wait_event_type, wait_event, blocked_by,
+ xact_start, xact_age_s, query_start, query_age_s, query_id, query, tags, trace_id
+ FROM ts_activity_sessions WHERE server_id = $1 AND instance = $2 AND pid = $3 AND collected_at >= $4 AND collected_at < $5),
+ backend AS (
+ SELECT coalesce($6::timestamptz, (SELECT backend_start FROM rows ORDER BY abs(extract(epoch FROM collected_at - $7::timestamptz)) LIMIT 1)) AS started)
+ SELECT * FROM (
+ SELECT rows.* FROM rows, backend WHERE rows.backend_start IS NOT DISTINCT FROM backend.started
+ ORDER BY collected_at DESC LIMIT 2000) newest ORDER BY collected_at", &[&server, &instance, &pid, &from, &to, &backend_start, &at]).await?))
+}
+
pub async fn current_activity(db: &Db, server: &str) -> Result<Value> {
let sessions = opt(db, "SELECT * FROM ts_activity_sessions WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_activity_sessions WHERE server_id = $1 AND collected_at > now() - interval '5 minutes') ORDER BY query_age_s DESC NULLS LAST", &[&server]).await?;
let locks = opt(db, "SELECT * FROM ts_lock_waits WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_lock_waits WHERE server_id = $1 AND collected_at > now() - interval '5 minutes') ORDER BY waiting_s DESC", &[&server]).await?;
diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.html
index 74d4f809dad0..2efe242c52e7 100644
--- a/rust/pgapi/src/ui/index.html
+++ b/rust/pgapi/src/ui/index.html
@@ -40,7 +40,8 @@
td.num, th.num { text-align: right; font-family: var(--mono); white-space: nowrap; }
td.mono { font-family: var(--mono); } .muted { color: var(--muted); } .ok { color: var(--ok); } .warn { color: var(--warn); } .err { color: var(--error); }
.q { font-family: var(--mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 520px; display: block; }
- .grid.two .q { max-width: 300px; }
+ .grid.two .q { max-width: 300px; } .panel.tight { overflow-x: auto; } .panel.tight .q { max-width: 240px; }
+ .nowrap { white-space: nowrap; } .small { font-size: 11px; }
pre { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 10px; font-family: var(--mono); font-size: 11.5px; overflow: auto; white-space: pre-wrap; word-break: break-word; margin: 0; max-height: 420px; }
.error-box { padding: 10px 14px; color: var(--error); font-family: var(--mono); font-size: 12px; white-space: pre-wrap; border: 1px solid var(--error); border-radius: 6px; }
.empty { color: var(--muted); padding: 8px 0; }
@@ -86,7 +87,7 @@
(() => {
// ---------- state & routing ----------
const PAGES = [
- ['overview', 'Overview'], ['queries', 'Queries'], ['activity', 'Activity'], ['waits', 'Wait events'],
+ ['overview', 'Overview'], ['queries', 'Queries'], ['activity', 'Activity'], ['waits', 'Wait events'], ['locks', 'Locks'],
['tables', 'Tables'], ['indexes', 'Indexes'], ['vacuum', 'Vacuum'], ['events', 'Events'], ['logs', 'Logs'],
['system', 'System'], ['schema', 'Schema'], ['settings', 'Settings'], ['collector', 'Collector health'],
];
@@ -440,6 +441,68 @@
];
};
+ const secs = v => v == null ? '–' : v >= 3600 ? (v / 3600).toFixed(1) + ' h' : v >= 90 ? Math.round(v / 60) + ' min' : Math.round(v) + ' s';
+ const pidCell = (pid, user, app) => el('span', { class: 'nowrap' }, el('span', { class: 'mono' }, pid), user || app ? [el('br'), el('span', { class: 'muted small' }, [user, app].filter(Boolean).join(' · '))] : null);
+ const lockCell = r => el('span', { class: 'nowrap' }, r.locktype || '–', el('br'), el('span', { class: 'muted small' }, r.wanted_mode || ''), r.relation ? [el('br'), el('span', { class: 'mono small' }, r.relation)] : null);
+ // Consecutive 10 s samples with the same state, statement, wait and blocker collapse into one span, so a
+ // blocker's history reads as "ran X for 8 s, then sat idle in transaction for 15 min". A gap over 30 s or a
+ // different backend_start (the pid was reused) starts a new span rather than bridging what was not sampled.
+ function sessionSpans(rows) {
+ const out = [];
+ const same = (a, b) => a.state === b.state && a.query === b.query && a.wait_event_type === b.wait_event_type && a.wait_event === b.wait_event && a.blocked_by === b.blocked_by && a.backend_start === b.backend_start && new Date(b.collected_at) - new Date(a.last) <= 30e3;
+ for (const r of rows) {
+ const last = out[out.length - 1];
+ if (last && same(last, r)) { last.last = r.collected_at; last.xact_age_s = r.xact_age_s; last.samples++; last.trace_id = r.trace_id || last.trace_id; }
+ else out.push({ ...r, first: r.collected_at, last: r.collected_at, samples: 1 });
+ }
+ return out;
+ }
+
+ pages.locks = async () => {
+ const bucket = bucketFor();
+ const d = await api(`/servers/${state.server}/locks`, { ...rangeQuery(), bucket, limit: 100 });
+ const byType = {};
+ for (const r of d.series) (byType[r.locktype] ||= []).push([new Date(r.bucket), r.avg_waiting_sessions]);
+ const series = Object.entries(byType).sort(([a], [b]) => a.localeCompare(b)).map(([k, pts], i) => ({ name: k, color: COLORS[(i + 3) % COLORS.length], points: pts }));
+ const per = BUCKET_LABEL[bucket] || bucket;
+ // A selected episode (instance:pid:from:to:backend_start:at) shows what the blocker was doing across its transaction.
+ const sel = state.params.session ? state.params.session.split(':').map(decodeURIComponent) : null;
+ // The history is a drill-down, so a failed fetch shows in its own panel instead of replacing the page.
+ const history = sel ? await api(`/servers/${state.server}/sessions/${sel[1]}`, { instance: sel[0], from: sel[2], to: sel[3], backend_start: sel[4] || null, at: sel[5] || null }).catch(e => ({ error: String(e.message || e) })) : null;
+ const clearSel = () => { const p = { ...state.params }; delete p.session; go('locks', p); };
+ return [
+ el('h1', {}, 'Locks', el('span', { class: 'sub' }, 'who waited for whom, from 10 s samples of blocked sessions')),
+ panel(`Sessions waiting on locks per ${per}, by lock type`, chart(series, { stacked: true, yfmt: v => fmt.dec(v, 2) })),
+ history ? el('div', { style: 'margin-top:12px' }, panel(null,
+ el('div', { class: 'toolbar' }, el('h2', { style: 'margin:0' }, `Blocker pid ${sel[1]} on ${sel[0]}`), el('span', { class: 'muted' }, `${fmt.ts(sel[2])} to ${fmt.ts(sel[3])}`), el('button', { onclick: clearSel }, '✕ close')),
+ history.error ? el('div', { class: 'error-box' }, `Couldn't load the session history: ${history.error}. Try again, and if it keeps happening check the API logs.`) : table(sessionSpans(history), [
+ { key: 'first', label: 'from', fmt: fmt.time }, { key: 'last', label: 'to', fmt: fmt.time },
+ { key: 'state', label: 'state', render: r => el('span', { class: r.state === 'idle in transaction' ? 'warn' : '' }, r.state) },
+ { key: 'wait_event_type', label: 'wait', fmt: (v, r) => v ? `${v}:${r.wait_event}` : 'CPU' },
+ { key: 'xact_age_s', label: 'txn age at end', num: true, fmt: secs }, { key: 'blocked_by', label: 'blocked by' },
+ { key: 'query', label: 'last statement', render: r => r.query_id ? el('a', { href: hashFor('query', { queryid: r.query_id, datname: r.datname }) }, queryLabel(r)) : queryLabel(r) },
+ { key: 'trace_id', label: 'trace', cls: 'mono', render: r => r.trace_id ? el('span', { title: r.trace_id }, r.trace_id.slice(0, 12) + '…') : null },
+ ], { empty: 'No samples for this backend in the window. Backends are only sampled once active for 5 s or idle in transaction for 60 s, so a short transaction leaves no history.' }))) : null,
+ el('div', { style: 'margin-top:12px' }, Object.assign(panel('Who blocked whom', table(d.pairs, [
+ { key: 'blocker_query', label: 'blocker was running', render: r => el('span', {}, queryCell(r.blocker_query), el('div', { class: 'muted', style: 'font-size:11px' }, [r.blocker_usename, r.blocker_application_name].filter(Boolean).join(' · '), r.blocker_idle_pct ? el('span', { class: r.blocker_idle_pct >= 50 ? 'warn' : '' }, ` · idle in transaction ${fmt.pct(r.blocker_idle_pct)} of the time`) : null)) },
+ { key: 'waiter_query', label: 'waiter', render: r => el('span', {}, queryCell(r.waiter_query), el('div', { class: 'muted', style: 'font-size:11px' }, [r.usename, r.application_name].filter(Boolean).join(' · '))) },
+ { key: 'locktype', label: 'lock', render: lockCell },
+ { key: 'waited_s', label: 'waited', num: true, fmt: secs }, { key: 'waiters', label: 'waiters', num: true, fmt: fmt.num }, { key: 'blockers', label: 'blockers', num: true, fmt: fmt.num },
+ { key: 'max_waiting_s', label: 'longest wait', num: true, fmt: secs }, { key: 'max_blocker_xact_age_s', label: 'blocker txn age', num: true, fmt: secs },
+ { key: 'last_seen', label: 'last seen', fmt: fmt.ago },
+ ], { sortKey: 'waited_s', empty: 'no blocked sessions sampled in this range' })), { className: 'panel tight' })),
+ el('div', { style: 'margin-top:12px' }, Object.assign(panel('Episodes (one waiter blocked by one backend; click for the blocker\'s history)', table(d.episodes, [
+ { key: 'first_seen', label: 'start', cls: 'nowrap', fmt: fmt.ts }, { key: 'waited_s', label: 'duration', num: true, fmt: secs },
+ { key: 'waiter_pid', label: 'waiter', render: r => pidCell(r.waiter_pid, r.usename, r.application_name) },
+ { key: 'waiter_query', label: 'waiting on', render: r => queryCell(r.waiter_query) },
+ { key: 'locktype', label: 'lock', render: lockCell },
+ { key: 'blocker_pid', label: 'blocker', render: r => el('span', { class: 'nowrap' }, pidCell(r.blocker_pid, r.blocker_usename, r.blocker_application_name), el('br'), el('span', { class: (r.blocker_state === 'idle in transaction' ? 'warn' : '') + ' small' }, r.blocker_state), el('span', { class: 'muted small' }, ` · txn ${secs(r.blocker_xact_age_s)}`)) },
+ { key: 'blocker_query', label: 'blocker last ran', render: r => queryCell(r.blocker_query) },
+ ], { onRow: r => { const from = new Date(+new Date(r.first_seen) - (r.blocker_xact_age_at_start_s || 0) * 1000 - 60e3).toISOString(), to = new Date(+new Date(r.last_seen) + 60e3).toISOString(); go('locks', { ...state.params, session: [r.instance, r.blocker_pid, from, to, r.blocker_backend_start || '', r.last_seen].map(encodeURIComponent).join(':') }); }, empty: 'no blocked sessions sampled in this range' })), { className: 'panel tight' })),
+ el('div', { style: 'margin-top:12px' }, panel('Deadlocks (from the log)', d.deadlocks.length ? d.deadlocks.map(e => el('details', { open: '' }, el('summary', {}, `${fmt.ts(e.at)} · ${e.datname || ''} · ${e.subject || ''}`), el('pre', {}, (e.after && (e.after.detail || e.after.message)) || JSON.stringify(e.after, null, 2)))) : el('div', { class: 'empty' }, 'none in range (needs log_lock_waits or deadlock logging and the logs collector)'))),
+ ];
+ };
+
pages.tables = async () => {
const [dbsel, db] = dbSelect(v => go('tables', { datname: v }));
if (!db) return [el('h1', {}, 'Tables'), el('div', { class: 'empty' }, 'no databases discovered yet')];
diff --git a/rust/pgcollector/collectors/lock_waits.yaml b/rust/pgcollector/collectors/lock_waits.yaml
index e584378f1cbe..76aebf86db76 100644
--- a/rust/pgcollector/collectors/lock_waits.yaml
+++ b/rust/pgcollector/collectors/lock_waits.yaml
@@ -7,12 +7,14 @@ scope: cluster
kind: gauge
query: |
SELECT w.pid AS waiter_pid,
+ w.backend_start AS waiter_backend_start,
w.datname, w.usename, w.application_name,
extract(epoch FROM now() - w.query_start)::float8 AS waiting_s,
l.locktype, l.mode AS wanted_mode, l.relation::bigint AS relation_oid,
CASE WHEN l.relation IS NOT NULL AND w.datname = current_database() THEN l.relation::regclass::text END AS relation,
regexp_replace(left(w.query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS waiter_query,
b.pid AS blocker_pid,
+ b.backend_start AS blocker_backend_start,
b.usename AS blocker_usename,
b.application_name AS blocker_application_name,
b.state AS blocker_state,