: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(pgapi): show backend CPU by user, code path and query in cores (#102651)
Nick Bestd55a9b8ac8fa
diff --git a/rust/pgapi/src/api.rs b/rust/pgapi/src/api.rsindex d55ba6278b59..e086053888d9 100644--- a/rust/pgapi/src/api.rs+++ b/rust/pgapi/src/api.rs@@ -138,6 +138,8 @@ struct BucketQ {range: Range,#[serde(default = "d_bucket")]bucket: String,+ /// Limit text and series to one database when the query id exists in several.+ datname: Option<String>,}fn d_bucket() -> String {"1m".into()@@ -149,7 +151,16 @@ async fn query_detail() -> R {let (f, t) = p.range.resolve()?;Ok(Json(- q::query_detail(&s.db, &server, queryid, f, t, &p.bucket).await?,+ q::query_detail(+ &s.db,+ &server,+ queryid,+ f,+ t,+ &p.bucket,+ p.datname.as_deref(),+ )+ .await?,))}async fn waits(State(s): S, Path(server): Path<String>, Query(p): Query<BucketQ>) -> R {diff --git a/rust/pgapi/src/mcp.rs b/rust/pgapi/src/mcp.rsindex d04841fe0c6f..e16259a6dfd4 100644--- a/rust/pgapi/src/mcp.rs+++ b/rust/pgapi/src/mcp.rs@@ -81,6 +81,8 @@ pub struct QueryArg {pub since: Option<String>,/// Series bucket width: 10s, 1m (default), 5m or 1h.pub bucket: Option<String>,+ /// Limit text and series to one database when the query id exists in several.+ pub datname: Option<String>,}#[derive(Deserialize, schemars::JsonSchema)]pub struct DbArg {@@ -210,6 +212,7 @@ impl PgMcp {f,t,a.bucket.as_deref().unwrap_or("1m"),+ a.datname.as_deref(),).await.map_err(err)?)@@ -340,7 +343,7 @@ impl PgMcp {.map_err(err)?)}#[tool(- description = "System view: host CPU/memory (pg_proctab), top backends by CPU, checkpoints, bgwriter, Aurora replica status and per-database commit/DML latency."+ description = "System view: host CPU % / memory / load and vCPU count (pg_proctab), CPU by user, by code path (query tags) and by query (cpu_seconds, avg_cores, host_pct, backends), a per-minute cores-by-user series, checkpoints, bgwriter, Aurora replica status and per-database commit/DML latency.")]async fn system_stats(&self,diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rsindex 1b5246feec15..04a5c7c95a4c 100644--- a/rust/pgapi/src/queries.rs+++ b/rust/pgapi/src/queries.rs@@ -262,6 +262,7 @@ pub async fn query_detail(from: Ts,to: Ts,bucket: &str,+ datname: Option<&str>,) -> Result<Value> {let interval = bucket_interval(bucket);// Latency histograms are per minute, so the finest latency bucket is a minute.@@ -275,14 +276,14 @@ pub async fn query_detail(} else {"NULL::jsonb AS tags"};- let texts = opt(db, &format!("SELECT datname, query, fingerprint, truncated, first_seen, last_seen, {query_tags} FROM cur_queries WHERE server_id = $1 AND queryid = $2"), &[&server, &queryid]).await?;+ let texts = opt(db, &format!("SELECT datname, query, fingerprint, truncated, first_seen, last_seen, {query_tags} FROM cur_queries WHERE server_id = $1 AND queryid = $2 AND ($3::text IS NULL OR datname = $3)"), &[&server, &queryid, &datname]).await?;let fingerprint: Option<i64> = texts.first().and_then(|t| json_i64(&t["fingerprint"]));let series = opt(db, &format!("SELECT {b} AS bucket, instance, datname,sum(calls)::bigint AS calls, sum(total_exec_time)::float8 AS total_ms,CASE WHEN sum(calls) > 0 THEN sum(total_exec_time) / sum(calls) END::float8 AS mean_ms,sum(rows)::bigint AS rows, sum(shared_blks_read)::bigint AS shared_blks_read, sum(shared_blks_hit)::bigint AS shared_blks_hit- FROM ts_query_stats WHERE server_id = $1 AND queryid = $2 AND collected_at >= $3 AND collected_at < $4- GROUP BY 1, 2, 3 ORDER BY 1", b = bucket_expr("collected_at", interval)), &[&server, &queryid, &from, &to]).await?;+ FROM ts_query_stats WHERE server_id = $1 AND queryid = $2 AND collected_at >= $3 AND collected_at < $4 AND ($5::text IS NULL OR datname = $5)+ GROUP BY 1, 2, 3 ORDER BY 1", b = bucket_expr("collected_at", interval)), &[&server, &queryid, &from, &to, &datname]).await?;let sampling = log_sampling_settings(db, server).await?;// Each histogram row carries the sample rate it was collected under: a sampled// count stands for 1/rate statements, an always-logged one for itself. Edges@@ -682,9 +683,74 @@ pub async fn system(db: &Db, server: &str, from: Ts, to: Ts) -> Result<Value> {round(((user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies)::numeric / nullif(user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies + idle_jiffies, 0)) * 100, 2)::float8 AS cpu_pct,round((iowait_jiffies::numeric / nullif(user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies + idle_jiffies, 0)) * 100, 2)::float8 AS iowait_pctFROM ts_system_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY 1", &[&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,+ sum(interval_seconds)::float8 AS covered_s+ 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?;let mem = opt(db, "SELECT collected_at, instance, mem_used_kb, mem_free_kb, mem_cached_kb, swap_used_kb, load1, load5 FROM ts_system_memory WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY 1", &[&server, &from, &to]).await?;- let backends = opt(db, "SELECT instance, datname, usename, application_name, backend_type, sum(utime_jiffies + stime_jiffies)::bigint AS cpu_jiffies, max(rss_kb)::bigint AS max_rss_kb- FROM ts_backend_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3, 4, 5 ORDER BY 6 DESC LIMIT 20", &[&server, &from, &to]).await?;++ // A jiffy is 10 ms, and /proc/stat sums to 100 jiffies per core per second, which+ // is where the core count comes from; `covered` counts each tick once.+ const CPU_CTES: &str = "+ WITH host AS (+ SELECT instance, sum(user_jiffies + nice_jiffies + system_jiffies + iowait_jiffies + idle_jiffies) / nullif(sum(interval_seconds), 0) / 100.0 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),+ covered AS (+ SELECT instance, sum(interval_seconds) AS covered_s+ FROM (SELECT DISTINCT instance, collected_at, interval_seconds FROM ts_backend_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3) t GROUP BY 1)";+ let by_user = opt(db, &format!("{CPU_CTES},+ per_pid AS (+ SELECT instance, datname, usename, application_name, backend_type, pid, backend_start, sum(utime_jiffies + stime_jiffies) AS jiffies+ FROM ts_backend_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3, 4, 5, 6, 7)+ SELECT p.instance, p.datname, p.usename, p.application_name, p.backend_type,+ (sum(p.jiffies) / 100.0)::float8 AS cpu_seconds,+ (sum(p.jiffies) / 100.0 / nullif(c.covered_s, 0))::float8 AS avg_cores,+ (sum(p.jiffies) / nullif(c.covered_s, 0) / nullif(h.ncpu, 0))::float8 AS host_pct,+ count(*)::bigint AS backends,+ (max(p.jiffies) / 100.0 / nullif(c.covered_s, 0))::float8 AS hottest_backend_cores+ FROM per_pid p JOIN covered c ON c.instance = p.instance LEFT JOIN host h ON h.instance = p.instance+ GROUP BY 1, 2, 3, 4, 5, c.covered_s, h.ncpu ORDER BY 6 DESC LIMIT 20"), &[&server, &from, &to]).await?;+ let by_user_series = opt(db, "+ WITH b AS (+ SELECT collected_at, instance, interval_seconds,+ coalesce(usename, backend_type) || CASE WHEN coalesce(application_name, '') <> '' THEN ' (' || application_name || ')' ELSE '' END AS label,+ utime_jiffies + stime_jiffies AS jiffies+ FROM ts_backend_cpu WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND interval_seconds > 0),+ top AS (SELECT label FROM b GROUP BY 1 ORDER BY sum(jiffies) DESC LIMIT 7)+ SELECT b.collected_at, b.instance, CASE WHEN t.label IS NULL THEN 'other' ELSE b.label END AS label,+ (sum(b.jiffies) / 100.0 / max(b.interval_seconds))::float8 AS cores+ FROM b LEFT JOIN top t ON t.label = b.label GROUP BY 1, 2, 3 ORDER BY 1", &[&server, &from, &to]).await?;+ let by_code_path = if has_column(db, "ts_backend_cpu", "tags").await {+ opt(db, &format!("{CPU_CTES}+ SELECT b.instance, b.tags,+ (sum(b.utime_jiffies + b.stime_jiffies) / 100.0)::float8 AS cpu_seconds,+ (sum(b.utime_jiffies + b.stime_jiffies) / 100.0 / nullif(c.covered_s, 0))::float8 AS avg_cores,+ (sum(b.utime_jiffies + b.stime_jiffies) / nullif(c.covered_s, 0) / nullif(h.ncpu, 0))::float8 AS host_pct,+ count(DISTINCT (b.pid, b.backend_start))::bigint AS backends+ FROM ts_backend_cpu b JOIN covered c ON c.instance = b.instance LEFT JOIN host h ON h.instance = b.instance+ WHERE b.server_id = $1 AND b.collected_at >= $2 AND b.collected_at < $3 AND b.tags IS NOT NULL AND b.tags <> '{{}}'::jsonb+ GROUP BY 1, 2, c.covered_s, h.ncpu ORDER BY 3 DESC LIMIT 15"), &[&server, &from, &to]).await?+ } else {+ vec![]+ };+ let by_query = if has_column(db, "ts_backend_cpu", "query_id").await {+ let query_tags = if has_column(db, "cur_queries", "tags").await {+ "q.tags"+ } else {+ "NULL::jsonb AS tags"+ };+ opt(db, &format!("{CPU_CTES}+ SELECT b.instance, b.datname, b.query_id AS queryid, q.query, {query_tags},+ (sum(b.utime_jiffies + b.stime_jiffies) / 100.0)::float8 AS cpu_seconds,+ (sum(b.utime_jiffies + b.stime_jiffies) / 100.0 / nullif(c.covered_s, 0))::float8 AS avg_cores,+ (sum(b.utime_jiffies + b.stime_jiffies) / nullif(c.covered_s, 0) / nullif(h.ncpu, 0))::float8 AS host_pct,+ count(DISTINCT (b.pid, b.backend_start))::bigint AS backends+ FROM ts_backend_cpu b JOIN covered c ON c.instance = b.instance LEFT JOIN host h ON h.instance = b.instance+ LEFT JOIN cur_queries q ON q.server_id = $1 AND q.instance = b.instance AND q.queryid = b.query_id AND q.datname = b.datname+ WHERE b.server_id = $1 AND b.collected_at >= $2 AND b.collected_at < $3 AND b.query_id IS NOT NULL+ GROUP BY 1, 2, 3, 4, 5, c.covered_s, h.ncpu ORDER BY 6 DESC LIMIT 15"), &[&server, &from, &to]).await?+ } else {+ vec![]+ };let checkpoints = opt(db, "SELECT log_time, log_stream, kind, buffers_written, buffers_pct, write_s, sync_s, total_s, distance_kb FROM ts_checkpoints WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY log_time DESC LIMIT 50", &[&server, &from, &to]).await?;let bgw = opt(db, "SELECT instance, sum(checkpoints_timed)::bigint AS checkpoints_timed, sum(checkpoints_req)::bigint AS checkpoints_req, sum(buffers_checkpoint)::bigint AS buffers_checkpoint, sum(buffers_clean)::bigint AS buffers_clean, sum(buffers_alloc)::bigint AS buffers_allocFROM ts_bgwriter WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1", &[&server, &from, &to]).await?;@@ -692,9 +758,11 @@ pub async fn system(db: &Db, server: &str, from: Ts, to: Ts) -> Result<Value> {let latency = opt(db, "SELECT datname, sum(commit_latency_us)::bigint AS commit_latency_us, sum(select_count)::bigint AS selects, sum(update_count)::bigint AS updates,CASE WHEN sum(update_count) > 0 THEN sum(update_latency_us) / sum(update_count) END::float8 AS avg_update_latency_usFROM ts_aurora_db_latency WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1", &[&server, &from, &to]).await?;- Ok(- json!({ "cpu": cpu, "memory": mem, "top_backends_by_cpu": backends, "checkpoints": checkpoints, "bgwriter": bgw, "aurora_replicas": repl, "aurora_db_latency": latency }),- )+ Ok(json!({+ "cpu": cpu, "host": host, "memory": mem,+ "cpu_by_user": by_user, "cpu_by_user_series": by_user_series, "cpu_by_code_path": by_code_path, "cpu_by_query": by_query,+ "checkpoints": checkpoints, "bgwriter": bgw, "aurora_replicas": repl, "aurora_db_latency": latency,+ }))}pub async fn collector_health(db: &Db) -> Result<Value> {diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.htmlindex 299a191c650b..f6bbc6a433ba 100644--- a/rust/pgapi/src/ui/index.html+++ b/rust/pgapi/src/ui/index.html@@ -151,8 +151,21 @@// ---------- simple SVG line chart ----------// series: [{name, color, points: [[Date, number | null]]}]; a null y breaks the line.- function chart(series, { yfmt = v => fmt.dec(v, 1) } = {}) {+ // stacked: every series is drawn as an area on top of the ones before it; a+ // missing x in a series counts as 0 so the stack stays continuous.+ function chart(series, { yfmt = v => fmt.dec(v, 1), stacked = false } = {}) {const W = 800, H = 140, P = { l: 48, r: 8, t: 8, b: 20 };+ if (stacked) {+ const xs = [...new Set(series.flatMap(s => s.points.map(p => +p[0])))].sort((a, b) => a - b);+ let base = new Map(xs.map(x => [x, 0]));+ series = series.map(s => {+ const own = new Map(s.points.map(p => [+p[0], p[1] || 0]));+ const top = new Map(xs.map(x => [x, base.get(x) + (own.get(x) || 0)]));+ const out = { ...s, points: xs.map(x => [new Date(x), top.get(x)]), base: xs.map(x => [new Date(x), base.get(x)]) };+ base = top;+ return out;+ });+ }const all = series.flatMap(s => s.points).filter(p => p[1] != null);if (!all.length) return el('div', { class: 'empty' }, 'no data points');const xs = all.map(p => +p[0]), ys = all.map(p => p[1]);@@ -167,6 +180,10 @@const pts = [...s.points].sort((a, b) => a[0] - b[0]);let d = '', pen = false;for (const p of pts) { if (p[1] == null) { pen = false; continue; } d += (pen ? 'L' : 'M') + X(+p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1); pen = true; }+ if (s.base) {+ const back = [...s.base].sort((a, b) => b[0] - a[0]).map(p => 'L' + X(+p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1)).join('');+ svg.append(n('path', { d: d + back + 'Z', fill: s.color, 'fill-opacity': 0.35, stroke: 'none' }));+ }svg.append(n('path', { d, fill: 'none', stroke: s.color, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' }));}return el('div', {}, svg, el('div', { class: 'legend' }, series.map(s => el('span', {}, el('i', { style: `background:${s.color}` }), s.name))));@@ -195,7 +212,7 @@),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: `#/${state.server}/query?queryid=${r.queryid}` }, queryLabel(r)) },+ { key: 'query', label: 'query', render: r => el('a', { href: `#/${state.server}/query?queryid=${r.queryid}${r.datname ? `&datname=${encodeURIComponent(r.datname)}` : ''}` }, queryLabel(r)) },{ key: 'calls', label: 'calls', num: true, fmt: fmt.num }, { key: 'mean_ms', label: 'mean', num: true, fmt: fmt.ms }, { key: 'pct_of_total_time', label: '% time', num: true, fmt: fmt.pct },])),panel('Top wait events (active sessions, sampled)', table(d.top_wait_events, [@@ -258,14 +275,14 @@{ key: 'datname', label: 'db' }, { key: 'rolname', label: 'role' },{ key: 'calls', label: 'calls', num: true, fmt: fmt.num }, { key: 'total_ms', label: 'total', num: true, fmt: fmt.ms }, { key: 'mean_ms', label: 'mean', num: true, fmt: fmt.ms }, { key: 'stddev_ms', label: 'stddev', num: true, fmt: fmt.ms },{ key: 'rows', label: 'rows', num: true, fmt: fmt.num }, { key: 'shared_blks_read', label: 'blks read', num: true, fmt: fmt.num }, { key: 'pct_of_total_time', label: '% time', num: true, render: r => el('span', {}, el('span', { class: 'bar', style: `width:${Math.min(100, r.pct_of_total_time || 0)}px` }), ' ', fmt.pct(r.pct_of_total_time)) },- ], { onRow: r => go('query', { queryid: r.queryid }), empty: tagFilter ? 'no queries seen with this tag in the range' : 'nothing in this range' })),+ ], { onRow: r => go('query', { queryid: r.queryid, ...(r.datname ? { datname: r.datname } : {}) }), empty: tagFilter ? 'no queries seen with this tag in the range' : 'nothing in this range' })),];};pages.query = async () => {const qid = state.params.queryid;const bucket = bucketFor(state.range);- const d = await api(`/servers/${state.server}/queries/${qid}`, { since: state.range, bucket });+ const d = await api(`/servers/${state.server}/queries/${qid}`, { since: state.range, bucket, datname: state.params.datname });const t = d.texts[0] || {};const byBucket = {};for (const r of d.series) { const k = r.bucket; (byBucket[k] ||= { calls: 0, total: 0 }); byBucket[k].calls += r.calls || 0; byBucket[k].total += r.total_ms || 0; }@@ -417,17 +434,44 @@pages.system = async () => {const d = await api(`/servers/${state.server}/system`, { since: state.range });const byInst = (rows, key) => { const m = {}; for (const r of rows) (m[r.instance] ||= []).push([new Date(r.collected_at), r[key]]); return Object.entries(m).map(([n, pts], i) => ({ name: n, color: COLORS[i], points: pts })); };+ const cpuTitle = 'Host CPU %' + (d.host.length ? ` (${d.host.map(h => `${h.instance}: ${h.ncpu} vCPU`).join(', ')})` : '');+ const noProctab = () => el('div', { class: 'empty' }, 'No pg_proctab data. Run CREATE EXTENSION pg_proctab in the database the collector connects to; rows start within 10 minutes.');+ const userSeries = (() => { const m = Object.create(null); for (const r of d.cpu_by_user_series) (m[`${r.label}${d.host.length > 1 ? ' @' + r.instance : ''}`] ||= []).push([new Date(r.collected_at), r.cores]); const names = Object.keys(m).sort((a, b) => a.startsWith('other') - b.startsWith('other')); return names.map((n, i) => ({ name: n, color: n.startsWith('other') ? '#565f73' : COLORS[i % COLORS.length], points: m[n] })); })();+ const cores = v => v == null ? '–' : fmt.dec(v, 3);+ const cpuCols = [+ { key: 'cpu_seconds', label: 'CPU time', num: true, fmt: v => fmt.dec(v, 1) + ' s' },+ { key: 'avg_cores', label: 'avg cores', num: true, fmt: cores },+ { key: 'host_pct', label: '% of host', num: true, fmt: v => v == null ? '–' : fmt.dec(v, 2) + '%' },+ { key: 'backends', label: 'backends', num: true, fmt: fmt.num },+ ];return [el('h1', {}, 'System'),el('div', { class: 'grid two' },- panel('CPU % (pg_proctab)', d.cpu.length ? chart(byInst(d.cpu, 'cpu_pct'), { yfmt: fmt.pct }) : el('div', { class: 'empty' }, 'no pg_proctab data (CREATE EXTENSION pg_proctab)')),+ panel(cpuTitle, d.cpu.length ? chart(byInst(d.cpu, 'cpu_pct'), { yfmt: fmt.pct }) : noProctab()),panel('Load average', d.memory.length ? chart(byInst(d.memory, 'load1'), { yfmt: v => fmt.dec(v, 2) }) : el('div', { class: 'empty' }, 'no pg_proctab data')),+ ),+ el('div', { style: 'margin-top:12px' }, panel('CPU by user (cores, stacked)', userSeries.length ? chart(userSeries, { yfmt: cores, stacked: true }) : noProctab())),+ el('div', { style: 'margin-top:12px' }, panel('CPU by user', table(d.cpu_by_user, [+ { key: 'usename', label: 'user', render: r => el('span', {}, r.usename || el('span', { class: 'muted' }, r.backend_type), r.application_name ? el('span', { class: 'muted' }, ' · ' + r.application_name) : null, d.host.length > 1 ? el('span', { class: 'muted' }, ' @' + r.instance) : null) },+ { key: 'datname', label: 'db' },+ ...cpuCols,+ { key: 'hottest_backend_cores', label: 'hottest backend', num: true, fmt: cores },+ ], { empty: 'no backend CPU rows in this range' }))),+ el('div', { style: 'margin-top:12px' }, panel('CPU by code path (query tags)', table(d.cpu_by_code_path, [+ { key: 'tags', label: 'code path', render: r => el('a', { href: `#/${state.server}/queries?tags=${encodeURIComponent(tagEntries(r.tags).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join(','))}` }, tagPills(r.tags, 4)) },+ ...cpuCols,+ ], { empty: 'no query tags seen on active backends in this range' }))),+ el('div', { style: 'margin-top:12px' }, panel('CPU by query (sampled from the active statement each minute)', table(d.cpu_by_query, [+ { key: 'query', label: 'query', render: r => el('a', { href: `#/${state.server}/query?queryid=${r.queryid}${r.datname ? `&datname=${encodeURIComponent(r.datname)}` : ''}` }, queryLabel(r)) },+ { key: 'datname', label: 'db' },+ ...cpuCols,+ ], { empty: 'no query ids seen on active backends in this range' }))),+ el('div', { class: 'grid two', style: 'margin-top:12px' },panel('Checkpoints (from the log)', table(d.checkpoints, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind' }, { key: 'buffers_written', label: 'buffers', num: true, fmt: fmt.num }, { key: 'buffers_pct', label: '%', num: true, fmt: fmt.pct }, { key: 'write_s', label: 'write', num: true, fmt: v => fmt.dec(v, 2) + ' s' }, { key: 'sync_s', label: 'sync', num: true, fmt: v => fmt.dec(v, 2) + ' s' }, { key: 'distance_kb', label: 'distance', num: true, fmt: v => fmt.bytes(v * 1024) }], { empty: 'none in range' })),panel('bgwriter / checkpointer (summed)', table(d.bgwriter, [{ key: 'instance', label: 'instance' }, { key: 'checkpoints_timed', label: 'timed', num: true, fmt: fmt.num }, { key: 'checkpoints_req', label: 'requested', num: true, fmt: fmt.num }, { key: 'buffers_checkpoint', label: 'ckpt buffers', num: true, fmt: fmt.num }, { key: 'buffers_clean', label: 'bgw buffers', num: true, fmt: fmt.num }, { key: 'buffers_alloc', label: 'allocated', num: true, fmt: fmt.num }])),panel('Aurora replicas', table(d.aurora_replicas, [{ key: 'instance_id', label: 'instance' }, { key: 'role', label: 'role' }, { key: 'replica_lag_ms', label: 'lag', num: true, fmt: v => v == null ? '–' : fmt.ms(v) }, { key: 'replay_latency_us', label: 'replay', num: true, fmt: v => fmt.ms(v / 1000) }, { key: 'active_txns', label: 'txns', num: true }, { key: 'storage_daemon_cpu', label: 'storage cpu', num: true, fmt: fmt.pct }], { empty: 'not Aurora' })),panel('Aurora per-database latency', table(d.aurora_db_latency, [{ key: 'datname', label: 'db' }, { key: 'commit_latency_us', label: 'commit latency (sum)', num: true, fmt: v => fmt.ms(v / 1000) }, { key: 'selects', label: 'selects', num: true, fmt: fmt.num }, { key: 'updates', label: 'updates', num: true, fmt: fmt.num }, { key: 'avg_update_latency_us', label: 'avg update', num: true, fmt: v => fmt.ms(v / 1000) }], { empty: 'not Aurora' })),),- d.top_backends_by_cpu.length ? el('div', { style: 'margin-top:12px' }, panel('Top backends by CPU (pg_proctab)', table(d.top_backends_by_cpu, [{ key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'application_name', label: 'app' }, { key: 'backend_type', label: 'type' }, { key: 'cpu_jiffies', label: 'cpu jiffies', num: true, fmt: fmt.num }, { key: 'max_rss_kb', label: 'max rss', num: true, fmt: v => fmt.bytes(v * 1024) }]))) : null,];};diff --git a/rust/pgcollector/DESIGN.md b/rust/pgcollector/DESIGN.mdindex 8aa13d58684e..18aa4e5dc37e 100644--- a/rust/pgcollector/DESIGN.md+++ b/rust/pgcollector/DESIGN.md@@ -133,7 +133,7 @@ Planned Tier B collectors:| 60s | replica status (Aurora) | A | `aurora_replica_status()` — lag, replay latency, oldest read view || 60s | memory contexts (Aurora) | A | `aurora_stat_memctx_usage()` — backends > 64 MB || 60s | system cpu / memory / disk | A | `pg_proctab`: `pg_cputime`, `pg_memusage`, `pg_loadavg`, `pg_diskusage` |-| 60s | backend cpu | A | `pg_proctab()` per pid joined to `pg_stat_activity` |+| 60s | backend cpu | A | `pg_proctab()` per pid joined to `pg_stat_activity`, with the active statement's `query_id` and query tags sampled at the tick || 30s | logs | B | CloudWatch Logs (RDS) or files: `ts_query_latency` (per-minute latency histograms, the source of quantiles), `ts_query_durations` (slow statements over `sample_rows_over_ms`), `ts_log_plans` (auto_explain), `ts_autovacuum_runs`, `ts_checkpoints`, `ts_temp_files`, `ts_log_errors`, `ts_logs` counts, deadlock/lock-wait/cancel events |On Aurora, `query_stats` reads `aurora_stat_statements` (adds Aurora-storage I/Odiff --git a/rust/pgcollector/collectors/backend_cpu.yaml b/rust/pgcollector/collectors/backend_cpu.yamlindex 3794a1bb3833..dea34fde80c9 100644--- a/rust/pgcollector/collectors/backend_cpu.yaml+++ b/rust/pgcollector/collectors/backend_cpu.yaml@@ -2,15 +2,21 @@ name: backend_cpudescription: >Per-backend CPU, page faults and I/O from /proc via pg_proctab, joined topg_stat_activity — attributes host CPU to users/queries (what pg_stat_kcache- would give). Cumulative per (pid, backend_start); rss is a gauge.+ would give). Cumulative per (pid, backend_start); rss is a gauge. The active+ statement's query_id and query tags are sampled at the tick so CPU can be+ grouped by query and by code path; idle backends carry neither.interval: 60sscope: clusterkind: cumulativerequires: { extension: pg_proctab }key: [pid, backend_start]-passthrough: [rss_kb, num_threads]+passthrough: [rss_kb, num_threads, query_id]+tags:+ from: query_tags_rawquery: |- SELECT a.pid, a.backend_start, a.datname, a.usename, a.application_name, a.backend_type,+ SELECT a.pid, a.backend_start, a.datname, a.usename, a.application_name, a.backend_type, a.state,+ NULL::bigint AS query_id,+ CASE WHEN a.state = 'active' THEN a.query END AS query_tags_raw,p.utime AS utime_jiffies, p.stime AS stime_jiffies,p.minflt, p.majflt,p.rchar AS read_chars, p.wchar AS write_chars, p.reads AS read_bytes, p.writes AS write_bytes,@@ -18,3 +24,16 @@ query: |FROM pg_proctab() pJOIN pg_stat_activity a ON a.pid = p.pidWHERE a.backend_type IN ('client backend', 'autovacuum worker', 'parallel worker', 'checkpointer', 'background writer', 'walwriter')+variants:+ - min_pg_version: 140000+ query: |+ SELECT a.pid, a.backend_start, a.datname, a.usename, a.application_name, a.backend_type, a.state,+ CASE WHEN a.state = 'active' THEN a.query_id END AS query_id,+ CASE WHEN a.state = 'active' THEN a.query END AS query_tags_raw,+ p.utime AS utime_jiffies, p.stime AS stime_jiffies,+ p.minflt, p.majflt,+ p.rchar AS read_chars, p.wchar AS write_chars, p.reads AS read_bytes, p.writes AS write_bytes,+ (p.rss * 4)::bigint AS rss_kb, p.num_threads+ FROM pg_proctab() p+ JOIN pg_stat_activity a ON a.pid = p.pid+ WHERE a.backend_type IN ('client backend', 'autovacuum worker', 'parallel worker', 'checkpointer', 'background writer', 'walwriter')diff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.mdindex a53282c9e451..f8a79c31cc36 100644--- a/rust/pgcollector/docs/deploy.md+++ b/rust/pgcollector/docs/deploy.md@@ -24,7 +24,9 @@ Nothing here requires a parameter-group change or a reboot.* `pg_stat_statements` — already in `shared_preload_libraries` on everycluster, but `CREATE EXTENSION` is per database and the collector reads- cluster-wide stats from the **maintenance database (`postgres`)**. Run+ cluster-wide stats through the **database named in the server URL** (the+ `aurora_user_management` credentials point at the application database, so+ `d63d9unoslck8q` on the PostHog clusters, not `postgres`). Run`CREATE EXTENSION IF NOT EXISTS pg_stat_statements` there (DDL user) if ithasn't been. This is the only step that is genuinely required.A cluster upgraded in place keeps the old extension definition, so also run@@ -33,11 +35,13 @@ Nothing here requires a parameter-group change or a reboot.`pgss_stale` event (plus a warning log) until the extension catches up.Below 1.8 (the PG13 definition) `query_stats` and `aurora_plans` collectnothing until the extension is updated.-* `pg_proctab` — optional. Not installed anywhere today; `CREATE EXTENSION- pg_proctab` in the maintenance database enables `system_cpu`,- `system_memory`, `system_disk`, `backend_cpu`. Until then those four log one- `skipping: prerequisite not met` line and re-check every 10 minutes. Its- functions may need `GRANT EXECUTE ... TO pgcollector`.+* `pg_proctab` — optional, supported on both Aurora and RDS for PostgreSQL.+ `CREATE EXTENSION pg_proctab` in the same database as above enables+ `system_cpu`, `system_memory`, `system_disk`, `backend_cpu` (host CPU, memory,+ load, disk counters and CPU per backend, grouped by user, code path and query+ in pgapi). Until then those four log one `skipping: prerequisite not met`+ line and re-check every 10 minutes. Its functions may need+ `GRANT EXECUTE ... TO pgcollector`.* `aurora_stat_*` / `aurora_replica_status` — built in, no setup.`aurora_compute_plan_id` (default on, 14.10+/15.5+) must stay on for`aurora_plans` and `plan_id` in activity samples.diff --git a/rust/pgcollector/src/collectors/mod.rs b/rust/pgcollector/src/collectors/mod.rsindex 1573571b2d41..27501bfb749c 100644--- a/rust/pgcollector/src/collectors/mod.rs+++ b/rust/pgcollector/src/collectors/mod.rs@@ -88,3 +88,20 @@ fn is_yaml(p: &Path) -> bool {.map(|x| x == "yaml" || x == "yml").unwrap_or(false)}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_embedded_collector_parses() {+ let mut names = Vec::new();+ for f in EMBEDDED.files().filter(|f| is_yaml(f.path())) {+ let raw = f.contents_utf8().expect("utf8");+ let c = declarative::SqlCollector::from_str(raw, &f.path().display().to_string())+ .unwrap_or_else(|e| panic!("{}: {e:#}", f.path().display()));+ names.push(c.name().to_string());+ }+ assert!(names.contains(&"backend_cpu".to_string()));+ }+}