: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): drop parse and bind rows, add per-collector retention (#100677)
Nick Best01150e160412
diff --git a/rust/pgcollector/DESIGN.md b/rust/pgcollector/DESIGN.mdindex 23bc2bd22721..c982558c84e0 100644--- a/rust/pgcollector/DESIGN.md+++ b/rust/pgcollector/DESIGN.md@@ -200,7 +200,8 @@ Two families:**Time series** `ts_<collector>` — append-only, `PARTITION BY RANGE (collected_at)`,daily partitions created ahead by the collector's sink on startup and hourly,-old partitions dropped by `retention_days` (default 14). Columns: `server_id`,+old partitions dropped by `retention_days` (default 14, per-collector override+via `[sink.retention]`). Columns: `server_id`,`instance`, `datname` (nullable for cluster scope), `collected_at`, `interval_seconds`, keycolumns, then metric columns. Index on `(server_id, collected_at)` and on keycolumns + time for the hot ones.@@ -258,6 +259,8 @@ own stats; database-scoped ones run on the writer unless `per_instance: true`.[sink]database_url = "postgres://pgcollector@stats-host/pgcollector"retention_days = 14+[sink.retention]+query_durations = 7 # per-collector override[defaults]statement_timeout = "5s"diff --git a/rust/pgcollector/deploy/pgcollector.example.toml b/rust/pgcollector/deploy/pgcollector.example.tomlindex 565e0abe4e44..3336ab360098 100644--- a/rust/pgcollector/deploy/pgcollector.example.toml+++ b/rust/pgcollector/deploy/pgcollector.example.toml@@ -2,6 +2,9 @@# TLS is required unless the URL says sslmode=disable (local dev) or sslmode=prefer.database_url = "${PGCOLLECTOR_SINK_URL}"retention_days = 14+# Per-collector overrides, keyed by collector name (the ts_<name> table).+[sink.retention]+query_durations = 7[defaults]statement_timeout = "5s"diff --git a/rust/pgcollector/deploy/values.example.yaml b/rust/pgcollector/deploy/values.example.yamlindex 330bde7a970f..dad49962b452 100644--- a/rust/pgcollector/deploy/values.example.yaml+++ b/rust/pgcollector/deploy/values.example.yaml@@ -82,6 +82,8 @@ configFiles:[sink]database_url = "${PGCOLLECTOR_SINK_URL}"retention_days = 14+ [sink.retention]+ query_durations = 7 # sampled statement log; the biggest table by far[defaults]databases = ["*"] # discover every database on each cluster, keep discoveringdiff --git a/rust/pgcollector/src/collectors/logs.rs b/rust/pgcollector/src/collectors/logs.rsindex 4bc2378b68f4..09b202d410ef 100644--- a/rust/pgcollector/src/collectors/logs.rs+++ b/rust/pgcollector/src/collectors/logs.rs@@ -122,7 +122,7 @@ impl Collector for Logs {let asm = extra.assemblers.entry(stream.clone()).or_default();for line in lines {if let Some(e) = asm.push(&re, &line) {- out.record(&stream, &e, cx);+ out.record(&stream, &e);}}}@@ -134,7 +134,7 @@ impl Collector for Logs {.unwrap_or(true){if let Some(e) = asm.flush() {- out.record(stream, &e, cx);+ out.record(stream, &e);}}}@@ -341,7 +341,7 @@ impl Outputs {r}- fn record(&mut self, stream: &str, e: &Entry, _cx: &CollectCtx<'_>) {+ fn record(&mut self, stream: &str, e: &Entry) {let rec = classify(e);let class = match &rec {Record::Duration { .. } => "duration",@@ -378,6 +378,11 @@ impl Outputs {if query.is_none() && e.query_id.is_none() {return;}+ // Extended-protocol clients log parse and bind separately; only execute+ // is comparable to execution time, and pgapi never reads the other two.+ if kind == "parse" || kind == "bind" {+ return;+ }let mut r = Self::base(stream, e);r.insert("duration_ms".into(), Value::Float(duration_ms));r.insert("kind".into(), Value::Text(kind));@@ -491,3 +496,45 @@ impl Outputs {self.errors.push(r);}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ 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 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",+ ];+ for l in lines {+ if let Some(e) = asm.push(&re, l) {+ out.record("writer", &e);+ }+ }+ if let Some(e) = asm.flush() {+ out.record("writer", &e);+ }+ 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!(+ out.counts[&(+ "writer".to_string(),+ "LOG".to_string(),+ "duration".to_string()+ )],+ 4+ );+ }+}diff --git a/rust/pgcollector/src/config.rs b/rust/pgcollector/src/config.rsindex c1b570ca3c1c..e91a90f07ed9 100644--- a/rust/pgcollector/src/config.rs+++ b/rust/pgcollector/src/config.rs@@ -20,6 +20,10 @@ pub struct SinkConfig {pub database_url: String,#[serde(default = "default_retention")]pub retention_days: u32,+ /// Per-collector retention in days, keyed by collector name (`ts_<name>`);+ /// overrides `retention_days` for that table only.+ #[serde(default)]+ pub retention: BTreeMap<String, u32>,}fn default_retention() -> u32 {14diff --git a/rust/pgcollector/src/sink/postgres.rs b/rust/pgcollector/src/sink/postgres.rsindex 3cb183e543a1..ab7d677b25d5 100644--- a/rust/pgcollector/src/sink/postgres.rs+++ b/rust/pgcollector/src/sink/postgres.rs@@ -15,6 +15,7 @@ use tokio_postgres::types::ToSql;pub struct PostgresSink {pool: Pool,retention_days: u32,+ 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>>>,}@@ -77,6 +78,7 @@ impl PostgresSink {let sink = Self {pool,retention_days: cfg.retention_days,+ retention_by_collector: cfg.retention.clone(),schema_cache: Mutex::new(BTreeMap::new()),};sink.migrate().await?;@@ -222,6 +224,14 @@ impl PostgresSink {Ok(())}+ fn retention_days_for(&self, table: &str) -> u32 {+ table+ .strip_prefix("ts_")+ .and_then(|name| self.retention_by_collector.get(name))+ .copied()+ .unwrap_or(self.retention_days)+ }+async fn ensure_partitions(&self, c: &deadpool_postgres::Client, table: &str) -> Result<()> {let today = Utc::now().date_naive();for d in -1..=2i64 {@@ -444,10 +454,11 @@ impl Sink for PostgresSink {.into_iter().map(|r| r.get(0)).collect();- let cutoff = (Utc::now().date_naive() - CDuration::days(self.retention_days as i64))- .format("%Y%m%d")- .to_string();+ let today = Utc::now().date_naive();for t in &tables {+ let cutoff = (today - CDuration::days(self.retention_days_for(t) as i64))+ .format("%Y%m%d")+ .to_string();self.ensure_partitions(&c, t).await?;let parts = c.query(@@ -503,3 +514,26 @@ fn to_sql(v: &Value) -> Box<dyn ToSql + Sync + Send> {Value::Json(j) => Box::new(j.clone()),}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn retention_override_applies_only_to_its_own_table() {+ let sink = PostgresSink {+ pool: Pool::builder(Manager::new(+ tokio_postgres::Config::new(),+ tokio_postgres::NoTls,+ ))+ .build()+ .unwrap(),+ retention_days: 14,+ retention_by_collector: BTreeMap::from([("query_durations".to_string(), 7)]),+ schema_cache: Mutex::new(BTreeMap::new()),+ };+ assert_eq!(sink.retention_days_for("ts_query_durations"), 7);+ assert_eq!(sink.retention_days_for("ts_query_stats"), 14);+ assert_eq!(sink.retention_days_for("ts_query_durations_extra"), 14);+ }+}