: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
fix(pgcollector): gate pg_stat_statements columns on the extension version (#99511)
Nick Best50f694c2eeaf
diff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.mdindex b69676d57bd4..e22f3e73c09f 100644--- a/rust/pgcollector/docs/deploy.md+++ b/rust/pgcollector/docs/deploy.md@@ -27,6 +27,10 @@ Nothing here requires a parameter-group change or a reboot.cluster-wide stats from the **maintenance database (`postgres`)**. Run`CREATE EXTENSION IF NOT EXISTS pg_stat_statements` there (DDL user) if ithasn't been. This is the only step that is genuinely required.+ A cluster upgraded in place keeps the old extension definition, so also run+ `ALTER EXTENSION pg_stat_statements UPDATE` there after a major upgrade. The+ collector reads the columns the installed version has and emits one+ `pgss_stale` event (plus a warning log) until the extension catches up.* `pg_proctab` — optional. Not installed anywhere today; `CREATE EXTENSIONpg_proctab` in the maintenance database enables `system_cpu`,`system_memory`, `system_disk`, `backend_cpu`. Until then those four log onediff --git a/rust/pgcollector/src/collector.rs b/rust/pgcollector/src/collector.rsindex ed94159e5c4a..94271ff472e8 100644--- a/rust/pgcollector/src/collector.rs+++ b/rust/pgcollector/src/collector.rs@@ -125,8 +125,17 @@ pub struct State {pub struct Capabilities {pub aurora: bool,pub aurora_version: Option<String>,- /// Extensions installed in the connected database.- pub extensions: std::collections::HashSet<String>,+ /// Extensions installed in the connected database, with their `extversion`.+ pub extensions: std::collections::HashMap<String, String>,+}++impl Capabilities {+ /// None when the extension is absent or its version string is not `major.minor`.+ pub fn pgss_version(&self) -> Option<(u32, u32)> {+ let raw = self.extensions.get("pg_stat_statements")?;+ let (major, minor) = raw.split_once('.')?;+ Some((major.parse().ok()?, minor.parse().ok()?))+ }}/// What a collector needs from a target before it can run.@@ -145,7 +154,7 @@ impl Requirements {return Some("requires Aurora".into());}if let Some(e) = &self.extension {- if !caps.extensions.contains(e) {+ if !caps.extensions.contains_key(e) {return Some(format!("requires extension {e} (CREATE EXTENSION {e})"));}}diff --git a/rust/pgcollector/src/collectors/aurora_plans.rs b/rust/pgcollector/src/collectors/aurora_plans.rsindex 20542db7f81a..c6e9ec8d606e 100644--- a/rust/pgcollector/src/collectors/aurora_plans.rs+++ b/rust/pgcollector/src/collectors/aurora_plans.rs@@ -47,7 +47,7 @@ impl Collector for AuroraPlans {} else {""};- let cols = statements::pgss_columns(cx.pg_version);+ let cols = statements::pgss_columns(statements::pgss_version(cx));let src = Source {name: "aurora_plans",aux_name: "query_plans",diff --git a/rust/pgcollector/src/collectors/query_stats.rs b/rust/pgcollector/src/collectors/query_stats.rsindex ca69a0c92c0d..8e4c1da35c3f 100644--- a/rust/pgcollector/src/collectors/query_stats.rs+++ b/rust/pgcollector/src/collectors/query_stats.rs@@ -64,7 +64,11 @@ impl Collector for QueryStats {} else {("pg_stat_statements(false)", "")};- let cols = statements::pgss_columns(cx.pg_version);+ let ext = statements::pgss_version(cx);+ let bundled = statements::bundled_pgss_version(cx.pg_version);+ let report_stale = ext < bundled && !extra.warned_stale;+ extra.warned_stale = ext < bundled;+ let cols = statements::pgss_columns(ext);let src = Source {name: "query_stats",aux_name: "queries",@@ -83,7 +87,20 @@ impl Collector for QueryStats {),text_key: &["queryid", "datname"],};- statements::collect(&src, cx, prev, extra, true).await+ let (mut snap, state) = statements::collect(&src, cx, prev, extra, true).await?;+ if report_stale {+ let installed = format!("{}.{}", ext.0, ext.1);+ let bundled = format!("{}.{}", bundled.0, bundled.1);+ tracing::warn!(server = cx.target.server_id, instance = cx.target.instance, installed, bundled,+ "pg_stat_statements is behind the server's bundled version; run ALTER EXTENSION pg_stat_statements UPDATE in the maintenance database");+ snap.events.push(Event {+ kind: "pgss_stale".into(),+ subject: cx.target.instance.clone(),+ before: Some(serde_json::json!({ "extversion": installed })),+ after: Some(serde_json::json!({ "extversion": bundled, "hint": "run ALTER EXTENSION pg_stat_statements UPDATE in the maintenance database; newer columns are skipped until then" })),+ });+ }+ Ok((snap, state))}}diff --git a/rust/pgcollector/src/collectors/statements.rs b/rust/pgcollector/src/collectors/statements.rsindex 11640127d163..898fdb16ce03 100644--- a/rust/pgcollector/src/collectors/statements.rs+++ b/rust/pgcollector/src/collectors/statements.rs@@ -22,6 +22,8 @@ pub struct Extra {pub known_ids: BTreeSet<i64>,pub dealloc: Option<i64>,pub warned_missing: bool,+ #[serde(default)]+ pub warned_stale: bool,/// `FINGERPRINT_VERSION` the known ids were fingerprinted with.#[serde(default)]pub fingerprint_version: u32,@@ -200,27 +202,47 @@ pub fn load_extra(prev: Option<&State>) -> Extra {}pub async fn pgss_installed(cx: &CollectCtx<'_>) -> bool {- cx.caps.extensions.contains("pg_stat_statements")+ cx.caps.extensions.contains_key("pg_stat_statements")+}++pub fn bundled_pgss_version(pg_version: u32) -> (u32, u32) {+ match pg_version / 10000 {+ ..=13 => (1, 8),+ 14 => (1, 9),+ 15 | 16 => (1, 10),+ 17 => (1, 11),+ _ => (1, 12),+ }}-/// Column list shared by pg_stat_statements and its Aurora superset, version-gated.-pub fn pgss_columns(v: u32) -> String {- let toplevel = if v >= 140000 {+/// Falls back to the server's bundled version when the probe could not read `extversion`.+pub fn pgss_version(cx: &CollectCtx<'_>) -> (u32, u32) {+ cx.caps+ .pgss_version()+ .unwrap_or_else(|| bundled_pgss_version(cx.pg_version))+}++/// The view's columns follow the installed extension version, not the server version.+/// A cluster upgraded in place keeps its old `pg_stat_statements` definition until+/// `ALTER EXTENSION pg_stat_statements UPDATE` runs, so a PG15 server can still expose+/// the 1.8 column set.+pub fn pgss_columns(ext: (u32, u32)) -> String {+ let toplevel = if ext >= (1, 9) {"s.toplevel"} else {"true AS toplevel"};- let io_time = if v >= 170000 {+ let io_time = if ext >= (1, 11) {"s.shared_blk_read_time AS blk_read_time, s.shared_blk_write_time AS blk_write_time"} else {"s.blk_read_time, s.blk_write_time"};- let temp_io = if v >= 150000 {+ let temp_io = if ext >= (1, 10) {"s.temp_blk_read_time, s.temp_blk_write_time,"} else {""};- let jit = if v >= 150000 {+ let jit = if ext >= (1, 10) {"s.jit_functions, s.jit_generation_time,"} else {""@@ -242,3 +264,61 @@ pub fn pgss_columns(v: u32) -> String {pub const AURORA_COLUMNS: &str = "s.storage_blks_read, s.storage_blk_read_time, s.orcache_blks_hit, s.orcache_blk_read_time,s.total_exec_peakmem, s.max_exec_peakmem, s.total_plan_peakmem, s.max_plan_peakmem,";++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pgss_columns_follow_the_extension_version_not_the_server() {+ type Case = ((u32, u32), &'static [&'static str], &'static [&'static str]);+ let cases: &[Case] = &[+ (+ (1, 8),+ &["true AS toplevel", "s.blk_read_time"],+ &["s.toplevel", "s.jit_functions", "s.temp_blk_read_time"],+ ),+ (+ (1, 9),+ &["s.toplevel", "s.blk_read_time"],+ &["s.jit_functions", "s.temp_blk_read_time"],+ ),+ (+ (1, 10),+ &[+ "s.toplevel",+ "s.jit_functions",+ "s.temp_blk_read_time",+ "s.blk_read_time",+ ],+ &["s.shared_blk_read_time"],+ ),+ (+ (1, 11),+ &["s.toplevel", "s.jit_functions", "s.shared_blk_read_time"],+ &["s.blk_read_time,"],+ ),+ ];+ for (ext, present, absent) in cases {+ let cols = pgss_columns(*ext);+ for p in *present {+ assert!(cols.contains(p), "{ext:?} should select {p}");+ }+ for a in *absent {+ assert!(!cols.contains(a), "{ext:?} should not select {a}");+ }+ }+ }++ #[test]+ fn extversion_minor_compares_numerically() {+ let mut caps = Capabilities::default();+ caps.extensions+ .insert("pg_stat_statements".into(), "1.10".into());+ assert_eq!(caps.pgss_version(), Some((1, 10)));+ assert!(caps.pgss_version() > Some((1, 9)));+ caps.extensions+ .insert("pg_stat_statements".into(), "".into());+ assert_eq!(caps.pgss_version(), None);+ }+}diff --git a/rust/pgcollector/src/pg.rs b/rust/pgcollector/src/pg.rsindex 06fe7b47db7b..dea78964efc7 100644--- a/rust/pgcollector/src/pg.rs+++ b/rust/pgcollector/src/pg.rs@@ -165,10 +165,11 @@ pub async fn capabilities(client: &Client) -> Result<crate::collector::Capabilit}}for r in client- .query("SELECT extname FROM pg_extension", &[])+ .query("SELECT extname, extversion FROM pg_extension", &[]).await?{- caps.extensions.insert(r.get::<_, String>(0));+ caps.extensions+ .insert(r.get::<_, String>(0), r.get::<_, String>(1));}Ok(caps)}