Skip to content

: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.

feat(pgcollector): store statement text once per fingerprint (#100679)

Nick Bestcbf23e1b4067
diff --git a/rust/pgapi/src/queries.rs b/rust/pgapi/src/queries.rs
index 48b20605fafa..da2abe494bd8 100644
--- a/rust/pgapi/src/queries.rs
+++ b/rust/pgapi/src/queries.rs
@@ -217,10 +217,12 @@ pub async fn query_detail(
};
let slow_samples = opt(
db,
- "SELECT log_time, log_stream, datname, usename, duration_ms, left(query, 500) AS query
- 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')
- ORDER BY duration_ms DESC LIMIT 10",
+ "SELECT d.log_time, d.log_stream, d.datname, d.usename, d.duration_ms, left(t.query, 500) AS query
+ FROM ts_query_durations d
+ LEFT JOIN cur_query_texts t ON t.server_id = d.server_id AND t.instance = d.instance AND t.datname = coalesce(d.datname, '') AND t.fingerprint = d.fingerprint
+ WHERE d.server_id = $1 AND d.collected_at >= $3 AND d.collected_at < $4
+ AND (d.query_id = $2 OR d.fingerprint = $5) AND d.kind NOT IN ('parse', 'bind')
+ ORDER BY d.duration_ms DESC LIMIT 10",
&[&server, &queryid, &from, &to, &fingerprint],
)
.await?;
diff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.md
index d451c4932efe..31e9fb55c06e 100644
--- a/rust/pgcollector/docs/deploy.md
+++ b/rust/pgcollector/docs/deploy.md
@@ -102,6 +102,8 @@ for the values. Key points:
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`.
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/migrations/0002_query_texts.sql b/rust/pgcollector/migrations/0002_query_texts.sql
new file mode 100644
index 000000000000..b96fe694a156
--- /dev/null
+++ b/rust/pgcollector/migrations/0002_query_texts.sql
@@ -0,0 +1,14 @@
+-- Statement text per fingerprint, joined by pgapi from ts_query_durations. Created
+-- here rather than on first data so the join works before the log collector has
+-- seen a statement.
+
+CREATE TABLE IF NOT EXISTS cur_query_texts (
+ server_id text NOT NULL,
+ instance text NOT NULL DEFAULT 'writer',
+ datname text NOT NULL DEFAULT '',
+ first_seen timestamptz NOT NULL,
+ last_seen timestamptz NOT NULL,
+ fingerprint bigint NOT NULL,
+ query text,
+ PRIMARY KEY (server_id, instance, datname, fingerprint)
+);
diff --git a/rust/pgcollector/src/collectors/logs.rs b/rust/pgcollector/src/collectors/logs.rs
index cf7a56a75edc..829c67dca9f5 100644
--- a/rust/pgcollector/src/collectors/logs.rs
+++ b/rust/pgcollector/src/collectors/logs.rs
@@ -16,7 +16,7 @@ use crate::collector::*;
use crate::config::{LogSource, LogsConfig};
use crate::logs::{
self,
- fingerprint::{fingerprint, redact_literals},
+ fingerprint::{fingerprint, redact_literals, representative_text},
parse::*,
};
use anyhow::Result;
@@ -182,11 +182,32 @@ impl Collector for Logs {
("query_id", "bigint"),
("fingerprint", "bigint"),
("duration_ms", "double precision"),
- ("query", "text"),
]),
by_statement(),
));
}
+ if !out.texts.is_empty() {
+ let rows = out
+ .texts
+ .into_iter()
+ .map(|((db, fp), q)| {
+ let mut r = Row::new();
+ r.insert("datname".into(), db.map(Value::Text).unwrap_or(Value::Null));
+ r.insert("fingerprint".into(), Value::Int(fp));
+ r.insert("query".into(), Value::Text(q));
+ r
+ })
+ .collect();
+ let mut snap = mk(
+ "query_texts",
+ vec!["fingerprint"],
+ rows,
+ types_of(&[("fingerprint", "bigint"), ("query", "text")]),
+ vec![],
+ );
+ snap.kind = Kind::Snapshot;
+ aux.push(snap);
+ }
{
aux.push(mk(
"log_plans",
@@ -320,6 +341,9 @@ fn types_of(t: &[(&str, &str)]) -> BTreeMap<String, String> {
#[derive(Default)]
struct Outputs {
durations: Vec<Row>,
+ /// (datname, fingerprint) → statement text, stored once per fingerprint in
+ /// `cur_query_texts` rather than on every duration row.
+ texts: BTreeMap<(Option<String>, i64), String>,
plans: Vec<Row>,
autovacuum: Vec<Row>,
checkpoints: Vec<Row>,
@@ -414,14 +438,16 @@ impl Outputs {
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(),
- query
- .as_deref()
- .map(|q| Value::Int(fingerprint(q)))
- .unwrap_or(Value::Null),
+ fp.map(Value::Int).unwrap_or(Value::Null),
);
- r.insert("query".into(), opt(&query));
+ 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 {
@@ -538,7 +564,7 @@ mod tests {
"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",
+ "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 */",
];
for l in lines {
if let Some(e) = asm.push(&re, l) {
@@ -548,6 +574,15 @@ mod tests {
if let Some(e) = asm.flush() {
out.record("writer", &e);
}
+ assert!(out.durations.iter().all(|r| !r.contains_key("query")));
+ assert!(out.texts.values().any(|q| q == "select count(*) from t"));
+ assert_eq!(
+ out.texts
+ .keys()
+ .map(|(db, _)| db.as_deref())
+ .collect::<Vec<_>>(),
+ [Some("app"), Some("app")]
+ );
let kinds: Vec<&Value> = out.durations.iter().map(|r| &r["kind"]).collect();
assert_eq!(
kinds,
diff --git a/rust/pgcollector/src/logs/fingerprint.rs b/rust/pgcollector/src/logs/fingerprint.rs
index bb99a5286fbf..d404aef0300c 100644
--- a/rust/pgcollector/src/logs/fingerprint.rs
+++ b/rust/pgcollector/src/logs/fingerprint.rs
@@ -38,6 +38,16 @@ pub fn redact_literals(sql: &str) -> String {
STRING.replace_all(sql, "'?'").into_owned()
}
+/// The representative text for a fingerprint. Comments are dropped like the
+/// fingerprint drops them: they do not change the shape, so any client could
+/// otherwise rewrite the text shown for every statement of that shape.
+pub fn representative_text(sql: &str) -> String {
+ COMMENT
+ .replace_all(&redact_literals(sql), " ")
+ .trim()
+ .to_string()
+}
+
/// Bump when `normalize` changes so stored query fingerprints are recomputed.
pub const FINGERPRINT_VERSION: u32 = 2;
@@ -54,6 +64,15 @@ pub fn fingerprint(sql: &str) -> i64 {
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn representative_text_redacts_literals_that_contain_comment_markers() {
+ assert_eq!(
+ representative_text("select 'sk-secret--suffix', 'x /* y */ z' from t -- note"),
+ "select '?', '?' from t"
+ );
+ }
+
#[test]
fn literals_params_and_lists_normalise_together() {
let a = fingerprint("SELECT * FROM t WHERE id = 42 AND name = 'bob' AND x IN (1, 2, 3)");
diff --git a/rust/pgcollector/src/sink/postgres.rs b/rust/pgcollector/src/sink/postgres.rs
index bb14f7d5eaa3..5514a0e21b80 100644
--- a/rust/pgcollector/src/sink/postgres.rs
+++ b/rust/pgcollector/src/sink/postgres.rs
@@ -52,8 +52,13 @@ fn datname_for(snap: &Snapshot, row: &crate::collector::Row) -> Option<String> {
})
}
-const MIGRATIONS: &[(&str, &str)] =
- &[("0001_base", include_str!("../../migrations/0001_base.sql"))];
+const MIGRATIONS: &[(&str, &str)] = &[
+ ("0001_base", include_str!("../../migrations/0001_base.sql")),
+ (
+ "0002_query_texts",
+ include_str!("../../migrations/0002_query_texts.sql"),
+ ),
+];
impl PostgresSink {
pub async fn connect(cfg: &SinkConfig) -> Result<Self> {
@@ -536,6 +541,14 @@ impl Sink for PostgresSink {
}
}
}
+ // Shared statement text has no partitions: expire rows unseen for longer than
+ // the duration rows that reference them are kept.
+ let text_days = self.retention_days_for("ts_query_durations") as i32;
+ c.execute(
+ "DELETE FROM cur_query_texts WHERE last_seen < now() - make_interval(days => $1)",
+ &[&text_days],
+ )
+ .await?;
// Parent indexes still invalid: a backfill that a restart or an error cut short.
let unfinished = c
.query(