: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): parse query tags out of statements into a tags column (#101971)
Nick Best42074a10fec4
diff --git a/docs/internal/pgcollector.md b/docs/internal/pgcollector.mdindex c5eade2b6379..77eefaa14674 100644--- a/docs/internal/pgcollector.md+++ b/docs/internal/pgcollector.md@@ -17,6 +17,10 @@ live in the crate: [`DESIGN.md`](../../rust/pgcollector/DESIGN.md),- **Output**: partitioned `ts_*` time series, `cur_*` current state, `events`,`collector_runs` in the stats database, daily partitions, `retention_days`.A collector adds columns to its table when its SELECT gains a column.+ Statement-bearing tables carry a `tags` jsonb column parsed from query+ comments (`/* key=value */`); see+ [`docs/query-tags.md`](../../rust/pgcollector/docs/query-tags.md) for the+ accepted shapes and the key vocabulary.- **Load**: every session runs with `statement_timeout = 5s` /`lock_timeout = 1s`; per-collector cost is tabulated in `docs/deploy.md`"Load profile". Per-backend collectors ship off by default.diff --git a/rust/pgcollector/DESIGN.md b/rust/pgcollector/DESIGN.mdindex ff74b0bdf2fd..8aa13d58684e 100644--- a/rust/pgcollector/DESIGN.md+++ b/rust/pgcollector/DESIGN.md@@ -109,7 +109,7 @@ Planned Tier B collectors:| Interval | Module | Tier | Source ||---|---|---|---|-| 10s | activity samples | A | `pg_stat_activity` — counts by (state, wait_event_type, wait_event, query_id, usename, datname); raw rows kept for sessions > 5s or blocked |+| 10s | activity samples | A | `pg_stat_activity` — counts by (state, wait_event_type, wait_event, query_id, query tags, usename, datname); raw rows kept for sessions > 5s or blocked || 10s | lock waits | A | `pg_locks` joined to `pg_blocking_pids()`; only emits when blocking exists || 60s | query stats | B | `pg_stat_statements` deltas keyed by (queryid, userid, dbid, toplevel) || 60s | database stats | A | `pg_stat_database` + `age(datfrozenxid)` |@@ -162,6 +162,15 @@ on the hot path and a second lookup only for unseen ids. A `fingerprint` from`pg_query` normalisation allows grouping the same shape across servers.Literals are stripped in the collector before anything leaves the process.+**Query tags** — key/value pairs in a SQL comment (`/* route='/api/x' */`,+`/* nodejs:PERSONS_WRITE<updatePersonsBatch> */`) name the code path that ran a+statement. They are parsed once in the collector (`src/tags.rs`) and stored as a+`tags` jsonb column on every table that carries statement text: activity samples+and sessions, logged durations, plans, errors and temp files, and `cur_queries`.+`pg_stat_statements` cannot split its counters by tag (comments are not part of+the query id), so per-tag load comes from the sampled sources. Format, vocabulary+and limits are in `docs/query-tags.md`.+**Query latency: what you can and cannot get.** `pg_stat_statements` exposes`calls`, `total`, `min`, `max`, `mean`, `stddev` per query — no per-calldistribution — so per-call quantiles (p95 of query X) cannot be derived from it.diff --git a/rust/pgcollector/collectors/activity_samples.yaml b/rust/pgcollector/collectors/activity_samples.yamlindex a9b068fe02b7..b2ab22b2022f 100644--- a/rust/pgcollector/collectors/activity_samples.yaml+++ b/rust/pgcollector/collectors/activity_samples.yaml@@ -1,14 +1,23 @@name: activity_samplesdescription: >ASH-style sample of pg_stat_activity every 10s: backend counts grouped by- state / wait event / query. Wait-event charts, connection counts and- "how often is query X seen running for >N seconds" all come from here.+ state / wait event / query / query tags. Wait-event charts, connection counts,+ "how often is query X seen running for >N seconds" and load per code path+ (tags) all come from here.interval: 10sscope: clusterkind: gauge+# The statement text is grouped on only to read its tag comments; `tags:` replaces+# it before anything is stored and merges the rows back per tag set.+tags:+ from: query_tags_raw+ merge:+ sum: [backends, active_over_1s, active_over_10s]+ max: [max_query_age_s, max_xact_age_s]query: |SELECT datname, usename, backend_type, state, wait_event_type, wait_event,NULL::bigint AS query_id,+ CASE WHEN state = 'active' THEN query END AS query_tags_raw,count(*)::bigint AS backends,count(*) FILTER (WHERE state = 'active' AND now() - query_start > interval '1 second')::bigint AS active_over_1s,count(*) FILTER (WHERE state = 'active' AND now() - query_start > interval '10 seconds')::bigint AS active_over_10s,@@ -17,7 +26,7 @@ query: |FROM pg_stat_activityWHERE backend_type IN ('client backend', 'autovacuum worker', 'parallel worker')AND pid <> pg_backend_pid()- GROUP BY 1,2,3,4,5,6,7+ GROUP BY 1,2,3,4,5,6,7,8variants:- aurora: truemin_pg_version: 140000@@ -25,6 +34,7 @@ variants:SELECT datname, usename, backend_type, state, wait_event_type, wait_event,CASE WHEN state = 'active' THEN query_id END AS query_id,CASE WHEN state = 'active' THEN plan_id END AS plan_id,+ CASE WHEN state = 'active' THEN query END AS query_tags_raw,count(*)::bigint AS backends,count(*) FILTER (WHERE state = 'active' AND now() - query_start > interval '1 second')::bigint AS active_over_1s,count(*) FILTER (WHERE state = 'active' AND now() - query_start > interval '10 seconds')::bigint AS active_over_10s,@@ -33,11 +43,12 @@ variants:FROM aurora_stat_activity()WHERE backend_type IN ('client backend', 'autovacuum worker', 'parallel worker')AND pid <> pg_backend_pid()- GROUP BY 1,2,3,4,5,6,7,8+ GROUP BY 1,2,3,4,5,6,7,8,9- min_pg_version: 140000query: |SELECT datname, usename, backend_type, state, wait_event_type, wait_event,CASE WHEN state = 'active' THEN query_id END AS query_id,+ CASE WHEN state = 'active' THEN query END AS query_tags_raw,count(*)::bigint AS backends,count(*) FILTER (WHERE state = 'active' AND now() - query_start > interval '1 second')::bigint AS active_over_1s,count(*) FILTER (WHERE state = 'active' AND now() - query_start > interval '10 seconds')::bigint AS active_over_10s,@@ -46,4 +57,4 @@ variants:FROM pg_stat_activityWHERE backend_type IN ('client backend', 'autovacuum worker', 'parallel worker')AND pid <> pg_backend_pid()- GROUP BY 1,2,3,4,5,6,7+ GROUP BY 1,2,3,4,5,6,7,8diff --git a/rust/pgcollector/collectors/activity_sessions.yaml b/rust/pgcollector/collectors/activity_sessions.yamlindex 1f4453c7b02b..eb12ca8aac0e 100644--- a/rust/pgcollector/collectors/activity_sessions.yaml+++ b/rust/pgcollector/collectors/activity_sessions.yaml@@ -5,6 +5,9 @@ description: >interval: 10sscope: clusterkind: gauge+tags:+ from: query_tags_raw+ trace_id: truequery: |SELECT pid, datname, usename, application_name, client_addr::text AS client_addr,backend_type, state, wait_event_type, wait_event,@@ -15,6 +18,7 @@ query: |backend_xid::text::bigint AS backend_xid,age(backend_xmin)::bigint AS backend_xmin_age,CASE WHEN wait_event_type = 'Lock' THEN pg_blocking_pids(pid)::text END AS blocked_by,+ query AS query_tags_raw,regexp_replace(left(query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS queryFROM pg_stat_activityWHERE backend_type = 'client backend' AND pid <> pg_backend_pid()@@ -33,6 +37,7 @@ variants:backend_xid::text::bigint AS backend_xid,age(backend_xmin)::bigint AS backend_xmin_age,CASE WHEN wait_event_type = 'Lock' THEN pg_blocking_pids(pid)::text END AS blocked_by,+ query AS query_tags_raw,regexp_replace(left(query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS queryFROM pg_stat_activityWHERE backend_type = 'client backend' AND pid <> pg_backend_pid()diff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.mdindex d3d9d3b6aac2..a53282c9e451 100644--- a/rust/pgcollector/docs/deploy.md+++ b/rust/pgcollector/docs/deploy.md@@ -56,7 +56,7 @@ misbehaving collector is cut off, not merely slow. Per tick:| collector | interval | cost | notes ||---|---|---|---|-| `activity_samples`, `activity_sessions` | 10s | one `pg_stat_activity` scan each | `pg_blocking_pids()` only for lock waiters |+| `activity_samples`, `activity_sessions` | 10s | one `pg_stat_activity` scan each, plus a regexp over each active backend's query text for query tags | `pg_blocking_pids()` only for lock waiters || `lock_waits` | 10s | `pg_stat_activity` scan; `pg_blocking_pids()` per lock waiter only | empty unless something is blocked || `query_stats` | 60s | `pg_stat_statements(false)` (no text); text for ≤500 new ids per tick | no query text on the hot path || `database_stats`, `bgwriter`, `wal`, `replication*`, `vacuum_progress`, `aurora_system_waits`, `aurora_db_latency`, `aurora_replica_status` | 60s | shared-memory counter reads | negligible |diff --git a/rust/pgcollector/docs/query-tags.md b/rust/pgcollector/docs/query-tags.mdnew file mode 100644index 000000000000..0952df39e05d--- /dev/null+++ b/rust/pgcollector/docs/query-tags.md@@ -0,0 +1,98 @@+# Query tags++A query tag is a key/value pair a client puts in a SQL comment so a statement can be+attributed to the code that ran it, rather than to its text.+pgcollector parses the tags out, stores them next to the statement, and pgapi groups,+filters and labels queries by them.++## What a client writes++Three comment shapes are accepted, because all three already run against our clusters:++| shape | example | where it comes from |+| --- | --- | --- |+| SQLCommenter | `/* route='/api/x', controller='PersonViewSet' */` | OpenTelemetry and Datadog instrumentation; values are percent-encoded |+| colon pairs | `/* team_id:42 query_type:recording_api_list_blocks */` | the shape PostHog uses for ClickHouse, reused by the CDP and replay services |+| ingestion prefix | `/* nodejs:PERSONS_WRITE:Tx<insertPerson:ingestion/merge> */` | `nodejs/src/common/utils/db/postgres.ts` |++A comment is a tag comment only when every token in it is a `key=value` or `key:value` pair.+Prose comments and planner hints stay in the text, and comment markers inside string literals, dollar quotes and `--` comments are never read as tags.+Tag values are stored as written: they are metadata the application chose to attach, not SQL literals, so redaction does not apply to them.+A statement may carry several tag comments; later ones override earlier keys.++**Put the comment at the front of the statement.**+`pg_stat_activity.query` is cut at `track_activity_query_size` (1 KB by default), so a trailing comment on a long statement never reaches the activity sampler.+Logged statements are complete, so a trailing SQLCommenter block still works there.++## Keys++Keys are lower-cased.+Two classes exist:++**Dimensions** describe a code path and are stored in the `tags` jsonb column of every statement-bearing table.+They can be grouped and filtered on.+Use these names so different services line up:++| key | meaning | example |+| --- | --- | --- |+| `service` | the process type | `web`, `celery`, `temporal`, `nodejs` |+| `route` | HTTP route pattern | `/api/projects/{id}/persons/` |+| `controller`, `action` | handler and method | `PersonViewSet`, `list` |+| `task` | Celery task name | `posthog.tasks.calculate_cohort` |+| `workflow`, `activity` | Temporal workflow and activity types | `batch-export`, `insert_into_s3` |+| `operation` | the named query in a repository | `updatePersonsBatch` |+| `caller` | the call site behind an operation | `ingestion/person-update-conflict` |+| `db_use` | which pool a Node service used | `PERSONS_WRITE` |+| `tx` | `true` when the statement ran inside an explicit transaction | |+| `product` | owning product area | `replay` |+| `query_type` | a hand-named query | `recording_api_list_blocks` |+| `team_id`, `user_id` | the tenant or actor | `42` |++`team_id` has many values, so group on it only inside a narrow range.+Any other key is stored as-is and can be grouped on; it just will not line up with other services.++**Context** identifies one request and is never grouped on:+`traceparent`, `tracestate`, `trace_id`, `span_id`, `request_id`, `x-request-id`, `session_id`, `task_id`, `job_id`, `run_id`, `workflow_id`, `activity_id`, `txid`.+These are dropped, except that a trace id (`trace_id`, or the second field of `traceparent`) is kept in a `trace_id` column on per-sample rows so a slow statement can be followed into its trace.++The ingestion prefix `nodejs:<DB_USE>[:Tx]<operation[:caller]>` is expanded into `service=nodejs`, `db_use`, `operation`, `caller` and `tx`.++## What can and cannot be attributed++`pg_stat_statements` hashes the parse tree, and comments are not part of it.+Every caller of a statement shares one `queryid` and one set of counters, and the stored text is whichever call the extension saw first.+So the collector cannot split `calls` or `total_exec_time` by tag.+What it does instead:++| source | table | tags |+| --- | --- | --- |+| `pg_stat_activity` every 10 s | `ts_activity_samples` | grouped by tag set; the API turns backend counts into average active sessions per code path |+| `pg_stat_activity` (long or blocked sessions) | `ts_activity_sessions` | per session, with `trace_id` |+| statement log (`log_min_duration_sample`) | `ts_query_latency` | one histogram per statement, minute and tag set; this is where per-tag calls, time and p50/p95/p99 come from |+| statement log (slow statements, plans) | `ts_query_durations`, `ts_log_plans` | per statement, with `trace_id` |+| statement log (errors, temp files) | `ts_log_errors`, `ts_temp_files` | per statement, with `trace_id` |+| `pg_stat_statements` text | `cur_queries` | tags of the first call seen, text stored without the tag comment |++In pgapi:++- `GET /servers/{id}/tags?key=operation` (MCP `query_tags`) is the per-code-path view.+- `GET /servers/{id}/queries?tags=operation=updatePersonsBatch` keeps the `pg_stat_statements` rows for queries seen with that tag in a sampled source inside the range. Their totals still include every caller. Percent-encode a value that contains a comma.+- `GET /servers/{id}/queries/{queryid}` returns `callers`: the tag sets seen while that query ran, with each set's share of samples.++## Adding tags to a declarative collector++A YAML collector selects the raw comment text into a column and names it under `tags:`:++```yaml+tags:+ from: query_tags_raw # the column holding the statement text; replaced by `tags`+ trace_id: true # also emit trace_id (per-sample rows only)+ merge: # for aggregates grouped by the statement text in SQL+ sum: [backends]+ max: [max_query_age_s]+query: |+ SELECT ..., query AS query_tags_raw+```++`merge` exists because a SQL `GROUP BY` on the statement text splits one code path into one row per request id or literal.+Once the context keys are gone those rows collide, and `merge` adds them back together.diff --git a/rust/pgcollector/src/collectors/declarative.rs b/rust/pgcollector/src/collectors/declarative.rsindex 3dfca2e81468..1bde354f9478 100644--- a/rust/pgcollector/src/collectors/declarative.rs+++ b/rust/pgcollector/src/collectors/declarative.rs@@ -41,6 +41,8 @@ pub struct Spec {pub variants: Vec<Variant>,#[serde(default)]pub description: String,+ /// Turn a raw statement/comment column into a `tags` jsonb column (see `tags.rs`).+ pub tags: Option<crate::tags::Spec>,}fn default_true() -> bool {true@@ -146,7 +148,11 @@ impl Collector for SqlCollector {.await.with_context(|| format!("{}: query failed", self.spec.name))?;let rows: Vec<Row> = pg_rows.iter().map(row_to_values).collect::<Result<_>>()?;- let types = pg_rows.first().map(column_types).unwrap_or_default();+ let mut types = pg_rows.first().map(column_types).unwrap_or_default();+ let rows = match &self.spec.tags {+ Some(t) => crate::tags::apply(rows, &mut types, t),+ None => rows,+ };let interval_seconds = prev.and_then(|p| p.collected_at)diff --git a/rust/pgcollector/src/collectors/logs.rs b/rust/pgcollector/src/collectors/logs.rsindex b6c8338a72cb..43fabd0b76e8 100644--- a/rust/pgcollector/src/collectors/logs.rs+++ b/rust/pgcollector/src/collectors/logs.rs@@ -20,6 +20,7 @@ use crate::logs::{histogram::Histogram,parse::*,};+use crate::tags;use anyhow::Result;use async_trait::async_trait;use once_cell::sync::OnceCell;@@ -189,6 +190,8 @@ impl Collector for Logs {("query_id", "bigint"),("fingerprint", "bigint"),("duration_ms", "double precision"),+ ("tags", "jsonb"),+ ("trace_id", "text"),]),by_statement(),));@@ -219,9 +222,15 @@ impl Collector for Logs {let rows = out.latency.into_iter()- .map(|((db, fp, qid, minute), h)| {+ .map(|((db, fp, qid, minute, tags), h)| {let mut r = Row::new();r.insert("datname".into(), db.map(Value::Text).unwrap_or(Value::Null));+ r.insert(+ "tags".into(),+ tags.and_then(|t| serde_json::from_str(&t).ok())+ .map(Value::Json)+ .unwrap_or(Value::Null),+ );r.insert("fingerprint".into(),fp.map(Value::Int).unwrap_or(Value::Null),@@ -259,6 +268,7 @@ impl Collector for Logs {("logged_counts", "integer[]"),("sample_rate", "double precision"),("hard_threshold_ms", "double precision"),+ ("tags", "jsonb"),]),by_statement(),));@@ -276,6 +286,8 @@ impl Collector for Logs {("duration_ms", "double precision"),("plan", "jsonb"),("query", "text"),+ ("tags", "jsonb"),+ ("trace_id", "text"),]),by_statement(),));@@ -309,6 +321,8 @@ impl Collector for Logs {("query_id", "bigint"),("size_bytes", "bigint"),("statement", "text"),+ ("tags", "jsonb"),+ ("trace_id", "text"),]),vec![],));@@ -325,6 +339,8 @@ impl Collector for Logs {("sqlstate", "text"),("statement", "text"),("detail", "text"),+ ("tags", "jsonb"),+ ("trace_id", "text"),]),vec![],));@@ -434,11 +450,13 @@ fn types_of(t: &[(&str, &str)]) -> BTreeMap<String, String> {.collect()}+/// (datname, fingerprint, query id, minute, tags as canonical JSON).type LatencyKey = (Option<String>,Option<i64>,Option<i64>,chrono::DateTime<chrono::Utc>,+ Option<String>,);#[derive(Default)]@@ -451,7 +469,8 @@ struct Outputs {sample_rate: f64,hard_threshold_ms: f64,durations: Vec<Row>,- /// (datname, fingerprint, query id, minute) → latency histogram.+ /// One histogram per statement, minute and tag set, so latency can be cut by+ /// code path even though pg_stat_statements cannot.latency: BTreeMap<LatencyKey, Histogram>,/// (datname, fingerprint) → statement text, stored once per fingerprint in/// `cur_query_texts` rather than on every duration row.@@ -472,6 +491,28 @@ fn text(s: &str) -> Value {fn opt(s: &Option<String>) -> Value {s.as_deref().map(text).unwrap_or(Value::Null)}+/// Tag comments come off before redaction, which would otherwise blank their+/// quoted values; the row gets the comment-free text plus `tags` and `trace_id`.+fn tagged(r: &mut Row, column: &str, statement: Option<&str>) {+ let ex = statement.map(tags::extract);+ r.insert(+ column.into(),+ ex.as_ref().map(|x| text(&x.sql)).unwrap_or(Value::Null),+ );+ tag_only(r, ex.as_ref());+}+fn tag_only(r: &mut Row, ex: Option<&tags::Extracted>) {+ r.insert(+ "tags".into(),+ ex.map(|x| tags::to_value(&x.tags)).unwrap_or(Value::Null),+ );+ r.insert(+ "trace_id".into(),+ ex.and_then(|x| x.trace_id.clone())+ .map(Value::Text)+ .unwrap_or(Value::Null),+ );+}fn json_to_value(v: &serde_json::Value) -> Value {match v {serde_json::Value::Null => Value::Null,@@ -548,6 +589,11 @@ impl Outputs {return;}let fp = query.as_deref().map(fingerprint);+ let ex = query.as_deref().map(tags::extract);+ let tag_key = ex+ .as_ref()+ .filter(|x| !x.tags.is_empty())+ .and_then(|x| serde_json::to_string(&x.tags).ok());if let (Some(fp), Some(q)) = (fp, &query) {self.texts.entry((e.db.clone(), fp))@@ -560,7 +606,7 @@ impl Outputs {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))+ .entry((e.db.clone(), fp, e.query_id, minute, tag_key)).or_default().add(duration_ms, always_logged);}@@ -574,6 +620,7 @@ impl Outputs {"fingerprint".into(),fp.map(Value::Int).unwrap_or(Value::Null),);+ tag_only(&mut r, ex.as_ref());self.durations.push(r);}Record::Plan {@@ -590,7 +637,7 @@ impl Outputs {.map(|q| Value::Int(fingerprint(q))).unwrap_or(Value::Null),);- r.insert("query".into(), opt(&query));+ tagged(&mut r, "query", query.as_deref());let mut plan = plan;if let Some(o) = plan.as_object_mut() {// auto_explain.log_parameter_max_length puts bound values here.@@ -620,7 +667,7 @@ impl Outputs {let mut r = Self::base(stream, e);r.insert("size_bytes".into(), Value::Int(size_bytes));r.insert("path".into(), Value::Text(path));- r.insert("statement".into(), opt(&e.statement));+ tagged(&mut r, "statement", e.statement.as_deref());r.insert("fingerprint".into(),e.statement@@ -665,7 +712,7 @@ impl Outputs {r.insert("sqlstate".into(), opt(&e.sqlstate));r.insert("message".into(), text(&e.message));r.insert("detail".into(), opt(&e.detail));- r.insert("statement".into(), opt(&e.statement));+ tagged(&mut r, "statement", e.statement.as_deref());r.insert("fingerprint".into(),e.statement@@ -697,6 +744,7 @@ mod tests {"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: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 */",+ "2026-08-27 18:22:51 UTC:10.1.2.3(5000):app@app:[142]:LOG: duration: 300.0 ms statement: /* nodejs:PERSONS_WRITE<fetchPerson> */ select count(*) from t /* not stored */",];for l in lines {if let Some(e) = asm.push(&re, l) {@@ -716,7 +764,16 @@ mod tests {[Some("app"), Some("app")]);let kinds: Vec<&Value> = out.durations.iter().map(|r| &r["kind"]).collect();- assert_eq!(kinds, [&Value::Text("statement".into())]);+ assert_eq!(kinds, [&Value::Text("statement".into()); 2]);+ // The tagged statement keeps its tags on the slow row and gets its own+ // histogram, although it shares the untagged statement's fingerprint.+ assert_eq!(+ out.durations[1]["tags"],+ Value::Json(+ serde_json::json!({ "service": "nodejs", "db_use": "PERSONS_WRITE", "operation": "fetchPerson" })+ )+ );+ assert_eq!(out.latency.keys().filter(|k| k.4.is_some()).count(), 1);// The 250 ms statement is over the always-log threshold, the executes were sampled.let mut hists: Vec<(i64, f64, i32, i32)> = out.latency@@ -724,18 +781,18 @@ mod tests {.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_eq!(hists, [(1, 250.0, 0, 1), (1, 300.0, 0, 1), (2, 3.0, 2, 0)]);assert!(out.latency.keys()- .all(|(_, _, _, minute)| minute.to_rfc3339() == "2026-08-27T18:22:00+00:00"));+ .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())],- 5+ 6);}}diff --git a/rust/pgcollector/src/collectors/statements.rs b/rust/pgcollector/src/collectors/statements.rsindex c1407880ff13..cae118ecba34 100644--- a/rust/pgcollector/src/collectors/statements.rs+++ b/rust/pgcollector/src/collectors/statements.rs@@ -140,13 +140,19 @@ pub async fn collect(let mut text_types = texts.first().map(column_types).unwrap_or_default();// Fingerprint the normalised text so log-derived rows (durations, plans, errors)// can be joined to cur_queries even without %Q in log_line_prefix.+ // pg_stat_statements keeps the text of whichever call it saw first, so the+ // tags here are that first caller's; per-caller attribution comes from samples.for r in &mut text_rows {if let Some(Value::Text(q)) = r.get("query") {let fp = crate::logs::fingerprint::fingerprint(q);+ let ex = crate::tags::extract(q);+ r.insert("query".into(), Value::Text(ex.sql));+ r.insert("tags".into(), crate::tags::to_value(&ex.tags));r.insert("fingerprint".into(), Value::Int(fp));}}text_types.insert("fingerprint".into(), "bigint".into());+ text_types.insert("tags".into(), "jsonb".into());extra.known_ids.extend(unseen);if extra.known_ids.len() > MAX_KNOWN {extra.known_ids = extradiff --git a/rust/pgcollector/src/main.rs b/rust/pgcollector/src/main.rsindex 53cd3c1c1d07..159da490de86 100644--- a/rust/pgcollector/src/main.rs+++ b/rust/pgcollector/src/main.rs@@ -6,6 +6,7 @@ mod logs;mod pg;mod scheduler;mod sink;+mod tags;use anyhow::Result;use clap::Parser;diff --git a/rust/pgcollector/src/tags.rs b/rust/pgcollector/src/tags.rsnew file mode 100644index 000000000000..8c9b39f2d9a7--- /dev/null+++ b/rust/pgcollector/src/tags.rs@@ -0,0 +1,535 @@+//! Query tags: key/value pairs in a SQL comment that name the code path that ran a+//! statement. Three comment shapes are accepted because all three are in production:+//! SQLCommenter `key='value'`, colon pairs `key:value`, and the ingestion service's+//! `nodejs:<DB_USE>[:Tx]<operation[:caller]>` prefix. See docs/query-tags.md.++use crate::collector::{Row, Value};+use once_cell::sync::Lazy;+use regex::Regex;+use serde::Deserialize;+use std::collections::BTreeMap;++pub type Tags = BTreeMap<String, String>;++const MAX_PAIRS: usize = 32;+const MAX_KEY: usize = 64;+const MAX_VALUE: usize = 256;++/// Keys that identify one request rather than one code path; grouping on them is+/// meaningless, so they are dropped and only a trace id survives as `trace_id`.+const CONTEXT_KEYS: &[&str] = &[+ "traceparent",+ "tracestate",+ "trace_id",+ "span_id",+ "request_id",+ "x-request-id",+ "session_id",+ "task_id",+ "job_id",+ "run_id",+ "workflow_id",+ "activity_id",+ "txid",+];++/// `nodejs:<DB_USE>[:Tx]<operation[:caller]>` as emitted by the ingestion service.+static NODEJS: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"^(?P<db_use>[A-Za-z_]+)(?P<tx>:Tx)?<(?P<op>[^:<>]+)(?::(?P<caller>[^<>]*))?>$")+ .unwrap()+});++#[derive(Debug, Default, Clone, PartialEq)]+pub struct Extracted {+ pub tags: Tags,+ pub trace_id: Option<String>,+ /// The statement with its tag comments removed. Other comments are kept.+ pub sql: String,+}++/// Later comments override earlier keys, so a trailing SQLCommenter block wins over a+/// leading prefix for a shared key. Comment markers inside string literals, dollar+/// quotes and `--` comments are text, not comments.+pub fn extract(sql: &str) -> Extracted {+ let mut out = Extracted::default();+ let b = sql.as_bytes();+ let mut i = 0;+ let mut removed = false;+ while i < b.len() {+ match b[i] {+ b'\'' => {+ // E'..' escapes with a backslash; plain literals double the quote.+ let escapes = i > 0 && matches!(b[i - 1], b'E' | b'e');+ let mut j = i + 1;+ while j < b.len() {+ if escapes && b[j] == b'\\' {+ j += 2;+ continue;+ }+ if b[j] == b'\'' {+ if j + 1 < b.len() && b[j + 1] == b'\'' {+ j += 2;+ continue;+ }+ break;+ }+ j += 1;+ }+ let j = (j + 1).min(b.len());+ out.sql.push_str(&sql[i..j]);+ i = j;+ }+ b'$' => {+ // $$ .. $$ or $tag$ .. $tag$; any other `$` is a parameter marker.+ let close = sql[i + 1..].find('$').map(|n| i + 1 + n).filter(|&c| {+ sql[i + 1..c]+ .bytes()+ .all(|x| x.is_ascii_alphanumeric() || x == b'_')+ });+ match close {+ Some(c) => {+ let tag = &sql[i..=c];+ let end = sql[c + 1..]+ .find(tag)+ .map(|n| c + 1 + n + tag.len())+ .unwrap_or(b.len());+ out.sql.push_str(&sql[i..end]);+ i = end;+ }+ None => {+ out.sql.push('$');+ i += 1;+ }+ }+ }+ b'-' if b.get(i + 1) == Some(&b'-') => {+ let end = sql[i..].find('\n').map(|n| i + n).unwrap_or(b.len());+ out.sql.push_str(&sql[i..end]);+ i = end;+ }+ b'/' if b.get(i + 1) == Some(&b'*') => {+ let Some(n) = sql[i + 2..].find("*/") else {+ out.sql.push_str(&sql[i..]);+ break;+ };+ let body = &sql[i + 2..i + 2 + n];+ let end = i + 2 + n + 2;+ match parse_comment(body) {+ Some(pairs) => {+ for (k, v) in pairs {+ absorb(&mut out, k, v);+ }+ removed = true;+ // Only the blanks around a removed leading comment go with it, so+ // the rest of the statement keeps its whitespace as written.+ let ends_blank = out.sql.chars().last().is_none_or(char::is_whitespace);+ i = end;+ if ends_blank {+ while i < b.len() && matches!(b[i], b' ' | b'\t') {+ i += 1;+ }+ }+ }+ None => {+ out.sql.push_str(&sql[i..end]);+ i = end;+ }+ }+ }+ _ => {+ let c = sql[i..].chars().next().unwrap();+ out.sql.push(c);+ i += c.len_utf8();+ }+ }+ }+ if removed {+ out.sql = out.sql.trim().to_string();+ }+ out+}++fn absorb(out: &mut Extracted, key: String, value: String) {+ if key == "traceparent" {+ // 00-<trace id>-<span id>-<flags>+ if let Some(id) = value.split('-').nth(1).filter(|id| id.len() == 32) {+ out.trace_id = Some(id.to_string());+ }+ return;+ }+ if key == "trace_id" {+ out.trace_id = Some(value);+ return;+ }+ if CONTEXT_KEYS.contains(&key.as_str()) {+ return;+ }+ if key == "nodejs" {+ expand_nodejs(&mut out.tags, &value);+ return;+ }+ out.tags.insert(key, value);+}++fn expand_nodejs(tags: &mut Tags, value: &str) {+ tags.insert("service".into(), "nodejs".into());+ let Some(c) = NODEJS.captures(value) else {+ tags.insert("operation".into(), value.to_string());+ return;+ };+ tags.insert("db_use".into(), c["db_use"].to_string());+ tags.insert("operation".into(), c["op"].to_string());+ if let Some(caller) = c.name("caller").filter(|m| !m.as_str().is_empty()) {+ tags.insert("caller".into(), caller.as_str().to_string());+ }+ if c.name("tx").is_some() {+ tags.insert("tx".into(), "true".into());+ }+}++/// `None` when any token is not a pair, so the caller leaves a prose comment in place.+pub fn parse_comment(body: &str) -> Option<Vec<(String, String)>> {+ let b: Vec<char> = body.chars().collect();+ let mut i = 0;+ let mut pairs = Vec::new();+ let is_sep = |c: char| c.is_whitespace() || c == ',';+ let is_key = |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-');+ loop {+ while i < b.len() && is_sep(b[i]) {+ i += 1;+ }+ if i == b.len() {+ break;+ }+ let ks = i;+ while i < b.len() && is_key(b[i]) {+ i += 1;+ }+ if i == ks {+ return None;+ }+ let key: String = b[ks..i].iter().collect::<String>().to_ascii_lowercase();+ while i < b.len() && b[i] == ' ' {+ i += 1;+ }+ if i == b.len() || !matches!(b[i], '=' | ':') {+ return None;+ }+ i += 1;+ while i < b.len() && b[i] == ' ' {+ i += 1;+ }+ let value = if i < b.len() && b[i] == '\'' {+ i += 1;+ let mut v = String::new();+ loop {+ if i == b.len() {+ return None;+ }+ match b[i] {+ '\\' if i + 1 < b.len() => {+ v.push(b[i + 1]);+ i += 2;+ }+ '\'' if i + 1 < b.len() && b[i + 1] == '\'' => {+ v.push('\'');+ i += 2;+ }+ '\'' => {+ i += 1;+ break;+ }+ c => {+ v.push(c);+ i += 1;+ }+ }+ }+ v+ } else {+ let vs = i;+ while i < b.len() && !is_sep(b[i]) {+ i += 1;+ }+ b[vs..i].iter().collect()+ };+ if key.len() <= MAX_KEY && pairs.len() < MAX_PAIRS {+ let decoded = percent_decode(&value);+ pairs.push((key, decoded.chars().take(MAX_VALUE).collect()));+ }+ }+ if pairs.is_empty() {+ None+ } else {+ Some(pairs)+ }+}++fn percent_decode(s: &str) -> String {+ if !s.contains('%') {+ return s.to_string();+ }+ let bytes = s.as_bytes();+ let mut out = Vec::with_capacity(bytes.len());+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i] == b'%' && i + 2 < bytes.len() {+ if let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 3])+ .ok()+ .and_then(|h| u8::from_str_radix(h, 16).ok())+ {+ out.push(v);+ i += 3;+ continue;+ }+ }+ out.push(bytes[i]);+ i += 1;+ }+ String::from_utf8_lossy(&out).into_owned()+}++pub fn to_value(tags: &Tags) -> Value {+ if tags.is_empty() {+ Value::Null+ } else {+ Value::Json(serde_json::to_value(tags).unwrap_or(serde_json::Value::Null))+ }+}++#[derive(Debug, Clone, Deserialize, Default)]+pub struct Spec {+ pub from: String,+ /// Also emit a `trace_id` column (per-sample rows only; meaningless once merged).+ #[serde(default)]+ pub trace_id: bool,+ /// Rows that share every column outside these lists after tagging are merged:+ /// a SQL GROUP BY on the raw comment splits one code path per request id, and+ /// the split is undone here once the request ids are gone.+ pub merge: Option<Merge>,+}++#[derive(Debug, Clone, Deserialize, Default)]+pub struct Merge {+ #[serde(default)]+ pub sum: Vec<String>,+ #[serde(default)]+ pub max: Vec<String>,+}++pub fn apply(rows: Vec<Row>, types: &mut BTreeMap<String, String>, spec: &Spec) -> Vec<Row> {+ types.remove(&spec.from);+ types.insert("tags".into(), "jsonb".into());+ if spec.trace_id {+ types.insert("trace_id".into(), "text".into());+ }+ let mut tagged = Vec::with_capacity(rows.len());+ for mut row in rows {+ let ex = match row.remove(&spec.from) {+ Some(Value::Text(s)) => extract(&s),+ _ => Extracted::default(),+ };+ row.insert("tags".into(), to_value(&ex.tags));+ if spec.trace_id {+ row.insert(+ "trace_id".into(),+ ex.trace_id.map(Value::Text).unwrap_or(Value::Null),+ );+ }+ tagged.push(row);+ }+ match &spec.merge {+ Some(m) => merge_rows(tagged, m),+ None => tagged,+ }+}++fn merge_rows(rows: Vec<Row>, m: &Merge) -> Vec<Row> {+ let mut index: BTreeMap<String, usize> = BTreeMap::new();+ let mut out: Vec<Row> = Vec::with_capacity(rows.len());+ for row in rows {+ let group: Vec<String> = row+ .keys()+ .filter(|k| !m.sum.contains(k) && !m.max.contains(k))+ .cloned()+ .collect();+ let k = crate::collector::key_of(&row, &group);+ match index.get(&k) {+ None => {+ index.insert(k, out.len());+ out.push(row);+ }+ Some(&i) => {+ let acc = &mut out[i];+ for c in &m.sum {+ let v = match (acc.get(c), row.get(c)) {+ (Some(Value::Int(a)), Some(Value::Int(b))) => Value::Int(a + b),+ (Some(a), Some(b)) => match (a.as_f64(), b.as_f64()) {+ (Some(x), Some(y)) => Value::Float(x + y),+ (None, Some(_)) => b.clone(),+ _ => a.clone(),+ },+ (None, Some(b)) => b.clone(),+ (a, None) => a.cloned().unwrap_or(Value::Null),+ };+ acc.insert(c.clone(), v);+ }+ for c in &m.max {+ let v = match (+ acc.get(c).and_then(Value::as_f64),+ row.get(c).and_then(Value::as_f64),+ ) {+ (Some(x), Some(y)) if y > x => row[c].clone(),+ (None, Some(_)) => row[c].clone(),+ _ => acc.get(c).cloned().unwrap_or(Value::Null),+ };+ acc.insert(c.clone(), v);+ }+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tags(pairs: &[(&str, &str)]) -> Tags {+ pairs+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect()+ }++ #[test]+ fn ingestion_prefix_is_expanded_into_structured_keys() {+ let e = extract(+ "/* nodejs:PERSONS_WRITE:Tx<fetchPerson:ingestion/person-update-conflict> */ SELECT 1",+ );+ assert_eq!(+ e.tags,+ tags(&[+ ("service", "nodejs"),+ ("db_use", "PERSONS_WRITE"),+ ("operation", "fetchPerson"),+ ("caller", "ingestion/person-update-conflict"),+ ("tx", "true"),+ ])+ );+ assert_eq!(e.sql, "SELECT 1");+ let e = extract("/* nodejs:PERSONS_WRITE<updatePersonsBatch> */\n UPDATE t SET a = $1");+ assert_eq!(e.tags["operation"], "updatePersonsBatch");+ assert!(!e.tags.contains_key("tx"));+ assert_eq!(e.sql, "UPDATE t SET a = $1");+ }++ #[test]+ fn sqlcommenter_and_colon_styles_merge_across_comments() {+ let e = extract(+ "/* nodejs:X<op> */ UPDATE t SET a = $1 /* operation='updatePerson',purpose='update%20now' */",+ );+ assert_eq!(e.tags["operation"], "updatePerson");+ assert_eq!(e.tags["purpose"], "update now");+ assert_eq!(e.sql, "UPDATE t SET a = $1");+ let e = extract("/* team_id:42 query_type:recording_api_list_blocks */ SELECT 1");+ assert_eq!(+ e.tags,+ tags(&[+ ("team_id", "42"),+ ("query_type", "recording_api_list_blocks")+ ])+ );+ }++ #[test]+ fn context_keys_are_dropped_and_trace_id_kept_apart() {+ let e = extract(+ "SELECT 1 /*route='/api/x',traceparent='00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01',request_id='abc'*/",+ );+ assert_eq!(e.tags, tags(&[("route", "/api/x")]));+ assert_eq!(+ e.trace_id.as_deref(),+ Some("0af7651916cd43dd8448eb211c80319c")+ );+ assert_eq!(e.sql, "SELECT 1");+ }++ #[test]+ fn prose_comments_and_hints_are_not_tags() {+ for sql in [+ "SELECT 1 /* token not in posthog_team, try PSAK below */",+ "/* truncated-query */ SELECT 1",+ "/*+ IndexScan(t) */ SELECT 1",+ "/* code */ SELECT 1",+ "SELECT 1 /* */",+ "SELECT a,\n b\n FROM t WHERE x = 'a b'",+ ] {+ let e = extract(sql);+ assert!(e.tags.is_empty(), "{sql}");+ assert_eq!(e.sql, sql, "untagged text must come back byte for byte");+ }+ assert_eq!(+ extract("/* route='/x' */ SELECT a,\n b\n FROM t WHERE x = 'a b'").sql,+ "SELECT a,\n b\n FROM t WHERE x = 'a b'"+ );+ for sql in [+ "SELECT '/* a:b */'",+ "SELECT E'\\'/* a:b */'",+ "SELECT $$/* a:b */$$, $fn$ /* c:d */ $fn$",+ "SELECT 1 -- /* a:b */",+ "SELECT 'it''s' || '/* a:b */'",+ ] {+ let e = extract(sql);+ assert!(e.tags.is_empty(), "{sql}");+ assert_eq!(e.sql, sql);+ }+ assert_eq!(extract("SELECT 'x' /* a:b */ FROM t").tags.len(), 1);+ }++ #[test]+ fn quoted_values_unescape_and_unterminated_comment_is_left_alone() {+ let p = parse_comment(" a='it\\'s', b='x''y' ").unwrap();+ assert_eq!(+ p,+ vec![("a".into(), "it's".into()), ("b".into(), "x'y".into())]+ );+ assert!(parse_comment("a='open").is_none());+ let e = extract("/* nodejs:X<op> */ SELECT /* trunc");+ assert_eq!(e.tags["operation"], "op");+ assert_eq!(e.sql, "SELECT /* trunc");+ }++ #[test]+ fn apply_merges_rows_that_only_differed_by_request_context() {+ let row = |raw: &str, backends: i64, age: f64| -> Row {+ let mut r = Row::new();+ r.insert("state".into(), Value::Text("active".into()));+ r.insert("query_tags_raw".into(), Value::Text(raw.into()));+ r.insert("backends".into(), Value::Int(backends));+ r.insert("max_query_age_s".into(), Value::Float(age));+ r+ };+ let rows = vec![+ row("/* route='/a', request_id='1' */", 1, 0.5),+ row("/* route='/a', request_id='2' */", 2, 3.0),+ row("/* route='/b' */", 1, 1.0),+ ];+ let spec = Spec {+ from: "query_tags_raw".into(),+ trace_id: false,+ merge: Some(Merge {+ sum: vec!["backends".into()],+ max: vec!["max_query_age_s".into()],+ }),+ };+ let mut types = BTreeMap::from([("query_tags_raw".to_string(), "text".to_string())]);+ let out = apply(rows, &mut types, &spec);+ assert_eq!(out.len(), 2);+ assert_eq!(out[0]["backends"], Value::Int(3));+ assert_eq!(out[0]["max_query_age_s"], Value::Float(3.0));+ assert!(!out[0].contains_key("query_tags_raw"));+ assert_eq!(types.get("tags").map(String::as_str), Some("jsonb"));+ assert!(!types.contains_key("query_tags_raw"));+ }+}