: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(pgcollector): per-minute latency histograms for query quantiles (#101249)
Nick Best814ecd87f0ce
diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rsindex da2abe494bd8..60218848bd4c 100644--- a/rust/pgapi/src/queries.rs+++ b/rust/pgapi/src/queries.rs@@ -145,6 +145,12 @@ pub async fn query_detail(bucket: &str,) -> Result<Value> {let interval = bucket_interval(bucket);+ // Latency histograms are per minute, so the finest latency bucket is a minute.+ let latency_interval = if interval == "10 seconds" {+ "1 minute"+ } 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 fingerprint: Option<i64> = texts.first().and_then(|t| json_i64(&t["fingerprint"]));let series = opt(db, &format!("SELECT {b} AS bucket, instance, datname,@@ -154,67 +160,55 @@ pub async fn query_detail(FROM ts_query_stats WHERE server_id = $1 AND queryid = $2 AND collected_at >= $3 AND collected_at < $4GROUP 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,- ];- // One scan serves both the per-bucket series and the whole-range row (bucket NULL):- // the cumulative weights are windowed twice, once per bucket and once overall.+ // 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+ // mirror pgcollector's histogram module (array ordinal i starts at+ // 10^((i-1)/20 - 2) ms); a quantile reports its bucket's upper edge, capped at the+ // largest duration seen. One pass serves the per-bucket series and the+ // whole-range row (bucket NULL).let quantile_sql = format!(- "WITH d AS (- SELECT {bucket} 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 fingerprint = $5) AND kind NOT IN ('parse', 'bind')),+ "WITH l AS (+ SELECT {bucket} AS bucket, max_ms, sampled_counts, logged_counts, sample_rate+ FROM ts_query_latency WHERE server_id = $1 AND collected_at >= $3 AND collected_at < $4+ AND (query_id = $2 OR fingerprint = $5)),+ h AS (+ SELECT bucket, 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 bucket, duration_ms,- sum(w) OVER (PARTITION BY bucket ORDER BY duration_ms) AS cw, sum(w) OVER (PARTITION BY bucket) AS tw,- sum(w) OVER (ORDER BY duration_ms) AS cw_all, sum(w) OVER () AS tw_all- 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- UNION ALL- SELECT NULL, count(*)::bigint,- count(*) FILTER (WHERE duration_ms < $6::float8 OR $6::float8 <= 0)::bigint,- min(duration_ms) FILTER (WHERE cw_all >= 0.5 * tw_all)::float8,- min(duration_ms) FILTER (WHERE cw_all >= 0.9 * tw_all)::float8,- min(duration_ms) FILTER (WHERE cw_all >= 0.95 * tw_all)::float8,- min(duration_ms) FILTER (WHERE cw_all >= 0.99 * tw_all)::float8,- max(duration_ms)::float8- FROM r- ORDER BY bucket NULLS FIRST",- bucket = bucket_expr("log_time", interval)+ SELECT bucket, i, sc, lc, power(10, i / 20.0 - 2) AS hi,+ sum(wc) OVER (PARTITION BY bucket ORDER BY i) AS cw, sum(wc) OVER (PARTITION BY bucket) AS tw,+ sum(wc) OVER (ORDER BY i) AS cw_all, sum(wc) OVER () AS tw_all+ FROM h),+ q AS (+ SELECT bucket, sum(sc + lc)::bigint AS samples, sum(sc)::bigint AS sampled,+ min(hi) FILTER (WHERE cw >= 0.5 * tw) AS p50, min(hi) FILTER (WHERE cw >= 0.9 * tw) AS p90,+ min(hi) FILTER (WHERE cw >= 0.95 * tw) AS p95, min(hi) FILTER (WHERE cw >= 0.99 * tw) AS p99+ FROM r GROUP BY bucket+ UNION ALL+ SELECT NULL, sum(sc + lc)::bigint, sum(sc)::bigint,+ min(hi) FILTER (WHERE cw_all >= 0.5 * tw_all), min(hi) FILTER (WHERE cw_all >= 0.9 * tw_all),+ min(hi) FILTER (WHERE cw_all >= 0.95 * tw_all), min(hi) FILTER (WHERE cw_all >= 0.99 * tw_all)+ FROM r),+ m AS (SELECT bucket, max(max_ms) AS max_ms FROM l GROUP BY GROUPING SETS ((bucket), ()))+ SELECT q.bucket, q.samples, q.sampled,+ least(q.p50, m.max_ms)::float8 AS p50, least(q.p90, m.max_ms)::float8 AS p90,+ 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 ON m.bucket IS NOT DISTINCT FROM q.bucket+ WHERE q.samples > 0+ ORDER BY q.bucket NULLS FIRST",+ bucket = bucket_expr("minute", latency_interval));- let (quantiles, latency_series): (Vec<Value>, Vec<Value>) = if quantiles_available {- opt(db, &quantile_sql, &quantile_params)- .await?- .into_iter()- .partition(|r| r["bucket"].is_null())- } else {- (vec![], vec![])- };+ let (quantiles, latency_series): (Vec<Value>, Vec<Value>) = opt(+ db,+ &quantile_sql,+ &[&server, &queryid, &from, &to, &fingerprint],+ )+ .await?+ .into_iter()+ .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@@ -235,8 +229,9 @@ pub async fn query_detail(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, "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),+ 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,"plans": aurora_plans, "logged_plans": logged_plans, "wait_events": waits }),)diff --git a/rust/pgcollector/DESIGN.md b/rust/pgcollector/DESIGN.mdindex a86955a20040..ff74b0bdf2fd 100644--- a/rust/pgcollector/DESIGN.md+++ b/rust/pgcollector/DESIGN.md@@ -134,7 +134,7 @@ Planned Tier B collectors:| 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` |-| 30s | logs | B | CloudWatch Logs (RDS) or files: `ts_query_durations` (latency quantiles), `ts_log_plans` (auto_explain), `ts_autovacuum_runs`, `ts_checkpoints`, `ts_temp_files`, `ts_log_errors`, `ts_logs` counts, deadlock/lock-wait/cancel events |+| 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/Oand per-query peak memory) and `activity_samples` reads `aurora_stat_activity`@@ -173,7 +173,7 @@ What we do instead:running it and for how long (`active_over_1s`, `active_over_10s`,`max_query_age_s`) — a sampled view of the tail, ASH-style;* real quantiles come from sampled statement logs (phase 4):- `log_min_duration_sample` + `log_statement_sample_rate` → `ts_query_durations`+ `log_min_duration_sample` + `log_statement_sample_rate` → `ts_query_latency` (histograms) and `ts_query_durations` (slow tail)keyed by the same `query_id`, from which the API computes p50/p95/p99.**Cumulative counters** — always stored as per-interval deltas. Rows whose everydiff --git a/rust/pgcollector/deploy/pgcollector.example.toml b/rust/pgcollector/deploy/pgcollector.example.tomlindex 3336ab360098..21e9cf670d77 100644--- a/rust/pgcollector/deploy/pgcollector.example.toml+++ b/rust/pgcollector/deploy/pgcollector.example.toml@@ -26,3 +26,8 @@ databases = ["posthog"][servers.overrides]activity = { interval = "5s" }sizes = { enabled = false }++# [servers.logs]+# source = "cloudwatch"+# log_group = "/aws/rds/cluster/<cluster-id>/postgresql"+# sample_rows_over_ms = 100 # slower statements keep a row of their own; all go in the histogramdiff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.mdindex 31e9fb55c06e..d3d9d3b6aac2 100644--- a/rust/pgcollector/docs/deploy.md+++ b/rust/pgcollector/docs/deploy.md@@ -101,9 +101,13 @@ for the values. Key points:## 3. Logs (statement durations, plans, autovacuum, checkpoints, errors)The `logs` collector reads the Postgres log and writes typed rows —-`ts_query_durations` is where **real per-query latency quantiles** come from.-Duration rows carry a fingerprint of the statement; the text itself is stored once-per fingerprint in `cur_query_texts`.+`ts_query_latency` is where **real per-query latency quantiles** come from: one row+per statement fingerprint and minute holding log-spaced histograms of the sampled+and of the always-logged durations (20 buckets per decade from 0.01 ms to 100 s),+with the sample rate they were collected under, so a statement's cost is+independent of how often it runs and the weighting survives a settings change. Durations at or above `sample_rows_over_ms`+(default 100) also keep their own `ts_query_durations` row for the slowest-samples+view; the statement text itself is stored once per fingerprint in `cur_query_texts`.On Aurora the log is already exported to CloudWatch Logs(`enabled_cloudwatch_logs_exports = ["postgresql"]`), one group per cluster,one stream per instance:diff --git a/rust/pgcollector/src/collector.rs b/rust/pgcollector/src/collector.rsindex cb9628256b4f..e3352ad0e4da 100644--- a/rust/pgcollector/src/collector.rs+++ b/rust/pgcollector/src/collector.rs@@ -38,6 +38,7 @@ pub enum Value {Text(String),Timestamp(DateTime<Utc>),Json(serde_json::Value),+ IntArray(Vec<i32>),}impl Value {@@ -61,6 +62,7 @@ impl Value {Value::Text(_) => "text",Value::Timestamp(_) => "timestamptz",Value::Json(_) => "jsonb",+ Value::IntArray(_) => "integer[]",}}}diff --git a/rust/pgcollector/src/collectors/logs.rs b/rust/pgcollector/src/collectors/logs.rsindex 829c67dca9f5..b6c8338a72cb 100644--- a/rust/pgcollector/src/collectors/logs.rs+++ b/rust/pgcollector/src/collectors/logs.rs@@ -17,6 +17,7 @@ use crate::config::{LogSource, LogsConfig};use crate::logs::{self,fingerprint::{fingerprint, redact_literals, representative_text},+ histogram::Histogram,parse::*,};use anyhow::Result;@@ -117,7 +118,13 @@ impl Collector for Logs {"log ingestion is behind (per-tick budget hit); will catch up over following ticks");}- let mut out = Outputs::default();+ let sampling = log_sampling(cx.conn).await;+ let mut out = Outputs {+ sample_rows_over_ms: cfg.sample_rows_over_ms,+ sample_rate: sampling.rate,+ hard_threshold_ms: sampling.hard_threshold_ms,+ ..Default::default()+ };for (stream, lines) in batch.lines {let asm = extra.assemblers.entry(stream.clone()).or_default();for line in lines {@@ -208,6 +215,54 @@ impl Collector for Logs {snap.kind = Kind::Snapshot;aux.push(snap);}+ {+ let rows = out+ .latency+ .into_iter()+ .map(|((db, fp, qid, minute), h)| {+ let mut r = Row::new();+ r.insert("datname".into(), db.map(Value::Text).unwrap_or(Value::Null));+ r.insert(+ "fingerprint".into(),+ fp.map(Value::Int).unwrap_or(Value::Null),+ );+ r.insert(+ "query_id".into(),+ qid.map(Value::Int).unwrap_or(Value::Null),+ );+ r.insert("minute".into(), Value::Timestamp(minute));+ r.insert("count".into(), Value::Int(h.n));+ r.insert("sum_ms".into(), Value::Float(h.sum_ms));+ r.insert("max_ms".into(), Value::Float(h.max_ms));+ r.insert("sampled_counts".into(), Value::IntArray(h.sampled));+ r.insert("logged_counts".into(), Value::IntArray(h.logged));+ r.insert("sample_rate".into(), Value::Float(out.sample_rate));+ r.insert(+ "hard_threshold_ms".into(),+ Value::Float(out.hard_threshold_ms),+ );+ r+ })+ .collect();+ aux.push(mk(+ "query_latency",+ vec![],+ rows,+ types_of(&[+ ("fingerprint", "bigint"),+ ("query_id", "bigint"),+ ("minute", "timestamptz"),+ ("count", "bigint"),+ ("sum_ms", "double precision"),+ ("max_ms", "double precision"),+ ("sampled_counts", "integer[]"),+ ("logged_counts", "integer[]"),+ ("sample_rate", "double precision"),+ ("hard_threshold_ms", "double precision"),+ ]),+ by_statement(),+ ));+ }{aux.push(mk("log_plans",@@ -332,15 +387,72 @@ impl Logs {}}+struct LogSampling {+ rate: f64,+ /// `log_min_duration_statement` in ms; negative means off.+ hard_threshold_ms: f64,+}++/// A statement at or above `log_min_duration_statement` is always logged; below it,+/// `log_statement_sample_rate` decides. Read per tick, because the log line itself+/// does not say which case it was and the settings can change under us.+async fn log_sampling(conn: &tokio_postgres::Client) -> LogSampling {+ let mut s = LogSampling {+ rate: 1.0,+ hard_threshold_ms: -1.0,+ };+ match conn+ .query(+ // reset_val, not setting: this session quiets its own statements by+ // setting log_min_duration_statement = -1, and that must not count as+ // the server's value.+ "SELECT name, reset_val FROM pg_settings WHERE name IN ('log_statement_sample_rate', 'log_min_duration_statement')",+ &[],+ )+ .await+ {+ Ok(rows) => {+ for r in rows {+ let (name, setting): (String, String) = (r.get(0), r.get(1));+ if let Ok(v) = setting.parse::<f64>() {+ match name.as_str() {+ "log_statement_sample_rate" => s.rate = v,+ "log_min_duration_statement" => s.hard_threshold_ms = v,+ _ => {}+ }+ }+ }+ }+ Err(e) => tracing::warn!(error = %e, "reading log sampling settings; weighting samples 1:1"),+ }+ s+}+fn types_of(t: &[(&str, &str)]) -> BTreeMap<String, String> {t.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()}+type LatencyKey = (+ Option<String>,+ Option<i64>,+ Option<i64>,+ chrono::DateTime<chrono::Utc>,+);+#[derive(Default)]struct Outputs {+ /// Durations below this only count in the histogram; see `LogsConfig`.+ sample_rows_over_ms: f64,+ /// The server's `log_statement_sample_rate` and `log_min_duration_statement`+ /// while these lines were logged; stored with every histogram row so the+ /// weighting survives a settings change.+ sample_rate: f64,+ hard_threshold_ms: f64,durations: Vec<Row>,+ /// (datname, fingerprint, query id, minute) → latency histogram.+ latency: BTreeMap<LatencyKey, Histogram>,/// (datname, fingerprint) → statement text, stored once per fingerprint in/// `cur_query_texts` rather than on every duration row.texts: BTreeMap<(Option<String>, i64), String>,@@ -435,19 +547,33 @@ impl Outputs {if kind == "parse" || kind == "bind" {return;}+ let fp = query.as_deref().map(fingerprint);+ if let (Some(fp), Some(q)) = (fp, &query) {+ self.texts+ .entry((e.db.clone(), fp))+ .or_insert_with(|| representative_text(q).chars().take(MAX_TEXT).collect());+ }+ if let Some(ts) = e.ts {+ let minute = ts+ - chrono::Duration::seconds(ts.timestamp().rem_euclid(60))+ - chrono::Duration::nanoseconds(ts.timestamp_subsec_nanos() as i64);+ let always_logged =+ self.hard_threshold_ms >= 0.0 && duration_ms >= self.hard_threshold_ms;+ self.latency+ .entry((e.db.clone(), fp, e.query_id, minute))+ .or_default()+ .add(duration_ms, always_logged);+ }+ if duration_ms < self.sample_rows_over_ms {+ return;+ }let mut r = Self::base(stream, e);r.insert("duration_ms".into(), Value::Float(duration_ms));r.insert("kind".into(), Value::Text(kind));- let fp = query.as_deref().map(fingerprint);r.insert("fingerprint".into(),fp.map(Value::Int).unwrap_or(Value::Null),);- if let (Some(fp), Some(q)) = (fp, &query) {- self.texts- .entry((e.db.clone(), fp))- .or_insert_with(|| representative_text(q).chars().take(MAX_TEXT).collect());- }self.durations.push(r);}Record::Plan {@@ -559,12 +685,18 @@ mod tests {fn parse_and_bind_durations_are_counted_but_not_stored() {let re = prefix_regex("%t:%r:%u@%d:[%p]:");let mut asm = Assembler::default();- let mut out = Outputs::default();+ let mut out = Outputs {+ sample_rows_over_ms: 100.0,+ sample_rate: 0.1,+ hard_threshold_ms: 200.0,+ ..Default::default()+ };let lines = ["2026-08-27 18:22:49 UTC:10.1.2.3(5000):app@app:[140]:LOG: duration: 0.010 ms parse <unnamed>: select id from t where id = $1","2026-08-27 18:22:49 UTC:10.1.2.3(5000):app@app:[140]:LOG: duration: 0.020 ms bind <unnamed>: select id from t where id = $1","2026-08-27 18:22:49 UTC:10.1.2.3(5000):app@app:[140]:LOG: duration: 1.500 ms execute <unnamed>: select id from t where id = $1",- "2026-08-27 18:22:50 UTC:10.1.2.3(5000):app@app:[141]:LOG: duration: 2.500 ms statement: select count(*) from t /* not stored */",+ "2026-08-27 18:22:59 UTC:10.1.2.3(5000):app@app:[140]:LOG: duration: 3.000 ms execute <unnamed>: select id from t where id = $1",+ "2026-08-27 18:22:50 UTC:10.1.2.3(5000):app@app:[141]:LOG: duration: 250.0 ms statement: select count(*) from t /* not stored */",];for l in lines {if let Some(e) = asm.push(&re, l) {@@ -584,20 +716,26 @@ mod tests {[Some("app"), Some("app")]);let kinds: Vec<&Value> = out.durations.iter().map(|r| &r["kind"]).collect();- assert_eq!(- kinds,- [- &Value::Text("execute".into()),- &Value::Text("statement".into())- ]- );+ assert_eq!(kinds, [&Value::Text("statement".into())]);+ // The 250 ms statement is over the always-log threshold, the executes were sampled.+ let mut hists: Vec<(i64, f64, i32, i32)> = out+ .latency+ .values()+ .map(|h| (h.n, h.max_ms, h.sampled.iter().sum(), h.logged.iter().sum()))+ .collect();+ hists.sort_by(|a, b| a.partial_cmp(b).unwrap());+ assert_eq!(hists, [(1, 250.0, 0, 1), (2, 3.0, 2, 0)]);+ assert!(out+ .latency+ .keys()+ .all(|(_, _, _, minute)| minute.to_rfc3339() == "2026-08-27T18:22:00+00:00"));assert_eq!(out.counts[&("writer".to_string(),"LOG".to_string(),"duration".to_string())],- 4+ 5);}}diff --git a/rust/pgcollector/src/config.rs b/rust/pgcollector/src/config.rsindex e91a90f07ed9..0ef8f2203012 100644--- a/rust/pgcollector/src/config.rs+++ b/rust/pgcollector/src/config.rs@@ -119,10 +119,18 @@ pub struct LogsConfig {/// Must match the server's `log_line_prefix`. RDS default shown.#[serde(default = "default_prefix")]pub log_line_prefix: String,+ /// Statement durations at or above this keep their own `ts_query_durations` row+ /// (for the slowest-samples view); every duration also counts in the per-minute+ /// histogram, which is what the quantiles come from.+ #[serde(default = "default_sample_rows_over_ms")]+ pub sample_rows_over_ms: f64,}fn default_prefix() -> String {"%t:%r:%u@%d:[%p]:".into()}+fn default_sample_rows_over_ms() -> f64 {+ 100.0+}#[derive(Debug, Deserialize, Clone, Default)]pub struct CollectorOverride {@@ -244,6 +252,7 @@ fn servers_from_env(explicit: &[ServerConfig]) -> Vec<ServerConfig> {log_group: Some(v.clone()),region: None,log_line_prefix: prefix,+ sample_rows_over_ms: default_sample_rows_over_ms(),});}}diff --git a/rust/pgcollector/src/logs/histogram.rs b/rust/pgcollector/src/logs/histogram.rsnew file mode 100644index 000000000000..4addecbf659f--- /dev/null+++ b/rust/pgcollector/src/logs/histogram.rs@@ -0,0 +1,95 @@+//! Per-minute latency histograms: a statement's quantiles cost one row of counters+//! per minute however often it runs. Bucket `i` (0-based) covers+//! `[10^(i/20 - 2), 10^((i+1)/20 - 2))` ms, 20 per decade from 0.01 ms to 100 s, plus+//! an overflow bucket; bucket 0 also takes anything smaller. pgapi derives the same+//! edges in SQL from the array ordinal, so the two must move together.++pub const PER_DECADE: usize = 20;+pub const DECADES: usize = 7;+pub const BUCKETS: usize = PER_DECADE * DECADES + 1;+const MIN_EXPONENT: f64 = -2.0;++pub fn bucket_index(ms: f64) -> usize {+ if ms.is_nan() || ms <= 0.0 {+ return 0;+ }+ // Nudged so a duration on an exact edge (10000 ms with 20/decade) lands in the+ // bucket that starts there rather than the one below it.+ let x = ((ms.log10() - MIN_EXPONENT) * PER_DECADE as f64 + 1e-9).floor();+ x.clamp(0.0, (BUCKETS - 1) as f64) as usize+}++#[cfg(test)]+pub fn lower_edge_ms(i: usize) -> f64 {+ 10f64.powf(i as f64 / PER_DECADE as f64 + MIN_EXPONENT)+}++/// Sampled and always-logged durations are counted apart: a sampled one stands for+/// 1/rate statements and an always-logged one for itself, and the two share a+/// bucket whenever `log_min_duration_statement` falls inside it.+#[derive(Debug, Clone, PartialEq)]+pub struct Histogram {+ pub sampled: Vec<i32>,+ pub logged: Vec<i32>,+ pub n: i64,+ pub sum_ms: f64,+ pub max_ms: f64,+}++impl Default for Histogram {+ fn default() -> Self {+ Self {+ sampled: vec![0; BUCKETS],+ logged: vec![0; BUCKETS],+ n: 0,+ sum_ms: 0.0,+ max_ms: 0.0,+ }+ }+}++impl Histogram {+ pub fn add(&mut self, ms: f64, always_logged: bool) {+ let counts = if always_logged {+ &mut self.logged+ } else {+ &mut self.sampled+ };+ counts[bucket_index(ms)] += 1;+ self.n += 1;+ self.sum_ms += ms;+ if ms > self.max_ms {+ self.max_ms = ms;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn edges_are_powers_of_ten_and_thresholds_land_on_them() {+ assert_eq!(bucket_index(0.0), 0);+ assert_eq!(bucket_index(0.005), 0);+ assert_eq!(bucket_index(0.01), 0);+ assert_eq!(bucket_index(9999.9), 119);+ assert_eq!(bucket_index(10000.0), 120);+ assert!((lower_edge_ms(120) - 10000.0).abs() < 1e-6);+ assert_eq!(bucket_index(1e9), BUCKETS - 1);+ assert_eq!(bucket_index(f64::NAN), 0);+ }++ #[test]+ fn histogram_accumulates() {+ let mut h = Histogram::default();+ for ms in [0.4, 0.5] {+ h.add(ms, false);+ }+ h.add(250.0, true);+ assert_eq!(h.n, 3);+ assert_eq!(h.max_ms, 250.0);+ assert_eq!(h.sampled.iter().sum::<i32>(), 2);+ assert_eq!(h.logged[bucket_index(250.0)], 1);+ }+}diff --git a/rust/pgcollector/src/logs/mod.rs b/rust/pgcollector/src/logs/mod.rsindex c1329d3277e4..ee8835312968 100644--- a/rust/pgcollector/src/logs/mod.rs+++ b/rust/pgcollector/src/logs/mod.rs@@ -3,6 +3,7 @@//! collector state.pub mod fingerprint;+pub mod histogram;pub mod parse;use anyhow::{Context, Result};diff --git a/rust/pgcollector/src/sink/postgres.rs b/rust/pgcollector/src/sink/postgres.rsindex 5514a0e21b80..18431af4b65a 100644--- a/rust/pgcollector/src/sink/postgres.rs+++ b/rust/pgcollector/src/sink/postgres.rs@@ -673,6 +673,7 @@ fn to_sql(v: &Value) -> Box<dyn ToSql + Sync + Send> {Value::Text(s) => Box::new(s.clone()),Value::Timestamp(t) => Box::new(*t),Value::Json(j) => Box::new(j.clone()),+ Value::IntArray(v) => Box::new(v.clone()),}}