: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): draw latency quantiles on the query detail chart (#95497)
Nick Bestd9c5589a1b49
diff --git a/rust/pgapi/src/api.rs b/rust/pgapi/src/api.rsindex 6f1eb75d65e1..5dc784f6df83 100644--- a/rust/pgapi/src/api.rs+++ b/rust/pgapi/src/api.rs@@ -100,16 +100,8 @@ async fn top_queries(State(s): S, Path(server): Path<String>, Query(p): Query<To.await?,))}-async fn query_detail(- State(s): S,- Path((server, queryid)): Path<(String, i64)>,- Query(r): Query<Range>,-) -> R {- let (f, t) = r.resolve()?;- Ok(Json(q::query_detail(&s.db, &server, queryid, f, t).await?))-}#[derive(Deserialize)]-struct WaitsQ {+struct BucketQ {#[serde(flatten)]range: Range,#[serde(default = "d_bucket")]@@ -118,7 +110,17 @@ struct WaitsQ {fn d_bucket() -> String {"1m".into()}-async fn waits(State(s): S, Path(server): Path<String>, Query(p): Query<WaitsQ>) -> R {+async fn query_detail(+ State(s): S,+ Path((server, queryid)): Path<(String, i64)>,+ Query(p): Query<BucketQ>,+) -> R {+ let (f, t) = p.range.resolve()?;+ Ok(Json(+ q::query_detail(&s.db, &server, queryid, 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?))}diff --git a/rust/pgapi/src/db.rs b/rust/pgapi/src/db.rsindex 0edfc46c63d9..8ce99d2dfe67 100644--- a/rust/pgapi/src/db.rs+++ b/rust/pgapi/src/db.rs@@ -19,7 +19,7 @@ pub struct Db {impl Db {pub async fn connect(url: &str) -> Result<Self> {let mut cfg: tokio_postgres::Config = url.parse().context("parsing PGAPI_DATABASE_URL")?;- cfg.ssl_mode(tokio_postgres::config::SslMode::Require);+ cfg.ssl_mode(tls_policy(&cfg));let tls = tls_connector();let mgr = Manager::from_config(cfg,@@ -164,6 +164,16 @@ pub fn row_to_json(r: &tokio_postgres::Row) -> Result<Value> {Ok(Value::Object(m))}+/// TLS is required unless the parsed URL carries `sslmode=disable` (local dev against+/// a plain Postgres). RDS always offers TLS, so deployed URLs carry no parameter.+fn tls_policy(cfg: &tokio_postgres::Config) -> tokio_postgres::config::SslMode {+ use tokio_postgres::config::SslMode;+ match cfg.get_ssl_mode() {+ SslMode::Disable => SslMode::Disable,+ _ => SslMode::Require,+ }+}+fn tls_connector() -> tokio_postgres_rustls::MakeRustlsConnect {let mut roots = rustls::RootCertStore::empty();let native = rustls_native_certs::load_native_certs();diff --git a/rust/pgapi/src/mcp.rs b/rust/pgapi/src/mcp.rsindex f4b3dcd7456e..0d76ba4f751d 100644--- a/rust/pgapi/src/mcp.rs+++ b/rust/pgapi/src/mcp.rs@@ -67,6 +67,8 @@ pub struct QueryArg {pub server: String,pub queryid: i64,pub since: Option<String>,+ /// Series bucket width: 10s, 1m (default), 5m or 1h.+ pub bucket: Option<String>,}#[derive(Deserialize, schemars::JsonSchema)]pub struct DbArg {@@ -158,16 +160,23 @@ impl PgMcp {.map_err(err)?)}#[tool(- description = "Everything about one query id: text, per-minute series, latency percentiles from sampled logs (p50/p90/p95/p99), slowest samples, execution plans (Aurora plan stats and auto_explain), wait events."+ 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.")]async fn query_detail(&self,Parameters(a): Parameters<QueryArg>,) -> Result<CallToolResult, McpError> {let (f, t) = range(&a.since)?;- ok(q::query_detail(&self.state.db, &a.server, a.queryid, f, t)- .await- .map_err(err)?)+ ok(q::query_detail(+ &self.state.db,+ &a.server,+ a.queryid,+ f,+ t,+ a.bucket.as_deref().unwrap_or("1m"),+ )+ .await+ .map_err(err)?)}#[tool(description = "Wait-event breakdown over time (average active sessions by wait event, sampled every 10s) plus exact Aurora wait counts/times when available."diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rsindex ca23c85471fe..59c8c0cb98cd 100644--- a/rust/pgapi/src/queries.rs+++ b/rust/pgapi/src/queries.rs@@ -9,6 +9,13 @@ use serde_json::{json, Value};type Ts = DateTime<Utc>;+/// Read a bigint back out of a row `Db::query` produced. Values past 2^53 come back+/// as strings so JavaScript keeps them intact; query ids and fingerprints always do.+fn json_i64(v: &Value) -> Option<i64> {+ v.as_i64()+ .or_else(|| v.as_str().and_then(|s| s.parse().ok()))+}+/// Query a table that may not exist yet (created on first data by the collector).async fn opt(db: &Db,@@ -115,26 +122,99 @@ async fn has_column(db: &Db, table: &str, col: &str) -> bool {.unwrap_or(false)}-pub async fn query_detail(db: &Db, server: &str, queryid: i64, from: Ts, to: Ts) -> Result<Value> {+/// Bucket width for time series; unknown values fall back to one minute.+fn bucket_interval(bucket: &str) -> &'static str {+ match bucket {+ "10s" => "10 seconds",+ "5m" => "5 minutes",+ "1h" => "1 hour",+ _ => "1 minute",+ }+}++fn bucket_expr(col: &str, interval: &str) -> String {+ format!("to_timestamp(floor(extract(epoch FROM {col}) / extract(epoch FROM interval '{interval}')) * extract(epoch FROM interval '{interval}'))")+}++pub async fn query_detail(+ db: &Db,+ server: &str,+ queryid: i64,+ from: Ts,+ to: Ts,+ bucket: &str,+) -> Result<Value> {+ let interval = bucket_interval(bucket);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 fingerprint: Option<i64> = texts.first().and_then(|t| t["fingerprint"].as_i64());- let series = opt(db, "SELECT date_trunc('minute', collected_at) AS minute, instance, datname,+ 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_hitFROM 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", &[&server, &queryid, &from, &to]).await?;- let quantiles = opt(db, "SELECT count(*)::bigint AS samples,- percentile_cont(0.5) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p50,- percentile_cont(0.9) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p90,- percentile_cont(0.95) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p95,- percentile_cont(0.99) WITHIN GROUP (ORDER BY duration_ms)::float8 AS p99,- max(duration_ms)::float8 AS max_ms, min(log_time) AS first_sample, max(log_time) AS last_sample- FROM ts_query_durations WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4- AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5))", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ GROUP BY 1, 2, 3 ORDER BY 1", b = bucket_expr("collected_at", interval)), &[&server, &queryid, &from, &to]).await?;+ let sampling = log_sampling_settings(db, server).await?;+ // With sampling off, the only logged durations are the always-logged slow tail,+ // which says nothing about the distribution; skip the quantiles entirely.+ let quantiles_available = sampling.enabled;+ // A statement over log_min_duration_statement is always logged, a sampled one+ // stands for 1/rate statements. Weighting by that makes the quantiles unbiased+ // above the sample floor; the log line itself does not say which case it was.+ // Extended-protocol statements log parse and bind durations as separate lines;+ // only the execute line is comparable to pg_stat_statements execution time.+ // `sampled` counts the rows the sampler chose; a bucket holding only the+ // always-logged tail must not pass the UI's per-quantile sample floor.+ let weight =+ "CASE WHEN $6::float8 > 0 AND duration_ms >= $6::float8 THEN 1.0 ELSE 1.0 / $7::float8 END";+ let quantile_params: [&(dyn tokio_postgres::types::ToSql + Sync); 7] = [+ &server,+ &queryid,+ &from,+ &to,+ &fingerprint,+ &sampling.hard_threshold_ms,+ &sampling.rate,+ ];+ let quantile_sql = |bucket_col: &str| {+ format!(+ "WITH d AS (+ SELECT {bucket_col} AS bucket, duration_ms, {weight} AS w+ FROM ts_query_durations WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4+ AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5))+ AND kind NOT IN ('parse', 'bind')),+ r AS (+ SELECT bucket, duration_ms, sum(w) OVER (PARTITION BY bucket ORDER BY duration_ms) AS cw,+ sum(w) OVER (PARTITION BY bucket) AS tw+ FROM d)+ SELECT bucket, count(*)::bigint AS samples,+ count(*) FILTER (WHERE duration_ms < $6::float8 OR $6::float8 <= 0)::bigint AS sampled,+ min(duration_ms) FILTER (WHERE cw >= 0.5 * tw)::float8 AS p50,+ min(duration_ms) FILTER (WHERE cw >= 0.9 * tw)::float8 AS p90,+ min(duration_ms) FILTER (WHERE cw >= 0.95 * tw)::float8 AS p95,+ min(duration_ms) FILTER (WHERE cw >= 0.99 * tw)::float8 AS p99,+ max(duration_ms)::float8 AS max_ms+ FROM r GROUP BY bucket ORDER BY bucket"+ )+ };+ let latency_series = if quantiles_available {+ opt(+ db,+ &quantile_sql(&bucket_expr("log_time", interval)),+ &quantile_params,+ )+ .await?+ } else {+ vec![]+ };+ let quantiles = if quantiles_available {+ opt(db, &quantile_sql("NULL::timestamptz"), &quantile_params).await?+ } else {+ vec![]+ };let slow_samples = opt(db, "SELECT log_time, log_stream, datname, usename, duration_ms, left(query, 500) AS queryFROM ts_query_durations WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4- AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5)) ORDER BY duration_ms DESC LIMIT 10", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ AND (query_id = $2 OR ($5::bigint IS NOT NULL AND fingerprint = $5)) AND kind NOT IN ('parse', 'bind')+ ORDER BY duration_ms DESC LIMIT 10", &[&server, &queryid, &from, &to, &fingerprint]).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@@ -144,23 +224,53 @@ pub async fn query_detail(db: &Db, server: &str, queryid: i64, from: Ts, to: Ts)let waits = opt(db, "SELECT wait_event_type, wait_event, sum(backends)::bigint AS samples FROM ts_activity_samplesWHERE server_id = $1 AND query_id = $2 AND collected_at >= $3 AND collected_at < $4 GROUP BY 1, 2 ORDER BY 3 DESC LIMIT 10", &[&server, &queryid, &from, &to]).await?;Ok(- json!({ "queryid": queryid, "texts": texts, "series": series, "latency_from_logs": quantiles.into_iter().next(), "slowest_samples": slow_samples,+ json!({ "queryid": queryid, "bucket": interval, "texts": texts, "series": series, "latency_series": latency_series,+ "latency_from_logs": quantiles.into_iter().next().filter(|q| json_i64(&q["samples"]).unwrap_or(0) > 0),+ "log_sampling": sampling, "slowest_samples": slow_samples,"plans": aurora_plans, "logged_plans": logged_plans, "wait_events": waits }),)}-pub async fn wait_events(db: &Db, server: &str, from: Ts, to: Ts, bucket: &str) -> Result<Value> {- let b = match bucket {- "10s" => "10 seconds",- "5m" => "5 minutes",- "1h" => "1 hour",- _ => "1 minute",+/// 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)]+struct LogSampling {+ /// `log_min_duration_sample`: statements below this are never sampled (-1 = off).+ sample_floor_ms: f64,+ /// `log_statement_sample_rate`, as configured.+ rate: f64,+ /// `log_min_duration_statement`: statements at or above this are always logged (-1 = off).+ hard_threshold_ms: f64,+ /// Sampling is on: a floor is set and the rate is above zero.+ enabled: bool,+}++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+ 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 {+ rows.iter()+ .find(|r| r["name"] == name)+ .and_then(|r| r["setting"].as_str()?.parse().ok())+ .unwrap_or(default)};- let sql = format!("SELECT to_timestamp(floor(extract(epoch FROM collected_at) / extract(epoch FROM interval '{b}')) * extract(epoch FROM interval '{b}')) AS bucket,+ let rate = get("log_statement_sample_rate", 1.0);+ let sample_floor_ms = get("log_min_duration_sample", -1.0);+ Ok(LogSampling {+ sample_floor_ms,+ rate,+ hard_threshold_ms: get("log_min_duration_statement", -1.0),+ enabled: sample_floor_ms >= 0.0 && rate > 0.0,+ })+}++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,round(avg(backends)::numeric, 2)::float8 AS avg_active_sessionsFROM ts_activity_samples WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 AND state = 'active'- GROUP BY 1, 2, 3, 4 ORDER BY 1");+ GROUP BY 1, 2, 3, 4 ORDER BY 1", b = bucket_expr("collected_at", bucket_interval(bucket)));let sampled = opt(db, &sql, &[&server, &from, &to]).await?;let measured = opt(db, "SELECT instance, type_name, event_name, sum(waits)::bigint AS waits, sum(wait_time)::bigint AS wait_time_usFROM ts_aurora_system_waits WHERE server_id = $1 AND collected_at >= $2 AND collected_at < $3 GROUP BY 1, 2, 3 ORDER BY 5 DESC LIMIT 30", &[&server, &from, &to]).await?;@@ -409,7 +519,18 @@ pub async fn schema_of_stats_db(db: &Db) -> Result<Value> {#[cfg(test)]mod tests {- use super::denied_function;+ use super::{denied_function, json_i64};+ use serde_json::json;++ #[test]+ fn bigints_read_back_from_number_or_string() {+ assert_eq!(json_i64(&json!(42)), Some(42));+ assert_eq!(+ json_i64(&json!("-9200948535353843818")),+ Some(-9200948535353843818)+ );+ assert_eq!(json_i64(&json!(null)), None);+ }#[test]fn denylist_catches_side_effecting_calls() {diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.htmlindex b63a313b26e6..e78c930121a9 100644--- a/rust/pgapi/src/ui/index.html+++ b/rust/pgapi/src/ui/index.html@@ -139,10 +139,10 @@const queryCell = q => el('span', { class: 'q', title: q || '' }, q || el('span', { class: 'muted' }, '(text not captured)'));// ---------- simple SVG line chart ----------- // series: [{name, color, points: [[Date, number]]}]+ // series: [{name, color, points: [[Date, number | null]]}]; a null y breaks the line.function chart(series, { yfmt = v => fmt.dec(v, 1) } = {}) {const W = 800, H = 140, P = { l: 48, r: 8, t: 8, b: 20 };- const all = series.flatMap(s => s.points);+ 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]);const x0 = Math.min(...xs), x1 = Math.max(...xs) || x0 + 1, y1 = Math.max(...ys, 0) || 1;@@ -154,11 +154,15 @@for (const [i, x] of [x0, (x0 + x1) / 2, x1].entries()) { const t = n('text', { x: X(x), y: H - 4, 'text-anchor': i === 0 ? 'start' : i === 1 ? 'middle' : 'end', fill: '#8b93a1', 'font-size': 10 }); t.textContent = fmt.time(new Date(x)); svg.append(t); }for (const s of series) {const pts = [...s.points].sort((a, b) => a[0] - b[0]);- svg.append(n('path', { d: pts.map((p, i) => (i ? 'L' : 'M') + X(+p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1)).join(' '), fill: 'none', stroke: s.color, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' }));+ 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; }+ 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))));}const COLORS = ['#7aa2f7', '#6cc38b', '#e0af68', '#f7768e', '#bb9af7', '#7dcfff', '#ff9e64', '#9ece6a'];+ const bucketFor = range => range === '15m' ? '10s' : range === '7d' ? '1h' : range === '24h' ? '5m' : '1m';+ const BUCKET_LABEL = { '10s': '10 seconds', '1m': 'minute', '5m': '5 minutes', '1h': 'hour' };// ---------- pages ----------const pages = {};@@ -218,19 +222,31 @@pages.query = async () => {const qid = state.params.queryid;- const d = await api(`/servers/${state.server}/queries/${qid}`, { since: state.range });+ const bucket = bucketFor(state.range);+ const d = await api(`/servers/${state.server}/queries/${qid}`, { since: state.range, bucket });const t = d.texts[0] || {};- const byMin = {};- for (const r of d.series) { const k = r.minute; (byMin[k] ||= { calls: 0, total: 0 }); byMin[k].calls += r.calls || 0; byMin[k].total += r.total_ms || 0; }- const pts = Object.entries(byMin).map(([m, v]) => [new Date(m), v]);- const lat = d.latency_from_logs || {};+ 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; }+ const pts = Object.entries(byBucket).map(([m, v]) => [new Date(m), v]);+ const lat = d.latency_from_logs;+ const per = BUCKET_LABEL[bucket] || bucket;+ // A quantile needs roughly 1/(1-q) samples before it is more than the bucket's max, so each line skips buckets below its own floor.+ // Buckets below a line's floor become null points, which chart() draws as gaps rather than bridging.+ const QUANTILES = [['p50', COLORS[0], 5], ['p90', COLORS[4], 20], ['p99', COLORS[3], 100]];+ const qseries = lat ? QUANTILES.map(([k, color, min]) => ({ name: k, color, points: (d.latency_series || []).map(r => [new Date(r.bucket), r.sampled >= min ? r[k] : null]) })).filter(s => s.points.some(p => p[1] != null)) : [];+ const samp = d.log_sampling || {};+ const latencyNote = lat+ ? `${fmt.num(lat.samples)} sampled statements in range (${fmt.dec(samp.rate * 100, 1)}% sample${samp.sample_floor_ms > 0 ? ` of statements over ${fmt.ms(samp.sample_floor_ms)}` : ''}) · range p50 ${fmt.ms(lat.p50)} · p90 ${fmt.ms(lat.p90)} · p99 ${fmt.ms(lat.p99)} · max ${fmt.ms(lat.max_ms)}`+ : samp.enabled === false ? 'mean only: statement sampling is off on this server (log_min_duration_sample / log_statement_sample_rate)'+ : '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),el('div', { class: 'grid two', style: 'margin-top:12px' },- panel('Calls per minute', chart([{ name: 'calls', color: COLORS[0], points: pts.map(([m, v]) => [m, v.calls]) }], { yfmt: fmt.num })),- panel('Mean time per minute', chart([{ name: 'mean ms', color: COLORS[2], points: pts.map(([m, v]) => [m, v.calls ? v.total / v.calls : 0]) }], { yfmt: v => fmt.ms(v) })),- panel('Latency from sampled statement log', lat.samples ? el('div', { class: 'grid tiles' }, tile('samples', fmt.num(lat.samples)), tile('p50', fmt.ms(lat.p50)), tile('p90', fmt.ms(lat.p90)), tile('p95', fmt.ms(lat.p95)), tile('p99', fmt.ms(lat.p99)), tile('max', fmt.ms(lat.max_ms))) : el('div', { class: 'empty' }, 'no sampled durations in this range (needs log_min_duration_sample and the logs collector)')),+ 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 }])),),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) }]))),@@ -257,7 +273,7 @@};pages.waits = async () => {- const d = await api(`/servers/${state.server}/waits`, { since: state.range, bucket: state.range === '15m' ? '10s' : state.range === '7d' ? '1h' : state.range === '24h' ? '5m' : '1m' });+ const d = await api(`/servers/${state.server}/waits`, { since: state.range, bucket: bucketFor(state.range) });const byEv = {};for (const r of d.sampled) { const k = `${r.wait_event_type}:${r.wait_event}`; (byEv[k] ||= []).push([new Date(r.bucket), r.avg_active_sessions]); }const top = Object.entries(byEv).map(([k, pts]) => [k, pts.reduce((a, p) => a + p[1], 0), pts]).sort((a, b) => b[1] - a[1]).slice(0, 8);diff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.mdindex 445583ff9ede..b69676d57bd4 100644--- a/rust/pgcollector/docs/deploy.md+++ b/rust/pgcollector/docs/deploy.md@@ -36,11 +36,12 @@ Nothing here requires a parameter-group change or a reboot.`aurora_compute_plan_id` (default on, 14.10+/15.5+) must stay on for`aurora_plans` and `plan_id` in activity samples.-Parameter-group niceties (dynamic, no reboot; both optional): append `%Q` to-`log_line_prefix` so log rows join `cur_queries` by query id instead of text-fingerprint; the log sampling, lock-wait and CloudWatch-export settings the-logs collector relies on are already set fleet-wide. Clusters that don't-preload `auto_explain` simply produce no `ts_log_plans`.+Parameter-group niceties (dynamic, no reboot): the log sampling, lock-wait and+CloudWatch-export settings the logs collector relies on are already set+fleet-wide. RDS and Aurora refuse to modify `log_line_prefix`, so there is no+`%Q` (query id) on log lines; the collector joins log rows to `cur_queries` by+text fingerprint instead. Clusters that don't preload `auto_explain` simply+produce no `ts_log_plans`.### Load profile on the monitored cluster@@ -115,7 +116,7 @@ Parameter-group settings that make this worthwhile (mostly already set):|---|---|---|| `log_min_duration_sample` / `log_statement_sample_rate` | `1000` / `0.01` | sampled per-statement durations → p50/p95/p99 || `log_min_duration_statement` | `10000` | every slow statement |-| `log_line_prefix` | RDS default + `%Q` | **query id on every line** so log rows join `cur_queries` exactly; without it we join on a text fingerprint |+| `log_line_prefix` | RDS default (not modifiable) | no query id on log lines, so log rows join `cur_queries` on a text fingerprint; self-managed Postgres can append `%Q` for an exact join || `auto_explain.*` | json, sample 0.01 | plans for sampled slow statements → `ts_log_plans` || `log_lock_waits`, `log_temp_files=0`, `log_checkpoints`, `log_autovacuum_min_duration=0` | on | events + `ts_temp_files`, `ts_checkpoints`, `ts_autovacuum_runs` |diff --git a/rust/pgcollector/src/collectors/statements.rs b/rust/pgcollector/src/collectors/statements.rsindex c2c01a9f71bd..11640127d163 100644--- a/rust/pgcollector/src/collectors/statements.rs+++ b/rust/pgcollector/src/collectors/statements.rs@@ -4,6 +4,7 @@use crate::collector::*;use crate::collectors::declarative::{column_types, row_to_values};+use crate::logs::fingerprint::FINGERPRINT_VERSION;use anyhow::{Context, Result};use serde::{Deserialize, Serialize};use std::collections::BTreeSet;@@ -21,6 +22,9 @@ pub struct Extra {pub known_ids: BTreeSet<i64>,pub dealloc: Option<i64>,pub warned_missing: bool,+ /// `FINGERPRINT_VERSION` the known ids were fingerprinted with.+ #[serde(default)]+ pub fingerprint_version: u32,}pub struct Source<'a> {@@ -183,8 +187,16 @@ pub async fn collect(}pub fn load_extra(prev: Option<&State>) -> Extra {- prev.map(|p| serde_json::from_value(p.extra.clone()).unwrap_or_default())- .unwrap_or_default()+ let mut extra: Extra = prev+ .map(|p| serde_json::from_value(p.extra.clone()).unwrap_or_default())+ .unwrap_or_default();+ // A normaliser change makes every stored fingerprint stale; forgetting the ids+ // makes the next ticks re-fetch their text and upsert fresh fingerprints.+ if extra.fingerprint_version != FINGERPRINT_VERSION {+ extra.known_ids.clear();+ extra.fingerprint_version = FINGERPRINT_VERSION;+ }+ extra}pub async fn pgss_installed(cx: &CollectCtx<'_>) -> bool {diff --git a/rust/pgcollector/src/logs/fingerprint.rs b/rust/pgcollector/src/logs/fingerprint.rsindex ac123fc4d055..bb99a5286fbf 100644--- a/rust/pgcollector/src/logs/fingerprint.rs+++ b/rust/pgcollector/src/logs/fingerprint.rs@@ -7,9 +7,14 @@ use once_cell::sync::Lazy;use regex::Regex;static COMMENT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?s)/\*.*?\*/|--[^\n]*").unwrap());-static STRING: Lazy<Regex> = Lazy::new(|| Regex::new(r"'(?:[^']|'')*'").unwrap());+// Escape/bit/hex string prefixes (E'..', B'..', X'..') go with the literal.+static STRING: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"(?i)\b[ebx]'(?:[^']|'')*'|'(?:[^']|'')*'").unwrap());static PARAM: Lazy<Regex> = Lazy::new(|| Regex::new(r"\$\d+").unwrap());static NUMBER: Lazy<Regex> = Lazy::new(|| Regex::new(r"\b\d+(?:\.\d+)?\b").unwrap());+// pg_stat_statements turns these constants into $n like any other literal.+static KEYWORD_CONST: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"(?i)\b(?:true|false|null)\b").unwrap());static LIST: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\s*\?(?:\s*,\s*\?)*\s*\)").unwrap());static WS: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s+").unwrap());static PUNCT: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s*([=<>!,()+\-*/])\s*").unwrap());@@ -19,6 +24,7 @@ pub fn normalize(sql: &str) -> String {let s = STRING.replace_all(&s, "?");let s = PARAM.replace_all(&s, "?");let s = NUMBER.replace_all(&s, "?");+ let s = KEYWORD_CONST.replace_all(&s, "?");let s = LIST.replace_all(&s, "(?)");let s = WS.replace_all(&s, " ");let s = PUNCT.replace_all(&s, "$1");@@ -32,6 +38,9 @@ pub fn redact_literals(sql: &str) -> String {STRING.replace_all(sql, "'?'").into_owned()}+/// Bump when `normalize` changes so stored query fingerprints are recomputed.+pub const FINGERPRINT_VERSION: u32 = 2;+/// FNV-1a 64 of the normalised text, as i64 so it fits a bigint column.pub fn fingerprint(sql: &str) -> i64 {let mut h: u64 = 0xcbf29ce484222325;@@ -55,6 +64,18 @@ mod tests {assert_ne!(a, fingerprint("select * from t where id = 1"));}+ #[test]+ fn keyword_constants_and_escape_strings_match_pgss_text() {+ // Logged statement text versus what pg_stat_statements stores for it.+ let logged = r#"UPDATE "t" SET "path" = E'a\nb', "shortcut" = false, "created_by_id" = NULL, "meta" = '{}'::jsonb WHERE "t"."id" = 7"#;+ let pgss = r#"UPDATE "t" SET "path" = $1, "shortcut" = $2, "created_by_id" = $3, "meta" = $4::jsonb WHERE "t"."id" = $5"#;+ assert_eq!(fingerprint(logged), fingerprint(pgss));+ assert_eq!(+ fingerprint("select * from t where enabled = TRUE and x = B'101'"),+ fingerprint("select * from t where enabled = $1 and x = $2")+ );+ }+#[test]fn redaction_keeps_shape_and_drops_values() {assert_eq!(