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): group, filter and label queries by their tags (#101956)

Nick Bestf45ce4452b2c
diff --git a/docs/internal/pgapi.md b/docs/internal/pgapi.md
index 2d2915ebfd4a..51b5c02e36eb 100644
--- a/docs/internal/pgapi.md
+++ b/docs/internal/pgapi.md
@@ -8,12 +8,21 @@ contract.
## Surfaces
-| path | what | auth |
-| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
-| `/api/v1/*` | JSON API: servers, overview, queries, activity, tables, indexes, vacuum, events, logs, system, schema, settings, collector health, guarded raw SQL | identity required |
-| `/mcp` | MCP streamable HTTP, 17 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, 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 |
+
+## Query tags
+
+Queries are labelled by the tags their clients put in SQL comments, not only by
+their text. `GET /servers/{id}/tags?key=<tag key>` (MCP `query_tags`) gives load
+per code path; `GET /servers/{id}/queries?tags=key=value` filters the
+`pg_stat_statements` list to queries seen with a tag; query detail lists 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).
## Identity and authorization
diff --git a/rust/pgapi/README.md b/rust/pgapi/README.md
index 9ff18897a14d..2fac645e50dd 100644
--- a/rust/pgapi/README.md
+++ b/rust/pgapi/README.md
@@ -11,11 +11,12 @@ PGAPI_DEV_MODE=1 [email protected] \
cargo run -p pgapi -- --database-url postgres://.../pgcollector
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)
```
MCP client config (Claude Code / Desktop): `{"type": "http", "url": "http://localhost:3400/mcp"}`.
-17 tools: `list_servers`, `server_overview`, `top_queries`, `query_detail`,
-`wait_events`, `current_activity`, `table_stats`, `index_stats`,
+18 tools: `list_servers`, `server_overview`, `top_queries`, `query_detail`,
+`query_tags`, `wait_events`, `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 5dc784f6df83..d55ba6278b59 100644
--- a/rust/pgapi/src/api.rs
+++ b/rust/pgapi/src/api.rs
@@ -42,6 +42,7 @@ pub fn router() -> Router<Arc<AppState>> {
.route("/servers/:server/overview", get(overview))
.route("/servers/:server/queries", get(top_queries))
.route("/servers/:server/queries/:queryid", get(query_detail))
+ .route("/servers/:server/tags", get(tags))
.route("/servers/:server/waits", get(waits))
.route("/servers/:server/activity", get(activity))
.route("/servers/:server/tables", get(tables))
@@ -78,6 +79,9 @@ struct TopQ {
order: String,
#[serde(default = "d_limit")]
limit: i64,
+ /// `key=value,key2=value2`: only queries seen with these tags in the range. A comma
+ /// inside a value is sent as `%2C`.
+ tags: Option<String>,
}
fn d_order() -> String {
"total_exec_time".into()
@@ -87,15 +91,43 @@ fn d_limit() -> i64 {
}
async fn top_queries(State(s): S, Path(server): Path<String>, Query(p): Query<TopQ>) -> R {
let (f, t) = p.range.resolve()?;
+ let tags = q::parse_tag_filter(p.tags.as_deref().unwrap_or(""))?;
Ok(Json(
q::top_queries(
&s.db,
&server,
f,
t,
+ q::QueryListOpts {
+ datname: p.datname.as_deref(),
+ order: &p.order,
+ limit: p.limit.clamp(1, 500),
+ tags: &tags,
+ },
+ )
+ .await?,
+ ))
+}
+#[derive(Deserialize)]
+struct TagsQ {
+ #[serde(flatten)]
+ range: Range,
+ key: Option<String>,
+ datname: Option<String>,
+ #[serde(default = "d_limit")]
+ limit: i64,
+}
+async fn tags(State(s): S, Path(server): Path<String>, Query(p): Query<TagsQ>) -> R {
+ let (f, t) = p.range.resolve()?;
+ Ok(Json(
+ q::tag_breakdown(
+ &s.db,
+ &server,
+ f,
+ t,
+ p.key.as_deref(),
p.datname.as_deref(),
- &p.order,
- p.limit.clamp(1, 500),
+ p.limit,
)
.await?,
))
diff --git a/rust/pgapi/src/mcp.rs b/rust/pgapi/src/mcp.rs
index 3a9901320c4d..d04841fe0c6f 100644
--- a/rust/pgapi/src/mcp.rs
+++ b/rust/pgapi/src/mcp.rs
@@ -61,6 +61,18 @@ pub struct TopQueriesArg {
/// One of total_exec_time (default), calls, mean_exec_time, rows, shared_blks_read, wal_bytes, storage_blks_read.
pub order: Option<String>,
pub limit: Option<i64>,
+ /// Only queries seen with these query tags in the window, as "key=value,key2=value2" (e.g. "operation=updatePersonsBatch"). Keys come from query_tags; percent-encode a comma inside a value.
+ pub tags: Option<String>,
+}
+#[derive(Deserialize, schemars::JsonSchema)]
+pub struct TagsArg {
+ pub server: String,
+ pub since: Option<String>,
+ /// Tag key to group on, e.g. "operation", "route", "service", "team_id". Omit to list the keys seen in the window.
+ pub key: Option<String>,
+ /// Restrict to one database.
+ pub datname: Option<String>,
+ pub limit: Option<i64>,
}
#[derive(Deserialize, schemars::JsonSchema)]
pub struct QueryArg {
@@ -140,27 +152,51 @@ impl PgMcp {
.map_err(err)?)
}
#[tool(
- description = "Top queries by total time / calls / mean time / rows / I/O over a window, with normalized text, exact mean and stddev, and share of total time."
+ description = "Top queries by total time / calls / mean time / rows / I/O over a window, with normalized text, first-seen query tags, exact mean and stddev, and share of total time. Filter by query tags to keep only queries a given code path ran."
)]
async fn top_queries(
&self,
Parameters(a): Parameters<TopQueriesArg>,
) -> Result<CallToolResult, McpError> {
let (f, t) = range(&a.since)?;
+ let tags = q::parse_tag_filter(a.tags.as_deref().unwrap_or("")).map_err(err)?;
ok(q::top_queries(
&self.state.db,
&a.server,
f,
t,
+ q::QueryListOpts {
+ datname: a.datname.as_deref(),
+ order: a.order.as_deref().unwrap_or("total_exec_time"),
+ limit: a.limit.unwrap_or(25).clamp(1, 200),
+ tags: &tags,
+ },
+ )
+ .await
+ .map_err(err)?)
+ }
+ #[tool(
+ description = "Database load per code path, from query tags (SQL comments such as /* nodejs:PERSONS_WRITE<updatePersonsBatch> */ or /* route='/api/x' */). Without a key: the tag keys seen in the window. With a key: one row per value with average active sessions (sampled pg_stat_activity), estimated calls, total time and p50/p95/p99 from sampled statement logs, and distinct queries."
+ )]
+ async fn query_tags(
+ &self,
+ Parameters(a): Parameters<TagsArg>,
+ ) -> Result<CallToolResult, McpError> {
+ let (f, t) = range(&a.since)?;
+ ok(q::tag_breakdown(
+ &self.state.db,
+ &a.server,
+ f,
+ t,
+ a.key.as_deref(),
a.datname.as_deref(),
- a.order.as_deref().unwrap_or("total_exec_time"),
- a.limit.unwrap_or(25).clamp(1, 200),
+ a.limit.unwrap_or(50),
)
.await
.map_err(err)?)
}
#[tool(
- description = "Everything about one query id: text, bucketed calls/mean series, latency percentiles per bucket and for the whole range from sampled logs (p50/p90/p95/p99, weighted for the server's log sampling settings), slowest samples, execution plans (Aurora plan stats and auto_explain), wait events."
+ description = "Everything about one query id: text and first-seen query tags, callers (tag sets seen while it ran, with share), bucketed calls/mean series, latency percentiles per bucket and for the whole range from sampled logs (p50/p90/p95/p99, weighted for the server's log sampling settings), slowest samples, execution plans (Aurora plan stats and auto_explain), wait events."
)]
async fn query_detail(
&self,
@@ -343,7 +379,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, 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, 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 60218848bd4c..1b5246feec15 100644
--- a/rust/pgapi/src/queries.rs
+++ b/rust/pgapi/src/queries.rs
@@ -60,7 +60,19 @@ pub async fn overview(db: &Db, server: &str, from: Ts, to: Ts) -> Result<Value>
FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND state = 'active'
GROUP BY 1, 2 ORDER BY 3 DESC LIMIT 15", &[&server, &from, &to]).await?;
let events = opt(db, "SELECT kind, count(*)::bigint AS n FROM events WHERE server_id = $1 AND at >= $2 AND at < $3 GROUP BY 1 ORDER BY 2 DESC", &[&server, &from, &to]).await?;
- let top = top_queries(db, server, from, to, None, "total_exec_time", 5).await?;
+ let top = top_queries(
+ db,
+ server,
+ from,
+ to,
+ QueryListOpts {
+ datname: None,
+ order: "total_exec_time",
+ limit: 5,
+ tags: &[],
+ },
+ )
+ .await?;
let vac = opt(db, "SELECT datname, relname, round(vacuum_ratio::numeric, 2)::float8 AS vacuum_ratio, round(freeze_ratio::numeric, 3)::float8 AS freeze_ratio, autovacuum_enabled
FROM ts_vacuum_needed WHERE server_id = $1 AND collected_at = (SELECT max(collected_at) FROM ts_vacuum_needed WHERE server_id = $1 AND collected_at >= $2)
AND (vacuum_ratio >= 1 OR freeze_ratio >= 0.5) ORDER BY greatest(vacuum_ratio, freeze_ratio * 2) DESC LIMIT 10", &[&server, &from]).await?;
@@ -69,15 +81,26 @@ pub async fn overview(db: &Db, server: &str, from: Ts, to: Ts) -> Result<Value>
)
}
+pub struct QueryListOpts<'a> {
+ pub datname: Option<&'a str>,
+ pub order: &'a str,
+ pub limit: i64,
+ pub tags: &'a [(String, String)],
+}
+
pub async fn top_queries(
db: &Db,
server: &str,
from: Ts,
to: Ts,
- datname: Option<&str>,
- order: &str,
- limit: i64,
+ opts: QueryListOpts<'_>,
) -> Result<Value> {
+ let QueryListOpts {
+ datname,
+ order,
+ limit,
+ tags,
+ } = opts;
let order_col = match order {
"calls" => "calls",
"mean_exec_time" => "mean_ms",
@@ -87,6 +110,36 @@ pub async fn top_queries(
"storage_blks_read" => "storage_blks_read",
_ => "total_ms",
};
+ // pg_stat_statements cannot split a query id by caller, so a tag filter keeps the
+ // ids that were seen with those tags in any sampled source (activity, logs) or
+ // whose first-seen text carried them.
+ let mut tagged_sources = Vec::new();
+ if !tags.is_empty() {
+ if has_column(db, "ts_activity_samples", "tags").await {
+ tagged_sources.push("SELECT DISTINCT query_id AS queryid, datname FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND query_id IS NOT NULL AND tags @> $6::jsonb");
+ }
+ if has_column(db, "ts_query_latency", "tags").await {
+ tagged_sources.push("SELECT DISTINCT query_id AS queryid, datname FROM ts_query_latency WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND query_id IS NOT NULL AND tags @> $6::jsonb");
+ tagged_sources.push("SELECT DISTINCT q.queryid, q.datname FROM ts_query_latency d JOIN cur_queries q ON q.server_id = $1 AND q.fingerprint = d.fingerprint AND q.datname = d.datname WHERE d.server_id = $1 AND d.collected_at >= $2 AND d.collected_at < $3 AND d.tags @> $6::jsonb");
+ }
+ if tagged_sources.is_empty() {
+ return Ok(json!([]));
+ }
+ }
+ let tag_filter = if tagged_sources.is_empty() {
+ String::new()
+ } else {
+ format!(
+ "AND (s.queryid, s.datname) IN ({})",
+ tagged_sources.join(" UNION ")
+ )
+ };
+ let tag_param: Option<Value> = (!tags.is_empty()).then(|| tags_object(tags));
+ let query_tags = if has_column(db, "cur_queries", "tags").await {
+ "q.tags"
+ } else {
+ "NULL::jsonb AS tags"
+ };
let sql = format!(
"WITH agg AS (
SELECT s.queryid, s.datname, s.rolname,
@@ -99,17 +152,21 @@ pub async fn top_queries(
{aurora}
count(DISTINCT s.instance)::bigint AS instances
FROM ts_query_stats s
- WHERE s.server_id = $1 AND s.collected_at >= $2 AND s.collected_at < $3 AND ($4::text IS NULL OR s.datname = $4)
+ WHERE s.server_id = $1 AND s.collected_at >= $2 AND s.collected_at < $3 AND ($4::text IS NULL OR s.datname = $4) {tag_filter}
GROUP BY 1, 2, 3)
- SELECT a.*, q.query, q.fingerprint,
+ SELECT a.*, q.query, q.fingerprint, {query_tags},
round((a.total_ms / nullif(sum(a.total_ms) OVER (), 0) * 100)::numeric, 2)::float8 AS pct_of_total_time
FROM agg a LEFT JOIN cur_queries q ON q.server_id = $1 AND q.queryid = a.queryid AND q.datname = a.datname
ORDER BY {order_col} DESC NULLS LAST LIMIT $5",
aurora = if has_column(db, "ts_query_stats", "storage_blks_read").await { "sum(s.storage_blks_read)::bigint AS storage_blks_read, max(s.max_exec_peakmem)::bigint AS max_exec_peakmem," } else { "NULL::bigint AS storage_blks_read, NULL::bigint AS max_exec_peakmem," },
);
- Ok(json!(
- opt(db, &sql, &[&server, &from, &to, &datname, &limit]).await?
- ))
+ // tokio-postgres rejects a parameter the statement never references.
+ let mut params: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
+ vec![&server, &from, &to, &datname, &limit];
+ if tag_param.is_some() {
+ params.push(&tag_param);
+ }
+ Ok(json!(opt(db, &sql, &params).await?))
}
async fn has_column(db: &Db, table: &str, col: &str) -> bool {
@@ -122,6 +179,68 @@ async fn has_column(db: &Db, table: &str, col: &str) -> bool {
.unwrap_or(false)
}
+/// `tags, trace_id` when the table has them, NULL placeholders until the collector's
+/// first tagged row adds the columns, so an older stats DB keeps serving.
+async fn tag_cols(db: &Db, table: &str) -> &'static str {
+ if has_column(db, table, "tags").await {
+ "tags, trace_id"
+ } else {
+ "NULL::jsonb AS tags, NULL::text AS trace_id"
+ }
+}
+async fn tag_cols_of(db: &Db, table: &str, alias: &str) -> String {
+ if has_column(db, table, "tags").await {
+ format!("{alias}.tags, {alias}.trace_id")
+ } else {
+ "NULL::jsonb AS tags, NULL::text AS trace_id".into()
+ }
+}
+
+/// `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 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()) {
+ let (k, v) = part
+ .split_once('=')
+ .or_else(|| part.split_once(':'))
+ .ok_or_else(|| anyhow::anyhow!("tag filter {part:?} is not key=value"))?;
+ let k = k.trim().to_ascii_lowercase();
+ anyhow::ensure!(!k.is_empty(), "tag filter {part:?} has an empty key");
+ out.push((k, percent_decode(v.trim())));
+ }
+ Ok(out)
+}
+
+fn percent_decode(s: &str) -> String {
+ let b = s.as_bytes();
+ let mut out = Vec::with_capacity(b.len());
+ let mut i = 0;
+ while i < b.len() {
+ if b[i] == b'%' && i + 2 < b.len() {
+ if let Some(v) = std::str::from_utf8(&b[i + 1..i + 3])
+ .ok()
+ .and_then(|h| u8::from_str_radix(h, 16).ok())
+ {
+ out.push(v);
+ i += 3;
+ continue;
+ }
+ }
+ out.push(b[i]);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+fn tags_object(tags: &[(String, String)]) -> Value {
+ Value::Object(
+ tags.iter()
+ .map(|(k, v)| (k.clone(), Value::String(v.clone())))
+ .collect(),
+ )
+}
+
/// Bucket width for time series; unknown values fall back to one minute.
fn bucket_interval(bucket: &str) -> &'static str {
match bucket {
@@ -151,7 +270,12 @@ pub async fn query_detail(
} else {
interval
};
- let texts = opt(db, "SELECT datname, query, fingerprint, truncated, first_seen, last_seen FROM cur_queries WHERE server_id = $1 AND queryid = $2", &[&server, &queryid]).await?;
+ let query_tags = if has_column(db, "cur_queries", "tags").await {
+ "tags"
+ } 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 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,
@@ -211,15 +335,16 @@ pub async fn query_detail(
.partition(|r| r["bucket"].is_null());
let slow_samples = opt(
db,
- "SELECT d.log_time, d.log_stream, d.datname, d.usename, d.duration_ms, left(t.query, 500) AS query
+ &format!("SELECT d.log_time, d.log_stream, d.datname, d.usename, d.duration_ms, left(t.query, 500) AS query, {}
FROM ts_query_durations d
LEFT JOIN cur_query_texts t ON t.server_id = d.server_id AND t.instance = d.instance AND t.datname = coalesce(d.datname, '') AND t.fingerprint = d.fingerprint
WHERE d.server_id = $1 AND d.collected_at >= $3 AND d.collected_at < $4
AND (d.query_id = $2 OR d.fingerprint = $5) AND d.kind NOT IN ('parse', 'bind')
- ORDER BY d.duration_ms DESC LIMIT 10",
+ ORDER BY d.duration_ms DESC LIMIT 10", tag_cols_of(db, "ts_query_durations", "d").await),
&[&server, &queryid, &from, &to, &fingerprint],
)
.await?;
+ let callers = query_callers(db, server, queryid, fingerprint, from, to).await?;
let aurora_plans = opt(db, "SELECT p.planid, p.plan_type, p.plan_captured_time, p.explain_plan,
(SELECT sum(calls) FROM ts_aurora_plans a WHERE a.server_id = $1 AND a.planid = p.planid AND a.queryid = $2 AND a.collected_at >= $3 AND a.collected_at < $4)::bigint AS calls,
(SELECT sum(total_exec_time) FROM ts_aurora_plans a WHERE a.server_id = $1 AND a.planid = p.planid AND a.queryid = $2 AND a.collected_at >= $3 AND a.collected_at < $4)::float8 AS total_ms
@@ -232,14 +357,14 @@ pub async fn query_detail(
json!({ "queryid": queryid, "bucket": interval, "latency_bucket": latency_interval, "texts": texts, "series": series, "latency_series": latency_series,
// Always-logged slow statements alone are a tail, not a distribution.
"latency_from_logs": quantiles.into_iter().next().filter(|q| json_i64(&q["sampled"]).unwrap_or(0) > 0),
- "log_sampling": sampling, "slowest_samples": slow_samples,
+ "log_sampling": sampling, "slowest_samples": slow_samples, "callers": callers,
"plans": aurora_plans, "logged_plans": logged_plans, "wait_events": waits }),
)
}
/// How the monitored server samples statement durations into its log. Drives the
/// quantile weighting and tells the UI what the samples cover.
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, Clone)]
struct LogSampling {
/// `log_min_duration_sample`: statements below this are never sampled (-1 = off).
sample_floor_ms: f64,
@@ -252,7 +377,9 @@ struct LogSampling {
}
async fn log_sampling_settings(db: &Db, server: &str) -> Result<LogSampling> {
- let rows = opt(db, "SELECT name, setting FROM cur_settings WHERE server_id = $1
+ // The collector silences its own statement logging with session-level SETs, and
+ // the settings snapshot is taken from that session; reset_val is the server value.
+ let rows = opt(db, "SELECT name, CASE WHEN source = 'session' THEN reset_val ELSE setting END AS setting FROM cur_settings WHERE server_id = $1
AND name IN ('log_min_duration_sample', 'log_statement_sample_rate', 'log_min_duration_statement')
ORDER BY instance", &[&server]).await?;
let get = |name: &str, default: f64| -> f64 {
@@ -271,6 +398,166 @@ async fn log_sampling_settings(db: &Db, server: &str) -> Result<LogSampling> {
})
}
+/// Which code paths ran this query in the range: tag sets seen in activity samples
+/// (weighted by backends seen) and in logged statements (one per statement).
+async fn query_callers(
+ db: &Db,
+ server: &str,
+ queryid: i64,
+ fingerprint: Option<i64>,
+ from: Ts,
+ to: Ts,
+) -> Result<Vec<Value>> {
+ let mut parts = Vec::new();
+ if has_column(db, "ts_activity_samples", "tags").await {
+ parts.push("SELECT tags, 'activity' AS source, sum(backends)::bigint AS samples FROM ts_activity_samples
+ WHERE server_id = $1 AND query_id = $2 AND collected_at >= $3 AND collected_at < $4 AND tags IS NOT NULL GROUP BY 1");
+ }
+ let latency = has_column(db, "ts_query_latency", "tags").await;
+ if latency {
+ parts.push("SELECT tags, 'log' AS source, sum(count)::bigint AS samples FROM ts_query_latency
+ WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4 AND (query_id = $2 OR fingerprint = $5)
+ AND tags IS NOT NULL GROUP BY 1");
+ }
+ if parts.is_empty() {
+ return Ok(vec![]);
+ }
+ // The share is over every tag set of the source, computed before the row cap.
+ let sql = format!(
+ "SELECT tags, source, samples,
+ round((samples::numeric / nullif(sum(samples) OVER (PARTITION BY source), 0)) * 100, 1)::float8 AS share_pct
+ FROM ({}) c ORDER BY samples DESC LIMIT 40",
+ parts.join(" UNION ALL ")
+ );
+ // tokio-postgres rejects a parameter the statement never references.
+ let mut params: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
+ vec![&server, &queryid, &from, &to];
+ if latency {
+ params.push(&fingerprint);
+ }
+ opt(db, &sql, &params).await
+}
+
+/// Without `key` only the tag keys seen in the range are listed. Duration metrics are
+/// weighted for log sampling the same way `query_detail` weights them.
+pub async fn tag_breakdown(
+ db: &Db,
+ server: &str,
+ from: Ts,
+ to: Ts,
+ key: Option<&str>,
+ datname: Option<&str>,
+ limit: i64,
+) -> Result<Value> {
+ let activity = has_column(db, "ts_activity_samples", "tags").await;
+ let latency = has_column(db, "ts_query_latency", "tags").await;
+ let mut keys: std::collections::BTreeMap<String, Value> = Default::default();
+ if activity {
+ for r in opt(db, "SELECT k AS key, count(DISTINCT tags ->> k)::bigint AS values, sum(backends)::bigint AS active_samples
+ FROM ts_activity_samples, LATERAL jsonb_object_keys(tags) k
+ WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND tags IS NOT NULL AND ($4::text IS NULL OR datname = $4) GROUP BY 1", &[&server, &from, &to, &datname]).await? {
+ let k = r["key"].as_str().unwrap_or("").to_string();
+ keys.insert(k.clone(), json!({ "key": k, "values": r["values"], "active_samples": r["active_samples"], "logged_statements": 0 }));
+ }
+ }
+ if latency {
+ for r in opt(db, "SELECT k AS key, count(DISTINCT tags ->> k)::bigint AS values, sum(count)::bigint AS logged_statements
+ FROM ts_query_latency, LATERAL jsonb_object_keys(tags) k
+ WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND tags IS NOT NULL AND ($4::text IS NULL OR datname = $4) GROUP BY 1", &[&server, &from, &to, &datname]).await? {
+ let k = r["key"].as_str().unwrap_or("").to_string();
+ let e = keys.entry(k.clone()).or_insert_with(|| json!({ "key": k, "values": r["values"], "active_samples": 0 }));
+ e["logged_statements"] = r["logged_statements"].clone();
+ if json_i64(&r["values"]).unwrap_or(0) > json_i64(&e["values"]).unwrap_or(0) {
+ e["values"] = r["values"].clone();
+ }
+ }
+ }
+ let sampling = log_sampling_settings(db, server).await?;
+ let Some(key) = key else {
+ return Ok(
+ json!({ "keys": keys.into_values().collect::<Vec<_>>(), "groups": [], "log_sampling": sampling }),
+ );
+ };
+ let mut groups: std::collections::BTreeMap<String, Value> = Default::default();
+ if activity {
+ let ticks = opt(db, "SELECT count(DISTINCT collected_at)::bigint AS n FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3", &[&server, &from, &to]).await?;
+ let ticks = ticks
+ .first()
+ .and_then(|r| json_i64(&r["n"]))
+ .unwrap_or(0)
+ .max(1) as f64;
+ for r in opt(db, "SELECT tags ->> $4 AS value, sum(backends)::bigint AS active_samples, sum(active_over_1s)::bigint AS active_over_1s, sum(active_over_10s)::bigint AS active_over_10s,
+ count(DISTINCT query_id)::bigint AS distinct_queries
+ FROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND state = 'active' AND tags ? $4::text
+ AND ($5::text IS NULL OR datname = $5) GROUP BY 1", &[&server, &from, &to, &key, &datname]).await? {
+ let v = r["value"].as_str().unwrap_or("").to_string();
+ let samples = json_i64(&r["active_samples"]).unwrap_or(0) as f64;
+ groups.insert(v.clone(), json!({ "value": v, "active_samples": r["active_samples"], "active_over_1s": r["active_over_1s"], "active_over_10s": r["active_over_10s"],
+ "avg_active_sessions": (samples / ticks * 100.0).round() / 100.0, "distinct_queries": r["distinct_queries"] }));
+ }
+ }
+ if latency {
+ // Same histogram arithmetic as query_detail, partitioned by tag value instead of
+ // time bucket. Estimated total time takes each bucket at its geometric middle.
+ let sql = "WITH l AS (
+ SELECT tags ->> $4 AS value, max_ms, sampled_counts, logged_counts, sample_rate, coalesce(query_id, fingerprint) AS q
+ FROM ts_query_latency WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND tags ? $4::text
+ AND ($5::text IS NULL OR datname = $5)),
+ h AS (
+ SELECT value, u.i, sum(u.sc)::float8 AS sc, sum(u.lc)::float8 AS lc,
+ sum(CASE WHEN l.sample_rate > 0 THEN u.sc / l.sample_rate ELSE 0 END + u.lc)::float8 AS wc
+ FROM l, unnest(l.sampled_counts, l.logged_counts) WITH ORDINALITY AS u(sc, lc, i)
+ WHERE u.sc > 0 OR u.lc > 0 GROUP BY 1, 2),
+ r AS (
+ SELECT value, i, sc, lc, wc, power(10, i / 20.0 - 2) AS hi,
+ sum(wc) OVER (PARTITION BY value ORDER BY i) AS cw, sum(wc) OVER (PARTITION BY value) AS tw
+ FROM h),
+ q AS (
+ SELECT value, sum(sc + lc)::bigint AS logged_statements, round(sum(wc)::numeric)::bigint AS est_calls,
+ sum(wc * hi / power(10, 0.025))::float8 AS est_total_ms,
+ min(hi) FILTER (WHERE cw >= 0.5 * tw) AS p50, min(hi) FILTER (WHERE cw >= 0.95 * tw) AS p95,
+ min(hi) FILTER (WHERE cw >= 0.99 * tw) AS p99
+ FROM r GROUP BY 1),
+ m AS (SELECT value, max(max_ms) AS max_ms, count(DISTINCT q)::bigint AS distinct_statements FROM l GROUP BY 1)
+ SELECT q.value, q.logged_statements, q.est_calls, q.est_total_ms, m.distinct_statements,
+ least(q.p50, m.max_ms)::float8 AS p50, least(q.p95, m.max_ms)::float8 AS p95, least(q.p99, m.max_ms)::float8 AS p99,
+ m.max_ms::float8 AS max_ms
+ FROM q JOIN m USING (value)";
+ for r in opt(db, sql, &[&server, &from, &to, &key, &datname]).await? {
+ let v = r["value"].as_str().unwrap_or("").to_string();
+ let e = groups.entry(v.clone()).or_insert_with(
+ || json!({ "value": v, "active_samples": 0, "avg_active_sessions": 0.0 }),
+ );
+ for k in [
+ "logged_statements",
+ "est_calls",
+ "est_total_ms",
+ "distinct_statements",
+ "p50",
+ "p95",
+ "p99",
+ "max_ms",
+ ] {
+ e[k] = r[k].clone();
+ }
+ }
+ }
+ let mut groups: Vec<Value> = groups.into_values().collect();
+ groups.sort_by(|a, b| {
+ let f = |v: &Value| {
+ (
+ json_i64(&v["active_samples"]).unwrap_or(0) as f64,
+ v["est_total_ms"].as_f64().unwrap_or(0.0),
+ )
+ };
+ f(b).partial_cmp(&f(a)).unwrap_or(std::cmp::Ordering::Equal)
+ });
+ groups.truncate(limit.clamp(1, 500) as usize);
+ Ok(
+ json!({ "key": key, "keys": keys.into_values().collect::<Vec<_>>(), "groups": groups, "log_sampling": sampling }),
+ )
+}
+
pub async fn wait_events(db: &Db, server: &str, from: Ts, to: Ts, bucket: &str) -> Result<Value> {
let sql = format!("SELECT {b} AS bucket,
instance, coalesce(wait_event_type, 'CPU') AS wait_event_type, coalesce(wait_event, 'CPU') AS wait_event,
@@ -381,12 +668,12 @@ pub async fn schema(db: &Db, server: &str, datname: &str, relname: Option<&str>)
}
pub async fn log_errors(db: &Db, server: &str, from: Ts, to: Ts, limit: i64) -> Result<Value> {
- let errors = opt(db, "SELECT log_time, log_stream, level, class, sqlstate, datname, usename, pid, query_id, message, detail, statement FROM ts_log_errors
- WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY log_time DESC LIMIT $4", &[&server, &from, &to, &limit]).await?;
+ let errors = opt(db, &format!("SELECT log_time, log_stream, level, class, sqlstate, datname, usename, pid, query_id, message, detail, statement, {} FROM ts_log_errors
+ WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY log_time DESC LIMIT $4", tag_cols(db, "ts_log_errors").await), &[&server, &from, &to, &limit]).await?;
let summary = opt(db, "SELECT class, sqlstate, left(message, 120) AS message, count(*)::bigint AS n FROM ts_log_errors
WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 20", &[&server, &from, &to]).await?;
let counts = opt(db, "SELECT level, class, sum(count)::bigint AS n FROM ts_logs WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2 ORDER BY 3 DESC", &[&server, &from, &to]).await?;
- let temp = opt(db, "SELECT log_time, datname, usename, query_id, size_bytes, left(statement, 300) AS statement FROM ts_temp_files WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY size_bytes DESC LIMIT 20", &[&server, &from, &to]).await?;
+ let temp = opt(db, &format!("SELECT log_time, datname, usename, query_id, size_bytes, left(statement, 300) AS statement, {} FROM ts_temp_files WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 ORDER BY size_bytes DESC LIMIT 20", tag_cols(db, "ts_temp_files").await), &[&server, &from, &to]).await?;
Ok(json!({ "summary": summary, "counts": counts, "recent": errors, "temp_files": temp }))
}
@@ -525,9 +812,26 @@ pub async fn schema_of_stats_db(db: &Db) -> Result<Value> {
#[cfg(test)]
mod tests {
- use super::{denied_function, json_i64};
+ use super::{denied_function, json_i64, parse_tag_filter};
use serde_json::json;
+ #[test]
+ fn tag_filters_accept_both_pair_styles_and_reject_bare_words() {
+ assert_eq!(
+ parse_tag_filter("Route=/api/x, service:web").unwrap(),
+ vec![
+ ("route".into(), "/api/x".into()),
+ ("service".into(), "web".into())
+ ]
+ );
+ assert_eq!(
+ parse_tag_filter("caller=a%2Cb").unwrap(),
+ vec![("caller".into(), "a,b".into())]
+ );
+ assert!(parse_tag_filter("web").is_err());
+ assert!(parse_tag_filter("=web").is_err());
+ }
+
#[test]
fn bigints_read_back_from_number_or_string() {
assert_eq!(json_i64(&json!(42)), Some(42));
diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.html
index e78c930121a9..299a191c650b 100644
--- a/rust/pgapi/src/ui/index.html
+++ b/rust/pgapi/src/ui/index.html
@@ -48,6 +48,10 @@
.legend i { display: inline-block; width: 10px; height: 3px; margin-right: 4px; vertical-align: middle; }
.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; }
+ .tag b { color: var(--muted); font-weight: 400; }
+ .chip { display: inline-flex; align-items: center; gap: 6px; padding: 3px 8px; border: 1px solid var(--accent); border-radius: 6px; font-family: var(--mono); font-size: 11px; }
+ .chip button { padding: 0 4px; border: 0; background: none; color: var(--muted); }
.clickable { cursor: pointer; } tr.clickable:hover td { background: var(--panel2); }
details summary { cursor: pointer; color: var(--muted); }
</style>
@@ -137,6 +141,13 @@
const panel = (title, ...kids) => el('div', { class: 'panel' }, title ? el('h2', {}, title) : null, ...kids);
const tile = (label, value, cls = '') => el('div', { class: 'panel tile' }, el('div', { class: 'v ' + cls }, value ?? '–'), el('div', { class: 'l' }, label));
const queryCell = q => el('span', { class: 'q', title: q || '' }, q || el('span', { class: 'muted' }, '(text not captured)'));
+ // Tags label a query by the code that ran it (/* nodejs:PERSONS_WRITE<updatePersonsBatch> */, /* route='/api/x' */).
+ const TAG_ORDER = ['service', 'db_use', 'operation', 'caller', 'route', 'controller', 'task', 'workflow', 'query_type', 'purpose', 'team_id'];
+ const tagEntries = tags => tags ? Object.entries(tags).sort(([a], [b]) => (TAG_ORDER.indexOf(a) + 1 || 99) - (TAG_ORDER.indexOf(b) + 1 || 99)) : [];
+ const tagPills = (tags, max = 5) => { const e = tagEntries(tags); if (!e.length) return null; return el('span', {}, e.slice(0, max).map(([k, v]) => el('span', { class: 'tag', title: `${k}=${v}` }, el('b', {}, k + '='), v)), e.length > max ? el('span', { class: 'muted' }, `+${e.length - max}`) : null); };
+ // The row label: tags first, SQL underneath, so a list reads by code path rather than by statement text.
+ const queryLabel = r => el('span', {}, tagPills(r.tags), r.tags && Object.keys(r.tags).length ? el('br') : null, queryCell(r.query));
+ const tagFilterChip = (tags, onClear) => tags ? el('span', { class: 'chip' }, tags, el('button', { title: 'clear tag filter', onclick: onClear }, '✕')) : null;
// ---------- simple SVG line chart ----------
// series: [{name, color, points: [[Date, number | null]]}]; a null y breaks the line.
@@ -184,7 +195,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}` }, queryCell(r.query)) },
+ { key: 'query', label: 'query', render: r => el('a', { href: `#/${state.server}/query?queryid=${r.queryid}` }, 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, [
@@ -204,19 +215,50 @@
pages.queries = async () => {
const order = state.params.order || 'total_exec_time';
- const rows = await api(`/servers/${state.server}/queries`, { since: state.range, order, limit: 200, datname: state.params.datname });
+ const group = state.params.group || '';
+ const tagFilter = state.params.tags || '';
const orders = [['total_exec_time', 'total time'], ['calls', 'calls'], ['mean_exec_time', 'mean time'], ['rows', 'rows'], ['shared_blks_read', 'blocks read'], ['wal_bytes', 'WAL bytes'], ['storage_blks_read', 'Aurora storage reads']];
const [dbsel] = dbSelect(v => go('queries', { ...state.params, datname: v }));
dbsel.prepend(el('option', { value: '', selected: state.params.datname ? null : '' }, 'all databases'));
+ const [rows, tagged] = await Promise.all([
+ group ? null : api(`/servers/${state.server}/queries`, { since: state.range, order, limit: 200, datname: state.params.datname, tags: tagFilter }),
+ api(`/servers/${state.server}/tags`, { since: state.range, key: group, datname: state.params.datname, limit: 200 }),
+ ]);
+ const keys = (tagged.keys || []).map(k => k.key);
+ const groupSel = el('select', { onchange: e => { const p = { ...state.params, group: e.target.value }; if (p.group) delete p.tags; go('queries', p); } },
+ el('option', { value: '', selected: group ? null : '' }, 'query'),
+ keys.map(k => el('option', { value: k, selected: k === group ? '' : null }, `tag: ${k}`)),
+ group && !keys.includes(group) ? el('option', { value: group, selected: '' }, `tag: ${group}`) : null);
+ const toolbar = el('div', { class: 'toolbar' },
+ el('label', {}, 'group by ', groupSel),
+ group ? null : el('label', {}, 'order by ', el('select', { onchange: e => go('queries', { ...state.params, order: e.target.value }) }, orders.map(([v, l]) => el('option', { value: v, selected: v === order ? '' : null }, l)))),
+ el('label', {}, 'database ', dbsel),
+ tagFilterChip(tagFilter, () => { const p = { ...state.params }; delete p.tags; go('queries', p); }));
+ if (group) {
+ const samp = tagged.log_sampling || {};
+ const sub = samp.enabled ? 'load per code path: active sessions from 10s samples, calls and latency from sampled statement logs' : 'load per code path from 10s activity samples (statement log sampling is off, so no calls or latency)';
+ return [
+ el('h1', {}, 'Queries by tag ', el('span', { class: 'mono' }, group), el('span', { class: 'sub' }, sub)),
+ toolbar,
+ panel(null, table(tagged.groups, [
+ { key: 'value', label: group, render: r => el('span', { class: 'tag', title: r.value }, r.value) },
+ { key: 'avg_active_sessions', label: 'avg active sessions', num: true, fmt: v => fmt.dec(v, 2) },
+ { key: 'active_over_10s', label: 'samples > 10s', num: true, fmt: fmt.num },
+ { key: 'distinct_queries', label: 'queries', num: true, render: r => fmt.num(r.distinct_queries ?? r.distinct_statements) },
+ { key: 'est_calls', label: 'est. calls', num: true, fmt: fmt.num }, { key: 'est_total_ms', label: 'est. total', num: true, fmt: fmt.ms },
+ { key: 'p50', label: 'p50', num: true, fmt: fmt.ms }, { key: 'p95', label: 'p95', num: true, fmt: fmt.ms }, { key: 'p99', label: 'p99', num: true, fmt: fmt.ms }, { key: 'max_ms', label: 'max', num: true, fmt: fmt.ms },
+ ], { sortKey: 'avg_active_sessions', onRow: r => { const p = { ...state.params, tags: `${group}=${encodeURIComponent(r.value)}` }; delete p.group; go('queries', p); }, empty: 'no tagged activity in this range (queries need a /* key=value */ comment)' })),
+ ];
+ }
return [
- el('h1', {}, 'Queries', el('span', { class: 'sub' }, 'pg_stat_statements, per-interval deltas summed over the range')),
- el('div', { class: 'toolbar' }, el('label', {}, 'order by ', el('select', { onchange: e => go('queries', { ...state.params, order: e.target.value }) }, orders.map(([v, l]) => el('option', { value: v, selected: v === order ? '' : null }, l)))), el('label', {}, 'database ', dbsel)),
+ el('h1', {}, 'Queries', el('span', { class: 'sub' }, tagFilter ? 'pg_stat_statements totals for queries seen with this tag; the totals include every caller of each query' : 'pg_stat_statements, per-interval deltas summed over the range')),
+ toolbar,
panel(null, table(rows, [
- { key: 'query', label: 'query', render: r => queryCell(r.query) },
+ { key: 'query', label: 'query', render: queryLabel },
{ 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 }) })),
+ ], { onRow: r => go('query', { queryid: r.queryid }), empty: tagFilter ? 'no queries seen with this tag in the range' : 'nothing in this range' })),
];
};
@@ -241,15 +283,19 @@
: 'mean only: no sampled durations in this range (needs log_min_duration_sample and the logs collector)';
return [
el('h1', {}, 'Query ', el('span', { class: 'mono' }, qid), el('span', { class: 'sub' }, t.datname || '')),
- panel('Text', el('pre', {}, t.query || '(not captured yet)'), t.truncated ? el('div', { class: 'muted' }, 'truncated at 10 KB') : null),
+ panel('Text', tagPills(t.tags, 12) ? el('div', { style: 'margin-bottom:8px' }, tagPills(t.tags, 12), el('span', { class: 'muted', style: 'font-size:11px' }, ' tags on the first call seen')) : null, el('pre', {}, t.query || '(not captured yet)'), t.truncated ? el('div', { class: 'muted' }, 'truncated at 10 KB') : null),
el('div', { class: 'grid two', style: 'margin-top:12px' },
panel(`Calls per ${per}`, chart([{ name: 'calls', color: COLORS[0], points: pts.map(([m, v]) => [m, v.calls]) }], { yfmt: fmt.num })),
panel(`Latency per ${per}`,
chart([{ name: 'mean', color: COLORS[2], points: pts.map(([m, v]) => [m, v.calls ? v.total / v.calls : 0]) }, ...qseries], { yfmt: v => fmt.ms(v) }),
el('div', { class: 'muted', style: 'margin-top:6px; font-size:11px' }, latencyNote)),
panel('Wait events while running', table(d.wait_events, [{ key: 'wait_event_type', label: 'type', fmt: v => v || 'CPU' }, { key: 'wait_event', label: 'event', fmt: v => v || '–' }, { key: 'samples', label: 'samples', num: true, fmt: fmt.num }])),
+ panel('Callers (tags seen while running)', table(d.callers, [
+ { key: 'tags', label: 'tags', render: r => tagPills(r.tags, 8) }, { key: 'source', label: 'source', fmt: v => v === 'activity' ? 'activity samples' : 'statement log' },
+ { key: 'samples', label: 'samples', num: true, fmt: fmt.num }, { key: 'share_pct', label: 'share', num: true, render: r => el('span', {}, el('span', { class: 'bar', style: `width:${Math.min(100, r.share_pct || 0)}px` }), ' ', fmt.pct(r.share_pct)) },
+ ], { empty: 'no tagged samples in range (queries need a /* key=value */ comment)' })),
),
- el('div', { style: 'margin-top:12px' }, panel('Slowest logged samples', table(d.slowest_samples, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'log_stream', label: 'instance' }, { key: 'usename', label: 'user' }, { key: 'duration_ms', label: 'duration', num: true, fmt: fmt.ms }, { key: 'query', label: 'statement', render: r => queryCell(r.query) }]))),
+ el('div', { style: 'margin-top:12px' }, panel('Slowest logged samples', table(d.slowest_samples, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'log_stream', label: 'instance' }, { key: 'usename', label: 'user' }, { key: 'duration_ms', label: 'duration', num: true, fmt: fmt.ms }, { key: 'tags', label: 'tags', render: r => tagPills(r.tags, 4) }, { 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 }, { key: 'query', label: 'statement', render: r => queryCell(r.query) }]))),
el('div', { style: 'margin-top:12px' }, panel('Execution plans (Aurora plan stats)', d.plans.length ? d.plans.map(p => el('details', { open: '' }, el('summary', {}, `plan ${p.planid} · ${p.plan_type} · calls ${fmt.num(p.calls)} · total ${fmt.ms(p.total_ms)} · captured ${fmt.ago(p.plan_captured_time)}`), el('pre', {}, p.explain_plan || ''))) : el('div', { class: 'empty' }, 'no plans (aurora_stat_plans is Aurora-only)'))),
el('div', { style: 'margin-top:12px' }, panel('auto_explain plans from the log', d.logged_plans.length ? d.logged_plans.map(p => el('details', {}, el('summary', {}, `${fmt.ts(p.log_time)} · ${fmt.ms(p.duration_ms)} · ${p.datname}`), el('pre', {}, JSON.stringify(p.plan, null, 2)))) : el('div', { class: 'empty' }, 'none in range'))),
];
@@ -266,7 +312,7 @@
el('div', { style: 'margin-top:12px' }, panel('Long-running / waiting / idle-in-transaction sessions', table(d.sessions, [
{ key: 'pid', label: 'pid', num: true }, { key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'application_name', label: 'app' }, { key: 'state', label: 'state' },
{ key: 'wait_event_type', label: 'wait', fmt: (v, r) => v ? `${v}:${r.wait_event}` : 'CPU' }, { key: 'query_age_s', label: 'query age', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'xact_age_s', label: 'xact age', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'blocked_by', label: 'blocked by' },
- { key: 'query', label: 'query', render: r => queryCell(r.query) },
+ { key: 'query', label: 'query', render: queryLabel },
], { empty: 'no interesting sessions right now' }))),
d.memory_hogs.length ? el('div', { style: 'margin-top:12px' }, panel('Backends over 64 MB (Aurora memory contexts)', table(d.memory_hogs, [{ key: 'pid', label: 'pid', num: true }, { key: 'usename', label: 'user' }, { key: 'allocated_bytes', label: 'allocated', num: true, fmt: fmt.bytes }, { key: 'top_context', label: 'largest context' }, { key: 'query', label: 'query', render: r => queryCell(r.query) }]))) : null,
];
@@ -362,9 +408,9 @@
panel('Errors grouped', table(d.summary, [{ key: 'class', label: 'class' }, { key: 'sqlstate', label: 'sqlstate', cls: 'mono' }, { key: 'message', label: 'message' }, { key: 'n', label: 'count', num: true, fmt: fmt.num }])),
),
el('div', { style: 'margin-top:12px' }, panel('Recent errors', table(d.recent, [
- { key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'level', label: 'level', render: r => el('span', { class: r.level === 'ERROR' ? 'warn' : 'err' }, r.level) }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'message', label: 'message' }, { key: 'statement', label: 'statement', render: r => queryCell(r.statement) },
+ { key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'level', label: 'level', render: r => el('span', { class: r.level === 'ERROR' ? 'warn' : 'err' }, r.level) }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'message', label: 'message' }, { key: 'statement', label: 'statement', render: r => el('span', {}, tagPills(r.tags, 3), queryCell(r.statement)) },
], { empty: 'no errors in range' }))),
- el('div', { style: 'margin-top:12px' }, panel('Largest temp-file spills', table(d.temp_files, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'size_bytes', label: 'size', num: true, fmt: fmt.bytes }, { key: 'statement', label: 'statement', render: r => queryCell(r.statement) }], { empty: 'none (needs log_temp_files)' }))),
+ el('div', { style: 'margin-top:12px' }, panel('Largest temp-file spills', table(d.temp_files, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'size_bytes', label: 'size', num: true, fmt: fmt.bytes }, { key: 'statement', label: 'statement', render: r => el('span', {}, tagPills(r.tags, 3), queryCell(r.statement)) }], { empty: 'none (needs log_temp_files)' }))),
];
};