: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): index statement log rows by fingerprint and query id (#100678)
Nick Best80d44846ff1f
diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rsindex 59c8c0cb98cd..48b20605fafa 100644--- a/rust/pgapi/src/queries.rs+++ b/rust/pgapi/src/queries.rs@@ -175,16 +175,17 @@ pub async fn query_detail(&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+ // 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.+ let quantile_sql = format!(+ "WITH d AS (+ SELECT {bucket} AS bucket, duration_ms, {weight} AS wFROM 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')),+ AND (query_id = $2 OR 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+ 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_allFROM d)SELECT bucket, count(*)::bigint AS samples,count(*) FILTER (WHERE duration_ms < $6::float8 OR $6::float8 <= 0)::bigint AS sampled,@@ -193,34 +194,42 @@ pub async fn query_detail(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?+ 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)+ );+ 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![], vec![])};- let slow_samples = opt(db, "SELECT log_time, log_stream, datname, usename, duration_ms, left(query, 500) AS query+ 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)) AND kind NOT IN ('parse', 'bind')- ORDER BY duration_ms DESC LIMIT 10", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ AND (query_id = $2 OR 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_msFROM cur_query_plans p WHERE p.server_id = $1 AND p.queryid = $2 ORDER BY calls DESC NULLS LAST", &[&server, &queryid, &from, &to]).await?;let logged_plans = opt(db, "SELECT log_time, datname, duration_ms, plan FROM ts_log_plans 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 5", &[&server, &queryid, &from, &to, &fingerprint]).await?;+ AND (query_id = $2 OR fingerprint = $5) ORDER BY duration_ms DESC LIMIT 5", &[&server, &queryid, &from, &to, &fingerprint]).await?;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(diff --git a/rust/pgcollector/DESIGN.md b/rust/pgcollector/DESIGN.mdindex c982558c84e0..a86955a20040 100644--- a/rust/pgcollector/DESIGN.md+++ b/rust/pgcollector/DESIGN.md@@ -203,8 +203,11 @@ daily partitions created ahead by the collector's sink on startup and hourly,old partitions dropped by `retention_days` (default 14, per-collector overridevia `[sink.retention]`). Columns: `server_id`,`instance`, `datname` (nullable for cluster scope), `collected_at`, `interval_seconds`, key-columns, then metric columns. Index on `(server_id, collected_at)` and on key-columns + time for the hot ones.+columns, then metric columns. Index on `(server_id, collected_at)`; a snapshot can+declare extra `(server_id, <cols>, collected_at)` indexes (`Snapshot.indexes`). On a+table that already has partitions the index is created `ON ONLY` the parent, and a+background task (retried by the hourly maintenance) builds the per-partition indexes+`CONCURRENTLY` and attaches them, so inserts are never blocked.**Current state** `cur_<collector>` — upsert by identity, with `first_seen`,`last_seen`, `content_hash`. Snapshot diffs append to `events(server_id,diff --git a/rust/pgcollector/src/collector.rs b/rust/pgcollector/src/collector.rsindex 94271ff472e8..cb9628256b4f 100644--- a/rust/pgcollector/src/collector.rs+++ b/rust/pgcollector/src/collector.rs@@ -99,6 +99,10 @@ pub struct Snapshot {/// Written by the sink after the primary rows.#[serde(default)]pub aux: Vec<Snapshot>,+ /// Extra indexes for a `ts_` table, one column list each, built as+ /// `(server_id, <cols>, collected_at)`.+ #[serde(default)]+ pub indexes: Vec<Vec<String>>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/rust/pgcollector/src/collectors/declarative.rs b/rust/pgcollector/src/collectors/declarative.rsindex 1d0a3a04094d..3dfca2e81468 100644--- a/rust/pgcollector/src/collectors/declarative.rs+++ b/rust/pgcollector/src/collectors/declarative.rs@@ -184,6 +184,7 @@ impl Collector for SqlCollector {rows,events,aux: vec![],+ indexes: vec![],},state,))diff --git a/rust/pgcollector/src/collectors/logs.rs b/rust/pgcollector/src/collectors/logs.rsindex 09b202d410ef..cf7a56a75edc 100644--- a/rust/pgcollector/src/collectors/logs.rs+++ b/rust/pgcollector/src/collectors/logs.rs@@ -141,7 +141,11 @@ impl Collector for Logs {}extra.assemblers.retain(|_, a| a.pending.is_some());- let mk = |name: &str, key: Vec<&str>, rows: Vec<Row>, types: BTreeMap<String, String>| {+ let mk = |name: &str,+ key: Vec<&str>,+ rows: Vec<Row>,+ types: BTreeMap<String, String>,+ indexes: Vec<Vec<String>>| {Snapshot {collector: name.into(),kind: Kind::Gauge,@@ -153,10 +157,21 @@ impl Collector for Logs {rows,events: vec![],aux: vec![],+ indexes,}};+ // pgapi looks statements up by fingerprint (RDS cannot log %Q, so query_id is+ // usually NULL) or by query id.+ let by_statement = || {+ vec![+ vec!["fingerprint".to_string()],+ vec!["query_id".to_string()],+ ]+ };let mut aux = Vec::new();- if !out.durations.is_empty() {+ // Always emitted, even empty, so an existing table gets its indexes without+ // waiting for a new statement.+ {aux.push(mk("query_durations",vec![],@@ -169,9 +184,10 @@ impl Collector for Logs {("duration_ms", "double precision"),("query", "text"),]),+ by_statement(),));}- if !out.plans.is_empty() {+ {aux.push(mk("log_plans",vec![],@@ -185,6 +201,7 @@ impl Collector for Logs {("plan", "jsonb"),("query", "text"),]),+ by_statement(),));}if !out.autovacuum.is_empty() {@@ -193,6 +210,7 @@ impl Collector for Logs {vec![],out.autovacuum,types_of(&[("log_time", "timestamptz"), ("aggressive", "boolean")]),+ vec![],));}if !out.checkpoints.is_empty() {@@ -201,6 +219,7 @@ impl Collector for Logs {vec![],out.checkpoints,types_of(&[("log_time", "timestamptz")]),+ vec![],));}if !out.temp_files.is_empty() {@@ -215,6 +234,7 @@ impl Collector for Logs {("size_bytes", "bigint"),("statement", "text"),]),+ vec![],));}if !out.errors.is_empty() {@@ -230,6 +250,7 @@ impl Collector for Logs {("statement", "text"),("detail", "text"),]),+ vec![],));}@@ -245,7 +266,13 @@ impl Collector for Logs {r}).collect();- let mut snap = mk("logs", vec![], counts, types_of(&[("count", "bigint")]));+ let mut snap = mk(+ "logs",+ vec![],+ counts,+ types_of(&[("count", "bigint")]),+ vec![],+ );snap.events = out.events;snap.aux = aux;Ok((@@ -273,6 +300,7 @@ impl Logs {rows: vec![],events: vec![],aux: vec![],+ indexes: vec![],},State {collected_at: Some(cx.now),diff --git a/rust/pgcollector/src/collectors/statements.rs b/rust/pgcollector/src/collectors/statements.rsindex c035209124e5..c1407880ff13 100644--- a/rust/pgcollector/src/collectors/statements.rs+++ b/rust/pgcollector/src/collectors/statements.rs@@ -59,6 +59,7 @@ pub fn empty(rows: vec![],events: vec![],aux: vec![],+ indexes: vec![],},State {collected_at: Some(cx.now),@@ -167,6 +168,7 @@ pub async fn collect(rows: text_rows,events: vec![],aux: vec![],+ indexes: vec![],});}@@ -183,6 +185,7 @@ pub async fn collect(rows: deltas,events,aux,+ indexes: vec![],},state,))diff --git a/rust/pgcollector/src/sink/postgres.rs b/rust/pgcollector/src/sink/postgres.rsindex ab7d677b25d5..bb14f7d5eaa3 100644--- a/rust/pgcollector/src/sink/postgres.rs+++ b/rust/pgcollector/src/sink/postgres.rs@@ -18,6 +18,8 @@ pub struct PostgresSink {retention_by_collector: BTreeMap<String, u32>,/// table → known columns, so we only hit the catalog when a new column shows up.schema_cache: Mutex<BTreeMap<String, HashSet<String>>>,+ /// Tables whose declared indexes this process already ensured.+ indexed: Mutex<HashSet<String>>,}/// Columns the sink owns. A collector row carrying one of these (e.g. `datname` from@@ -80,6 +82,7 @@ impl PostgresSink {retention_days: cfg.retention_days,retention_by_collector: cfg.retention.clone(),schema_cache: Mutex::new(BTreeMap::new()),+ indexed: Mutex::new(HashSet::new()),};sink.migrate().await?;sink.maintain().await?;@@ -154,6 +157,9 @@ impl PostgresSink {if !exists {self.create_table(c, table, snap, &wanted).await?;}+ if snap.kind != Kind::Snapshot && !snap.indexes.is_empty() {+ self.ensure_indexes(c, table, &snap.indexes).await?;+ }let cols = c.query("SELECT column_name FROM information_schema.columns WHERE table_name = $1",@@ -232,6 +238,42 @@ impl PostgresSink {.unwrap_or(self.retention_days)}+ /// Parent-only index: no build on existing partitions, which would hold a lock on+ /// the table for the whole build. New partitions inherit it; old ones get theirs+ /// concurrently in the background, and the parent turns valid once all are attached.+ async fn ensure_indexes(+ &self,+ c: &deadpool_postgres::Client,+ table: &str,+ indexes: &[Vec<String>],+ ) -> Result<()> {+ if !self.indexed.lock().unwrap().insert(table.to_string()) {+ return Ok(());+ }+ for cols in indexes {+ c.batch_execute(&format!(+ "BEGIN; SELECT pg_advisory_xact_lock(hashtext('pgcollector:{table}')); \+ CREATE INDEX IF NOT EXISTS {} ON ONLY {table} ({}); COMMIT;",+ index_name(table, cols),+ index_cols(cols)+ ))+ .await+ .with_context(|| format!("indexing {table}"))?;+ }+ self.spawn_backfill(table);+ Ok(())+ }++ /// Background, because a `CONCURRENTLY` build of a large partition takes minutes.+ fn spawn_backfill(&self, table: &str) {+ let (pool, table) = (self.pool.clone(), table.to_string());+ tokio::spawn(async move {+ if let Err(e) = backfill_partition_indexes(&pool, &table).await {+ tracing::warn!(table, error = %format!("{e:#}"), "partition index backfill failed");+ }+ });+ }+async fn ensure_partitions(&self, c: &deadpool_postgres::Client, table: &str) -> Result<()> {let today = Utc::now().date_naive();for d in -1..=2i64 {@@ -379,13 +421,30 @@ impl Sink for PostgresSink {).await?;}- if snap.rows.is_empty() {- return Ok(());- }let table = match snap.kind {Kind::Snapshot => format!("cur_{}", snap.collector),_ => format!("ts_{}", snap.collector),};+ if snap.rows.is_empty() {+ // An existing table gets its declared indexes from the first snapshot of+ // this process, rows or not, rather than waiting for the next row.+ if snap.kind != Kind::Snapshot+ && !snap.indexes.is_empty()+ && !self.indexed.lock().unwrap().contains(&table)+ {+ let exists = c+ .query_opt(+ "SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = $1",+ &[&table],+ )+ .await?+ .is_some();+ if exists {+ self.ensure_indexes(&c, &table, &snap.indexes).await?;+ }+ }+ return Ok(());+ }self.ensure_table(&c, &table, snap).await?;match snap.kind {Kind::Snapshot => self.write_cur(&c, &table, snap).await,@@ -477,10 +536,99 @@ impl Sink for PostgresSink {}}}+ // Parent indexes still invalid: a backfill that a restart or an error cut short.+ let unfinished = c+ .query(+ "SELECT DISTINCT x.indrelid::regclass::text FROM pg_index x \+ JOIN pg_class t ON t.oid = x.indrelid \+ WHERE t.relkind = 'p' AND t.relname LIKE 'ts\\_%' AND NOT x.indisvalid",+ &[],+ )+ .await?;+ for row in unfinished {+ self.spawn_backfill(&row.get::<_, String>(0));+ }Ok(())}}+/// Attach a partition index for every partition the table's invalid parent indexes+/// still lack, one at a time: two concurrent builds on the same partition deadlock.+/// Runs on a connection taken out of the pool and held for the whole job, so the+/// advisory lock that keeps a second collector process off the table is released+/// however the job ends.+async fn backfill_partition_indexes(pool: &Pool, table: &str) -> Result<()> {+ let c = deadpool_postgres::Object::take(pool.get().await?);+ let locked: bool = c+ .query_one(+ "SELECT pg_try_advisory_lock(hashtext('pgcollector:backfill:' || $1))",+ &[&table],+ )+ .await?+ .get(0);+ if !locked {+ return Ok(());+ }+ let parents = c+ .query(+ "SELECT i.relname, array_agg(a.attname::text ORDER BY k.ord) \+ FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid \+ JOIN LATERAL unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord) ON true \+ JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = k.attnum \+ WHERE x.indrelid = $1::text::regclass AND NOT x.indisvalid \+ GROUP BY i.relname",+ &[&table],+ )+ .await?;+ for parent_row in parents {+ let parent: String = parent_row.get(0);+ let cols: Vec<String> = parent_row.get(1);+ let suffix = parent+ .strip_prefix(table)+ .with_context(|| format!("index {parent} is not named after {table}"))?;+ let missing = c+ .query(+ "SELECT p.inhrelid::regclass::text FROM pg_inherits p \+ WHERE p.inhparent = $1::text::regclass AND NOT EXISTS ( \+ SELECT 1 FROM pg_inherits i JOIN pg_index x ON x.indexrelid = i.inhrelid \+ WHERE i.inhparent = $2::text::regclass AND x.indrelid = p.inhrelid) \+ ORDER BY 1 DESC",+ &[&table, &parent],+ )+ .await?;+ for row in missing {+ let part: String = row.get(0);+ let child = format!("{part}{suffix}");+ tracing::info!(partition = part, index = child, "building partition index");+ // A build that failed part-way leaves an invalid index under this name.+ c.batch_execute(&format!("DROP INDEX CONCURRENTLY IF EXISTS {child}"))+ .await?;+ c.batch_execute(&format!(+ "CREATE INDEX CONCURRENTLY {child} ON {part} ({})",+ cols.iter().map(|c| q(c)).collect::<Vec<_>>().join(", ")+ ))+ .await+ .with_context(|| format!("building {child}"))?;+ c.batch_execute(&format!("ALTER INDEX {parent} ATTACH PARTITION {child}"))+ .await?;+ }+ }+ Ok(())+}++fn index_name(table: &str, cols: &[String]) -> String {+ format!("{table}_{}_idx", cols.join("_"))+}++fn index_cols(cols: &[String]) -> String {+ std::iter::once("server_id")+ .chain(cols.iter().map(String::as_str))+ .chain(std::iter::once("collected_at"))+ .map(q)+ .collect::<Vec<_>>()+ .join(", ")+}+fn q(ident: &str) -> String {format!("\"{}\"", ident.replace('"', "\"\""))}@@ -531,6 +679,7 @@ mod tests {retention_days: 14,retention_by_collector: BTreeMap::from([("query_durations".to_string(), 7)]),schema_cache: Mutex::new(BTreeMap::new()),+ indexed: Mutex::new(HashSet::new()),};assert_eq!(sink.retention_days_for("ts_query_durations"), 7);assert_eq!(sink.retention_days_for("ts_query_stats"), 14);