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): mark events on charts and add a database load chart (#102697)

Nick Besta03d31b12435
diff --git a/docs/internal/pgapi.md b/docs/internal/pgapi.md
index 51b5c02e36eb..0e02a6b11a01 100644
--- a/docs/internal/pgapi.md
+++ b/docs/internal/pgapi.md
@@ -24,6 +24,15 @@ per code path; `GET /servers/{id}/queries?tags=key=value` filters the
`callers` seen while the query ran. The tag format and key vocabulary are in
[`rust/pgcollector/docs/query-tags.md`](../../rust/pgcollector/docs/query-tags.md).
+## Charts
+
+The UI draws its charts from bucketed endpoints. `GET /servers/{id}/load?bucket=1m`
+gives average active sessions per bucket by wait event type, summed over instances,
+with the host core count; it is the Overview page's database load chart. Every ranged
+endpoint accepts `since` or absolute `from`/`to`, which is how a range dragged on a
+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.
+
## 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 a97d73de6afe..80ba6d3a1219 100644
--- a/rust/pgapi/README.md
+++ b/rust/pgapi/README.md
@@ -12,6 +12,7 @@ PGAPI_DEV_MODE=1 [email protected] \
curl localhost:3400/api/v1/servers
curl "localhost:3400/api/v1/servers/<id>/queries?since=1h&order=total_exec_time"
curl "localhost:3400/api/v1/servers/<id>/tags?since=1h&key=operation" # load per code path (query tags)
+curl "localhost:3400/api/v1/servers/<id>/load?since=1h&bucket=1m" # active sessions by wait type, per bucket
```
MCP client config (Claude Code / Desktop): `{"type": "http", "url": "http://localhost:3400/mcp"}`.
diff --git a/rust/pgapi/src/api.rs b/rust/pgapi/src/api.rs
index 56dfa40d7428..d557e458dfc4 100644
--- a/rust/pgapi/src/api.rs
+++ b/rust/pgapi/src/api.rs
@@ -49,6 +49,7 @@ pub fn router() -> Router<Arc<AppState>> {
.route("/me", get(me))
.route("/servers", get(servers))
.route("/servers/:server/overview", get(overview))
+ .route("/servers/:server/load", get(load))
.route("/servers/:server/queries", get(top_queries))
.route("/servers/:server/queries/:queryid", get(query_detail))
.route("/servers/:server/tags", get(tags))
@@ -173,6 +174,10 @@ async fn query_detail(
.await?,
))
}
+async fn load(State(s): S, Path(server): Path<String>, Query(p): Query<BucketQ>) -> R {
+ let (f, t) = p.range.resolve()?;
+ Ok(Json(q::db_load(&s.db, &server, f, t, &p.bucket).await?))
+}
async fn waits(State(s): S, Path(server): Path<String>, Query(p): Query<BucketQ>) -> R {
let (f, t) = p.range.resolve()?;
Ok(Json(q::wait_events(&s.db, &server, f, t, &p.bucket).await?))
@@ -205,6 +210,8 @@ struct OptDbQ {
range: Range,
datname: Option<String>,
kind: Option<String>,
+ /// Comma-separated `LIKE` patterns of event kinds to leave out, applied before the limit.
+ exclude: Option<String>,
relname: Option<String>,
#[serde(default = "d_limit")]
limit: i64,
@@ -226,6 +233,7 @@ async fn events(State(s): S, Path(server): Path<String>, Query(p): Query<OptDbQ>
f,
t,
p.kind.as_deref(),
+ &q::split_list(p.exclude.as_deref()),
p.limit.clamp(1, 1000),
)
.await?,
diff --git a/rust/pgapi/src/mcp.rs b/rust/pgapi/src/mcp.rs
index e16259a6dfd4..b279cb79d079 100644
--- a/rust/pgapi/src/mcp.rs
+++ b/rust/pgapi/src/mcp.rs
@@ -299,6 +299,7 @@ impl PgMcp {
f,
t,
a.kind.as_deref(),
+ &[],
a.limit.unwrap_or(100).clamp(1, 1000),
)
.await
diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rs
index 04a5c7c95a4c..818da45001bf 100644
--- a/rust/pgapi/src/queries.rs
+++ b/rust/pgapi/src/queries.rs
@@ -198,6 +198,15 @@ async fn tag_cols_of(db: &Db, table: &str, alias: &str) -> String {
/// `route=/api/x,service=web` (or `key:value`) into pairs; keys are lower-cased and
/// values are percent-decoded, so a value holding a comma travels as `%2C`.
+pub fn split_list(csv: Option<&str>) -> Vec<String> {
+ csv.unwrap_or("")
+ .split(',')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_owned)
+ .collect()
+}
+
pub fn parse_tag_filter(s: &str) -> Result<Vec<(String, String)>> {
let mut out = Vec::new();
for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
@@ -571,6 +580,28 @@ pub async fn wait_events(db: &Db, server: &str, from: Ts, to: Ts, bucket: &str)
Ok(json!({ "sampled": sampled, "measured_aurora": measured }))
}
+/// Average active sessions per bucket, split by wait event type and summed over instances,
+/// with the host core count as the line load is compared against.
+pub async fn db_load(db: &Db, server: &str, from: Ts, to: Ts, bucket: &str) -> Result<Value> {
+ // Sample rows are split by database, user and query, so the average must divide the
+ // summed backends by the number of samples, not the number of rows.
+ let sql = 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),
+ active AS (
+ SELECT {b} AS bucket, instance, coalesce(wait_event_type, 'CPU') AS wait_event_type, sum(backends) AS backends
+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND state = 'active' GROUP BY 1, 2, 3)
+ SELECT a.bucket, a.wait_event_type, round(sum(a.backends::float8 / s.n)::numeric, 2)::float8 AS avg_active_sessions
+ FROM active a JOIN samples s USING (bucket, instance) GROUP BY 1, 2 ORDER BY 1, 2",
+ b = bucket_expr("collected_at", bucket_interval(bucket))
+ );
+ let series = opt(db, &sql, &[&server, &from, &to]).await?;
+ let host = opt(db, "SELECT instance, round(sum(user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies + idle_jiffies) / nullif(sum(interval_seconds), 0) / 100.0)::bigint AS ncpu
+ FROM ts_system_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND interval_seconds > 0 GROUP BY 1", &[&server, &from, &to]).await?;
+ Ok(json!({ "bucket": bucket_interval(bucket), "series": series, "host": host }))
+}
+
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?;
@@ -650,10 +681,13 @@ pub async fn events(
from: Ts,
to: Ts,
kind: Option<&str>,
+ exclude: &[String],
limit: i64,
) -> Result<Value> {
- Ok(json!(opt(db, "SELECT id, at, instance, datname, kind, subject, before, after FROM events WHERE server_id = $1 AND at >= $2 AND at < $3 AND ($4::text IS NULL OR kind LIKE $4)
- ORDER BY at DESC LIMIT $5", &[&server, &from, &to, &kind, &limit]).await?))
+ // Excluded kinds are dropped before the limit, so frequent routine kinds cannot crowd out the rest.
+ Ok(json!(opt(db, "SELECT id, at, instance, datname, kind, subject, before, after FROM events
+ WHERE server_id = $1 AND at >= $2 AND at < $3 AND ($4::text IS NULL OR kind LIKE $4) AND NOT (kind LIKE ANY($5::text[]))
+ ORDER BY at DESC LIMIT $6", &[&server, &from, &to, &kind, &exclude, &limit]).await?))
}
pub async fn settings(db: &Db, server: &str, non_default_only: bool) -> Result<Value> {
diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.html
index b6d63ae960f9..74d4f809dad0 100644
--- a/rust/pgapi/src/ui/index.html
+++ b/rust/pgapi/src/ui/index.html
@@ -54,6 +54,8 @@
.u-select { background: rgba(122, 162, 247, .18); }
.u-hz .u-cursor-x { border-right: 1px dashed var(--muted); }
.u-cursor-pt { border-width: 0 !important; }
+ .marker { position: absolute; top: 0; bottom: 0; width: 0; border-left: 1px dashed var(--c); pointer-events: none; }
+ .marker i { position: absolute; top: -1px; left: -4px; width: 8px; height: 8px; background: var(--c); border-radius: 0 0 4px 4px; pointer-events: auto; cursor: help; }
.kv td:first-child { color: var(--muted); width: 180px; }
.pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; background: var(--panel2); border: 1px solid var(--border); }
.tag { display: inline-block; font-family: var(--mono); font-size: 11px; color: var(--accent); background: rgba(122, 162, 247, .1); border: 1px solid rgba(122, 162, 247, .3); border-radius: 4px; padding: 0 5px; margin: 0 4px 2px 0; max-width: 260px; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; white-space: nowrap; }
@@ -189,20 +191,41 @@
// stacked: every series is drawn as an area on top of the ones before it, so missing is always 0.
// Every chart on a page shares one cursor, and dragging across any of them sets the range.
const charts = [];
+ // Markers for the events in range are fetched once per page and drawn on every chart on it. The
+ // routine kinds (pg_stat_statements evictions, cancelled statements, lock waits) would smother the rest, so they are left out.
+ let markerEvents = Promise.resolve([]);
+ const MARKER_EXCLUDE = 'pgss_dealloc,log_cancel,log_lock%';
+ const markerColor = k => k.startsWith('settings') ? '#e0af68' : k.startsWith('schema') || k.startsWith('extensions') ? '#7aa2f7' : k.startsWith('log_') ? '#f7768e' : '#8b93a1';
+ function loadMarkers() {
+ markerEvents = api(`/servers/${state.server}/events`, { ...rangeQuery(), exclude: MARKER_EXCLUDE, limit: 500 }).catch(() => []);
+ }
+ function drawMarkers(u, events) {
+ for (const m of u.over.querySelectorAll('.marker')) m.remove();
+ const { min, max } = u.scales.x;
+ for (const e of events) {
+ const x = +new Date(e.at) / 1000;
+ if (x < min || x > max) continue;
+ const title = `${e.kind}: ${e.subject}${e.datname ? ` (${e.datname})` : ''}\n${fmt.ts(e.at)}`;
+ u.over.append(el('div', { class: 'marker', style: `left:${u.valToPos(x, 'x')}px; --c:${markerColor(e.kind)}` }, el('i', { title })));
+ }
+ }
const AXIS = { stroke: '#8b93a1', font: '11px -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, sans-serif', grid: { stroke: '#2c313a', width: 1 }, ticks: { stroke: '#2c313a', width: 1 } };
function chart(series, { yfmt = v => fmt.dec(v, 1), stacked = false, missing = 0, height = 170 } = {}) {
+ if (stacked) series = [...series.filter(s => !s.line), ...series.filter(s => s.line)];
if (typeof uPlot === 'undefined') return el('div', { class: 'empty' }, 'Charts need cdn.jsdelivr.net, which this browser could not load. The tables below still work.');
if (!series.some(s => s.points.some(p => p[1] != null))) return el('div', { class: 'empty' }, 'no data points');
const sec = t => Math.floor(+t / 1000);
const xs = padGaps([...new Set(series.flatMap(s => s.points.map(p => sec(p[0]))))].sort((a, b) => a - b));
const at = new Map(xs.map((x, i) => [x, i]));
- const raw = series.map(s => { const col = Array(xs.length).fill(stacked ? 0 : missing); for (const [t, v] of s.points) if (v != null) col[at.get(sec(t))] = v; return col; });
+ const raw = series.map(s => { const col = Array(xs.length).fill(s.line ? null : stacked ? 0 : missing); for (const [t, v] of s.points) if (v != null) col[at.get(sec(t))] = v; return col; });
// Band [upper, lower] clips the upper series' fill to its own layer; the lowest visible series fills down to zero on its own.
- // Hidden series are left out of the running total, so toggling one in the legend restacks the rest.
+ // Hidden series are left out of the running total, so toggling one in the legend restacks the rest. Line series
+ // stay unstacked and sit after the stacked ones, so the band indexes stay contiguous.
const stack = show => {
const acc = Array(xs.length).fill(0);
- const data = raw.map((col, i) => show(i) ? col.map((v, j) => (acc[j] += v)) : col);
- const vis = raw.map((_, i) => i).filter(show);
+ const inStack = i => !series[i].line && show(i);
+ const data = raw.map((col, i) => inStack(i) ? col.map((v, j) => (acc[j] += v)) : col);
+ const vis = raw.map((_, i) => i).filter(inStack);
return { data, bands: vis.slice(1).map((si, k) => ({ series: [si + 1, vis[k] + 1] })) };
};
let { data, bands } = stacked ? stack(() => true) : { data: raw, bands: [] };
@@ -215,9 +238,9 @@
axes: [{ ...AXIS }, { ...AXIS, size: 60, values: (u, vals) => vals.map(yfmt) }],
series: [
{ value: (u, v) => v == null ? '' : fmt.ts(new Date(v * 1000)) },
- ...series.map(s => ({ label: s.name, stroke: s.color, width: 1.5, points: { show: false }, fill: stacked ? s.color + '59' : null, spanGaps: false, value: (u, v, si, di) => di == null || raw[si - 1][di] == null ? '–' : yfmt(raw[si - 1][di]) })),
+ ...series.map(s => ({ label: s.name, stroke: s.color, width: 1.5, points: { show: false }, dash: s.line ? [4, 4] : null, fill: stacked && !s.line ? s.color + '59' : null, spanGaps: !!s.line, value: (u, v, si, di) => di == null || raw[si - 1][di] == null ? '–' : yfmt(raw[si - 1][di]) })),
],
- hooks: { setSeries: stacked ? [restack] : [], setSelect: [u => {
+ hooks: { setSeries: stacked ? [restack] : [], draw: [u => markerEvents.then(ev => drawMarkers(u, ev))], setSelect: [u => {
if (u.select.width < 4) return;
const from = u.posToVal(u.select.left, 'x'), to = u.posToVal(u.select.left + u.select.width, 'x');
u.setSelect({ width: 0, height: 0 }, false);
@@ -260,7 +283,14 @@
const dbSelect = (onchange) => { const dbs = sv().databases || []; const cur = state.params.datname || dbs[0] || ''; const s = el('select', { onchange: e => onchange(e.target.value) }, dbs.map(d => el('option', { value: d, selected: d === cur ? '' : null }, d))); return [s, cur]; };
pages.overview = async () => {
- const d = await api(`/servers/${state.server}/overview`, { ...rangeQuery() });
+ const bucket = bucketFor();
+ const [d, load] = await Promise.all([api(`/servers/${state.server}/overview`, { ...rangeQuery() }), api(`/servers/${state.server}/load`, { ...rangeQuery(), bucket })]);
+ const byType = {};
+ for (const r of load.series) (byType[r.wait_event_type] ||= []).push([new Date(r.bucket), r.avg_active_sessions]);
+ const loadSeries = Object.entries(byType).sort(([a], [b]) => (a === 'CPU') - (b === 'CPU') || a.localeCompare(b)).reverse()
+ .map(([k, pts], i) => ({ name: k, color: k === 'CPU' ? COLORS[1] : COLORS[(i + 2) % COLORS.length], points: pts }));
+ const ncpu = load.host.reduce((a, h) => a + (h.ncpu || 0), 0);
+ if (ncpu && load.series.length) { const ts = load.series.map(r => new Date(r.bucket)); loadSeries.push({ name: 'vCPUs', color: '#8b93a1', line: true, points: [[new Date(Math.min(...ts)), ncpu], [new Date(Math.max(...ts)), ncpu]] }); }
const conns = d.connections.reduce((a, c) => { a[c.state] = (a[c.state] || 0) + c.backends; return a; }, {});
const dbs = d.databases;
const sum = k => dbs.reduce((a, r) => a + (r[k] || 0), 0);
@@ -272,6 +302,7 @@
tile('commits', fmt.num(sum('xact_commit'))), tile('rollbacks', fmt.num(sum('xact_rollback'))), tile('cache hit', hit == null ? '–' : hit.toFixed(2) + '%', hit != null && hit < 95 ? 'warn' : ''),
tile('deadlocks', fmt.num(sum('deadlocks')), sum('deadlocks') ? 'err' : ''), tile('temp bytes', fmt.bytes(sum('temp_bytes'))), tile('max xid age', fmt.num(Math.max(0, ...dbs.map(r => r.xid_age || 0)))),
),
+ el('div', { style: 'margin-top:12px' }, panel(`Database load (average active sessions per ${BUCKET_LABEL[bucket] || bucket}, by wait type)`, chart(loadSeries, { stacked: true, yfmt: v => fmt.dec(v, 2) }))),
el('div', { class: 'grid two', style: 'margin-top:12px' },
panel('Top queries by total time', table(d.top_queries, [
{ key: 'query', label: 'query', render: r => el('a', { href: hashFor('query', { queryid: r.queryid, datname: r.datname }) }, queryLabel(r)) },
@@ -585,6 +616,7 @@
const fn = pages[state.page];
if (!fn) { main.replaceChildren(el('div', { class: 'error-box' }, `unknown page ${state.page}`)); return; }
destroyCharts();
+ loadMarkers();
main.replaceChildren(el('div', { class: 'muted' }, 'loading…'));
try { const out = await fn(); main.replaceChildren(...[out].flat(Infinity).filter(Boolean)); }
catch (e) { main.replaceChildren(el('div', { class: 'error-box' }, String(e.message || e))); }