: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): Postgres telemetry collector for RDS/Aurora (#90491)
Nick Best1e6d5b394152
diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex 024280d49eb4..e265e9632004 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -94,6 +94,12 @@dockerfile: ./rust/Dockerfileproject: x5whcmg6rl+# Postgres telemetry collector: scrapes pg_stat_* /+# Aurora stats / logs from RDS clusters into a stats Postgres. See rust/pgcollector.+- image: pgcollector+ dockerfile: ./rust/Dockerfile+ project: wb2br45dsr # pg-monitoring+- image: kafka-deduplicatordockerfile: ./rust/Dockerfileproject: vznmbshh6qdiff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 2a78d3e3b5cb..dd82068986a4 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -161,6 +161,7 @@ jobs:"hypercache-server": 40,"ingestion-consumer": 20,"ingestion-control-plane": 41,+ "pgcollector": 45,"k8s-awareness": 116,"kafka-assigner": 175,"kafka-assigner-proto": 5,diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.ymlindex 0b45de935ecd..c6511e3313cc 100644--- a/.github/workflows/rust-docker-build.yml+++ b/.github/workflows/rust-docker-build.yml@@ -177,6 +177,9 @@ jobs:- release: ingestion-control-planedigest_key: ingestion-control-planevalues_key: image+ - release: pgcollector+ digest_key: pgcollector+ values_key: image- release: kafka-deduplicatordigest_key: kafka-deduplicatorvalues_key: imagediff --git a/docs/internal/pgcollector.md b/docs/internal/pgcollector.mdnew file mode 100644index 000000000000..c5eade2b6379--- /dev/null+++ b/docs/internal/pgcollector.md@@ -0,0 +1,29 @@+# pgcollector — Postgres telemetry collector++`rust/pgcollector` scrapes telemetry from our RDS/Aurora clusters (pg*stat*\*,+Aurora stat functions, `pg_proctab`, CloudWatch-exported logs) into a stats+Postgres. `rust/pgapi`+([pgapi.md](pgapi.md)) serves the data. Design, catalog and deployment details+live in the crate: [`DESIGN.md`](../../rust/pgcollector/DESIGN.md),+[`docs/deploy.md`](../../rust/pgcollector/docs/deploy.md),+[`docs/telemetry-sources.md`](../../rust/pgcollector/docs/telemetry-sources.md).++## Contract++- **Inputs**: one `pg_monitor`-tier user per monitored cluster, discovered from+ `PGCOLLECTOR_SERVER_<ID>_URL` / `_READER_URL` / `_LOG_GROUP` env vars (one+ golden-chart `psql:` entry per cluster), plus a TOML config for the sink and+ defaults. `pgbouncer: false` everywhere: sessions set GUCs.+- **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.+- **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.+- **Security**: TLS required for sink and targets unless the URL says+ `sslmode=disable`/`prefer`; the collector's own statements are kept out of+ the server log; statement text taken from logs and `pg_stat_activity` is+ stored with string literals redacted; `pg_stat_statements` text is already+ normalised by Postgres.+- **Ops**: `/healthz`, `/readyz`, `/metrics` on `:9187`; `--check`, `--once`,+ `--parse-log` for validation.diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex fec1691b1321..d574c7828336 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -882,6 +882,32 @@ dependencies = ["uuid",]+[[package]]+name = "aws-sdk-cloudwatchlogs"+version = "1.139.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fc3c01b7bd640e686bea5d4a3d7c58a3b4293534b36e82dc1bbbad5d98e648c"+dependencies = [+ "arc-swap",+ "aws-credential-types",+ "aws-runtime",+ "aws-smithy-async",+ "aws-smithy-eventstream",+ "aws-smithy-http 0.63.6",+ "aws-smithy-json 0.62.7",+ "aws-smithy-observability",+ "aws-smithy-runtime",+ "aws-smithy-runtime-api",+ "aws-smithy-types",+ "aws-types",+ "bytes",+ "fastrand",+ "http 0.2.12",+ "http 1.4.0",+ "regex-lite",+ "tracing",+]+[[package]]name = "aws-sdk-dynamodb"version = "1.116.0"@@ -1066,7 +1092,7 @@ dependencies = ["hex","http 0.2.12","http-body 0.4.6",- "md-5",+ "md-5 0.10.6","pin-project-lite","sha1","sha2 0.10.9",@@ -1112,6 +1138,7 @@ version = "0.63.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231"dependencies = [+ "aws-smithy-eventstream","aws-smithy-runtime-api","aws-smithy-types","bytes",@@ -3573,6 +3600,39 @@ dependencies = ["regex",]+[[package]]+name = "deadpool"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e98a7e119cd347f4201e1159b19831029e203e2d8b790547708e8157b4acf1e"+dependencies = [+ "deadpool-runtime",+ "tokio",+]++[[package]]+name = "deadpool-postgres"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65a536565624b97fc19f758cd01b15d12908d3344425066efc8162236fbd3749"+dependencies = [+ "async-trait",+ "deadpool",+ "getrandom 0.4.1",+ "tokio",+ "tokio-postgres",+ "tracing",+]++[[package]]+name = "deadpool-runtime"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2657f61fb1dd8bf37a8d51093cc7cee4e77125b22f7753f49b289f831bec2bae"+dependencies = [+ "tokio",+]+[[package]]name = "debug-ignore"version = "1.0.5"@@ -3744,10 +3804,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"dependencies = ["const-oid 0.9.6",+ "der_derive",+ "flagset","pem-rfc7468","zeroize",]+[[package]]+name = "der_derive"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "deranged"version = "0.5.8"@@ -3837,7 +3910,7 @@ dependencies = ["petgraph 0.6.5","rayon","serde",- "toml",+ "toml 0.5.11",][[package]]@@ -4546,6 +4619,12 @@ dependencies = ["uuid",]+[[package]]+name = "flagset"+version = "0.4.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"+[[package]]name = "flatbuffers"version = "25.12.19"@@ -4976,11 +5055,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"dependencies = ["cfg-if",+ "js-sys","libc","r-efi","rand_core 0.10.1","wasip2","wasip3",+ "wasm-bindgen",][[package]]@@ -5110,7 +5191,7 @@ dependencies = ["smallvec","static_assertions","target-spec",- "toml",+ "toml 0.5.11",][[package]]@@ -5125,7 +5206,7 @@ dependencies = ["guppy-workspace-hack","semver","serde",- "toml",+ "toml 0.5.11",][[package]]@@ -5362,7 +5443,7 @@ dependencies = ["chrono-tz","hmac 0.12.1","indexmap 2.13.0",- "md-5",+ "md-5 0.10.6","once_cell","quick_cache","rand 0.8.5",@@ -5509,6 +5590,16 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"+[[package]]+name = "humantime-serde"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c"+dependencies = [+ "humantime",+ "serde",+]+[[package]]name = "hybrid-array"version = "0.4.10"@@ -5928,6 +6019,25 @@ dependencies = ["quick-error 2.0.1",]+[[package]]+name = "include_dir"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd"+dependencies = [+ "include_dir_macros",+]++[[package]]+name = "include_dir_macros"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75"+dependencies = [+ "proc-macro2",+ "quote",+]+[[package]]name = "indent_write"version = "2.2.0"@@ -6904,13 +7014,14 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"[[package]]name = "libredox"-version = "0.1.12"+version = "0.1.21"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616"+checksum = "d7955dfc218a8afb29dfeffd540e3a6e96baeb94fe7138228dd7cc6937fbbf96"dependencies = ["bitflags 2.11.0","libc",- "redox_syscall 0.7.2",+ "plain",+ "redox_syscall 0.9.3",][[package]]@@ -7183,6 +7294,16 @@ dependencies = ["digest 0.10.7",]+[[package]]+name = "md-5"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"+dependencies = [+ "cfg-if",+ "digest 0.11.3",+]+[[package]]name = "md5"version = "0.8.0"@@ -7866,6 +7987,15 @@ dependencies = ["objc2-foundation",]+[[package]]+name = "objc2-system-configuration"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396"+dependencies = [+ "objc2-core-foundation",+]+[[package]]name = "objc2-ui-kit"version = "0.3.2"@@ -7937,7 +8067,7 @@ dependencies = ["humantime","hyper 1.9.0","itertools 0.14.0",- "md-5",+ "md-5 0.10.6","parking_lot","percent-encoding","quick-xml 0.39.4",@@ -8768,6 +8898,41 @@ dependencies = ["serde",]+[[package]]+name = "pgcollector"+version = "0.1.0"+dependencies = [+ "anyhow",+ "async-trait",+ "aws-config",+ "aws-sdk-cloudwatchlogs",+ "axum 0.7.9",+ "bytes",+ "chrono",+ "clap",+ "deadpool-postgres",+ "futures",+ "glob",+ "humantime-serde",+ "include_dir",+ "once_cell",+ "prometheus",+ "regex",+ "rust_decimal",+ "rustls 0.23.37",+ "serde",+ "serde_json",+ "serde_yaml",+ "shellexpand",+ "tokio",+ "tokio-postgres",+ "tokio-postgres-rustls",+ "toml 0.8.23",+ "tracing",+ "tracing-subscriber",+ "webpki-roots 1.0.6",+]+[[package]]name = "phf"version = "0.11.3"@@ -8787,6 +8952,16 @@ dependencies = ["phf_shared 0.12.1",]+[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_shared 0.13.1",+ "serde",+]+[[package]]name = "phf_generator"version = "0.11.3"@@ -8828,6 +9003,15 @@ dependencies = ["siphasher 1.0.2",]+[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher 1.0.2",+]+[[package]]name = "pico-args"version = "0.5.0"@@ -8980,6 +9164,38 @@ dependencies = ["portable-atomic",]+[[package]]+name = "postgres-protocol"+version = "0.6.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514"+dependencies = [+ "base64 0.22.1",+ "byteorder",+ "bytes",+ "fallible-iterator 0.2.0",+ "hmac 0.13.0",+ "md-5 0.11.0",+ "memchr",+ "rand 0.10.2",+ "sha2 0.11.0",+ "stringprep",+]++[[package]]+name = "postgres-types"+version = "0.2.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be"+dependencies = [+ "bytes",+ "chrono",+ "fallible-iterator 0.2.0",+ "postgres-protocol",+ "serde_core",+ "serde_json",+]+[[package]]name = "posthog-replay-anonymizer"version = "0.4.7"@@ -9074,7 +9290,7 @@ dependencies = ["log","nix 0.26.4","once_cell",- "protobuf",+ "protobuf 3.7.2","protobuf-codegen","smallvec","spin 0.10.0",@@ -9164,7 +9380,7 @@ version = "3.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983"dependencies = [- "toml_edit",+ "toml_edit 0.23.10+spec-1.0.0",][[package]]@@ -9210,6 +9426,21 @@ dependencies = ["watto",]+[[package]]+name = "prometheus"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1"+dependencies = [+ "cfg-if",+ "fnv",+ "lazy_static",+ "memchr",+ "parking_lot",+ "protobuf 2.28.0",+ "thiserror 1.0.69",+]+[[package]]name = "prometheus-rw-proto"version = "0.1.0"@@ -9473,6 +9704,12 @@ dependencies = ["serde_json",]+[[package]]+name = "protobuf"+version = "2.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94"+[[package]]name = "protobuf"version = "3.7.2"@@ -9492,7 +9729,7 @@ checksum = "5d3976825c0014bbd2f3b34f0001876604fe87e0c86cd8fa54251530f1544ace"dependencies = ["anyhow","once_cell",- "protobuf",+ "protobuf 3.7.2","protobuf-parse","regex","tempfile",@@ -9508,7 +9745,7 @@ dependencies = ["anyhow","indexmap 2.13.0","log",- "protobuf",+ "protobuf 3.7.2","protobuf-support","tempfile","thiserror 1.0.69",@@ -10078,9 +10315,9 @@ dependencies = [[[package]]name = "redox_syscall"-version = "0.7.2"+version = "0.9.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6d94dd2f7cd932d4dc02cc8b2b50dfd38bd079a4e5d79198b99743d7fcf9a4b4"+checksum = "d678d17679829e73d371e96880897e98fee2ded7acc0a50bdf8af2affa4b2fe5"dependencies = ["bitflags 2.11.0",]@@ -10491,6 +10728,7 @@ dependencies = ["borsh","bytes","num-traits",+ "postgres-types","rand 0.8.5","rkyv","serde",@@ -11036,6 +11274,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "serde_spanned"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"+dependencies = [+ "serde",+]+[[package]]name = "serde_urlencoded"version = "0.7.1"@@ -11177,6 +11424,15 @@ dependencies = ["lazy_static",]+[[package]]+name = "shellexpand"+version = "3.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8"+dependencies = [+ "dirs",+]+[[package]]name = "shlex"version = "1.3.0"@@ -11520,7 +11776,7 @@ dependencies = ["hmac 0.12.1","itoa","log",- "md-5",+ "md-5 0.10.6","memchr","once_cell","percent-encoding",@@ -11536,7 +11792,7 @@ dependencies = ["thiserror 2.0.18","tracing","uuid",- "whoami",+ "whoami 1.6.1",][[package]]@@ -11562,7 +11818,7 @@ dependencies = ["home","itoa","log",- "md-5",+ "md-5 0.10.6","memchr","once_cell","rand 0.8.5",@@ -11576,7 +11832,7 @@ dependencies = ["thiserror 2.0.18","tracing","uuid",- "whoami",+ "whoami 1.6.1",][[package]]@@ -12598,6 +12854,27 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"+[[package]]+name = "tls_codec"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"+dependencies = [+ "tls_codec_derive",+ "zeroize",+]++[[package]]+name = "tls_codec_derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "tokio"version = "1.52.1"@@ -12646,6 +12923,47 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-postgres"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3"+dependencies = [+ "async-trait",+ "byteorder",+ "bytes",+ "fallible-iterator 0.2.0",+ "futures-channel",+ "futures-util",+ "log",+ "parking_lot",+ "percent-encoding",+ "phf 0.13.1",+ "pin-project-lite",+ "postgres-protocol",+ "postgres-types",+ "rand 0.10.2",+ "socket2 0.6.3",+ "tokio",+ "tokio-util",+ "whoami 2.1.3",+]++[[package]]+name = "tokio-postgres-rustls"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27d684bad428a0f2481f42241f821db42c54e2dc81d8c00db8536c506b0a0144"+dependencies = [+ "const-oid 0.9.6",+ "ring 0.17.14",+ "rustls 0.23.37",+ "tokio",+ "tokio-postgres",+ "tokio-rustls 0.26.4",+ "x509-cert",+]+[[package]]name = "tokio-retry"version = "0.3.0"@@ -12724,6 +13042,27 @@ dependencies = ["serde",]+[[package]]+name = "toml"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"+dependencies = [+ "serde",+ "serde_spanned",+ "toml_datetime 0.6.11",+ "toml_edit 0.22.27",+]++[[package]]+name = "toml_datetime"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"+dependencies = [+ "serde",+]+[[package]]name = "toml_datetime"version = "0.7.5+spec-1.1.0"@@ -12733,6 +13072,20 @@ dependencies = ["serde_core",]+[[package]]+name = "toml_edit"+version = "0.22.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"+dependencies = [+ "indexmap 2.13.0",+ "serde",+ "serde_spanned",+ "toml_datetime 0.6.11",+ "toml_write",+ "winnow",+]+[[package]]name = "toml_edit"version = "0.23.10+spec-1.0.0"@@ -12740,7 +13093,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269"dependencies = ["indexmap 2.13.0",- "toml_datetime",+ "toml_datetime 0.7.5+spec-1.1.0","toml_parser","winnow",]@@ -12754,6 +13107,12 @@ dependencies = ["winnow",]+[[package]]+name = "toml_write"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"+[[package]]name = "tonic"version = "0.11.0"@@ -13518,6 +13877,15 @@ version = "0.11.1+wasi-snapshot-preview1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"+[[package]]+name = "wasi"+version = "0.14.7+wasi-0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c"+dependencies = [+ "wasip2",+]+[[package]]name = "wasip2"version = "1.0.2+wasi-0.2.9"@@ -13542,6 +13910,15 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"+[[package]]+name = "wasite"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42"+dependencies = [+ "wasi 0.14.7+wasi-0.2.4",+]+[[package]]name = "wasm-bindgen"version = "0.2.112"@@ -13742,7 +14119,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"dependencies = ["libredox",- "wasite",+ "wasite 0.1.0",+]++[[package]]+name = "whoami"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c"+dependencies = [+ "libc",+ "libredox",+ "objc2-system-configuration",+ "wasite 1.0.2",+ "web-sys",][[package]]@@ -14125,6 +14515,18 @@ dependencies = ["tap",]+[[package]]+name = "x509-cert"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"+dependencies = [+ "const-oid 0.9.6",+ "der",+ "spki",+ "tls_codec",+]+[[package]]name = "xattr"version = "1.6.1"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex c6cdb3f522dd..4a60110dfd6b 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -71,6 +71,7 @@ members = ["personhog-test-harness","affected-services","property-vals-rs",+ "pgcollector",]# NOTE: cargo allows only one crate with `links = "python"` (i.e. one pyo3 version) perdiff --git a/rust/owners.yaml b/rust/owners.yamlindex baa18514c308..0ff7bace8a84 100644--- a/rust/owners.yaml+++ b/rust/owners.yaml@@ -13,6 +13,8 @@ rules:owners: team-feature-flags- match: '/hogql/'owners: team-data-tools+ - match: ['/pgcollector/', '/pgapi/']+ owners: team-ingestion- match:- '/ingestion-consumer/'- '/kafka-assigner-proto/'diff --git a/rust/pgcollector/.gitignore b/rust/pgcollector/.gitignorenew file mode 100644index 000000000000..b0cb622b21d4--- /dev/null+++ b/rust/pgcollector/.gitignore@@ -0,0 +1,2 @@+/.local/+/pgcollector.tomldiff --git a/rust/pgcollector/Cargo.toml b/rust/pgcollector/Cargo.tomlnew file mode 100644index 000000000000..4dc4f316a6ff--- /dev/null+++ b/rust/pgcollector/Cargo.toml@@ -0,0 +1,41 @@+[package]+name = "pgcollector"+version = "0.1.0"+edition = "2021"+publish = false+description = "Postgres telemetry collector for RDS/Aurora, writing to a stats Postgres"++[dependencies]+anyhow = { workspace = true }+async-trait = { workspace = true }+aws-config = { workspace = true }+# Pinned: 1.140+ requires rustc 1.94.1; the workspace image is rust:1.91.+aws-sdk-cloudwatchlogs = "=1.139.0"+axum = { workspace = true }+bytes = { workspace = true }+chrono = { workspace = true }+clap = { workspace = true, features = ["env"] }+deadpool-postgres = "0.14"+futures = { workspace = true }+glob = "0.3"+humantime-serde = "1"+include_dir = "0.7"+once_cell = { workspace = true }+prometheus = "0.13"+regex = { workspace = true }+rust_decimal = { version = "1", features = ["db-tokio-postgres"] }+rustls = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+serde_yaml = "0.9"+shellexpand = "3"+tokio = { workspace = true }+tokio-postgres = { version = "0.7", features = ["with-chrono-0_4", "with-serde_json-1"] }+tokio-postgres-rustls = "0.13"+toml = "0.8"+tracing = { workspace = true }+tracing-subscriber = { workspace = true }+webpki-roots = "1"++[lints]+workspace = truediff --git a/rust/pgcollector/DESIGN.md b/rust/pgcollector/DESIGN.mdnew file mode 100644index 000000000000..23bc2bd22721--- /dev/null+++ b/rust/pgcollector/DESIGN.md@@ -0,0 +1,305 @@+# pgcollector — design++A self-owned Postgres telemetry collector. Scrapes telemetry+from a fleet of RDS/Aurora instances and writes it to a Postgres stats database.+An API / UI / MCP server will sit on top of the stats DB later; this document+covers only the collector and its storage schema.++**Goal:** every stat we collect, and how it is aggregated, is a change we control.+Adding a column or a whole new stat source should be a two-minute edit, not a+feature request.++Decisions already made:++| Decision | Choice |+|---|---|+| Language | Rust |+| Storage | Postgres, native range partitioning by time, short retention (days–weeks) |+| Targets | RDS / Aurora Postgres almost exclusively |+| Deployment | One long-running binary per environment, many target servers per binary |++---++## 1. Architecture++```text+┌──────────────┐ pg_stat_* / catalogs / logs ┌──────────────────────────────┐ Snapshot ┌────────────┐+│ RDS / Aurora │ ◄──────────────────────────── │ pgcollector │ ─────────► │ Sink │+│ (N servers) │ │ scheduler + collector mods │ │ (stats PG) │+└──────────────┘ └──────────────────────────────┘ └────────────┘+```++* **Scheduler** — for each configured server, opens a small connection pool+ (2–3 conns) and drives every enabled collector on its own tick. Ticks are+ aligned to wall-clock boundaries (`:00`, `:10`, …) so samples from different+ servers line up.+* **Collector** — produces a `Snapshot` (batch of rows + identity + timestamp)+ each tick. Two kinds, see §2.+* **Sink** — trait. First implementation writes straight to the stats+ Postgres. Future: HTTP-to-ingest-API, file/S3 for replay. Collection code+ never knows where data goes.++The collector holds **per-collector, per-server in-memory `State`** so cumulative+sources (`pg_stat_statements`, `pg_stat_user_tables`, …) are turned into deltas+without reading back from storage.++## 2. Two tiers of collectors++### Tier A — declarative SQL collectors (`collectors/*.yaml`)++Most stats are "run this query every N seconds, key by these columns, diff these+counters". Those are YAML files loaded at startup — no code:++```yaml+name: table_stats+interval: 10m+scope: database # cluster = once per server | database = once per db+min_pg_version: 12+kind: cumulative # cumulative | gauge | snapshot+key: [schemaname, relname]+query: |+ SELECT schemaname, relname, seq_scan, seq_tup_read, idx_scan, idx_tup_fetch,+ n_tup_ins, n_tup_upd, n_tup_del, n_tup_hot_upd,+ n_live_tup, n_dead_tup, n_mod_since_analyze,+ vacuum_count, autovacuum_count, analyze_count, autoanalyze_count,+ last_vacuum, last_autovacuum, last_analyze, last_autoanalyze+ FROM pg_stat_user_tables+```++`kind` tells the pipeline what to do with the rows:++| kind | behaviour |+|---|---|+| `gauge` | write rows as-is with `collected_at` |+| `cumulative` | numeric non-key columns are diffed against the previous tick per `key`; negative delta or changed `stats_reset` ⇒ drop tick, re-baseline; non-numeric columns pass through |+| `snapshot` | rows are a full picture of an entity set; sink upserts into a current table and records a content hash so diffs become `events` |++The sink derives the target table (`ts_<name>` / `cur_<name>`) from the query's+result columns and adds missing columns (`ALTER TABLE … ADD COLUMN … NULL`) on+first sight. **Adding a stat = adding a column to the SELECT.**++### Tier B — code collectors (`src/collectors/*.rs`)++For the few sources that need real logic. Same trait:++```rust+#[async_trait]+pub trait Collector: Send + Sync {+ fn name(&self) -> &str;+ fn interval(&self) -> Duration;+ fn scope(&self) -> Scope; // Cluster | Database+ fn min_pg_version(&self) -> u32 { 120000 }+ async fn collect(&self, cx: &CollectCtx, prev: Option<&State>) -> Result<(Snapshot, State)>;+}+```++Planned Tier B collectors:++* **`query_stats`** — `pg_stat_statements` deltas (§4).+* (`activity_samples`, `activity_sessions`, `lock_waits` turned out to be+ expressible in SQL — they are Tier A YAML.)+* **`schema`** — catalog snapshot + diff → schema-change events.+* **`vacuum_needed`** — derived: per-table dead tuples vs. effective autovacuum+ threshold (reloptions ⊕ GUCs), `age(relfrozenxid)` vs `autovacuum_freeze_max_age`.+* **`logs`** — RDS log tailing (phase 4).+* **`explain`** — plan collection (phase 4).+* **`system`** — CloudWatch metrics (phase 4).++## 3. Catalog of what we collect++| 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 | 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)` |+| 60s | bgwriter / checkpointer | A | `pg_stat_bgwriter`; `pg_stat_checkpointer` on 17+ |+| 60s | wal | A | `pg_stat_wal` (14+) |+| 60s | io | A | `pg_stat_io` (16+) |+| 60s | archiver | A | `pg_stat_archiver` |+| 60s | replication | A | `pg_stat_replication`, `pg_replication_slots`, `pg_stat_wal_receiver`, recovery status / replay lag (Aurora: `aurora_replica_status()` when present) |+| 60s | vacuum progress | A | `pg_stat_progress_vacuum` / `_analyze` / `_cluster` / `_create_index` |+| 10m | table stats | A | `pg_stat_user_tables`, `pg_statio_user_tables` |+| 10m | index stats | A | `pg_stat_user_indexes`, `pg_statio_user_indexes` |+| 10m | relation sizes | A | `pg_total_relation_size` etc., TOAST, bloat estimate (heuristic, no pgstattuple) |+| 10m | vacuum needed | B | derived from table stats + settings |+| 1h | schema | B | `pg_class`, `pg_attribute`, `pg_index`, `pg_constraint`, partitions, view defs |+| 1h | settings | A (snapshot) | `pg_settings` |+| 1h | extensions / roles / version | A (snapshot) | `pg_extension`, `pg_roles`, `version()` |+| 60s | query plans (Aurora) | B | `aurora_stat_plans` — pgss split by `planid`, plan text into `cur_query_plans` |+| 60s | system waits (Aurora) | A | `aurora_stat_system_waits` — exact wait counts/time per event |+| 10s | backend waits (Aurora) | A | `aurora_stat_backend_waits(pid)` for non-idle backends, top 5 events |+| 60s | db latency (Aurora) | A | `aurora_stat_get_db_commit_latency`, `aurora_stat_dml_activity` |+| 60s | replica status (Aurora) | A | `aurora_replica_status()` — lag, replay latency, oldest read view |+| 60s | memory contexts (Aurora) | A | `aurora_stat_memctx_usage()` — backends > 64 MB |+| 60s | system cpu / memory / disk | A | `pg_proctab`: `pg_cputime`, `pg_memusage`, `pg_loadavg`, `pg_diskusage` |+| 60s | backend cpu | A | `pg_proctab()` per pid joined to `pg_stat_activity` |+| 30s | logs | B | CloudWatch Logs (RDS) or files: `ts_query_durations` (latency quantiles), `ts_log_plans` (auto_explain), `ts_autovacuum_runs`, `ts_checkpoints`, `ts_temp_files`, `ts_log_errors`, `ts_logs` counts, deadlock/lock-wait/cancel events |++On Aurora, `query_stats` reads `aurora_stat_statements` (adds Aurora-storage I/O+and per-query peak memory) and `activity_samples` reads `aurora_stat_activity`+(adds `plan_id`). Collectors declare `requires: {aurora, extension}`; the+scheduler probes each target's capabilities and skips unmet ones, re-checking+every 10 minutes so `CREATE EXTENSION` is picked up live. See+`docs/telemetry-sources.md` for the research behind these.++## 4. Identity and delta semantics++**Server** — `server_id` from config (stable human name) plus+`pg_control_system().system_identifier` recorded on `cur_servers`. Aurora+failover keeps the same system identifier; restore-from-snapshot does not,+which we surface as an event rather than silently splitting history.++**Database** — `(server_id, datname)`. `oid` stored, not part of the key.++**Relation** — `(server_id, datname, schemaname, relname)`; `oid` alongside.+`pg_repack` and table recreation change OIDs; names survive.++**Query** — `query_id` (from `compute_query_id = on`, PG14+; falls back to+`pg_stat_statements.queryid`). Text is stored once in `cur_queries` keyed by+`(server_id, query_id)`, fetched with `pg_stat_statements(showtext := false)`+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 latency: what you can and cannot get.** `pg_stat_statements` exposes+`calls`, `total`, `min`, `max`, `mean`, `stddev` per query — no per-call+distribution — so per-call quantiles (p95 of query X) cannot be derived from it.+What we do instead:++* store `sumsq_exec_time` per interval (`calls × (stddev² + mean²)` is cumulative+ and deltas cleanly), so mean **and** stddev are exact for any time range;+* `activity_samples` (10s) records, per `query_id`, how many backends were seen+ running it and for how long (`active_over_1s`, `active_over_10s`,+ `max_query_age_s`) — a sampled view of the tail, ASH-style;+* real quantiles come from sampled statement logs (phase 4):+ `log_min_duration_sample` + `log_statement_sample_rate` → `ts_query_durations`+ keyed by the same `query_id`, from which the API computes p50/p95/p99.++**Cumulative counters** — always stored as per-interval deltas. Rows whose every+counter delta is zero are not written (idle pg_stat_statements entries would+otherwise dominate). Reset detection:++1. `stats_reset` column present and changed → drop tick, re-baseline.+2. Any numeric delta < 0 → drop tick, re-baseline (per row, not whole tick).+3. Row absent in previous state → baseline, no emit.+4. `pg_stat_statements_info.dealloc` incremented → emit `event: pgss_dealloc`+ (means our top-N is lossy; raise `pg_stat_statements.max`).++Previous state is in memory. On clean shutdown it is persisted to the stats DB+(`collector_state` table, JSONB) so a restart loses at most one interval.++**Activity sampling** — each 10s tick records aggregate counts, plus raw rows for+"interesting" backends (active > 5s, waiting on a lock, idle-in-transaction+> 60s). Wait-event charts come from the aggregate; blocked-session drill-down+from the raw rows.++## 5. Storage schema (stats Postgres)++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`,+`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.++**Current state** `cur_<collector>` — upsert by identity, with `first_seen`,+`last_seen`, `content_hash`. Snapshot diffs append to `events(server_id,+datname, at, kind, subject, before jsonb, after jsonb)`.++Hand-written tables (Tier B): `ts_query_stats`, `cur_queries`,+`ts_activity_samples`, `ts_activity_sessions`, `ts_lock_waits`,+`cur_relations`, `cur_indexes`, `cur_settings`, `events`, `collector_state`,+`collector_runs` (self-metrics: per collector/server tick duration, rows,+error). Roll-ups (`ts_query_stats_1h`) are done by a periodic job in the sink,+not by the collector.++Migrations: `migrations/*.sql`, applied by the sink on startup (`sqlx` migrate).++## 6. Operational safety on RDS++* Role: `GRANT pg_monitor` (covers `pg_read_all_stats` + `pg_read_all_settings`).+ No table data. Provisioned as a `monitor` tier in `aurora_user_management`.+* Never behind PgBouncer: session GUCs would be lost under transaction pooling.+ The collector checks for `SHOW pool_mode` and refuses to start. `pg_stats` (column stats, contains sample values) is opt-in.+* Every session: `statement_timeout = 5s`, `lock_timeout = 1s`,+ `application_name = 'pgcollector'`, `default_transaction_read_only = on`.+* Expensive collectors (`sizes`, `schema`) run against a reader endpoint if+ `reader_url` is configured, else against the writer.+* Per-server concurrency = 1 heavy collector at a time; 10s collectors have a+ reserved connection so a slow `sizes` tick never delays activity sampling.+* Sink outage: bounded on-disk buffer (default 200 MB); drop 10m-tier+ snapshots before 10s-tier ones.+* Self-metrics into `collector_runs` and exposed at `/metrics` (Prometheus) so+ the collector's own footprint on the DB is visible.+* RDS specifics: `rds_superuser` not needed; `log_line_prefix`/`auto_explain`+ are parameter-group changes documented in `docs/rds-setup.md` (phase 4).++## 7. Config++Deployment is via the PostHog golden chart; see `docs/deploy.md`. Two ways to+declare servers, merged by `id`:++* **Env vars** (the normal path — one Helm `psql:` entry per cluster):+ `PGCOLLECTOR_SERVER_<ID>_URL`, `..._READER_URL`, `..._INSTANCE_<NAME>_URL`.+* **TOML `[[servers]]`** for per-server overrides and instance lists.++Databases are re-discovered every `rediscover_interval`; new databases get+their collectors started, dropped ones stopped. Per-collector settings merge+`[defaults.overrides]` → `[servers.overrides]` (`enabled`, `interval`).++Identity gains an `instance` dimension (`writer` | name from `instances`):+cluster-scoped collectors run per instance because Aurora replicas keep their+own stats; database-scoped ones run on the writer unless `per_instance: true`.++```toml+[sink]+database_url = "postgres://pgcollector@stats-host/pgcollector"+retention_days = 14++[defaults]+statement_timeout = "5s"+databases = ["*"] # or explicit list; excludes template*/rdsadmin++[defaults.overrides]+sizes = { interval = "30m" }++[[servers]] # optional when PGCOLLECTOR_SERVER_PROD_MAIN_URL is set+id = "prod-main"+url = "${PGCOLLECTOR_SERVER_PROD_MAIN_URL}"+reader_url = "${PGCOLLECTOR_SERVER_PROD_MAIN_READER_URL}"+databases = ["posthog"]+[servers.instances]+reader-1 = "${PROD_MAIN_READER_1_URL}"+[servers.overrides]+activity = { interval = "5s" }+sizes = { enabled = false }+```++Secrets come from env (`${VAR}` expansion in URLs).++## 8. Phasing++1. ✅ **Skeleton** — config, scheduler, `Collector` trait, YAML loader, Postgres+ sink with auto-DDL + partitioning, Tier A collectors, `collector_runs`.+2. ✅ **`query_stats` + `activity_samples` / `activity_sessions` + `lock_waits`**.+3. ✅ **Aurora + pg_proctab sources** (Tier 1 of `docs/telemetry-sources.md`).+ Validated against stub functions with the documented shapes; needs a first+ run on a real Aurora cluster.+4. ✅ **Schema / settings / extension snapshots → change events; `vacuum_needed`; xid age.**+5. ✅ **Logs** — CloudWatch Logs + file sources, prefix-driven parser, durations+ (real latency quantiles), auto_explain plans, autovacuum, checkpoints, temp+ files, errors, deadlock/lock-wait/cancel events. Query fingerprint on+ `cur_queries` for joining when `%Q` isn't in the prefix.+6. ✅ **`pgapi`** — REST + MCP (17 tools) over the stats DB; edge-provided+ identity (Tailscale whois / ALB Cognito JWT / auth gateway), domain+ allowlist, read-only. UI still to come.+7. UI on top of `pgapi` on top of the stats DB (separate design).++## 9. Non-goals (for now)++* Multi-tenant SaaS concerns (org/user auth) — single team, single stats DB.+* Long retention / downsampled cold storage.+* Running `EXPLAIN ANALYZE` on production. Never.diff --git a/rust/pgcollector/README.md b/rust/pgcollector/README.mdnew file mode 100644index 000000000000..37bc7dbd360a--- /dev/null+++ b/rust/pgcollector/README.md@@ -0,0 +1,87 @@+# pgcollector++A Postgres telemetry collector for RDS/Aurora: query statistics, activity and+wait events, table/index/vacuum health, schema and settings changes, and+statement-level data from the Postgres log, written to a Postgres stats+database that `pgapi` serves.+See [DESIGN.md](DESIGN.md) for the full design.++## Run++```sh+cp deploy/pgcollector.example.toml pgcollector.toml # edit servers + sink+cargo run -p pgcollector -- --check # validate config + collectors+cargo run -p pgcollector -- --once # run every collector once, print to stdout+cargo run -p pgcollector # run forever+```++Target role: `GRANT pg_monitor TO pgcollector;` — nothing else.++TLS is required for every connection (sink and targets) unless the URL says+`sslmode=disable` (local dev) or `sslmode=prefer`. Statement text taken from+logs and `pg_stat_activity` is stored with string literals replaced by `'?'`.++Servers can be declared in TOML or discovered from env vars+(`PGCOLLECTOR_SERVER_<ID>_URL`, `..._READER_URL`, `..._INSTANCE_<NAME>_URL`) —+see [docs/deploy.md](docs/deploy.md) for the Helm + Terraform setup.+`/healthz`, `/readyz`, `/metrics` on `:9187`.++## Adding a stat++Most collectors are YAML in `collectors/`, compiled into the binary; a+`--collectors-dir` overlay can replace, add, or (`enabled: false`) remove one+at runtime. To add a column, add it to the+`SELECT`; the sink adds the column to `ts_<name>` / `cur_<name>` on the next+tick. To add a new stat source, add a new file:++```yaml+name: my_stats+interval: 60s+scope: cluster # or: database+kind: cumulative # gauge | cumulative | snapshot+key: [some_id]+query: SELECT ...+variants: # optional, version-specific SQL (highest matching wins)+ - min_pg_version: 170000+ query: SELECT ...+```++`per_instance: true|false` overrides the default (cluster scope → every+instance, database scope → writer only).++Rules: cast anything that isn't bool/int/float/numeric/text/timestamptz/json+(`::text`, `::bigint`, `::float8`). `cumulative` diffs every numeric non-key+column per `key` and understands a `stats_reset` column.++Logic-heavy collectors (`pg_stat_statements`, activity sampling, locks, schema+diffs) are Rust in `src/collectors/` implementing the same `Collector` trait.++Validate a `log_line_prefix` against a log file:+`pgcollector --parse-log postgresql.log --log-line-prefix '%t:%r:%u@%d:[%p]:%Q:'`.++## Local testing++`test/setup-local.sh` starts a throwaway PG16 with `pg_stat_statements`,+`auto_explain`, file logging into `.local/pglog/`, and stub `aurora_*`+functions (`test/aurora_stubs.sql`) so the Aurora collectors can be exercised.++## Layout++```text+src/collector.rs Collector trait, Snapshot/Row/Value, shared delta logic+src/collectors/ registry + declarative (YAML) collector+src/scheduler.rs per-server, per-collector tick loops+src/sink/ Sink trait; Postgres sink (auto-DDL, partitions, retention)+src/pg.rs target connections (TLS, session safety settings, PgBouncer guard)+src/http.rs /healthz /readyz /metrics+deploy/, docs/deploy.md golden-chart values + Terraform user tier+collectors/*.yaml Tier A collectors+migrations/*.sql hand-written sink tables+```++## Provenance++Every query in `collectors/` and `src/collectors/` was written for this project+against the PostgreSQL and Aurora documentation. Nothing is copied from+pgwatch, postgres_exporter or any other project; the+research notes in `docs/telemetry-sources.md` cite their docs only.diff --git a/rust/pgcollector/collectors/activity_samples.yaml b/rust/pgcollector/collectors/activity_samples.yamlnew file mode 100644index 000000000000..a9b068fe02b7--- /dev/null+++ b/rust/pgcollector/collectors/activity_samples.yaml@@ -0,0 +1,49 @@+name: activity_samples+description: >+ 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.+interval: 10s+scope: cluster+kind: gauge+query: |+ SELECT datname, usename, backend_type, state, wait_event_type, wait_event,+ NULL::bigint AS query_id,+ 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,+ max(extract(epoch FROM now() - query_start))::float8 AS max_query_age_s,+ max(extract(epoch FROM now() - xact_start))::float8 AS max_xact_age_s+ FROM pg_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+variants:+ - aurora: true+ min_pg_version: 140000+ query: |+ 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,+ 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,+ max(extract(epoch FROM now() - query_start))::float8 AS max_query_age_s,+ max(extract(epoch FROM now() - xact_start))::float8 AS max_xact_age_s+ 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+ - min_pg_version: 140000+ query: |+ SELECT datname, usename, backend_type, state, wait_event_type, wait_event,+ CASE WHEN state = 'active' THEN query_id END AS query_id,+ 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,+ max(extract(epoch FROM now() - query_start))::float8 AS max_query_age_s,+ max(extract(epoch FROM now() - xact_start))::float8 AS max_xact_age_s+ FROM pg_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,7diff --git a/rust/pgcollector/collectors/activity_sessions.yaml b/rust/pgcollector/collectors/activity_sessions.yamlnew file mode 100644index 000000000000..1f4453c7b02b--- /dev/null+++ b/rust/pgcollector/collectors/activity_sessions.yaml@@ -0,0 +1,41 @@+name: activity_sessions+description: >+ Raw rows for "interesting" backends only: active > 5s, waiting on a lock,+ or idle in transaction > 60s. Drill-down companion to activity_samples.+interval: 10s+scope: cluster+kind: gauge+query: |+ SELECT pid, datname, usename, application_name, client_addr::text AS client_addr,+ backend_type, state, wait_event_type, wait_event,+ NULL::bigint AS query_id,+ backend_start, xact_start, query_start, state_change,+ extract(epoch FROM now() - query_start)::float8 AS query_age_s,+ extract(epoch FROM now() - xact_start)::float8 AS xact_age_s,+ 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,+ regexp_replace(left(query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS query+ FROM pg_stat_activity+ WHERE backend_type = 'client backend' AND pid <> pg_backend_pid()+ AND ( (state = 'active' AND now() - query_start > interval '5 seconds')+ OR wait_event_type = 'Lock'+ OR (state = 'idle in transaction' AND now() - state_change > interval '60 seconds'))+variants:+ - min_pg_version: 140000+ query: |+ SELECT pid, datname, usename, application_name, client_addr::text AS client_addr,+ backend_type, state, wait_event_type, wait_event,+ query_id,+ backend_start, xact_start, query_start, state_change,+ extract(epoch FROM now() - query_start)::float8 AS query_age_s,+ extract(epoch FROM now() - xact_start)::float8 AS xact_age_s,+ 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,+ regexp_replace(left(query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS query+ FROM pg_stat_activity+ WHERE backend_type = 'client backend' AND pid <> pg_backend_pid()+ AND ( (state = 'active' AND now() - query_start > interval '5 seconds')+ OR wait_event_type = 'Lock'+ OR (state = 'idle in transaction' AND now() - state_change > interval '60 seconds'))diff --git a/rust/pgcollector/collectors/aurora_backend_waits.yaml b/rust/pgcollector/collectors/aurora_backend_waits.yamlnew file mode 100644index 000000000000..ce7afc461fb5--- /dev/null+++ b/rust/pgcollector/collectors/aurora_backend_waits.yaml@@ -0,0 +1,30 @@+name: aurora_backend_waits+description: >+ Per-session wait profile (aurora_stat_backend_waits) for non-idle client+ backends only: top 5 wait events by cumulative time since the connection+ opened. Gauge — cumulative per pid, and pids get reused, so the API should+ key on (pid, backend_start). wait_time is milliseconds.+interval: 10s+scope: cluster+kind: gauge+# Off by default: one aurora_stat_backend_waits() call per non-idle backend+# every 10s. Enable per server once the active-backend count is known to be+# small (overrides.aurora_backend_waits.enabled = true).+enabled: false+requires: { aurora: true }+query: |+ SELECT pid, backend_start, datname, usename, application_name, state,+ wait_event_type AS current_wait_event_type, wait_event AS current_wait_event,+ query_id, type_name, event_name, waits, wait_time+ FROM (+ SELECT a.pid, a.backend_start, a.datname, a.usename, a.application_name, a.state,+ a.wait_event_type, a.wait_event, a.query_id,+ wt.type_name, we.event_name, bw.waits, bw.wait_time,+ rank() OVER (PARTITION BY a.pid ORDER BY bw.wait_time DESC) AS r+ FROM pg_stat_activity a+ CROSS JOIN LATERAL aurora_stat_backend_waits(a.pid) bw+ NATURAL JOIN aurora_stat_wait_type() wt+ NATURAL JOIN aurora_stat_wait_event() we+ WHERE a.backend_type = 'client backend' AND a.state <> 'idle' AND a.pid <> pg_backend_pid()+ ) x+ WHERE r <= 5diff --git a/rust/pgcollector/collectors/aurora_db_latency.yaml b/rust/pgcollector/collectors/aurora_db_latency.yamlnew file mode 100644index 000000000000..9540066ac83c--- /dev/null+++ b/rust/pgcollector/collectors/aurora_db_latency.yaml@@ -0,0 +1,27 @@+name: aurora_db_latency+description: >+ Per-database commit latency (aurora_stat_get_db_commit_latency) and DML+ counts + latency by statement class (aurora_stat_dml_activity). All+ cumulative microseconds/counts; reset by pg_stat_reset, so stats_reset from+ pg_stat_database is included for reset detection.+interval: 60s+scope: cluster+kind: cumulative+requires: { aurora: true }+key: [datname]+query: |+ SELECT d.datname,+ aurora_stat_get_db_commit_latency(d.oid)::bigint AS commit_latency_us,+ (dml).select_count::bigint AS select_count,+ (dml).select_latency_microsecs::bigint AS select_latency_us,+ (dml).insert_count::bigint AS insert_count,+ (dml).insert_latency_microsecs::bigint AS insert_latency_us,+ (dml).update_count::bigint AS update_count,+ (dml).update_latency_microsecs::bigint AS update_latency_us,+ (dml).delete_count::bigint AS delete_count,+ (dml).delete_latency_microsecs::bigint AS delete_latency_us,+ s.stats_reset+ FROM pg_database d+ JOIN pg_stat_database s ON s.datid = d.oid+ CROSS JOIN LATERAL aurora_stat_dml_activity(d.oid) dml+ WHERE NOT d.datistemplate AND d.datname <> 'rdsadmin'diff --git a/rust/pgcollector/collectors/aurora_memctx.yaml b/rust/pgcollector/collectors/aurora_memctx.yamlnew file mode 100644index 000000000000..89761dc11d54--- /dev/null+++ b/rust/pgcollector/collectors/aurora_memctx.yaml@@ -0,0 +1,30 @@+name: aurora_memctx+description: >+ Memory context usage per backend (aurora_stat_memctx_usage), aggregated per+ pid with its largest context. Only backends over 64 MB allocated are+ recorded, so this is empty on a healthy instance and names the culprit when+ something balloons.+interval: 60s+scope: cluster+kind: gauge+# Off by default: aurora_stat_memctx_usage() returns every context of every+# process (tens of rows per backend) and is scanned twice here. Enable when+# investigating memory growth (overrides.aurora_memctx.enabled = true).+enabled: false+requires: { aurora: true }+query: |+ WITH per_pid AS (+ SELECT pid, sum(allocated)::bigint AS allocated_bytes, sum(used)::bigint AS used_bytes,+ sum(instances)::bigint AS contexts+ FROM aurora_stat_memctx_usage() GROUP BY pid+ ), top_ctx AS (+ SELECT DISTINCT ON (pid) pid, name AS top_context, allocated AS top_context_bytes+ FROM aurora_stat_memctx_usage() ORDER BY pid, allocated DESC+ )+ SELECT p.pid, a.backend_start, a.datname, a.usename, a.application_name, a.backend_type, a.state,+ a.query_id, regexp_replace(left(a.query, 500), $$'(?:[^']|'')*'$$, '''?''', 'g') AS query,+ p.allocated_bytes, p.used_bytes, p.contexts, t.top_context, t.top_context_bytes+ FROM per_pid p+ JOIN top_ctx t USING (pid)+ LEFT JOIN pg_stat_activity a ON a.pid = p.pid+ WHERE p.allocated_bytes > 64 * 1024 * 1024diff --git a/rust/pgcollector/collectors/aurora_replica_status.yaml b/rust/pgcollector/collectors/aurora_replica_status.yamlnew file mode 100644index 000000000000..f0c8a4899bea--- /dev/null+++ b/rust/pgcollector/collectors/aurora_replica_status.yaml@@ -0,0 +1,29 @@+name: aurora_replica_status+description: >+ Aurora's replication view (pg_stat_replication is empty on Aurora): one row+ per instance in the cluster with replica lag, replay latency, oldest read+ view, and storage-daemon CPU. Writer-only (same data from every instance).+interval: 60s+scope: cluster+kind: gauge+per_instance: false+requires: { aurora: true }+query: |+ SELECT server_id AS instance_id,+ CASE WHEN session_id = 'MASTER_SESSION_ID' THEN 'writer' ELSE 'reader' END AS role,+ replica_lag_in_msec::float8 AS replica_lag_ms,+ cur_replay_latency_in_usec::bigint AS replay_latency_us,+ active_txns::bigint AS active_txns,+ durable_lsn::text AS durable_lsn,+ highest_lsn_rcvd::text AS highest_lsn_rcvd,+ current_read_lsn::text AS current_read_lsn,+ oldest_read_view_lsn::text AS oldest_read_view_lsn,+ feedback_xmin::text::bigint AS feedback_xmin,+ pending_read_ios::bigint AS pending_read_ios,+ read_ios::bigint AS read_ios,+ cpu::float8 AS storage_daemon_cpu,+ log_stream_speed_in_kib_per_second::float8 AS log_stream_kib_s,+ last_transport_error::bigint AS last_transport_error,+ last_error_timestamp,+ last_update_timestamp+ FROM aurora_replica_status()diff --git a/rust/pgcollector/collectors/aurora_system_waits.yaml b/rust/pgcollector/collectors/aurora_system_waits.yamlnew file mode 100644index 000000000000..fe165db7c8f5--- /dev/null+++ b/rust/pgcollector/collectors/aurora_system_waits.yaml@@ -0,0 +1,15 @@+name: aurora_system_waits+description: >+ Exact cumulative wait counts and wait time per wait event for this instance+ (aurora_stat_system_waits). Unlike activity sampling this is measured, not+ sampled. wait_time is microseconds. Resets on instance restart.+interval: 60s+scope: cluster+kind: cumulative+requires: { aurora: true }+key: [type_name, event_name]+query: |+ SELECT t.type_name, e.event_name, w.waits, w.wait_time+ FROM aurora_stat_system_waits() w+ NATURAL JOIN aurora_stat_wait_type() t+ NATURAL JOIN aurora_stat_wait_event() ediff --git a/rust/pgcollector/collectors/backend_cpu.yaml b/rust/pgcollector/collectors/backend_cpu.yamlnew file mode 100644index 000000000000..3794a1bb3833--- /dev/null+++ b/rust/pgcollector/collectors/backend_cpu.yaml@@ -0,0 +1,20 @@+name: backend_cpu+description: >+ Per-backend CPU, page faults and I/O from /proc via pg_proctab, joined to+ pg_stat_activity — attributes host CPU to users/queries (what pg_stat_kcache+ would give). Cumulative per (pid, backend_start); rss is a gauge.+interval: 60s+scope: cluster+kind: cumulative+requires: { extension: pg_proctab }+key: [pid, backend_start]+passthrough: [rss_kb, num_threads]+query: |+ SELECT a.pid, a.backend_start, a.datname, a.usename, a.application_name, a.backend_type,+ p.utime AS utime_jiffies, p.stime AS stime_jiffies,+ p.minflt, p.majflt,+ p.rchar AS read_chars, p.wchar AS write_chars, p.reads AS read_bytes, p.writes AS write_bytes,+ (p.rss * 4)::bigint AS rss_kb, p.num_threads+ FROM pg_proctab() p+ JOIN pg_stat_activity a ON a.pid = p.pid+ WHERE a.backend_type IN ('client backend', 'autovacuum worker', 'parallel worker', 'checkpointer', 'background writer', 'walwriter')diff --git a/rust/pgcollector/collectors/bgwriter.yaml b/rust/pgcollector/collectors/bgwriter.yamlnew file mode 100644index 000000000000..277e1b7e1465--- /dev/null+++ b/rust/pgcollector/collectors/bgwriter.yaml@@ -0,0 +1,24 @@+name: bgwriter+description: Checkpoint and background writer activity (pg_stat_bgwriter; split with pg_stat_checkpointer on 17+).+interval: 60s+scope: cluster+kind: cumulative+key: [id]+query: |+ SELECT 1 AS id,+ checkpoints_timed, checkpoints_req,+ checkpoint_write_time, checkpoint_sync_time,+ buffers_checkpoint, buffers_clean, maxwritten_clean,+ buffers_backend, buffers_backend_fsync, buffers_alloc,+ stats_reset+ FROM pg_stat_bgwriter+variants:+ - min_pg_version: 170000+ query: |+ SELECT 1 AS id,+ c.num_timed AS checkpoints_timed, c.num_requested AS checkpoints_req,+ c.write_time AS checkpoint_write_time, c.sync_time AS checkpoint_sync_time,+ c.buffers_written AS buffers_checkpoint,+ b.buffers_clean, b.maxwritten_clean, b.buffers_alloc,+ b.stats_reset+ FROM pg_stat_bgwriter b, pg_stat_checkpointer cdiff --git a/rust/pgcollector/collectors/database_stats.yaml b/rust/pgcollector/collectors/database_stats.yamlnew file mode 100644index 000000000000..6b37a0c2a3bc--- /dev/null+++ b/rust/pgcollector/collectors/database_stats.yaml@@ -0,0 +1,36 @@+name: database_stats+description: Per-database throughput, cache hit, temp files, deadlocks, xid age.+interval: 60s+scope: cluster+kind: cumulative+key: [datname]+query: |+ SELECT d.datname,+ s.numbackends,+ s.xact_commit, s.xact_rollback,+ s.blks_read, s.blks_hit,+ s.tup_returned, s.tup_fetched, s.tup_inserted, s.tup_updated, s.tup_deleted,+ s.conflicts, s.temp_files, s.temp_bytes, s.deadlocks,+ s.blk_read_time, s.blk_write_time,+ s.stats_reset,+ age(d.datfrozenxid)::bigint AS xid_age+ FROM pg_stat_database s+ JOIN pg_database d ON d.oid = s.datid+ WHERE NOT d.datistemplate AND d.datname <> 'rdsadmin'+variants:+ - min_pg_version: 140000+ query: |+ SELECT d.datname,+ s.numbackends,+ s.xact_commit, s.xact_rollback,+ s.blks_read, s.blks_hit,+ s.tup_returned, s.tup_fetched, s.tup_inserted, s.tup_updated, s.tup_deleted,+ s.conflicts, s.temp_files, s.temp_bytes, s.deadlocks,+ s.blk_read_time, s.blk_write_time,+ s.session_time, s.active_time, s.idle_in_transaction_time,+ s.sessions, s.sessions_abandoned, s.sessions_fatal, s.sessions_killed,+ s.stats_reset,+ age(d.datfrozenxid)::bigint AS xid_age+ FROM pg_stat_database s+ JOIN pg_database d ON d.oid = s.datid+ WHERE NOT d.datistemplate AND d.datname <> 'rdsadmin'diff --git a/rust/pgcollector/collectors/extensions.yaml b/rust/pgcollector/collectors/extensions.yamlnew file mode 100644index 000000000000..6e2d3027b6a4--- /dev/null+++ b/rust/pgcollector/collectors/extensions.yaml@@ -0,0 +1,9 @@+name: extensions+description: Installed extensions per database. Snapshot with change events.+interval: 1h+scope: database+kind: snapshot+key: [extname]+query: |+ SELECT e.extname, e.extversion, n.nspname AS schemaname, e.extrelocatable AS relocatable+ FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespacediff --git a/rust/pgcollector/collectors/index_stats.yaml b/rust/pgcollector/collectors/index_stats.yamlnew file mode 100644index 000000000000..d2da721944f2--- /dev/null+++ b/rust/pgcollector/collectors/index_stats.yaml@@ -0,0 +1,12 @@+name: index_stats+description: Per-index usage counters; drives unused-index detection.+interval: 10m+scope: database+kind: cumulative+key: [schemaname, relname, indexrelname]+query: |+ SELECT s.schemaname, s.relname, s.indexrelname, s.indexrelid::bigint AS indexrelid,+ s.idx_scan, s.idx_tup_read, s.idx_tup_fetch,+ io.idx_blks_read, io.idx_blks_hit+ FROM pg_stat_user_indexes s+ JOIN pg_statio_user_indexes io ON io.indexrelid = s.indexreliddiff --git a/rust/pgcollector/collectors/lock_waits.yaml b/rust/pgcollector/collectors/lock_waits.yamlnew file mode 100644index 000000000000..e584378f1cbe--- /dev/null+++ b/rust/pgcollector/collectors/lock_waits.yaml@@ -0,0 +1,27 @@+name: lock_waits+description: >+ Blocking graph: one row per (waiter, blocker) pair, with the ungranted lock the+ waiter is queued on. Empty unless something is blocked.+interval: 10s+scope: cluster+kind: gauge+query: |+ SELECT w.pid AS waiter_pid,+ w.datname, w.usename, w.application_name,+ extract(epoch FROM now() - w.query_start)::float8 AS waiting_s,+ l.locktype, l.mode AS wanted_mode, l.relation::bigint AS relation_oid,+ CASE WHEN l.relation IS NOT NULL AND w.datname = current_database() THEN l.relation::regclass::text END AS relation,+ regexp_replace(left(w.query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS waiter_query,+ b.pid AS blocker_pid,+ b.usename AS blocker_usename,+ b.application_name AS blocker_application_name,+ b.state AS blocker_state,+ b.wait_event_type AS blocker_wait_event_type,+ extract(epoch FROM now() - b.xact_start)::float8 AS blocker_xact_age_s,+ regexp_replace(left(b.query, 2000), $$'(?:[^']|'')*'$$, '''?''', 'g') AS blocker_query+ -- pre-filter first so pg_blocking_pids() (which takes lock-manager locks)+ -- runs only for backends actually waiting on a lock, never once per backend+ FROM (SELECT * FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND pid <> pg_backend_pid()) w+ JOIN LATERAL unnest(pg_blocking_pids(w.pid)) AS bp(pid) ON true+ JOIN pg_stat_activity b ON b.pid = bp.pid+ LEFT JOIN pg_locks l ON l.pid = w.pid AND NOT l.granteddiff --git a/rust/pgcollector/collectors/replication.yaml b/rust/pgcollector/collectors/replication.yamlnew file mode 100644index 000000000000..7d4a9814a194--- /dev/null+++ b/rust/pgcollector/collectors/replication.yaml@@ -0,0 +1,16 @@+name: replication+description: Streaming replication lag per standby, plus slot retention. Empty on replicas.+interval: 60s+scope: cluster+kind: gauge+query: |+ SELECT r.application_name, r.client_addr::text AS client_addr, r.state, r.sync_state,+ pg_wal_lsn_diff(pg_current_wal_lsn(), r.sent_lsn)::bigint AS sent_lag_bytes,+ pg_wal_lsn_diff(pg_current_wal_lsn(), r.write_lsn)::bigint AS write_lag_bytes,+ pg_wal_lsn_diff(pg_current_wal_lsn(), r.flush_lsn)::bigint AS flush_lag_bytes,+ pg_wal_lsn_diff(pg_current_wal_lsn(), r.replay_lsn)::bigint AS replay_lag_bytes,+ extract(epoch FROM r.write_lag)::float8 AS write_lag_seconds,+ extract(epoch FROM r.flush_lag)::float8 AS flush_lag_seconds,+ extract(epoch FROM r.replay_lag)::float8 AS replay_lag_seconds+ FROM pg_stat_replication r+ WHERE NOT pg_is_in_recovery()diff --git a/rust/pgcollector/collectors/replication_slots.yaml b/rust/pgcollector/collectors/replication_slots.yamlnew file mode 100644index 000000000000..63281d92db6c--- /dev/null+++ b/rust/pgcollector/collectors/replication_slots.yaml@@ -0,0 +1,12 @@+name: replication_slots+description: Replication slots and how much WAL they are holding back.+interval: 60s+scope: cluster+kind: gauge+query: |+ SELECT slot_name, plugin, slot_type, database, active, temporary,+ wal_status,+ CASE WHEN pg_is_in_recovery() THEN NULL+ ELSE pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)::bigint END AS retained_wal_bytes,+ safe_wal_size::bigint AS safe_wal_size+ FROM pg_replication_slotsdiff --git a/rust/pgcollector/collectors/schema_constraints.yaml b/rust/pgcollector/collectors/schema_constraints.yamlnew file mode 100644index 000000000000..f35d5651f0ef--- /dev/null+++ b/rust/pgcollector/collectors/schema_constraints.yaml@@ -0,0 +1,18 @@+name: schema_constraints+description: Primary/unique/foreign-key/check constraints. Snapshot with change events.+interval: 1h+scope: database+kind: snapshot+prefers_reader: true+key: [schemaname, relname, conname]+query: |+ SELECT n.nspname AS schemaname, t.relname, c.conname, c.contype::text AS contype,+ pg_get_constraintdef(c.oid, true) AS definition,+ c.convalidated AS is_validated, c.condeferrable AS is_deferrable,+ CASE WHEN c.confrelid <> 0 THEN (SELECT fn.nspname || '.' || fc.relname FROM pg_class fc JOIN pg_namespace fn ON fn.oid = fc.relnamespace WHERE fc.oid = c.confrelid) END AS referenced_table,+ (SELECT string_agg(a.attname, ',' ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY k(attnum, ord)+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum) AS columns+ FROM pg_constraint c+ JOIN pg_class t ON t.oid = c.conrelid+ JOIN pg_namespace n ON n.oid = t.relnamespace+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')diff --git a/rust/pgcollector/collectors/schema_indexes.yaml b/rust/pgcollector/collectors/schema_indexes.yamlnew file mode 100644index 000000000000..cab026887fa8--- /dev/null+++ b/rust/pgcollector/collectors/schema_indexes.yaml@@ -0,0 +1,29 @@+name: schema_indexes+description: >+ Index definitions, validity and shape. Snapshot: index created/dropped/became+ invalid become schema_indexes_* events. Pair with index_stats for unused-index+ detection.+interval: 1h+scope: database+kind: snapshot+prefers_reader: true+key: [schemaname, relname, indexname]+query: |+ SELECT n.nspname AS schemaname, t.relname, i.relname AS indexname, i.oid::bigint AS oid,+ pg_get_indexdef(i.oid) AS definition,+ am.amname AS access_method,+ x.indisunique AS is_unique, x.indisprimary AS is_primary, x.indisvalid AS is_valid,+ x.indisready AS is_ready, x.indisexclusion AS is_exclusion,+ x.indnkeyatts::bigint AS n_key_columns, x.indnatts::bigint AS n_columns,+ x.indpred IS NOT NULL AS is_partial, x.indexprs IS NOT NULL AS has_expression,+ (SELECT string_agg(a.attname, ',' ORDER BY k.ord)+ FROM unnest(x.indkey) WITH ORDINALITY k(attnum, ord)+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum) AS columns,+ array_to_string(i.reloptions, ',') AS reloptions+ FROM pg_index x+ JOIN pg_class i ON i.oid = x.indexrelid+ JOIN pg_class t ON t.oid = x.indrelid+ JOIN pg_namespace n ON n.oid = t.relnamespace+ JOIN pg_am am ON am.oid = i.relam+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')+ AND n.nspname NOT LIKE 'pg_temp%'diff --git a/rust/pgcollector/collectors/schema_relations.yaml b/rust/pgcollector/collectors/schema_relations.yamlnew file mode 100644index 000000000000..d68ed2c1e870--- /dev/null+++ b/rust/pgcollector/collectors/schema_relations.yaml@@ -0,0 +1,33 @@+name: schema_relations+description: >+ Tables, partitioned tables, views and materialized views with their columns+ (as JSON) and storage options. Snapshot: changes become schema_relations_*+ events with before/after (column added, type changed, table dropped ...).+interval: 1h+scope: database+kind: snapshot+prefers_reader: true+key: [schemaname, relname]+query: |+ SELECT n.nspname AS schemaname, c.relname, c.oid::bigint AS oid, c.relkind::text AS relkind,+ c.relpersistence::text AS persistence,+ pg_get_userbyid(c.relowner) AS owner,+ c.relhasindex AS has_index, c.relispartition AS is_partition,+ (SELECT pn.nspname || '.' || pc.relname FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhparent JOIN pg_namespace pn ON pn.oid = pc.relnamespace WHERE i.inhrelid = c.oid LIMIT 1) AS parent,+ CASE WHEN c.relkind = 'p' THEN pg_get_partkeydef(c.oid) END AS partition_key,+ CASE WHEN c.relispartition THEN pg_get_expr(c.relpartbound, c.oid) END AS partition_bound,+ array_to_string(c.reloptions, ',') AS reloptions,+ (SELECT count(*) FROM pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped)::bigint AS n_columns,+ (SELECT jsonb_agg(jsonb_build_object(+ 'name', a.attname, 'type', format_type(a.atttypid, a.atttypmod),+ 'notnull', a.attnotnull, 'default', pg_get_expr(d.adbin, d.adrelid),+ 'identity', a.attidentity, 'generated', a.attgenerated)+ ORDER BY a.attnum)+ FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum+ WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped) AS columns,+ CASE WHEN c.relkind IN ('v', 'm') THEN pg_get_viewdef(c.oid, true) END AS view_definition+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE c.relkind IN ('r', 'p', 'v', 'm')+ AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')+ AND n.nspname NOT LIKE 'pg_temp%'diff --git a/rust/pgcollector/collectors/settings.yaml b/rust/pgcollector/collectors/settings.yamlnew file mode 100644index 000000000000..5e21247e53b9--- /dev/null+++ b/rust/pgcollector/collectors/settings.yaml@@ -0,0 +1,9 @@+name: settings+description: Every GUC; snapshot diffs produce setting_change events.+interval: 1h+scope: cluster+kind: snapshot+key: [name]+query: |+ SELECT name, setting, unit, source, boot_val, reset_val, pending_restart, category+ FROM pg_settingsdiff --git a/rust/pgcollector/collectors/sizes.yaml b/rust/pgcollector/collectors/sizes.yamlnew file mode 100644index 000000000000..6a7141f43458--- /dev/null+++ b/rust/pgcollector/collectors/sizes.yaml@@ -0,0 +1,19 @@+name: sizes+description: >+ Table/index/TOAST sizes. Four size functions per relation (each stats the+ relation's files), so hourly and on the reader.+interval: 1h+scope: database+kind: gauge+prefers_reader: true+query: |+ SELECT n.nspname AS schemaname, c.relname, c.relkind::text AS relkind,+ c.reltuples::bigint AS reltuples,+ pg_relation_size(c.oid) AS heap_bytes,+ pg_indexes_size(c.oid) AS index_bytes,+ COALESCE(pg_total_relation_size(c.reltoastrelid), 0) AS toast_bytes,+ pg_total_relation_size(c.oid) AS total_bytes+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE c.relkind IN ('r', 'p', 'm')+ AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')diff --git a/rust/pgcollector/collectors/system_cpu.yaml b/rust/pgcollector/collectors/system_cpu.yamlnew file mode 100644index 000000000000..93254260e816--- /dev/null+++ b/rust/pgcollector/collectors/system_cpu.yaml@@ -0,0 +1,13 @@+name: system_cpu+description: >+ Host CPU jiffies from /proc/stat via pg_proctab (CREATE EXTENSION pg_proctab;+ no reboot). Cumulative; utilisation = (user+nice+system+iowait) / total delta.+interval: 60s+scope: cluster+kind: cumulative+requires: { extension: pg_proctab }+key: [id]+query: |+ SELECT 1 AS id, "user" AS user_jiffies, nice AS nice_jiffies, system AS system_jiffies,+ idle AS idle_jiffies, iowait AS iowait_jiffies+ FROM pg_cputime()diff --git a/rust/pgcollector/collectors/system_disk.yaml b/rust/pgcollector/collectors/system_disk.yamlnew file mode 100644index 000000000000..4d98dfe9b960--- /dev/null+++ b/rust/pgcollector/collectors/system_disk.yaml@@ -0,0 +1,13 @@+name: system_disk+description: Per-device I/O counters from /proc/diskstats via pg_proctab (cumulative).+interval: 60s+scope: cluster+kind: cumulative+requires: { extension: pg_proctab }+key: [devname]+query: |+ SELECT devname, reads_completed, reads_merged, sectors_read, readtime AS read_time_ms,+ writes_completed, writes_merged, sectors_written, writetime AS write_time_ms,+ iotime AS io_time_ms, totaliotime AS weighted_io_time_ms+ FROM pg_diskusage()+ WHERE devname !~ '^(loop|ram)'diff --git a/rust/pgcollector/collectors/system_memory.yaml b/rust/pgcollector/collectors/system_memory.yamlnew file mode 100644index 000000000000..7d822d2c3921--- /dev/null+++ b/rust/pgcollector/collectors/system_memory.yaml@@ -0,0 +1,12 @@+name: system_memory+description: Host memory and load from pg_proctab (values in kB).+interval: 60s+scope: cluster+kind: gauge+requires: { extension: pg_proctab }+query: |+ SELECT m.memused AS mem_used_kb, m.memfree AS mem_free_kb, m.memshared AS mem_shared_kb,+ m.membuffers AS mem_buffers_kb, m.memcached AS mem_cached_kb,+ m.swapused AS swap_used_kb, m.swapfree AS swap_free_kb, m.swapcached AS swap_cached_kb,+ l.load1::float8 AS load1, l.load5::float8 AS load5, l.load15::float8 AS load15+ FROM pg_memusage() m, pg_loadavg() ldiff --git a/rust/pgcollector/collectors/table_stats.yaml b/rust/pgcollector/collectors/table_stats.yamlnew file mode 100644index 000000000000..7dea1b39a011--- /dev/null+++ b/rust/pgcollector/collectors/table_stats.yaml@@ -0,0 +1,21 @@+name: table_stats+description: Per-table scan/tuple/vacuum counters (pg_stat_user_tables + pg_statio_user_tables).+interval: 10m+scope: database+kind: cumulative+key: [schemaname, relname]+passthrough: [n_live_tup, n_dead_tup, n_mod_since_analyze, xid_age, mxid_age, reltuples, relpages]+query: |+ SELECT s.schemaname, s.relname, s.relid::bigint AS relid,+ s.seq_scan, s.seq_tup_read, s.idx_scan, s.idx_tup_fetch,+ s.n_tup_ins, s.n_tup_upd, s.n_tup_del, s.n_tup_hot_upd,+ s.n_live_tup, s.n_dead_tup, s.n_mod_since_analyze,+ s.vacuum_count, s.autovacuum_count, s.analyze_count, s.autoanalyze_count,+ s.last_vacuum, s.last_autovacuum, s.last_analyze, s.last_autoanalyze,+ io.heap_blks_read, io.heap_blks_hit, io.idx_blks_read, io.idx_blks_hit,+ io.toast_blks_read, io.toast_blks_hit, io.tidx_blks_read, io.tidx_blks_hit,+ age(c.relfrozenxid)::bigint AS xid_age, mxid_age(c.relminmxid)::bigint AS mxid_age,+ c.reltuples::bigint AS reltuples, c.relpages::bigint AS relpages+ FROM pg_stat_user_tables s+ JOIN pg_statio_user_tables io ON io.relid = s.relid+ JOIN pg_class c ON c.oid = s.reliddiff --git a/rust/pgcollector/collectors/vacuum_needed.yaml b/rust/pgcollector/collectors/vacuum_needed.yamlnew file mode 100644index 000000000000..9a18c11dd6cf--- /dev/null+++ b/rust/pgcollector/collectors/vacuum_needed.yaml@@ -0,0 +1,64 @@+name: vacuum_needed+description: >+ Tables that autovacuum should be handling right now, with the effective+ thresholds (reloptions override GUCs): dead tuples vs vacuum threshold,+ modified-since-analyze vs analyze threshold, inserts vs insert-vacuum+ threshold (13+), and xid/mxid age vs freeze limits. Only rows over 50% of a+ threshold are emitted, so this is usually short and the API can alert on+ ratio >= 1.0.+interval: 10m+scope: database+kind: gauge+min_pg_version: 130000+query: |+ WITH gucs AS (+ SELECT current_setting('autovacuum_vacuum_threshold')::bigint AS vac_thr,+ current_setting('autovacuum_vacuum_scale_factor')::float8 AS vac_sf,+ current_setting('autovacuum_analyze_threshold')::bigint AS ana_thr,+ current_setting('autovacuum_analyze_scale_factor')::float8 AS ana_sf,+ current_setting('autovacuum_vacuum_insert_threshold')::bigint AS ins_thr,+ current_setting('autovacuum_vacuum_insert_scale_factor')::float8 AS ins_sf,+ current_setting('autovacuum_freeze_max_age')::bigint AS freeze_max,+ current_setting('autovacuum_multixact_freeze_max_age')::bigint AS mx_freeze_max+ ), t AS (+ SELECT n.nspname AS schemaname, c.relname, c.oid,+ c.reltuples::float8 AS reltuples,+ s.n_live_tup, s.n_dead_tup, s.n_mod_since_analyze, s.n_ins_since_vacuum,+ s.last_autovacuum, s.last_vacuum, s.last_autoanalyze, s.last_analyze,+ age(c.relfrozenxid)::bigint AS xid_age, mxid_age(c.relminmxid)::bigint AS mxid_age,+ COALESCE((SELECT option_value::bigint FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_vacuum_threshold'), g.vac_thr) AS vac_thr,+ COALESCE((SELECT option_value::float8 FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_vacuum_scale_factor'), g.vac_sf) AS vac_sf,+ COALESCE((SELECT option_value::bigint FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_analyze_threshold'), g.ana_thr) AS ana_thr,+ COALESCE((SELECT option_value::float8 FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_analyze_scale_factor'), g.ana_sf) AS ana_sf,+ COALESCE((SELECT option_value::bigint FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_vacuum_insert_threshold'), g.ins_thr) AS ins_thr,+ COALESCE((SELECT option_value::float8 FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_vacuum_insert_scale_factor'), g.ins_sf) AS ins_sf,+ COALESCE((SELECT option_value::bigint FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_freeze_max_age'), g.freeze_max) AS freeze_max,+ COALESCE((SELECT option_value::bigint FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_multixact_freeze_max_age'), g.mx_freeze_max) AS mx_freeze_max,+ COALESCE((SELECT option_value::bool FROM pg_options_to_table(c.reloptions) WHERE option_name = 'autovacuum_enabled'), true) AS autovacuum_enabled+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ JOIN pg_stat_user_tables s ON s.relid = c.oid+ CROSS JOIN gucs g+ WHERE c.relkind IN ('r', 'm')+ ), scored AS (+ SELECT *,+ GREATEST(vac_thr + vac_sf * GREATEST(reltuples, 0), 1)::float8 AS vacuum_threshold,+ GREATEST(ana_thr + ana_sf * GREATEST(reltuples, 0), 1)::float8 AS analyze_threshold,+ GREATEST(ins_thr + ins_sf * GREATEST(reltuples, 0), 1)::float8 AS insert_threshold+ FROM t+ )+ SELECT schemaname, relname, oid::bigint AS relid, autovacuum_enabled,+ n_live_tup, n_dead_tup, n_mod_since_analyze, n_ins_since_vacuum,+ vacuum_threshold, analyze_threshold, insert_threshold,+ (n_dead_tup / vacuum_threshold)::float8 AS vacuum_ratio,+ (n_mod_since_analyze / analyze_threshold)::float8 AS analyze_ratio,+ (n_ins_since_vacuum / insert_threshold)::float8 AS insert_ratio,+ xid_age, freeze_max, (xid_age::float8 / freeze_max)::float8 AS freeze_ratio,+ mxid_age, mx_freeze_max, (mxid_age::float8 / mx_freeze_max)::float8 AS mx_freeze_ratio,+ last_autovacuum, last_vacuum, last_autoanalyze, last_analyze+ FROM scored+ WHERE n_dead_tup / vacuum_threshold >= 0.5+ OR n_mod_since_analyze / analyze_threshold >= 0.5+ OR n_ins_since_vacuum / insert_threshold >= 0.5+ OR xid_age::float8 / freeze_max >= 0.5+ OR mxid_age::float8 / mx_freeze_max >= 0.5diff --git a/rust/pgcollector/collectors/vacuum_progress.yaml b/rust/pgcollector/collectors/vacuum_progress.yamlnew file mode 100644index 000000000000..105abe111b81--- /dev/null+++ b/rust/pgcollector/collectors/vacuum_progress.yaml@@ -0,0 +1,23 @@+name: vacuum_progress+description: In-flight VACUUM operations. Usually empty.+interval: 60s+scope: cluster+kind: gauge+query: |+ SELECT p.pid, p.datname, p.relid::bigint AS relid, p.phase,+ p.heap_blks_total, p.heap_blks_scanned, p.heap_blks_vacuumed,+ p.index_vacuum_count, p.max_dead_tuples, p.num_dead_tuples,+ extract(epoch FROM now() - a.xact_start)::float8 AS running_seconds,+ a.query+ FROM pg_stat_progress_vacuum p+ JOIN pg_stat_activity a ON a.pid = p.pid+variants:+ - min_pg_version: 170000+ query: |+ SELECT p.pid, p.datname, p.relid::bigint AS relid, p.phase,+ p.heap_blks_total, p.heap_blks_scanned, p.heap_blks_vacuumed,+ p.index_vacuum_count, p.max_dead_tuple_bytes AS max_dead_tuples, p.dead_tuple_bytes AS num_dead_tuples,+ extract(epoch FROM now() - a.xact_start)::float8 AS running_seconds,+ a.query+ FROM pg_stat_progress_vacuum p+ JOIN pg_stat_activity a ON a.pid = p.piddiff --git a/rust/pgcollector/collectors/wal.yaml b/rust/pgcollector/collectors/wal.yamlnew file mode 100644index 000000000000..a89f56c4bb1d--- /dev/null+++ b/rust/pgcollector/collectors/wal.yaml@@ -0,0 +1,13 @@+name: wal+description: WAL generation and write/sync activity.+interval: 60s+scope: cluster+kind: cumulative+min_pg_version: 140000+key: [id]+query: |+ SELECT 1 AS id,+ wal_records, wal_fpi, wal_bytes::bigint AS wal_bytes, wal_buffers_full,+ wal_write, wal_sync, wal_write_time, wal_sync_time,+ stats_reset+ FROM pg_stat_waldiff --git a/rust/pgcollector/deploy/pgcollector.example.toml b/rust/pgcollector/deploy/pgcollector.example.tomlnew file mode 100644index 000000000000..565e0abe4e44--- /dev/null+++ b/rust/pgcollector/deploy/pgcollector.example.toml@@ -0,0 +1,25 @@+[sink]+# TLS is required unless the URL says sslmode=disable (local dev) or sslmode=prefer.+database_url = "${PGCOLLECTOR_SINK_URL}"+retention_days = 14++[defaults]+statement_timeout = "5s"+databases = ["*"]++[defaults.overrides]+# sizes = { interval = "30m" }++# Optional when PGCOLLECTOR_SERVER_<ID>_URL env vars are set (see docs/deploy.md).+[[servers]]+id = "prod-main"+url = "postgres://pgcollector:${PROD_MAIN_PASSWORD}@prod-main.xxxx.us-east-1.rds.amazonaws.com:5432/postgres"+reader_url = "postgres://pgcollector:${PROD_MAIN_PASSWORD}@prod-main-ro.xxxx.us-east-1.rds.amazonaws.com:5432/postgres"+databases = ["posthog"]++[servers.instances]+# reader-1 = "postgres://pgcollector:${PROD_MAIN_PASSWORD}@prod-main-instance-2.xxxx.us-east-1.rds.amazonaws.com:5432/postgres"++[servers.overrides]+activity = { interval = "5s" }+sizes = { enabled = false }diff --git a/rust/pgcollector/deploy/values.example.yaml b/rust/pgcollector/deploy/values.example.yamlnew file mode 100644index 000000000000..330bde7a970f--- /dev/null+++ b/rust/pgcollector/deploy/values.example.yaml@@ -0,0 +1,93 @@+# Golden-chart (charts/posthog-app) values for pgcollector.+# Copy to charts/apps/pgcollector/values.yaml and adjust the psql: entries.++image:+ name: pgcollector+ repository: 795637471508.dkr.ecr.us-east-1.amazonaws.com/pgcollector++command: ["/pgcollector"]+args: ["--config", "/etc/pgcollector/pgcollector.toml"]++role: k8s-pgcollector++# Worker: no HTTP surface except probes/metrics on :9187.+service:+ enabled: false+autoscaling:+ minPods: 1+ maxPods: 1+monitoring:+ prometheus:+ path: /metrics+ port: "9187"+livenessProbe:+ httpGet: { path: /healthz, port: 9187 }+readinessProbe:+ httpGet: { path: /readyz, port: 9187 }++resources:+ requests: { cpu: 250m, memory: 256Mi }+ limits: { cpu: 250m, memory: 512Mi }++# One psql: entry for the sink, then one per monitored cluster.+#+# pgbouncer: false is REQUIRED on every entry — pgcollector sets per-session+# statement_timeout/lock_timeout and refuses to start behind a transaction pooler.+#+# Monitored clusters need no [[servers]] config at all: the env var names below are+# the convention pgcollector discovers servers from:+# PGCOLLECTOR_SERVER_<ID>_URL writer / cluster endpoint+# PGCOLLECTOR_SERVER_<ID>_READER_URL load-balanced reader endpoint+# PGCOLLECTOR_SERVER_<ID>_INSTANCE_<NAME>_URL per-instance endpoint (optional)+# PGCOLLECTOR_SERVER_<ID>_LOG_GROUP CloudWatch log group for the logs collector+# <ID> and <NAME> are lower-cased with _ → - to form server_id / instance.+psql:+ pgcollector: # the sink; user must be in the `ddl` tier+ pgbouncer: false+ write:+ enabled: true+ env:+ PGCOLLECTOR_SINK_URL: POSTGRES_URL++ cloud: # monitored cluster; user in the `monitor` tier+ pgbouncer: false+ write:+ enabled: true+ env:+ PGCOLLECTOR_SERVER_CLOUD_URL: POSTGRES_URL+ read:+ enabled: true+ env:+ PGCOLLECTOR_SERVER_CLOUD_READER_URL: POSTGRES_URL++ persons:+ pgbouncer: false+ write:+ enabled: true+ env:+ PGCOLLECTOR_SERVER_PERSONS_URL: POSTGRES_URL+ read:+ enabled: true+ env:+ PGCOLLECTOR_SERVER_PERSONS_READER_URL: POSTGRES_URL++env:+ PGCOLLECTOR_SERVER_CLOUD_LOG_GROUP: /aws/rds/cluster/<cloud-cluster-id>/postgresql+ PGCOLLECTOR_SERVER_PERSONS_LOG_GROUP: /aws/rds/cluster/<persons-cluster-id>/postgresql++configFiles:+ pgcollector:+ path: /etc/pgcollector/pgcollector.toml+ content: |+ [sink]+ database_url = "${PGCOLLECTOR_SINK_URL}"+ retention_days = 14++ [defaults]+ databases = ["*"] # discover every database on each cluster, keep discovering+ rediscover_interval = "10m"++ # Global per-collector tuning; [[servers]] blocks (optional) can override per cluster.+ [defaults.overrides]+ # sizes = { interval = "30m" }+ # settings = { enabled = false }diff --git a/rust/pgcollector/docs/deploy.md b/rust/pgcollector/docs/deploy.mdnew file mode 100644index 000000000000..bdf16929d3b0--- /dev/null+++ b/rust/pgcollector/docs/deploy.md@@ -0,0 +1,198 @@+# Deploying pgcollector++## 1. Database users (posthog-cloud-infra)++`aurora_user_management/v3.0.0` has four tiers, all built on+`pg_read_all_data` / `pg_write_all_data`. None fit a monitoring agent:+`readonly` grants SELECT on every table (too much) while still **not** letting+the role see other users' rows in `pg_stat_statements` / `pg_stat_activity`+(too little — that needs `pg_read_all_stats`, which `pg_monitor` includes).++Add a `monitor` tier to the module. It is the same shape as the others:++```hcl+# variables.tf+variable "users_monitor" {+ description = "Users granted pg_monitor (pg_read_all_stats + pg_read_all_settings + pg_stat_scan_tables): full visibility into stats views and settings, NO data access. For telemetry agents such as pgcollector."+ type = list(string)+ default = []+}++# main.tf — locals+tier = merge(+ ...,+ { for u in var.users_monitor : u => "monitor" },+)+all_users = concat(..., var.users_monitor)++builtin_roles = {+ ...+ monitor = ["pg_monitor"]+}+database_privileges = {+ ...+ monitor = ["CONNECT"]+}+```++(`validate_tiers`' error message should mention the new list.)++Then, per monitored cluster, add `"pgcollector"` to `users_monitor` in that+cluster's users config — for the `cloud` cluster that's the `posthog_app_db_users`+module outputs (a new `cloud_users_monitor` output feeding the v3 lane), for+`persons` the `postgres-persons` configuration.++The **sink** database is a normal app database: pgcollector creates and alters+its own tables, so its user goes in `users_ddl` of whichever config manages+the stats cluster.++`pg_monitor` is enough for every collector shipped today, including+`pg_stat_statements` (the extension must be installed in the target database+— `CREATE EXTENSION pg_stat_statements` once, by a DDL user — and+`shared_preload_libraries` must include it, which is the RDS default parameter+group's setting on Aurora Postgres).++### Extensions and Aurora functions++Nothing here requires a parameter-group change or a reboot.++* `pg_stat_statements` — already in `shared_preload_libraries` on every+ cluster, but `CREATE EXTENSION` is per database and the collector reads+ cluster-wide stats from the **maintenance database (`postgres`)**. Run+ `CREATE EXTENSION IF NOT EXISTS pg_stat_statements` there (DDL user) if it+ hasn't been. This is the only step that is genuinely required.+* `pg_proctab` — optional. Not installed anywhere today; `CREATE EXTENSION+ pg_proctab` in the maintenance database enables `system_cpu`,+ `system_memory`, `system_disk`, `backend_cpu`. Until then those four log one+ `skipping: prerequisite not met` line and re-check every 10 minutes. Its+ functions may need `GRANT EXECUTE ... TO pgcollector`.+* `aurora_stat_*` / `aurora_replica_status` — built in, no setup.+ `aurora_compute_plan_id` (default on, 14.10+/15.5+) must stay on for+ `aurora_plans` and `plan_id` in activity samples.++Parameter-group niceties (dynamic, no reboot; both optional): append `%Q` to+`log_line_prefix` so log rows join `cur_queries` by query id instead of text+fingerprint; the log sampling, lock-wait and CloudWatch-export settings the+logs collector relies on are already set fleet-wide. Clusters that don't+preload `auto_explain` simply produce no `ts_log_plans`.++### Load profile on the monitored cluster++Every session runs with `statement_timeout = 5s` and `lock_timeout = 1s`, so a+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 |+| `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 |+| `aurora_plans` | 5m | `aurora_stat_plans(false)`; plan text for new plan ids | ≤ `pg_stat_statements.max` rows |+| `table_stats`, `index_stats`, `vacuum_needed` | 10m | one catalog/stats scan per database | linear in relations; on the writer |+| `sizes` | 1h | four size functions per relation | reader endpoint when configured |+| `schema_*`, `settings`, `extensions` | 1h | catalog reads | reader for schema |+| `system_*`, `backend_cpu` | 60s | `/proc` reads via `pg_proctab` | only if the extension exists |+| `aurora_backend_waits`, `aurora_memctx` | — | **off by default** | per-backend function calls; enable per server via `overrides.<name>.enabled = true` |+| `logs` | 30s | no database load | CloudWatch Logs API; bounded per tick |++### Discovering every database on a cluster++`databases = ["*"]` lists `pg_database` and connects to each one with the same+credentials. That works because v3 grants `CONNECT` on the *module's*+`database_name` only — so a cluster with several databases needs the monitor+user granted CONNECT on each, or (simpler) `GRANT CONNECT ON DATABASE x TO+pgcollector` handled by the same lane. For clusters with one application+database this is a non-issue.++## 2. Helm (charts/posthog-app)++See [`deploy/values.example.yaml`](../deploy/values.example.yaml). Key points:++* **`pgbouncer: false` on every `psql:` entry.** pgcollector sets session GUCs+ and needs stable backends; it refuses to start if it detects PgBouncer.+* **Monitored servers come from env var names**, not from the TOML. A `psql:`+ entry whose `write.env` maps `PGCOLLECTOR_SERVER_<ID>_URL: POSTGRES_URL` is all+ it takes; add `read.env: {PGCOLLECTOR_SERVER_<ID>_READER_URL: POSTGRES_URL}` for+ the reader endpoint.+ Adding a cluster = one `psql:` entry + one Terraform user.+* `configFiles:` carries the TOML (sink URL, retention, defaults). Explicit+ `[[servers]]` blocks are still allowed for per-server overrides and+ `instances`; they merge with env-discovered servers by `id`.+* Probes and metrics on `:9187` (`/healthz`, `/readyz`, `/metrics`), scraped+ via the chart's `monitoring.prometheus` pod annotations.++## 3. Logs (statement durations, plans, autovacuum, checkpoints, errors)++The `logs` collector reads the Postgres log and writes typed rows —+`ts_query_durations` is where **real per-query latency quantiles** come from.+On Aurora the log is already exported to CloudWatch Logs+(`enabled_cloudwatch_logs_exports = ["postgresql"]`), one group per cluster,+one stream per instance:++```text+PGCOLLECTOR_SERVER_CLOUD_LOG_GROUP=/aws/rds/cluster/<cluster-id>/postgresql+PGCOLLECTOR_SERVER_CLOUD_LOG_LINE_PREFIX='%t:%r:%u@%d:[%p]:' # only if not the RDS default+```++or in TOML: `logs = { source = "cloudwatch", log_group = "...", log_line_prefix = "..." }`.+The IRSA role needs `logs:FilterLogEvents` (and `logs:DescribeLogStreams`) on+those groups. The collector polls every 30s with a 10s lag, keeps its cursor in+`collector_state`, and warns when it falls behind.++Parameter-group settings that make this worthwhile (mostly already set):++| parameter | value | gives |+|---|---|---|+| `log_min_duration_sample` / `log_statement_sample_rate` | `1000` / `0.01` | sampled per-statement durations → p50/p95/p99 |+| `log_min_duration_statement` | `10000` | every slow statement |+| `log_line_prefix` | RDS default + `%Q` | **query id on every line** so log rows join `cur_queries` exactly; without it we join on a text fingerprint |+| `auto_explain.*` | json, sample 0.01 | plans for sampled slow statements → `ts_log_plans` |+| `log_lock_waits`, `log_temp_files=0`, `log_checkpoints`, `log_autovacuum_min_duration=0` | on | events + `ts_temp_files`, `ts_checkpoints`, `ts_autovacuum_runs` |++Validate a prefix against a downloaded log file with+`pgcollector --parse-log file.log --log-line-prefix '%t:%r:%u@%d:[%p]:%Q:'`.++The collector's own sessions try `SET log_min_duration_statement = -1` etc. so+they don't log themselves; grant `SET` on those GUCs to the monitor role if you+see pgcollector's queries in the log.++## 4. Replicas / multiple instances++Aurora replicas each have **their own** `pg_stat_statements`,+`pg_stat_activity`, bgwriter and I/O counters. The cluster reader endpoint+load-balances across them, so stats read through it are from "whichever+replica answered" and are useless as a time series. To see reader workload,+give pgcollector each instance endpoint:++```text+PGCOLLECTOR_SERVER_CLOUD_INSTANCE_READER_1_URL=postgres://.../ (instance endpoint)+PGCOLLECTOR_SERVER_CLOUD_INSTANCE_READER_2_URL=postgres://.../+```++or in TOML:++```toml+[[servers]]+id = "cloud"+url = "${PGCOLLECTOR_SERVER_CLOUD_URL}"+[servers.instances]+reader-1 = "${CLOUD_READER_1_URL}"+reader-2 = "${CLOUD_READER_2_URL}"+```++Cluster-scoped collectors then run against the writer **and** each instance,+and every row carries `instance` (`writer`, `reader-1`, …). Database-scoped+collectors (table/index stats, sizes, schema) run on the writer only by+default; set `per_instance: true` on a collector to change that.++Instance endpoints aren't something the `psql:` harness produces today; the+credentials are the same as the writer's, so they can be passed via+`secret_env_app_specific`, or (phase 4) discovered from the RDS API+(`rds:DescribeDBClusters` on the IRSA role) so new replicas are picked up+automatically. Aurora failover keeps the cluster endpoint pointing at the+current writer, so the `writer` series survives a failover; the promoted+instance's series moves from `reader-N` to `writer` at that point.++## 5. pgapi++The API + MCP server over this stats DB lives in `rust/pgapi` (separate PR) with its own README.diff --git a/rust/pgcollector/docs/telemetry-sources.md b/rust/pgcollector/docs/telemetry-sources.mdnew file mode 100644index 000000000000..508488a60e04--- /dev/null+++ b/rust/pgcollector/docs/telemetry-sources.md@@ -0,0 +1,179 @@+# Telemetry sources on Aurora PostgreSQL beyond pg_stat_*++Research (2026-08) into what Aurora PostgreSQL 15/16/17 exposes that could give+pgcollector more than the usual `pg_stat_*` views, ranked by value. Our fleet runs Aurora+`aurora-postgresql15/16/17` (some 18), with Performance Insights enabled+(7-day retention), `pg_stat_statements` (`max=10000`, `track=all`),+`auto_explain` on some clusters (json, 1% sample), `log_min_duration_sample=1s`+at 1% and `log_lock_waits=on`.++## Not available on Aurora (don't plan around them)++`pg_stat_monitor`, `pg_stat_kcache`, `pg_qualstats`, `pg_wait_sampling`,+`pageinspect`, `pg_walinspect`. The first three are what community tools use+for latency histograms, per-query CPU, and predicate stats; none are on the+[Aurora extension list](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraPostgreSQLReleaseNotes/AuroraPostgreSQL.Extensions.html).++## Tier 1 — free, built-in, high value++### `aurora_stat_statements(showtext)` — drop-in upgrade of `query_stats`++All `pg_stat_statements` columns plus 11 more (APG 14.9+/15.4+; peak-memory+columns 14.12+/15.7+/16.3+):++* `storage_blks_read`, `storage_blk_read_time` — blocks/time read from **Aurora+ storage** (vs. `shared_blks_read`, which on Aurora includes OS cache). This is+ the real "did this query hit the network" signal.+* `orcache_blks_hit`, `orcache_blk_read_time` — Optimized Reads tiered cache.+* `total/min/max_exec_peakmem`, `*_plan_peakmem` — **peak memory per query**.+ Most monitoring tools lack this; it's the direct answer to "which query is+ blowing `work_mem`".++Same `queryid`, same reset function. Plan: `query_stats` detects+`aurora_version()` and switches its SQL; the sink just gains columns.++### `aurora_stat_plans(showtext)` + `aurora_stat_activity()` — per-plan stats++APG 14.10+/15.5+, **on by default** (`aurora_compute_plan_id`), no+`auto_explain` overhead. Every `pg_stat_statements` row split by `planid`, with+`explain_plan` text, `plan_type` (`estimate`/`actual`), `plan_captured_time`.+`aurora_stat_activity()` = `pg_stat_activity` + `plan_id`, so activity samples+can be grouped by (query_id, plan_id).++Commercial tools expose this as "plan statistics"; we get it cheaply, plus+we can store *every* plan variant and diff them (plan flips). Limited to+`pg_stat_statements.max` plans.++### `aurora_stat_system_waits()` / `aurora_stat_backend_waits(pid)` — wait *time*++Cumulative `waits` and `wait_time` (ms) per wait event, instance-wide and per+backend. Our `activity_samples` only *sample* wait events every+10s; this gives exact counts and durations — e.g. total ms spent in+`IO:XactSync` or `Lock:transactionid` per minute, and per-session wait+profiles for the "interesting" backends we already record. Join with+`aurora_stat_wait_type()` / `aurora_stat_wait_event()` for names.+`aurora_wait_report(seconds)` (needs `aurora_stat_utils`) is the same thing+pre-diffed; we do our own diffing so we don't need it.++### `aurora_stat_get_db_commit_latency(oid)` and `aurora_stat_dml_activity(oid)`++Per-database cumulative **commit latency** (µs; what CloudWatch's CommitLatency+is computed from) and per-database SELECT/INSERT/UPDATE/DELETE **counts and+latency**. Cheap deltas, one row per database per minute. Gives "average+latency per statement class per database" that `pg_stat_database` cannot.+Reset by `pg_stat_reset`, so reuse `stats_reset` from `pg_stat_database`.++### `aurora_replica_status()`++Per-replica replay lag (ms), oldest read-view xid, CPU, current LSN — this is+the replication view on Aurora, since `pg_stat_replication` is empty.+Replaces the community `replication` collector on Aurora.++### `pg_proctab` — OS stats from SQL (no CloudWatch needed)++Supported on Aurora. `pg_cputime()`, `pg_loadavg()`, `pg_memusage()`,+`pg_diskusage()`, and **`pg_proctab()` per process** (utime/stime/RSS per+backend). Per-backend CPU is what `pg_stat_kcache` would give; joined to `pg_stat_activity` it attributes CPU to queries/users.+Cheaper and lower-latency than CloudWatch for host metrics.++### `aurora_stat_memctx_usage()`++Memory-context usage across backends (community PG only has this for your own+backend until 18). Catches the one connection eating 8 GB.++## Tier 2 — worth having, opt-in or expensive++### Performance Insights API (`pi:GetResourceMetrics`, `DescribeDimensionKeys`)++Already enabled on every cluster. Gives **DB load (average active sessions)+per second, decomposed by `db.sql_tokenized` × `db.wait_event`**, plus per-SQL+counters (`calls_per_sec`, `rows_per_call`, `blks_hit_per_sec`, …) and 7 days+of history. The valuable part is the *per-query wait profile*, which nothing+in-database provides. Costs API calls (rate-limited), needs+`pi:*` on the IRSA role, and its SQL ids (`db.sql_tokenized.id`) are AWS's+own hash, not `queryid` — join on normalized text. Still no per-call latency+quantiles.++### `pgstattuple` — exact bloat++`pgstattuple_approx(rel)` (heap, cheap-ish) and `pgstatindex` for B-trees give+real dead-tuple %, free space, leaf fragmentation, versus the usual+statistical estimate. Run weekly on the reader for tables over N GB; never on+the writer during business hours.++### `pg_buffercache`++What's in `shared_buffers` by relation. PG16+ `pg_buffercache_summary()` and+`pg_buffercache_usage_counts()` are cheap; per-relation aggregation scans every+buffer (fine every 10m on the reader). Answers "is my hot table actually+cached".++### `hypopg` — validate index recommendations++Hypothetical indexes + `EXPLAIN` on the reader: propose an index, see the plan+and cost change without building it. Index advisors usually model this+offline; we can ask the real planner. Foundation for our own advisor (phase 5).++### `log_fdw` — read logs via SQL++`list_postgres_log_files()` / `create_foreign_table_for_log_file()`; with+`log_destination=csvlog` the rows are structured. Functions are owned by+`rds_superuser` and must be granted. An alternative to the RDS+`DownloadDBLogFilePortion` API for the phase-4 log collector — no AWS SDK, same+credentials — but reads only the current instance's files and doubles log+storage. Decide in phase 4; the API path is probably simpler for CloudWatch-+exported logs (`enabled_cloudwatch_logs_exports = ["postgresql"]` is already on).++### `pg_freespacemap`, `pg_visibility`++Free-space and all-visible/all-frozen fractions per relation → vacuum+effectiveness and index-only-scan eligibility. Full-relation scans; opt-in,+reader only, large tables weekly.++### `aurora_stat_logical_wal_cache()`, `aurora_stat_optimized_reads_cache()`++Only if logical replication (`pglogical` is loaded on some clusters) or+Optimized Reads instances are in play. Cheap, cluster-scope, add when needed.++## Tier 3 — not telemetry / skip++`pgaudit` (audit, not perf), `rds_tools`, `pg_tle`, `pg_cron` (could schedule+`pgstattuple` in-database instead of from the collector — not needed),+`plprofiler` (on-demand PL/pgSQL profiling; niche), `apg_plan_mgmt` (plan+pinning; a remediation tool rather than a stat source, but its+`dba_plans` view could be read if it's ever enabled).++## Status++Tier 1 is implemented (`collectors/aurora_*.yaml`, `system_*.yaml`,+`backend_cpu.yaml`, `src/collectors/aurora_plans.rs`, Aurora paths in+`query_stats` and `activity_samples`). Validated against stub functions with+the documented column shapes (`test/aurora_stubs.sql`) and a real+`pg_proctab`; the first run against an actual Aurora cluster is still owed.++## Recommended order++1. **Aurora variants of existing collectors** (cheap, immediate): `query_stats`+ → `aurora_stat_statements`; new `aurora_waits` (system + backend);+ `aurora_db_latency` (commit latency + DML activity); `aurora_replica_status`.+ All gated on `aurora_version()` existing.+2. **`aurora_plans`**: per-plan stats + plan text into `ts_query_plan_stats` /+ `cur_query_plans`; `plan_id` added to `activity_samples` via+ `aurora_stat_activity()`.+3. **`pg_proctab`** system + per-backend CPU (needs `CREATE EXTENSION`).+4. Phase 4 logs (real latency quantiles) — the configured+ `log_min_duration_sample`/`auto_explain` already produce the data.+5. Opt-in heavy collectors: `pgstattuple`, `pg_buffercache`, `pg_visibility`.+6. `hypopg`-backed index validation once the schema collector exists.+7. Performance Insights ingestion, if the per-query wait profile proves+ valuable enough to justify the API plumbing.++Sources: [Aurora functions reference](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Appendix.AuroraPostgreSQL.Functions.html),+[aurora_stat_statements](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora_stat_statements.html),+[aurora_stat_plans](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora_stat_plans.html),+[aurora_stat_backend_waits](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora_stat_backend_waits.html),+[aurora_stat_dml_activity](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora_stat_dml_activity.html),+[aurora_stat_get_db_commit_latency](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora_stat_get_db_commit_latency.html),+[log_fdw](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_PostgreSQL.Extensions.log_fdw.html),+[Performance Insights API](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.API.html),+[pg_stat_monitor not on Aurora (re:Post)](https://repost.aws/questions/QUGNBveStSTx66XIIN9IrT-w/add-support-for-postgresql-pg-stat-monitor-extension-in-rds-aurora).diff --git a/rust/pgcollector/migrations/0001_base.sql b/rust/pgcollector/migrations/0001_base.sqlnew file mode 100644index 000000000000..6d184506fa32--- /dev/null+++ b/rust/pgcollector/migrations/0001_base.sql@@ -0,0 +1,48 @@+-- Hand-written tables. Tier A ts_*/cur_* tables are created by the sink on demand.++CREATE TABLE IF NOT EXISTS events (+ id bigserial PRIMARY KEY,+ server_id text NOT NULL,+ instance text NOT NULL DEFAULT 'writer',+ datname text,+ at timestamptz NOT NULL,+ kind text NOT NULL, -- stats_reset | pgss_dealloc | schema_change | setting_change | ...+ subject text NOT NULL,+ before jsonb,+ after jsonb+);+CREATE INDEX IF NOT EXISTS events_server_at ON events (server_id, at DESC);++CREATE TABLE IF NOT EXISTS collector_runs (+ collector text NOT NULL,+ server_id text NOT NULL,+ instance text NOT NULL DEFAULT 'writer',+ datname text,+ started_at timestamptz NOT NULL,+ duration_ms bigint NOT NULL,+ rows bigint NOT NULL,+ error text+);+CREATE INDEX IF NOT EXISTS collector_runs_at ON collector_runs (started_at DESC);++CREATE TABLE IF NOT EXISTS collector_state (+ collector text NOT NULL,+ server_id text NOT NULL,+ instance text NOT NULL DEFAULT 'writer',+ datname text NOT NULL DEFAULT '',+ state jsonb NOT NULL,+ updated_at timestamptz NOT NULL,+ PRIMARY KEY (collector, server_id, instance, datname)+);++CREATE TABLE IF NOT EXISTS cur_servers (+ server_id text PRIMARY KEY,+ system_identifier bigint,+ version_num int,+ version text,+ aurora_version text,+ instances text[] NOT NULL DEFAULT '{}',+ databases text[] NOT NULL DEFAULT '{}',+ first_seen timestamptz NOT NULL,+ last_seen timestamptz NOT NULL+);diff --git a/rust/pgcollector/src/collector.rs b/rust/pgcollector/src/collector.rsnew file mode 100644index 000000000000..ed94159e5c4a--- /dev/null+++ b/rust/pgcollector/src/collector.rs@@ -0,0 +1,470 @@+//! Core types shared by every collector and sink.++use anyhow::Result;+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::time::Duration;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Scope {+ /// Run once per server (pg_stat_statements, pg_stat_bgwriter, replication ...)+ Cluster,+ /// Run once per database (pg_stat_user_tables, sizes, schema ...)+ Database,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Kind {+ /// Rows written as-is per tick.+ Gauge,+ /// Numeric non-key columns diffed against previous tick per key.+ Cumulative,+ /// Full picture of an entity set; upserted into cur_* and diffed into events.+ Snapshot,+}++/// A single cell. Deliberately small: everything Postgres stats views emit fits here.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum Value {+ Null,+ Bool(bool),+ Int(i64),+ Float(f64),+ Text(String),+ Timestamp(DateTime<Utc>),+ Json(serde_json::Value),+}++impl Value {+ pub fn as_f64(&self) -> Option<f64> {+ match self {+ Value::Int(i) => Some(*i as f64),+ Value::Float(f) => Some(*f),+ _ => None,+ }+ }+ pub fn is_numeric(&self) -> bool {+ matches!(self, Value::Int(_) | Value::Float(_))+ }+ /// Postgres column type used when the sink auto-creates a column for this value.+ pub fn pg_type(&self) -> &'static str {+ match self {+ Value::Null => "text",+ Value::Bool(_) => "boolean",+ Value::Int(_) => "bigint",+ Value::Float(_) => "double precision",+ Value::Text(_) => "text",+ Value::Timestamp(_) => "timestamptz",+ Value::Json(_) => "jsonb",+ }+ }+}++/// One row: ordered column name → value.+pub type Row = BTreeMap<String, Value>;++/// Identity of where a snapshot came from.+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct Target {+ pub server_id: String,+ /// Which instance of the server: "writer", or a name from `[servers.instances]`.+ pub instance: String,+ /// None for cluster-scoped collectors.+ pub datname: Option<String>,+}++/// The unit of output. One per collector per target per tick.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Snapshot {+ pub collector: String,+ pub kind: Kind,+ pub target: Target,+ pub collected_at: DateTime<Utc>,+ /// Seconds since the previous successful tick (what deltas are over). 0 on first tick.+ pub interval_seconds: f64,+ pub key: Vec<String>,+ /// Postgres column types (DDL names) as reported by the result set, so the sink+ /// creates columns with the right type even when the first tick's value is NULL.+ #[serde(default)]+ pub types: BTreeMap<String, String>,+ pub rows: Vec<Row>,+ /// Out-of-band events discovered during collection (stats reset, dealloc, ...).+ pub events: Vec<Event>,+ /// Secondary snapshots produced by the same tick (e.g. newly seen query texts).+ /// Written by the sink after the primary rows.+ #[serde(default)]+ pub aux: Vec<Snapshot>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Event {+ pub kind: String,+ pub subject: String,+ pub before: Option<serde_json::Value>,+ pub after: Option<serde_json::Value>,+}++/// Opaque per-(collector,target) state carried between ticks. Serialisable so it+/// can be persisted on shutdown.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct State {+ pub collected_at: Option<DateTime<Utc>>,+ /// Previous raw rows keyed by the collector's key columns (joined with \x1f).+ pub rows: BTreeMap<String, Row>,+ /// Anything collector-specific.+ pub extra: serde_json::Value,+}++/// What a target server/database offers, probed once per connection.+#[derive(Debug, Clone, Default)]+pub struct Capabilities {+ pub aurora: bool,+ pub aurora_version: Option<String>,+ /// Extensions installed in the connected database.+ pub extensions: std::collections::HashSet<String>,+}++/// What a collector needs from a target before it can run.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]+pub struct Requirements {+ #[serde(default)]+ pub aurora: bool,+ #[serde(default)]+ pub extension: Option<String>,+}++impl Requirements {+ /// None if satisfied, else a human reason.+ pub fn unmet(&self, caps: &Capabilities) -> Option<String> {+ if self.aurora && !caps.aurora {+ return Some("requires Aurora".into());+ }+ if let Some(e) = &self.extension {+ if !caps.extensions.contains(e) {+ return Some(format!("requires extension {e} (CREATE EXTENSION {e})"));+ }+ }+ None+ }+}++pub struct CollectCtx<'a> {+ pub target: Target,+ pub server: &'a crate::config::ServerConfig,+ pub conn: &'a tokio_postgres::Client,+ pub pg_version: u32,+ pub caps: &'a Capabilities,+ pub now: DateTime<Utc>,+}++#[async_trait]+pub trait Collector: Send + Sync {+ fn name(&self) -> &str;+ /// One line for `--check` output and docs.+ fn description(&self) -> &str {+ ""+ }+ /// Collectors that cost more than a catalog read on large clusters ship+ /// disabled and are switched on per server via `overrides.<name>.enabled`.+ fn default_enabled(&self) -> bool {+ true+ }+ fn interval(&self) -> Duration;+ fn scope(&self) -> Scope;+ fn kind(&self) -> Kind;+ /// PG_VERSION_NUM style, e.g. 160000.+ fn min_pg_version(&self) -> u32 {+ 120000+ }+ /// Prefer the reader endpoint when one is configured.+ fn prefers_reader(&self) -> bool {+ false+ }+ /// Server-side prerequisites; the scheduler skips (and periodically re-checks)+ /// targets that don't satisfy them.+ fn requires(&self) -> Requirements {+ Requirements::default()+ }+ /// Run against every configured instance (writer + each `[servers.instances]`), not+ /// just the writer. Defaults to true for cluster scope: pg_stat_statements,+ /// pg_stat_activity, bgwriter etc. are per-instance on Aurora replicas.+ fn per_instance(&self) -> bool {+ self.scope() == Scope::Cluster+ }+ async fn collect(&self, cx: &CollectCtx<'_>, prev: Option<&State>)+ -> Result<(Snapshot, State)>;+}++pub fn key_of(row: &Row, key: &[String]) -> String {+ key.iter()+ .map(|k| match row.get(k) {+ Some(Value::Text(s)) => s.clone(),+ Some(v) => serde_json::to_string(v).unwrap_or_default(),+ None => String::new(),+ })+ .collect::<Vec<_>>()+ .join("\u{1f}")+}++/// Shared diff logic for `Kind::Snapshot` collectors: compares the current entity set+/// with the previous tick's and emits `<name>_added` / `<name>_removed` /+/// `<name>_changed` events with the full before/after rows. No events on the first+/// tick (no baseline) — a restart must not look like a schema change.+pub fn diff_snapshot(+ name: &str,+ current: &[Row],+ key: &[String],+ prev: Option<&State>,+ now: DateTime<Utc>,+) -> (State, Vec<Event>) {+ let mut next = State {+ collected_at: Some(now),+ rows: BTreeMap::new(),+ extra: serde_json::Value::Null,+ };+ let mut events = Vec::new();+ for row in current {+ next.rows.insert(key_of(row, key), row.clone());+ }+ if let Some(p) = prev.filter(|p| !p.rows.is_empty() || p.collected_at.is_some()) {+ for (k, row) in &next.rows {+ match p.rows.get(k) {+ None => events.push(Event {+ kind: format!("{name}_added"),+ subject: k.replace('\u{1f}', "."),+ before: None,+ after: Some(serde_json::to_value(row).unwrap()),+ }),+ Some(old) if old != row => events.push(Event {+ kind: format!("{name}_changed"),+ subject: k.replace('\u{1f}', "."),+ before: Some(serde_json::to_value(changed_cols(old, row, false)).unwrap()),+ after: Some(serde_json::to_value(changed_cols(old, row, true)).unwrap()),+ }),+ _ => {}+ }+ }+ for (k, old) in &p.rows {+ if !next.rows.contains_key(k) {+ events.push(Event {+ kind: format!("{name}_removed"),+ subject: k.replace('\u{1f}', "."),+ before: Some(serde_json::to_value(old).unwrap()),+ after: None,+ });+ }+ }+ }+ (next, events)+}++/// Only the columns that differ (plus nothing else) — keeps events readable.+fn changed_cols(old: &Row, new: &Row, take_new: bool) -> Row {+ let src = if take_new { new } else { old };+ old.iter()+ .chain(new.iter())+ .map(|(c, _)| c)+ .filter(|c| old.get(*c) != new.get(*c))+ .filter_map(|c| src.get(c).map(|v| (c.clone(), v.clone())))+ .collect()+}++/// Shared delta logic for `Kind::Cumulative` collectors.+///+/// Rules (see DESIGN.md §4):+/// * row absent in `prev` → baseline, not emitted+/// * `stats_reset` changed → row dropped, re-baselined+/// * any numeric delta < 0 → row dropped, re-baselined+/// * non-numeric columns pass through from the current row+/// * rows whose every counter delta is zero are not emitted (idle entries)+pub fn compute_deltas(+ current: Vec<Row>,+ key: &[String],+ prev: Option<&State>,+ now: DateTime<Utc>,+) -> (Vec<Row>, State, Vec<Event>) {+ compute_deltas_with(current, key, &[], prev, now)+}++/// Like `compute_deltas`, but `passthrough` numeric columns are copied as-is+/// (gauges riding along with counters, e.g. `rss` next to `utime`).+pub fn compute_deltas_with(+ current: Vec<Row>,+ key: &[String],+ passthrough: &[String],+ prev: Option<&State>,+ now: DateTime<Utc>,+) -> (Vec<Row>, State, Vec<Event>) {+ let mut next = State {+ collected_at: Some(now),+ rows: BTreeMap::new(),+ extra: serde_json::Value::Null,+ };+ let mut out = Vec::with_capacity(current.len());+ let mut events = Vec::new();+ for row in current {+ let k = key_of(&row, key);+ if let Some(prev_row) = prev.and_then(|p| p.rows.get(&k)) {+ let reset = matches!((row.get("stats_reset"), prev_row.get("stats_reset")), (Some(a), Some(b)) if a != b);+ if reset {+ events.push(Event {+ kind: "stats_reset".into(),+ subject: k.clone(),+ before: None,+ after: None,+ });+ } else if let Some(delta) = delta_row(&row, prev_row, key, passthrough) {+ let changed = delta.iter().any(|(c, v)| {+ !key.iter().any(|k| k == c)+ && !passthrough.contains(c)+ && v.as_f64().map(|f| f != 0.0).unwrap_or(false)+ });+ if changed {+ out.push(delta);+ }+ }+ }+ next.rows.insert(k, row);+ }+ (out, next, events)+}++fn delta_row(cur: &Row, prev: &Row, key: &[String], passthrough: &[String]) -> Option<Row> {+ let mut d = Row::new();+ for (col, v) in cur {+ if key.iter().any(|k| k == col) || passthrough.contains(col) || !v.is_numeric() {+ d.insert(col.clone(), v.clone());+ continue;+ }+ let p = prev.get(col).and_then(Value::as_f64).unwrap_or(0.0);+ let c = v.as_f64().unwrap();+ if c < p {+ return None; // counter went backwards → reset we couldn't see+ }+ d.insert(+ col.clone(),+ match v {+ Value::Int(i) => Value::Int(+ i - prev+ .get(col)+ .and_then(|x| {+ if let Value::Int(pi) = x {+ Some(*pi)+ } else {+ None+ }+ })+ .unwrap_or(0),+ ),+ _ => Value::Float(c - p),+ },+ );+ }+ Some(d)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn row(pairs: &[(&str, Value)]) -> Row {+ pairs+ .iter()+ .map(|(k, v)| (k.to_string(), v.clone()))+ .collect()+ }++ #[test]+ fn first_tick_is_baseline_only() {+ let rows = vec![row(&[+ ("relname", Value::Text("t".into())),+ ("seq_scan", Value::Int(10)),+ ])];+ let (out, st, _) = compute_deltas(rows, &["relname".into()], None, Utc::now());+ assert!(out.is_empty());+ assert_eq!(st.rows.len(), 1);+ }++ #[test]+ fn snapshot_diff_emits_add_change_remove_but_not_on_first_tick() {+ let key = vec!["name".to_string()];+ let t0 = vec![+ row(&[+ ("name", Value::Text("a".into())),+ ("setting", Value::Text("1".into())),+ ]),+ row(&[+ ("name", Value::Text("b".into())),+ ("setting", Value::Text("1".into())),+ ]),+ ];+ let (st, ev) = diff_snapshot("settings", &t0, &key, None, Utc::now());+ assert!(ev.is_empty());+ let t1 = vec![+ row(&[+ ("name", Value::Text("a".into())),+ ("setting", Value::Text("2".into())),+ ]),+ row(&[+ ("name", Value::Text("c".into())),+ ("setting", Value::Text("1".into())),+ ]),+ ];+ let (_, ev) = diff_snapshot("settings", &t1, &key, Some(&st), Utc::now());+ let kinds: Vec<_> = ev.iter().map(|e| e.kind.as_str()).collect();+ assert!(+ kinds.contains(&"settings_changed")+ && kinds.contains(&"settings_added")+ && kinds.contains(&"settings_removed")+ );+ let ch = ev.iter().find(|e| e.kind == "settings_changed").unwrap();+ assert_eq!(ch.after.as_ref().unwrap()["setting"], "2");+ assert!(ch.after.as_ref().unwrap().get("name").is_none());+ }++ #[test]+ fn unchanged_rows_are_not_emitted() {+ let key = vec!["relname".to_string()];+ let t = vec![row(&[+ ("relname", Value::Text("a".into())),+ ("seq_scan", Value::Int(10)),+ ])];+ let (_, st, _) = compute_deltas(t.clone(), &key, None, Utc::now());+ let (out, _, _) = compute_deltas(t, &key, Some(&st), Utc::now());+ assert!(out.is_empty());+ }++ #[test]+ fn second_tick_emits_delta_and_drops_negative() {+ let key = vec!["relname".to_string()];+ let t0 = vec![+ row(&[+ ("relname", Value::Text("a".into())),+ ("seq_scan", Value::Int(10)),+ ]),+ row(&[+ ("relname", Value::Text("b".into())),+ ("seq_scan", Value::Int(10)),+ ]),+ ];+ let (_, st, _) = compute_deltas(t0, &key, None, Utc::now());+ let t1 = vec![+ row(&[+ ("relname", Value::Text("a".into())),+ ("seq_scan", Value::Int(15)),+ ]),+ row(&[+ ("relname", Value::Text("b".into())),+ ("seq_scan", Value::Int(3)),+ ]), // reset+ ];+ let (out, _, _) = compute_deltas(t1, &key, Some(&st), Utc::now());+ assert_eq!(out.len(), 1);+ assert_eq!(out[0]["seq_scan"], Value::Int(5));+ }+}diff --git a/rust/pgcollector/src/collectors/aurora_plans.rs b/rust/pgcollector/src/collectors/aurora_plans.rsnew file mode 100644index 000000000000..20542db7f81a--- /dev/null+++ b/rust/pgcollector/src/collectors/aurora_plans.rs@@ -0,0 +1,72 @@+//! `aurora_stat_plans` (APG 14.10+/15.5+, on by default): pg_stat_statements split by+//! plan id, with the plan text. Lets us see plan flips and per-plan cost.++use super::query_stats::aurora_has_peakmem;+use super::statements::{self, Source};+use crate::collector::*;+use anyhow::Result;+use async_trait::async_trait;+use std::time::Duration;++pub struct AuroraPlans;++const KEY: &[&str] = &["queryid", "planid", "datname", "rolname", "toplevel"];++#[async_trait]+impl Collector for AuroraPlans {+ fn name(&self) -> &str {+ "aurora_plans"+ }+ fn interval(&self) -> Duration {+ Duration::from_secs(300)+ }+ fn scope(&self) -> Scope {+ Scope::Cluster+ }+ fn kind(&self) -> Kind {+ Kind::Cumulative+ }+ fn min_pg_version(&self) -> u32 {+ 140000+ }+ fn requires(&self) -> Requirements {+ Requirements {+ aurora: true,+ extension: Some("pg_stat_statements".into()),+ }+ }++ async fn collect(+ &self,+ cx: &CollectCtx<'_>,+ prev: Option<&State>,+ ) -> Result<(Snapshot, State)> {+ let extra = statements::load_extra(prev);+ let extra_cols = if aurora_has_peakmem(cx.caps.aurora_version.as_deref(), cx.pg_version) {+ statements::AURORA_COLUMNS+ } else {+ ""+ };+ let cols = statements::pgss_columns(cx.pg_version);+ let src = Source {+ name: "aurora_plans",+ aux_name: "query_plans",+ stats_sql: format!(+ "SELECT s.queryid, s.planid, {cols} {extra_cols}+ s.plan_type, s.plan_captured_time, s.planid AS _id+ FROM aurora_stat_plans(false) s JOIN pg_database d ON d.oid = s.dbid LEFT JOIN pg_roles r ON r.oid = s.userid+ WHERE s.queryid IS NOT NULL AND s.planid IS NOT NULL"+ ),+ key: KEY,+ text_sql: format!(+ "SELECT DISTINCT ON (s.planid, d.datname) s.planid, s.queryid, d.datname,+ left(s.explain_plan, {n}) AS explain_plan, s.plan_type, s.plan_captured_time+ FROM aurora_stat_plans(true) s JOIN pg_database d ON d.oid = s.dbid+ WHERE s.planid = ANY($1) ORDER BY s.planid, d.datname, s.calls DESC",+ n = statements::MAX_TEXT_BYTES * 4+ ),+ text_key: &["planid", "datname"],+ };+ statements::collect(&src, cx, prev, extra, false).await+ }+}diff --git a/rust/pgcollector/src/collectors/declarative.rs b/rust/pgcollector/src/collectors/declarative.rsnew file mode 100644index 000000000000..1d0a3a04094d--- /dev/null+++ b/rust/pgcollector/src/collectors/declarative.rs@@ -0,0 +1,254 @@+//! Tier A: a collector defined entirely by a YAML file (see collectors/*.yaml).++use crate::collector::*;+use anyhow::{Context, Result};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use serde::Deserialize;+use std::path::Path;+use std::time::Duration;+use tokio_postgres::types::Type;++#[derive(Debug, Deserialize)]+pub struct Spec {+ pub name: String,+ #[serde(with = "humantime_serde")]+ pub interval: Duration,+ pub scope: Scope,+ pub kind: Kind,+ #[serde(default = "default_min_version")]+ pub min_pg_version: u32,+ #[serde(default)]+ pub key: Vec<String>,+ #[serde(default)]+ pub prefers_reader: bool,+ /// Override the default (cluster scope → every instance, database scope → writer only).+ pub per_instance: Option<bool>,+ /// Server-side prerequisites (`aurora: true`, `extension: pg_proctab`).+ #[serde(default)]+ pub requires: Requirements,+ /// Ship disabled (opt in via overrides). For collectors whose cost scales+ /// with backends/relations rather than being a single catalog read.+ #[serde(default = "default_true")]+ pub enabled: bool,+ /// For `cumulative`: numeric columns that are gauges and must not be diffed.+ #[serde(default)]+ pub passthrough: Vec<String>,+ /// Query used by default.+ pub query: String,+ /// Optional version-specific queries: first entry whose `min_pg_version <= server` wins.+ #[serde(default)]+ pub variants: Vec<Variant>,+ #[serde(default)]+ pub description: String,+}+fn default_true() -> bool {+ true+}+fn default_min_version() -> u32 {+ 120000+}++#[derive(Debug, Deserialize)]+pub struct Variant {+ #[serde(default)]+ pub min_pg_version: u32,+ /// Only use this variant on Aurora.+ #[serde(default)]+ pub aurora: bool,+ pub query: String,+}++pub struct SqlCollector {+ spec: Spec,+}++impl SqlCollector {+ pub fn from_file(path: &Path) -> Result<Self> {+ let raw = std::fs::read_to_string(path)?;+ Self::from_str(&raw, &path.display().to_string())+ }++ pub fn from_str(raw: &str, origin: &str) -> Result<Self> {+ let mut spec: Spec =+ serde_yaml::from_str(raw).with_context(|| format!("parsing {origin}"))?;+ // Most specific first: Aurora variants before generic, then highest version.+ spec.variants.sort_by(|a, b| {+ b.aurora+ .cmp(&a.aurora)+ .then(b.min_pg_version.cmp(&a.min_pg_version))+ });+ if spec.kind != Kind::Gauge {+ anyhow::ensure!(+ !spec.key.is_empty(),+ "{}: kind {:?} requires `key`",+ spec.name,+ spec.kind+ );+ }+ Ok(Self { spec })+ }++ fn query_for(&self, pg_version: u32, aurora: bool) -> &str {+ self.spec+ .variants+ .iter()+ .find(|v| v.min_pg_version <= pg_version && (!v.aurora || aurora))+ .map(|v| v.query.as_str())+ .unwrap_or(&self.spec.query)+ }+}++#[async_trait]+impl Collector for SqlCollector {+ fn name(&self) -> &str {+ &self.spec.name+ }+ fn description(&self) -> &str {+ self.spec.description.lines().next().unwrap_or("")+ }+ fn interval(&self) -> Duration {+ self.spec.interval+ }+ fn scope(&self) -> Scope {+ self.spec.scope+ }+ fn kind(&self) -> Kind {+ self.spec.kind+ }+ fn min_pg_version(&self) -> u32 {+ self.spec.min_pg_version+ }+ fn prefers_reader(&self) -> bool {+ self.spec.prefers_reader+ }+ fn per_instance(&self) -> bool {+ self.spec+ .per_instance+ .unwrap_or(self.spec.scope == Scope::Cluster)+ }+ fn requires(&self) -> Requirements {+ self.spec.requires.clone()+ }+ fn default_enabled(&self) -> bool {+ self.spec.enabled+ }++ async fn collect(+ &self,+ cx: &CollectCtx<'_>,+ prev: Option<&State>,+ ) -> Result<(Snapshot, State)> {+ let sql = self.query_for(cx.pg_version, cx.caps.aurora);+ let pg_rows = cx+ .conn+ .query(sql, &[])+ .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 interval_seconds = prev+ .and_then(|p| p.collected_at)+ .map(|t| (cx.now - t).num_milliseconds() as f64 / 1000.0)+ .unwrap_or(0.0);++ let (rows, state, events) = match self.spec.kind {+ Kind::Cumulative => {+ compute_deltas_with(rows, &self.spec.key, &self.spec.passthrough, prev, cx.now)+ }+ Kind::Snapshot => {+ let (state, events) =+ diff_snapshot(&self.spec.name, &rows, &self.spec.key, prev, cx.now);+ (rows, state, events)+ }+ Kind::Gauge => (+ rows,+ State {+ collected_at: Some(cx.now),+ ..Default::default()+ },+ vec![],+ ),+ };++ Ok((+ Snapshot {+ collector: self.spec.name.clone(),+ kind: self.spec.kind,+ target: cx.target.clone(),+ collected_at: cx.now,+ interval_seconds,+ key: self.spec.key.clone(),+ types,+ rows,+ events,+ aux: vec![],+ },+ state,+ ))+ }+}++/// DDL type names for the sink, from the result set's column types.+pub fn column_types(r: &tokio_postgres::Row) -> std::collections::BTreeMap<String, String> {+ r.columns()+ .iter()+ .map(|c| {+ let t = match *c.type_() {+ Type::BOOL => "boolean",+ Type::INT2 | Type::INT4 | Type::INT8 | Type::OID => "bigint",+ Type::FLOAT4 | Type::FLOAT8 | Type::NUMERIC => "double precision",+ Type::TIMESTAMPTZ => "timestamptz",+ Type::JSON | Type::JSONB => "jsonb",+ _ => "text",+ };+ (c.name().to_string(), t.to_string())+ })+ .collect()+}++/// Convert a tokio_postgres row into our Value model. Covers the types the stats+/// views actually emit; anything else falls back to text via a cast-free `to_string`.+pub fn row_to_values(r: &tokio_postgres::Row) -> Result<Row> {+ let mut out = Row::new();+ for (i, col) in r.columns().iter().enumerate() {+ let v = match *col.type_() {+ Type::BOOL => r.try_get::<_, Option<bool>>(i)?.map(Value::Bool),+ Type::INT2 => r+ .try_get::<_, Option<i16>>(i)?+ .map(|x| Value::Int(x as i64)),+ Type::INT4 => r+ .try_get::<_, Option<i32>>(i)?+ .map(|x| Value::Int(x as i64)),+ Type::INT8 | Type::OID => match *col.type_() {+ Type::OID => r+ .try_get::<_, Option<u32>>(i)?+ .map(|x| Value::Int(x as i64)),+ _ => r.try_get::<_, Option<i64>>(i)?.map(Value::Int),+ },+ Type::FLOAT4 => r+ .try_get::<_, Option<f32>>(i)?+ .map(|x| Value::Float(x as f64)),+ Type::FLOAT8 => r.try_get::<_, Option<f64>>(i)?.map(Value::Float),+ Type::NUMERIC => r+ .try_get::<_, Option<rust_decimal::Decimal>>(i)?+ .map(|d| Value::Float(d.try_into().unwrap_or(f64::NAN))),+ Type::TIMESTAMPTZ => r+ .try_get::<_, Option<DateTime<Utc>>>(i)?+ .map(Value::Timestamp),+ Type::JSON | Type::JSONB => r+ .try_get::<_, Option<serde_json::Value>>(i)?+ .map(Value::Json),+ Type::TEXT | Type::VARCHAR | Type::NAME | Type::BPCHAR | Type::CHAR => {+ r.try_get::<_, Option<String>>(i)?.map(Value::Text)+ }+ ref t => anyhow::bail!(+ "column {} has unsupported type {t}; cast it to text/bigint/float8 in the query",+ col.name()+ ),+ };+ out.insert(col.name().to_string(), v.unwrap_or(Value::Null));+ }+ Ok(out)+}diff --git a/rust/pgcollector/src/collectors/logs.rs b/rust/pgcollector/src/collectors/logs.rsnew file mode 100644index 000000000000..4bc2378b68f4--- /dev/null+++ b/rust/pgcollector/src/collectors/logs.rs@@ -0,0 +1,493 @@+//! Log collector (Tier B): pulls new log lines from the configured source, parses+//! and classifies them, and writes typed records:+//!+//! * `ts_query_durations` — every logged statement duration (this is where real+//! per-call latency quantiles come from: `log_min_duration_sample` ++//! `log_statement_sample_rate` on RDS)+//! * `ts_log_plans` — auto_explain plans (JSON)+//! * `ts_autovacuum_runs` — parsed autovacuum / autoanalyze reports+//! * `ts_checkpoints` — parsed checkpoint reports+//! * `ts_temp_files` — temp file spills+//! * `ts_log_errors` — ERROR/FATAL/PANIC with statement + sqlstate+//! * `ts_log_counts` — counts by level/class per tick (primary snapshot)+//! * events — deadlocks, lock waits, cancellations++use crate::collector::*;+use crate::config::{LogSource, LogsConfig};+use crate::logs::{+ self,+ fingerprint::{fingerprint, redact_literals},+ parse::*,+};+use anyhow::Result;+use async_trait::async_trait;+use once_cell::sync::OnceCell;+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::time::Duration;++pub struct Logs {+ cw: OnceCell<aws_sdk_cloudwatchlogs::Client>,+}+impl Logs {+ pub fn new() -> Self {+ Self {+ cw: OnceCell::new(),+ }+ }+}++#[derive(Default, Serialize, Deserialize)]+struct Extra {+ file: logs::FileCursor,+ cloudwatch: logs::CloudWatchCursor,+ assemblers: BTreeMap<String, Assembler>,+}++const MAX_TEXT: usize = 2000;+const MAX_BYTES_PER_TICK: usize = 32 * 1024 * 1024;+const MAX_EVENTS_PER_TICK: usize = 20_000;++#[async_trait]+impl Collector for Logs {+ fn name(&self) -> &str {+ "logs"+ }+ fn interval(&self) -> Duration {+ Duration::from_secs(30)+ }+ fn scope(&self) -> Scope {+ Scope::Cluster+ }+ fn kind(&self) -> Kind {+ Kind::Gauge+ }+ fn per_instance(&self) -> bool {+ false+ }++ async fn collect(+ &self,+ cx: &CollectCtx<'_>,+ prev: Option<&State>,+ ) -> Result<(Snapshot, State)> {+ let mut extra: Extra = prev+ .map(|p| serde_json::from_value(p.extra.clone()).unwrap_or_default())+ .unwrap_or_default();+ let cfg: &LogsConfig = match &cx.server.logs {+ Some(c) => c,+ None => return Ok(self.empty(cx, &extra)),+ };+ let re = prefix_regex(&cfg.log_line_prefix);++ let batch = match &cfg.source {+ LogSource::File => logs::poll_files(&cfg.paths, &mut extra.file, MAX_BYTES_PER_TICK)?,+ LogSource::Cloudwatch => {+ let group = cfg.log_group.clone().ok_or_else(|| {+ anyhow::anyhow!("logs.log_group is required for source = cloudwatch")+ })?;+ let client = match self.cw.get() {+ Some(c) => c,+ None => {+ let mut loader =+ aws_config::defaults(aws_config::BehaviorVersion::latest());+ if let Some(r) = &cfg.region {+ loader = loader.region(aws_config::Region::new(r.clone()));+ }+ let c = aws_sdk_cloudwatchlogs::Client::new(&loader.load().await);+ self.cw.set(c).ok();+ self.cw.get().unwrap()+ }+ };+ logs::poll_cloudwatch(+ client,+ &group,+ &mut extra.cloudwatch,+ 10,+ MAX_EVENTS_PER_TICK,+ )+ .await?+ }+ };++ if batch.backlog > 0 {+ tracing::warn!(+ server = cx.target.server_id,+ backlog = batch.backlog,+ "log ingestion is behind (per-tick budget hit); will catch up over following ticks"+ );+ }+ let mut out = Outputs::default();+ for (stream, lines) in batch.lines {+ 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);+ }+ }+ }+ // Entries waiting on a possible continuation are flushed if older than a tick.+ for (stream, asm) in extra.assemblers.iter_mut() {+ if let Some(p) = &asm.pending {+ if p.ts+ .map(|t| (cx.now - t).num_seconds() > 30)+ .unwrap_or(true)+ {+ if let Some(e) = asm.flush() {+ out.record(stream, &e, cx);+ }+ }+ }+ }+ extra.assemblers.retain(|_, a| a.pending.is_some());++ let mk = |name: &str, key: Vec<&str>, rows: Vec<Row>, types: BTreeMap<String, String>| {+ Snapshot {+ collector: name.into(),+ kind: Kind::Gauge,+ target: cx.target.clone(),+ collected_at: cx.now,+ interval_seconds: 0.0,+ key: key.into_iter().map(str::to_string).collect(),+ types,+ rows,+ events: vec![],+ aux: vec![],+ }+ };+ let mut aux = Vec::new();+ if !out.durations.is_empty() {+ aux.push(mk(+ "query_durations",+ vec![],+ out.durations,+ types_of(&[+ ("log_time", "timestamptz"),+ ("pid", "bigint"),+ ("query_id", "bigint"),+ ("fingerprint", "bigint"),+ ("duration_ms", "double precision"),+ ("query", "text"),+ ]),+ ));+ }+ if !out.plans.is_empty() {+ aux.push(mk(+ "log_plans",+ vec![],+ out.plans,+ types_of(&[+ ("log_time", "timestamptz"),+ ("pid", "bigint"),+ ("query_id", "bigint"),+ ("fingerprint", "bigint"),+ ("duration_ms", "double precision"),+ ("plan", "jsonb"),+ ("query", "text"),+ ]),+ ));+ }+ if !out.autovacuum.is_empty() {+ aux.push(mk(+ "autovacuum_runs",+ vec![],+ out.autovacuum,+ types_of(&[("log_time", "timestamptz"), ("aggressive", "boolean")]),+ ));+ }+ if !out.checkpoints.is_empty() {+ aux.push(mk(+ "checkpoints",+ vec![],+ out.checkpoints,+ types_of(&[("log_time", "timestamptz")]),+ ));+ }+ if !out.temp_files.is_empty() {+ aux.push(mk(+ "temp_files",+ vec![],+ out.temp_files,+ types_of(&[+ ("log_time", "timestamptz"),+ ("pid", "bigint"),+ ("query_id", "bigint"),+ ("size_bytes", "bigint"),+ ("statement", "text"),+ ]),+ ));+ }+ if !out.errors.is_empty() {+ aux.push(mk(+ "log_errors",+ vec![],+ out.errors,+ types_of(&[+ ("log_time", "timestamptz"),+ ("pid", "bigint"),+ ("query_id", "bigint"),+ ("sqlstate", "text"),+ ("statement", "text"),+ ("detail", "text"),+ ]),+ ));+ }++ let counts: Vec<Row> = out+ .counts+ .into_iter()+ .map(|((stream, level, class), n)| {+ let mut r = Row::new();+ r.insert("log_stream".into(), Value::Text(stream));+ r.insert("level".into(), Value::Text(level));+ r.insert("class".into(), Value::Text(class));+ r.insert("count".into(), Value::Int(n));+ r+ })+ .collect();+ let mut snap = mk("logs", vec![], counts, types_of(&[("count", "bigint")]));+ snap.events = out.events;+ snap.aux = aux;+ Ok((+ snap,+ State {+ collected_at: Some(cx.now),+ rows: Default::default(),+ extra: serde_json::to_value(&extra)?,+ },+ ))+ }+}++impl Logs {+ fn empty(&self, cx: &CollectCtx<'_>, extra: &Extra) -> (Snapshot, State) {+ (+ Snapshot {+ collector: "logs".into(),+ kind: Kind::Gauge,+ target: cx.target.clone(),+ collected_at: cx.now,+ interval_seconds: 0.0,+ key: vec![],+ types: Default::default(),+ rows: vec![],+ events: vec![],+ aux: vec![],+ },+ State {+ collected_at: Some(cx.now),+ rows: Default::default(),+ extra: serde_json::to_value(extra).unwrap(),+ },+ )+ }+}++fn types_of(t: &[(&str, &str)]) -> BTreeMap<String, String> {+ t.iter()+ .map(|(a, b)| (a.to_string(), b.to_string()))+ .collect()+}++#[derive(Default)]+struct Outputs {+ durations: Vec<Row>,+ plans: Vec<Row>,+ autovacuum: Vec<Row>,+ checkpoints: Vec<Row>,+ temp_files: Vec<Row>,+ errors: Vec<Row>,+ counts: BTreeMap<(String, String, String), i64>,+ events: Vec<Event>,+}++/// Statement text as stored: literals redacted, then truncated.+fn text(s: &str) -> Value {+ Value::Text(redact_literals(s).chars().take(MAX_TEXT).collect())+}+fn opt(s: &Option<String>) -> Value {+ s.as_deref().map(text).unwrap_or(Value::Null)+}+fn json_to_value(v: &serde_json::Value) -> Value {+ match v {+ serde_json::Value::Null => Value::Null,+ serde_json::Value::Bool(b) => Value::Bool(*b),+ serde_json::Value::Number(n) => n+ .as_i64()+ .map(Value::Int)+ .or_else(|| n.as_f64().map(Value::Float))+ .unwrap_or(Value::Null),+ serde_json::Value::String(s) => Value::Text(s.clone()),+ other => Value::Json(other.clone()),+ }+}++impl Outputs {+ fn base(stream: &str, e: &Entry) -> Row {+ let mut r = Row::new();+ r.insert(+ "log_time".into(),+ e.ts.map(Value::Timestamp).unwrap_or(Value::Null),+ );+ r.insert("log_stream".into(), Value::Text(stream.to_string()));+ r.insert("pid".into(), e.pid.map(Value::Int).unwrap_or(Value::Null));+ r.insert("datname".into(), opt(&e.db));+ r.insert("usename".into(), opt(&e.user));+ r.insert("application_name".into(), opt(&e.app));+ r.insert(+ "query_id".into(),+ e.query_id.map(Value::Int).unwrap_or(Value::Null),+ );+ r+ }++ fn record(&mut self, stream: &str, e: &Entry, _cx: &CollectCtx<'_>) {+ let rec = classify(e);+ let class = match &rec {+ Record::Duration { .. } => "duration",+ Record::Plan { .. } => "plan",+ Record::Autovacuum(_) => "autovacuum",+ Record::Checkpoint(_) => "checkpoint",+ Record::LockWait { .. } => "lock_wait",+ Record::Deadlock => "deadlock",+ Record::TempFile { .. } => "temp_file",+ Record::Cancel { .. } => "cancel",+ Record::Connection { .. } => "connection",+ Record::Error => "error",+ Record::Other => "other",+ };+ *self+ .counts+ .entry((stream.to_string(), e.level.clone(), class.to_string()))+ .or_default() += 1;+ let subject = |e: &Entry| {+ format!(+ "{}@{} pid {}",+ e.user.as_deref().unwrap_or(""),+ e.db.as_deref().unwrap_or(""),+ e.pid.unwrap_or(0)+ )+ };+ match rec {+ Record::Duration {+ duration_ms,+ kind,+ query,+ } => {+ // Bare "duration: X ms" (no text) only carries information with a query id.+ if query.is_none() && e.query_id.is_none() {+ return;+ }+ let mut r = Self::base(stream, e);+ r.insert("duration_ms".into(), Value::Float(duration_ms));+ r.insert("kind".into(), Value::Text(kind));+ r.insert(+ "fingerprint".into(),+ query+ .as_deref()+ .map(|q| Value::Int(fingerprint(q)))+ .unwrap_or(Value::Null),+ );+ r.insert("query".into(), opt(&query));+ self.durations.push(r);+ }+ Record::Plan {+ duration_ms,+ query,+ plan,+ } => {+ let mut r = Self::base(stream, e);+ r.insert("duration_ms".into(), Value::Float(duration_ms));+ r.insert(+ "fingerprint".into(),+ query+ .as_deref()+ .map(|q| Value::Int(fingerprint(q)))+ .unwrap_or(Value::Null),+ );+ r.insert("query".into(), opt(&query));+ let mut plan = plan;+ if let Some(o) = plan.as_object_mut() {+ // auto_explain.log_parameter_max_length puts bound values here.+ o.remove("Query Parameters");+ if let Some(serde_json::Value::String(q)) = o.get_mut("Query Text") {+ *q = redact_literals(q);+ }+ }+ r.insert("plan".into(), Value::Json(plan));+ self.plans.push(r);+ }+ Record::Autovacuum(fields) => {+ let mut r = Self::base(stream, e);+ for (k, v) in fields {+ r.insert(k, json_to_value(&v));+ }+ self.autovacuum.push(r);+ }+ Record::Checkpoint(fields) => {+ let mut r = Self::base(stream, e);+ for (k, v) in fields {+ r.insert(k, json_to_value(&v));+ }+ self.checkpoints.push(r);+ }+ Record::TempFile { size_bytes, path } => {+ 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));+ r.insert(+ "fingerprint".into(),+ e.statement+ .as_deref()+ .map(|q| Value::Int(fingerprint(q)))+ .unwrap_or(Value::Null),+ );+ self.temp_files.push(r);+ }+ Record::LockWait {+ waiting_pid,+ lock_type,+ target,+ wait_ms,+ acquired,+ } => {+ if !acquired {+ self.events.push(Event { kind: "log_lock_wait".into(), subject: subject(e), before: None,+ after: Some(serde_json::json!({ "at": e.ts, "pid": waiting_pid, "lock_type": lock_type, "target": target, "wait_ms": wait_ms,+ "detail": e.detail, "statement": e.statement.as_deref().map(|s| redact_literals(s).chars().take(MAX_TEXT).collect::<String>()), "log_stream": stream })) });+ }+ }+ Record::Deadlock => {+ self.events.push(Event { kind: "log_deadlock".into(), subject: subject(e), before: None,+ after: Some(serde_json::json!({ "at": e.ts, "detail": e.detail.as_deref().map(redact_literals), "hint": e.hint, "statement": e.statement.as_deref().map(redact_literals), "log_stream": stream })) });+ self.push_error(stream, e, "deadlock");+ }+ Record::Cancel { reason } => {+ self.events.push(Event { kind: "log_cancel".into(), subject: subject(e), before: None,+ after: Some(serde_json::json!({ "at": e.ts, "reason": reason, "statement": e.statement.as_deref().map(|s| redact_literals(s).chars().take(MAX_TEXT).collect::<String>()), "log_stream": stream })) });+ self.push_error(stream, e, "cancel");+ }+ Record::Error => self.push_error(stream, e, "error"),+ Record::Connection { .. } | Record::Other => {}+ }+ }++ fn push_error(&mut self, stream: &str, e: &Entry, class: &str) {+ let mut r = Self::base(stream, e);+ r.insert("level".into(), Value::Text(e.level.clone()));+ r.insert("class".into(), Value::Text(class.into()));+ 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));+ r.insert(+ "fingerprint".into(),+ e.statement+ .as_deref()+ .map(|q| Value::Int(fingerprint(q)))+ .unwrap_or(Value::Null),+ );+ self.errors.push(r);+ }+}diff --git a/rust/pgcollector/src/collectors/mod.rs b/rust/pgcollector/src/collectors/mod.rsnew file mode 100644index 000000000000..1573571b2d41--- /dev/null+++ b/rust/pgcollector/src/collectors/mod.rs@@ -0,0 +1,90 @@+//! Collector registry.+//!+//! Tier A (YAML) collectors compiled into the binary from `collectors/` at build time,+//! optionally overlaid at runtime by `--collectors-dir` (same `name` replaces, a new+//! name adds, `enabled: false` in an overlay file removes). Tier B (code) collectors+//! are registered below.++pub mod aurora_plans;+pub mod declarative;+pub mod logs;+pub mod query_stats;+pub mod statements;++use crate::collector::Collector;+use anyhow::{Context, Result};+use include_dir::{include_dir, Dir};+use std::collections::BTreeMap;+use std::path::Path;+use std::sync::Arc;++static EMBEDDED: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/collectors");++pub struct Registry {+ collectors: Vec<Arc<dyn Collector>>,+}++impl Registry {+ pub fn load(overlay: Option<&Path>) -> Result<Self> {+ let mut by_name: BTreeMap<String, Arc<dyn Collector>> = BTreeMap::new();++ for f in EMBEDDED.files().filter(|f| is_yaml(f.path())) {+ let raw = f.contents_utf8().context("embedded collector not utf8")?;+ let c = declarative::SqlCollector::from_str(+ raw,+ &format!("embedded {}", f.path().display()),+ )?;+ by_name.insert(c.name().to_string(), Arc::new(c));+ }++ if let Some(dir) = overlay.filter(|d| d.exists()) {+ let mut paths: Vec<_> = std::fs::read_dir(dir)+ .with_context(|| format!("reading {}", dir.display()))?+ .filter_map(|e| e.ok())+ .map(|e| e.path())+ .filter(|p| is_yaml(p))+ .collect();+ paths.sort();+ for path in paths {+ let raw = std::fs::read_to_string(&path)?;+ let disabled: serde_yaml::Value = serde_yaml::from_str(&raw)?;+ let name = disabled+ .get("name")+ .and_then(|v| v.as_str())+ .map(str::to_string);+ if disabled.get("enabled").and_then(|v| v.as_bool()) == Some(false) {+ if let Some(n) = name {+ tracing::info!(collector = n, "disabled by overlay");+ by_name.remove(&n);+ }+ continue;+ }+ let c = declarative::SqlCollector::from_file(&path)?;+ tracing::info!(collector = c.name(), path = %path.display(), "overlay collector");+ by_name.insert(c.name().to_string(), Arc::new(c));+ }+ }++ // Tier B — code collectors.+ by_name.insert("query_stats".into(), Arc::new(query_stats::QueryStats));+ by_name.insert("aurora_plans".into(), Arc::new(aurora_plans::AuroraPlans));+ by_name.insert("logs".into(), Arc::new(logs::Logs::new()));++ Ok(Self {+ collectors: by_name.into_values().collect(),+ })+ }++ pub fn iter(&self) -> impl Iterator<Item = &Arc<dyn Collector>> {+ self.collectors.iter()+ }+ pub fn len(&self) -> usize {+ self.collectors.len()+ }+}++fn is_yaml(p: &Path) -> bool {+ p.extension()+ .map(|x| x == "yaml" || x == "yml")+ .unwrap_or(false)+}diff --git a/rust/pgcollector/src/collectors/query_stats.rs b/rust/pgcollector/src/collectors/query_stats.rsnew file mode 100644index 000000000000..ca69a0c92c0d--- /dev/null+++ b/rust/pgcollector/src/collectors/query_stats.rs@@ -0,0 +1,104 @@+//! `pg_stat_statements` deltas (Tier B). On Aurora, reads `aurora_stat_statements`+//! instead, which adds Aurora-storage I/O and per-query peak memory columns.+//!+//! What this cannot give you: per-call latency quantiles. pg_stat_statements has no+//! histogram; real p95/p99 come from sampled statement logs (phase 4,+//! `ts_query_durations`) keyed by the same `queryid`.++use super::statements::{self, Source};+use crate::collector::*;+use anyhow::Result;+use async_trait::async_trait;+use std::time::Duration;++pub struct QueryStats;++const KEY: &[&str] = &["queryid", "datname", "rolname", "toplevel"];++#[async_trait]+impl Collector for QueryStats {+ fn name(&self) -> &str {+ "query_stats"+ }+ fn interval(&self) -> Duration {+ Duration::from_secs(60)+ }+ fn scope(&self) -> Scope {+ Scope::Cluster+ }+ fn kind(&self) -> Kind {+ Kind::Cumulative+ }+ fn min_pg_version(&self) -> u32 {+ 130000+ }++ async fn collect(+ &self,+ cx: &CollectCtx<'_>,+ prev: Option<&State>,+ ) -> Result<(Snapshot, State)> {+ let mut extra = statements::load_extra(prev);+ if !statements::pgss_installed(cx).await {+ if !extra.warned_missing {+ tracing::warn!(server = cx.target.server_id, instance = cx.target.instance,+ "pg_stat_statements is not installed in the maintenance database; run CREATE EXTENSION pg_stat_statements there");+ extra.warned_missing = true;+ }+ return Ok(statements::empty(+ self.name(),+ KEY,+ cx,+ &extra,+ Default::default(),+ ));+ }+ extra.warned_missing = false;++ // aurora_stat_statements exists from APG 14.9 / 15.4; peakmem columns from 14.12 / 15.7 / 16.3.+ // We only use the Aurora function when the peakmem columns exist, to keep one SQL shape.+ let aurora =+ cx.caps.aurora && aurora_has_peakmem(cx.caps.aurora_version.as_deref(), cx.pg_version);+ let (func, extra_cols) = if aurora {+ ("aurora_stat_statements(false)", statements::AURORA_COLUMNS)+ } else {+ ("pg_stat_statements(false)", "")+ };+ let cols = statements::pgss_columns(cx.pg_version);+ let src = Source {+ name: "query_stats",+ aux_name: "queries",+ stats_sql: format!(+ "SELECT s.queryid, {cols} {extra_cols} s.queryid AS _id+ FROM {func} s JOIN pg_database d ON d.oid = s.dbid LEFT JOIN pg_roles r ON r.oid = s.userid+ WHERE s.queryid IS NOT NULL"+ ),+ key: KEY,+ text_sql: format!(+ "SELECT DISTINCT ON (s.queryid, d.datname) s.queryid, d.datname,+ left(s.query, {n}) AS query, length(s.query) > {n} AS truncated+ FROM pg_stat_statements(true) s JOIN pg_database d ON d.oid = s.dbid+ WHERE s.queryid = ANY($1) ORDER BY s.queryid, d.datname, s.calls DESC",+ n = statements::MAX_TEXT_BYTES+ ),+ text_key: &["queryid", "datname"],+ };+ statements::collect(&src, cx, prev, extra, true).await+ }+}++/// aurora_version() looks like "16.3.0" / "15.7.1"; peakmem columns landed in 14.12 / 15.7 / 16.3.+pub fn aurora_has_peakmem(aurora_version: Option<&str>, pg_version: u32) -> bool {+ let Some(v) = aurora_version else {+ return false;+ };+ let mut it = v.split('.').filter_map(|p| p.parse::<u32>().ok());+ let (major, minor) = (it.next().unwrap_or(0), it.next().unwrap_or(0));+ match major {+ 14 => minor >= 12,+ 15 => minor >= 7,+ 16 => minor >= 3,+ m if m >= 17 => true,+ _ => pg_version >= 170000,+ }+}diff --git a/rust/pgcollector/src/collectors/statements.rs b/rust/pgcollector/src/collectors/statements.rsnew file mode 100644index 000000000000..c2c01a9f71bd--- /dev/null+++ b/rust/pgcollector/src/collectors/statements.rs@@ -0,0 +1,232 @@+//! Shared machinery for pg_stat_statements-shaped sources: `pg_stat_statements`,+//! `aurora_stat_statements`, `aurora_stat_plans`. Deltas the counters, tracks which+//! ids have had their text fetched, and emits the text as an aux snapshot.++use crate::collector::*;+use crate::collectors::declarative::{column_types, row_to_values};+use anyhow::{Context, Result};+use serde::{Deserialize, Serialize};+use std::collections::BTreeSet;++pub const MAX_TEXT_BYTES: usize = 10 * 1024;+const MAX_KNOWN: usize = 50_000;+/// Query texts fetched per tick. `pg_stat_statements(true)` materialises every+/// entry's text server-side, so keep the per-tick call count low and spread the+/// initial backfill over a few ticks.+const TEXT_BATCH: usize = 500;++#[derive(Default, Serialize, Deserialize)]+pub struct Extra {+ /// Ids (queryid, or planid for plans) whose text is already in the sink.+ pub known_ids: BTreeSet<i64>,+ pub dealloc: Option<i64>,+ pub warned_missing: bool,+}++pub struct Source<'a> {+ pub name: &'a str,+ pub aux_name: &'a str,+ /// Counter query; must emit a hidden `_id` column carrying the text id.+ pub stats_sql: String,+ pub key: &'a [&'a str],+ /// Text query taking `$1 bigint[]` of ids.+ pub text_sql: String,+ pub text_key: &'a [&'a str],+}++pub fn empty(+ name: &str,+ key: &[&str],+ cx: &CollectCtx<'_>,+ extra: &Extra,+ prev_rows: std::collections::BTreeMap<String, Row>,+) -> (Snapshot, State) {+ (+ Snapshot {+ collector: name.into(),+ kind: Kind::Cumulative,+ target: cx.target.clone(),+ collected_at: cx.now,+ interval_seconds: 0.0,+ key: key.iter().map(|s| s.to_string()).collect(),+ types: Default::default(),+ rows: vec![],+ events: vec![],+ aux: vec![],+ },+ State {+ collected_at: Some(cx.now),+ rows: prev_rows,+ extra: serde_json::to_value(extra).unwrap(),+ },+ )+}++pub async fn collect(+ src: &Source<'_>,+ cx: &CollectCtx<'_>,+ prev: Option<&State>,+ mut extra: Extra,+ watch_dealloc: bool,+) -> Result<(Snapshot, State)> {+ let pg_rows = cx+ .conn+ .query(&src.stats_sql, &[])+ .await+ .with_context(|| src.name.to_string())?;+ let rows: Vec<Row> = pg_rows.iter().map(row_to_values).collect::<Result<_>>()?;+ let mut types = pg_rows.first().map(column_types).unwrap_or_default();+ types.remove("_id");+ let key: Vec<String> = src.key.iter().map(|s| s.to_string()).collect();+ let interval_seconds = prev+ .and_then(|p| p.collected_at)+ .map(|t| (cx.now - t).num_milliseconds() as f64 / 1000.0)+ .unwrap_or(0.0);+ let (mut deltas, mut state, mut events) = compute_deltas(rows, &key, prev, cx.now);+ for d in &mut deltas {+ d.remove("_id");+ }++ if watch_dealloc && cx.pg_version >= 140000 {+ if let Some(r) = cx+ .conn+ .query_opt("SELECT dealloc FROM pg_stat_statements_info", &[])+ .await?+ {+ let dealloc: i64 = r.get(0);+ if let Some(prev_d) = extra.dealloc {+ if dealloc > prev_d {+ events.push(Event {+ kind: "pgss_dealloc".into(), subject: cx.target.instance.clone(),+ before: Some(serde_json::json!({ "dealloc": prev_d })),+ after: Some(serde_json::json!({ "dealloc": dealloc, "hint": "pg_stat_statements.max is too small for this workload; top-N is lossy" })),+ });+ }+ }+ extra.dealloc = Some(dealloc);+ }+ }++ let mut unseen: Vec<i64> = state+ .rows+ .values()+ .filter_map(|r| {+ if let Some(Value::Int(q)) = r.get("_id") {+ Some(*q)+ } else {+ None+ }+ })+ .filter(|q| !extra.known_ids.contains(q))+ .collect::<BTreeSet<_>>()+ .into_iter()+ .collect();+ let mut aux = Vec::new();+ if !unseen.is_empty() {+ unseen.truncate(TEXT_BATCH);+ let texts = cx+ .conn+ .query(&src.text_sql, &[&unseen])+ .await+ .with_context(|| format!("{} text", src.name))?;+ let mut text_rows: Vec<Row> = texts.iter().map(row_to_values).collect::<Result<_>>()?;+ 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.+ for r in &mut text_rows {+ if let Some(Value::Text(q)) = r.get("query") {+ let fp = crate::logs::fingerprint::fingerprint(q);+ r.insert("fingerprint".into(), Value::Int(fp));+ }+ }+ text_types.insert("fingerprint".into(), "bigint".into());+ extra.known_ids.extend(unseen);+ if extra.known_ids.len() > MAX_KNOWN {+ extra.known_ids = extra+ .known_ids+ .iter()+ .rev()+ .take(MAX_KNOWN / 2)+ .copied()+ .collect();+ }+ aux.push(Snapshot {+ collector: src.aux_name.into(),+ kind: Kind::Snapshot,+ target: cx.target.clone(),+ collected_at: cx.now,+ interval_seconds: 0.0,+ key: src.text_key.iter().map(|s| s.to_string()).collect(),+ types: text_types,+ rows: text_rows,+ events: vec![],+ aux: vec![],+ });+ }++ state.extra = serde_json::to_value(&extra)?;+ Ok((+ Snapshot {+ collector: src.name.into(),+ kind: Kind::Cumulative,+ target: cx.target.clone(),+ collected_at: cx.now,+ interval_seconds,+ key,+ types,+ rows: deltas,+ events,+ aux,+ },+ state,+ ))+}++pub fn load_extra(prev: Option<&State>) -> Extra {+ prev.map(|p| serde_json::from_value(p.extra.clone()).unwrap_or_default())+ .unwrap_or_default()+}++pub async fn pgss_installed(cx: &CollectCtx<'_>) -> bool {+ cx.caps.extensions.contains("pg_stat_statements")+}++/// 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 {+ "s.toplevel"+ } else {+ "true AS toplevel"+ };+ let io_time = if v >= 170000 {+ "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 {+ "s.temp_blk_read_time, s.temp_blk_write_time,"+ } else {+ ""+ };+ let jit = if v >= 150000 {+ "s.jit_functions, s.jit_generation_time,"+ } else {+ ""+ };+ format!(+ "d.datname, COALESCE(r.rolname, s.userid::text) AS rolname, {toplevel},+ s.calls, s.total_exec_time, s.rows,+ s.calls * (s.stddev_exec_time * s.stddev_exec_time + s.mean_exec_time * s.mean_exec_time) AS sumsq_exec_time,+ s.plans, s.total_plan_time,+ s.shared_blks_hit, s.shared_blks_read, s.shared_blks_dirtied, s.shared_blks_written,+ s.local_blks_hit, s.local_blks_read, s.local_blks_dirtied, s.local_blks_written,+ s.temp_blks_read, s.temp_blks_written, {temp_io}+ {io_time},+ s.wal_records, s.wal_fpi, s.wal_bytes::bigint AS wal_bytes, {jit}"+ )+}++/// Extra columns from aurora_stat_statements / aurora_stat_plans (APG 14.9+/15.4+; peakmem 14.12+/15.7+/16.3+).+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,";diff --git a/rust/pgcollector/src/config.rs b/rust/pgcollector/src/config.rsnew file mode 100644index 000000000000..c1b570ca3c1c--- /dev/null+++ b/rust/pgcollector/src/config.rs@@ -0,0 +1,255 @@+use anyhow::{Context, Result};+use serde::Deserialize;+use std::collections::{BTreeMap, HashMap};+use std::path::Path;+use std::time::Duration;++#[derive(Debug, Deserialize, Clone)]+pub struct Config {+ pub sink: SinkConfig,+ #[serde(default)]+ pub defaults: Defaults,+ #[serde(default)]+ pub http: HttpConfig,+ #[serde(default)]+ pub servers: Vec<ServerConfig>,+}++#[derive(Debug, Deserialize, Clone)]+pub struct SinkConfig {+ pub database_url: String,+ #[serde(default = "default_retention")]+ pub retention_days: u32,+}+fn default_retention() -> u32 {+ 14+}++#[derive(Debug, Deserialize, Clone)]+pub struct HttpConfig {+ /// Bind address for /healthz, /readyz, /metrics.+ #[serde(default = "default_listen")]+ pub listen: String,+}+impl Default for HttpConfig {+ fn default() -> Self {+ Self {+ listen: default_listen(),+ }+ }+}+fn default_listen() -> String {+ "0.0.0.0:9187".into()+}++#[derive(Debug, Deserialize, Clone)]+pub struct Defaults {+ #[serde(with = "humantime_serde", default = "default_stmt_timeout")]+ pub statement_timeout: Duration,+ /// Databases for `scope: database` collectors. `["*"]` = discover (and keep discovering).+ #[serde(default = "default_databases")]+ pub databases: Vec<String>,+ /// How often to re-discover databases on each server.+ #[serde(with = "humantime_serde", default = "default_rediscover")]+ pub rediscover_interval: Duration,+ /// Global per-collector overrides; per-server `overrides` merge on top.+ #[serde(default)]+ pub overrides: HashMap<String, CollectorOverride>,+}+impl Default for Defaults {+ fn default() -> Self {+ Self {+ statement_timeout: default_stmt_timeout(),+ databases: default_databases(),+ rediscover_interval: default_rediscover(),+ overrides: HashMap::new(),+ }+ }+}+fn default_stmt_timeout() -> Duration {+ Duration::from_secs(5)+}+fn default_databases() -> Vec<String> {+ vec!["*".into()]+}+fn default_rediscover() -> Duration {+ Duration::from_secs(600)+}++#[derive(Debug, Deserialize, Clone)]+pub struct ServerConfig {+ /// Stable name; becomes `server_id` in every table.+ pub id: String,+ /// Writer (cluster) endpoint.+ pub url: String,+ /// Load-balanced reader endpoint. Used by `prefers_reader` collectors only.+ pub reader_url: Option<String>,+ /// Individual instance endpoints (name → url). Cluster-scope collectors run against+ /// the writer *and* each of these, tagged with `instance`. Aurora replicas keep their+ /// own pg_stat_statements / pg_stat_activity, so this is how reader workload is seen.+ #[serde(default)]+ pub instances: BTreeMap<String, String>,+ pub databases: Option<Vec<String>>,+ #[serde(default)]+ pub overrides: HashMap<String, CollectorOverride>,+ /// Where this server's Postgres log lives. None = the `logs` collector is idle.+ pub logs: Option<LogsConfig>,+}++#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum LogSource {+ File,+ Cloudwatch,+}++#[derive(Debug, Deserialize, Clone)]+pub struct LogsConfig {+ pub source: LogSource,+ /// `file`: globs of log files to tail.+ #[serde(default)]+ pub paths: Vec<String>,+ /// `cloudwatch`: log group, e.g. /aws/rds/cluster/<cluster-id>/postgresql+ pub log_group: Option<String>,+ pub region: Option<String>,+ /// Must match the server's `log_line_prefix`. RDS default shown.+ #[serde(default = "default_prefix")]+ pub log_line_prefix: String,+}+fn default_prefix() -> String {+ "%t:%r:%u@%d:[%p]:".into()+}++#[derive(Debug, Deserialize, Clone, Default)]+pub struct CollectorOverride {+ pub enabled: Option<bool>,+ #[serde(with = "humantime_serde", default)]+ pub interval: Option<Duration>,+}++/// Effective per-collector settings after merging defaults + server overrides.+#[derive(Debug, Clone)]+pub struct Effective {+ pub enabled: bool,+ pub interval: Option<Duration>,+}++impl Config {+ pub fn load(path: &Path) -> Result<Self> {+ let raw =+ std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;+ let expanded = shellexpand::env(&raw).context("expanding ${ENV} in config")?;+ let mut cfg: Config = toml::from_str(&expanded).context("parsing config")?;+ cfg.servers.extend(servers_from_env(&cfg.servers));+ anyhow::ensure!(+ !cfg.servers.is_empty(),+ "no servers: add [[servers]] or PGCOLLECTOR_SERVER_<ID>_URL env vars"+ );+ let mut seen = std::collections::HashSet::new();+ for s in &cfg.servers {+ anyhow::ensure!(seen.insert(s.id.clone()), "duplicate server id {}", s.id);+ }+ Ok(cfg)+ }++ pub fn databases_for(&self, s: &ServerConfig) -> Vec<String> {+ s.databases+ .clone()+ .unwrap_or_else(|| self.defaults.databases.clone())+ }++ pub fn effective(&self, s: &ServerConfig, collector: &str, default_enabled: bool) -> Effective {+ let mut e = Effective {+ enabled: default_enabled,+ interval: None,+ };+ for o in [+ self.defaults.overrides.get(collector),+ s.overrides.get(collector),+ ]+ .into_iter()+ .flatten()+ {+ if let Some(en) = o.enabled {+ e.enabled = en;+ }+ if let Some(i) = o.interval {+ e.interval = Some(i);+ }+ }+ e+ }+}++/// Servers declared purely through the environment, so a Helm `psql:` entry is all it+/// takes to monitor a new cluster:+///+/// PGCOLLECTOR_SERVER_<ID>_URL writer url (required)+/// PGCOLLECTOR_SERVER_<ID>_READER_URL reader endpoint (optional)+/// PGCOLLECTOR_SERVER_<ID>_INSTANCE_<NAME>_URL per-instance endpoint (optional, repeatable)+/// PGCOLLECTOR_SERVER_<ID>_LOG_GROUP CloudWatch log group (optional)+/// PGCOLLECTOR_SERVER_<ID>_LOG_LINE_PREFIX if not the RDS default+///+/// `<ID>` is lower-cased and `_` → `-` to form the server id. Explicit [[servers]] with+/// the same id win.+fn servers_from_env(explicit: &[ServerConfig]) -> Vec<ServerConfig> {+ const P: &str = "PGCOLLECTOR_SERVER_";+ let mut found: BTreeMap<String, ServerConfig> = BTreeMap::new();+ let vars: Vec<(String, String)> = std::env::vars().filter(|(k, _)| k.starts_with(P)).collect();+ for (k, v) in &vars {+ let rest = &k[P.len()..];+ if let Some(raw_id) = rest+ .strip_suffix("_URL")+ .filter(|r| !r.contains("_INSTANCE_") && !r.ends_with("_READER"))+ {+ let id = norm(raw_id);+ found+ .entry(id.clone())+ .or_insert_with(|| ServerConfig {+ id,+ url: v.clone(),+ reader_url: None,+ instances: BTreeMap::new(),+ databases: None,+ overrides: HashMap::new(),+ logs: None,+ })+ .url = v.clone();+ }+ }+ for (k, v) in &vars {+ let rest = &k[P.len()..];+ if let Some(raw_id) = rest.strip_suffix("_READER_URL") {+ if let Some(s) = found.get_mut(&norm(raw_id)) {+ s.reader_url = Some(v.clone());+ }+ } else if let Some((raw_id, inst)) = rest+ .strip_suffix("_URL")+ .and_then(|r| r.split_once("_INSTANCE_"))+ {+ if let Some(s) = found.get_mut(&norm(raw_id)) {+ s.instances.insert(norm(inst), v.clone());+ }+ } else if let Some(raw_id) = rest.strip_suffix("_LOG_GROUP") {+ if let Some(s) = found.get_mut(&norm(raw_id)) {+ let prefix = std::env::var(format!("{P}{raw_id}_LOG_LINE_PREFIX"))+ .unwrap_or_else(|_| default_prefix());+ s.logs = Some(LogsConfig {+ source: LogSource::Cloudwatch,+ paths: vec![],+ log_group: Some(v.clone()),+ region: None,+ log_line_prefix: prefix,+ });+ }+ }+ }+ found+ .into_values()+ .filter(|s| !explicit.iter().any(|e| e.id == s.id))+ .collect()+}++fn norm(s: &str) -> String {+ s.to_lowercase().replace('_', "-")+}diff --git a/rust/pgcollector/src/http.rs b/rust/pgcollector/src/http.rsnew file mode 100644index 000000000000..4f61d604f855--- /dev/null+++ b/rust/pgcollector/src/http.rs@@ -0,0 +1,99 @@+//! /healthz, /readyz and /metrics for the golden chart's probes and Prometheus+//! pod-annotation scraping.++use axum::{extract::State, http::StatusCode, routing::get, Router};+use once_cell::sync::Lazy;+use prometheus::{+ Encoder, HistogramVec, IntCounterVec, IntGaugeVec, Registry as PromRegistry, TextEncoder,+};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;++pub static METRICS: Lazy<Metrics> = Lazy::new(Metrics::new);++pub struct Metrics {+ pub registry: PromRegistry,+ pub tick_seconds: HistogramVec,+ pub rows: IntCounterVec,+ pub errors: IntCounterVec,+ pub targets: IntGaugeVec,+}++impl Metrics {+ fn new() -> Self {+ let registry = PromRegistry::new();+ let tick_seconds = HistogramVec::new(+ prometheus::histogram_opts!("pgcollector_tick_seconds", "collector tick duration")+ .buckets(vec![0.005, 0.02, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]),+ &["collector", "server"],+ )+ .unwrap();+ let rows = IntCounterVec::new(+ prometheus::opts!("pgcollector_rows_total", "rows emitted"),+ &["collector", "server"],+ )+ .unwrap();+ let errors = IntCounterVec::new(+ prometheus::opts!("pgcollector_errors_total", "tick errors"),+ &["collector", "server", "stage"],+ )+ .unwrap();+ let targets = IntGaugeVec::new(+ prometheus::opts!(+ "pgcollector_targets",+ "active (server, instance, database) targets"+ ),+ &["server"],+ )+ .unwrap();+ registry.register(Box::new(tick_seconds.clone())).unwrap();+ registry.register(Box::new(rows.clone())).unwrap();+ registry.register(Box::new(errors.clone())).unwrap();+ registry.register(Box::new(targets.clone())).unwrap();+ Self {+ registry,+ tick_seconds,+ rows,+ errors,+ targets,+ }+ }+}++#[derive(Clone, Default)]+pub struct Readiness(pub Arc<AtomicBool>);+impl Readiness {+ pub fn set(&self, ready: bool) {+ self.0.store(ready, Ordering::Relaxed);+ }+}++pub async fn serve(listen: String, ready: Readiness) -> anyhow::Result<()> {+ let app = Router::new()+ .route("/healthz", get(|| async { "ok" }))+ .route(+ "/readyz",+ get(|State(r): State<Readiness>| async move {+ if r.0.load(Ordering::Relaxed) {+ (StatusCode::OK, "ready")+ } else {+ (StatusCode::SERVICE_UNAVAILABLE, "not ready")+ }+ }),+ )+ .route(+ "/metrics",+ get(|| async {+ let mut buf = Vec::new();+ TextEncoder::new()+ .encode(&METRICS.registry.gather(), &mut buf)+ .unwrap();+ ([("content-type", "text/plain; version=0.0.4")], buf)+ }),+ )+ .with_state(ready);+ let listener = tokio::net::TcpListener::bind(&listen).await?;+ tracing::info!(listen, "http listening");+ axum::serve(listener, app).await?;+ Ok(())+}diff --git a/rust/pgcollector/src/logs/fingerprint.rs b/rust/pgcollector/src/logs/fingerprint.rsnew file mode 100644index 000000000000..ac123fc4d055--- /dev/null+++ b/rust/pgcollector/src/logs/fingerprint.rs@@ -0,0 +1,66 @@+//! Query fingerprint: a stable 64-bit hash of a query with literals, parameter+//! markers and IN-list lengths normalised away. Applied to both pg_stat_statements+//! text (already `$1`-normalised) and raw statement text from logs so the two can+//! be joined when `%Q` (query id) isn't in `log_line_prefix`.++use once_cell::sync::Lazy;+use regex::Regex;++static COMMENT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?s)/\*.*?\*/|--[^\n]*").unwrap());+static STRING: Lazy<Regex> = Lazy::new(|| Regex::new(r"'(?:[^']|'')*'").unwrap());+static PARAM: Lazy<Regex> = Lazy::new(|| Regex::new(r"\$\d+").unwrap());+static NUMBER: Lazy<Regex> = Lazy::new(|| Regex::new(r"\b\d+(?:\.\d+)?\b").unwrap());+static LIST: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\s*\?(?:\s*,\s*\?)*\s*\)").unwrap());+static WS: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s+").unwrap());+static PUNCT: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s*([=<>!,()+\-*/])\s*").unwrap());++pub fn normalize(sql: &str) -> String {+ let s = COMMENT.replace_all(sql, " ");+ let s = STRING.replace_all(&s, "?");+ let s = PARAM.replace_all(&s, "?");+ let s = NUMBER.replace_all(&s, "?");+ let s = LIST.replace_all(&s, "(?)");+ let s = WS.replace_all(&s, " ");+ let s = PUNCT.replace_all(&s, "$1");+ s.trim().trim_end_matches(';').trim().to_lowercase()+}++/// Replace string literals with `'?'` and leave everything else intact, so stored+/// statement text keeps its shape but not the values (credentials, tokens, PII)+/// that logs and pg_stat_activity carry verbatim.+pub fn redact_literals(sql: &str) -> String {+ STRING.replace_all(sql, "'?'").into_owned()+}++/// FNV-1a 64 of the normalised text, as i64 so it fits a bigint column.+pub fn fingerprint(sql: &str) -> i64 {+ let mut h: u64 = 0xcbf29ce484222325;+ for b in normalize(sql).bytes() {+ h ^= b as u64;+ h = h.wrapping_mul(0x100000001b3);+ }+ h as i64+}++#[cfg(test)]+mod tests {+ use super::*;+ #[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)");+ let b = fingerprint("select * from t where id = $1 and name = $2 and x in ($3)");+ let c = fingerprint("select *\n from t where id=7 and name='al''ice' and x in (9,8,7,6);");+ assert_eq!(a, b);+ assert_eq!(a, c);+ assert_ne!(a, fingerprint("select * from t where id = 1"));+ }++ #[test]+ fn redaction_keeps_shape_and_drops_values() {+ assert_eq!(+ redact_literals("select * from t where token = 'sk-secret' and n = 42"),+ "select * from t where token = '?' and n = 42"+ );+ assert_eq!(redact_literals("select 'it''s'"), "select '?'");+ }+}diff --git a/rust/pgcollector/src/logs/mod.rs b/rust/pgcollector/src/logs/mod.rsnew file mode 100644index 000000000000..c1329d3277e4--- /dev/null+++ b/rust/pgcollector/src/logs/mod.rs@@ -0,0 +1,183 @@+//! Log ingestion: sources that yield new raw lines since the last tick, keyed by+//! log stream (RDS instance id / file name), with cursors serialised into+//! collector state.++pub mod fingerprint;+pub mod parse;++use anyhow::{Context, Result};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::io::{Read, Seek, SeekFrom};++pub struct Batch {+ /// stream name → lines (in order)+ pub lines: BTreeMap<String, Vec<String>>,+ /// Bytes/events still unread because the per-tick budget ran out.+ pub backlog: u64,+}++// ---------- file source (self-hosted / local dev) ----------++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct FileCursor {+ /// path → (byte offset, partial trailing line)+ pub offsets: BTreeMap<String, (u64, String)>,+ pub initialised: bool,+}++/// Tail every file matching the globs. On the very first run we start at the end+/// of existing files (no history replay); afterwards every new byte is read.+pub fn poll_files(globs: &[String], cur: &mut FileCursor, max_bytes: usize) -> Result<Batch> {+ let mut paths: Vec<std::path::PathBuf> = Vec::new();+ for g in globs {+ for p in glob::glob(g)+ .with_context(|| format!("bad glob {g}"))?+ .flatten()+ {+ if p.is_file() {+ paths.push(p);+ }+ }+ }+ paths.sort();+ let mut lines: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut budget = max_bytes;+ let first = !cur.initialised;+ for p in &paths {+ let key = p.to_string_lossy().to_string();+ let len = std::fs::metadata(p)?.len();+ let (mut off, mut partial) = cur+ .offsets+ .get(&key)+ .cloned()+ .unwrap_or((if first { len } else { 0 }, String::new()));+ if len < off {+ off = 0;+ partial.clear();+ } // truncated / rotated in place+ if len > off && budget > 0 {+ let mut f = std::fs::File::open(p)?;+ f.seek(SeekFrom::Start(off))?;+ let take = ((len - off) as usize).min(budget);+ let mut buf = vec![0u8; take];+ f.read_exact(&mut buf)?;+ budget -= take;+ off += take as u64;+ let text = partial + &String::from_utf8_lossy(&buf);+ let mut parts: Vec<&str> = text.split('\n').collect();+ partial = parts.pop().unwrap_or("").to_string();+ let stream = p+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_default();+ lines+ .entry(stream)+ .or_default()+ .extend(parts.into_iter().map(str::to_string));+ }+ cur.offsets.insert(key, (off, partial));+ }+ // forget files that no longer exist+ cur.offsets+ .retain(|k, _| paths.iter().any(|p| p.to_string_lossy() == *k));+ cur.initialised = true;+ let backlog: u64 = paths+ .iter()+ .filter_map(|p| {+ let key = p.to_string_lossy().to_string();+ let len = std::fs::metadata(p).ok()?.len();+ Some(len.saturating_sub(cur.offsets.get(&key).map(|o| o.0).unwrap_or(len)))+ })+ .sum();+ Ok(Batch { lines, backlog })+}++// ---------- CloudWatch Logs source (RDS / Aurora) ----------++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct CloudWatchCursor {+ /// Last event timestamp (ms) fully consumed.+ pub last_ts: Option<i64>,+ /// Event ids seen at `last_ts`, to dedupe the boundary.+ pub seen_at_last_ts: Vec<String>,+ pub initialised: bool,+}++/// Aurora exports each instance's Postgres log to+/// `/aws/rds/cluster/<cluster>/postgresql` with one stream per instance.+/// We read the whole group with FilterLogEvents; events lag real time by a few+/// seconds, so we stop `lag_secs` short of now.+pub async fn poll_cloudwatch(+ client: &aws_sdk_cloudwatchlogs::Client,+ group: &str,+ cur: &mut CloudWatchCursor,+ lag_secs: i64,+ max_events: usize,+) -> Result<Batch> {+ let now_ms = chrono::Utc::now().timestamp_millis();+ let end = now_ms - lag_secs * 1000;+ let start = match cur.last_ts {+ Some(t) => t,+ None if !cur.initialised => end - 60_000, // first run: last minute only+ None => end - 60_000,+ };+ let mut lines: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut token: Option<String> = None;+ let mut max_ts = cur.last_ts.unwrap_or(start);+ let mut ids_at_max: Vec<String> = if cur.last_ts == Some(max_ts) {+ cur.seen_at_last_ts.clone()+ } else {+ vec![]+ };+ let mut n = 0usize;+ loop {+ let mut req = client+ .filter_log_events()+ .log_group_name(group)+ .start_time(start)+ .end_time(end);+ if let Some(t) = &token {+ req = req.next_token(t);+ }+ let resp = req+ .send()+ .await+ .with_context(|| format!("FilterLogEvents {group}"))?;+ for ev in resp.events() {+ let (Some(ts), Some(msg)) = (ev.timestamp(), ev.message()) else {+ continue;+ };+ let id = ev.event_id().unwrap_or_default().to_string();+ if Some(ts) == cur.last_ts && cur.seen_at_last_ts.contains(&id) {+ continue;+ }+ if ts > max_ts {+ max_ts = ts;+ ids_at_max.clear();+ }+ if ts == max_ts {+ ids_at_max.push(id);+ }+ let stream = ev.log_stream_name().unwrap_or("unknown").to_string();+ let v = lines.entry(stream).or_default();+ for l in msg.split('\n') {+ v.push(l.to_string());+ }+ n += 1;+ }+ token = resp.next_token().map(str::to_string);+ if token.is_none() || n >= max_events {+ break;+ }+ }+ if n > 0 {+ cur.last_ts = Some(max_ts);+ cur.seen_at_last_ts = ids_at_max;+ }+ cur.initialised = true;+ Ok(Batch {+ lines,+ backlog: if token.is_some() { 1 } else { 0 },+ })+}diff --git a/rust/pgcollector/src/logs/parse.rs b/rust/pgcollector/src/logs/parse.rsnew file mode 100644index 000000000000..88f5966aa42a--- /dev/null+++ b/rust/pgcollector/src/logs/parse.rs@@ -0,0 +1,530 @@+//! Postgres log parsing: `log_line_prefix`-driven prefix regex, multi-line entry+//! assembly, and classification into typed records.++use chrono::{DateTime, NaiveDateTime, Utc};+use once_cell::sync::Lazy;+use regex::Regex;+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++/// Build a regex for a `log_line_prefix`. Supports the escapes that matter for RDS+/// (`%t %m %n %r %h %u %d %p %Q %a %e %l %x %v %c %s %i %b %P %q %%`).+pub fn prefix_regex(prefix: &str) -> Regex {+ let mut re = String::from("^");+ let mut chars = prefix.chars().peekable();+ while let Some(c) = chars.next() {+ if c != '%' {+ re.push_str(®ex::escape(&c.to_string()));+ continue;+ }+ match chars.next() {+ Some('t') => re.push_str(r"(?P<ts>\d{4}-\d\d-\d\d \d\d:\d\d:\d\d(?:\.\d+)? [A-Z]+)"),+ Some('m') => re.push_str(r"(?P<ts>\d{4}-\d\d-\d\d \d\d:\d\d:\d\d(?:\.\d+)? [A-Z]+)"),+ Some('n') => re.push_str(r"(?P<epoch>\d+(?:\.\d+)?)"),+ Some('r') => re.push_str(r"(?P<remote>[^:\[]*(?:\[local\])?[^:]*)"),+ Some('h') => re.push_str(r"(?P<host>[^:]*)"),+ Some('u') => re.push_str(r"(?P<user>[^@:\[]*)"),+ Some('d') => re.push_str(r"(?P<db>[^:\[]*)"),+ Some('p') => re.push_str(r"(?P<pid>\d+)"),+ Some('P') => re.push_str(r"(?P<leader>\d*)"),+ Some('Q') => re.push_str(r"(?P<qid>-?\d*)"),+ Some('a') => re.push_str(r"(?P<app>[^:]*)"),+ Some('e') => re.push_str(r"(?P<sqlstate>[0-9A-Z]{5})"),+ Some('l') => re.push_str(r"(?P<line>\d+)"),+ Some('x') => re.push_str(r"(?P<xid>\d+)"),+ Some('v') => re.push_str(r"(?P<vxid>[\d/]*)"),+ Some('c') => re.push_str(r"(?P<session>[0-9a-f.]+)"),+ Some('s') => re.push_str(r"(?P<sess_start>\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [A-Z]+)"),+ Some('i') => re.push_str(r"(?P<tag>[^:]*)"),+ Some('b') => re.push_str(r"(?P<btype>[^:]*)"),+ Some('q') => {+ /* rest is session-only; everything after is optional */+ re.push_str("(?:");+ }+ Some('%') => re.push('%'),+ Some(o) => re.push_str(®ex::escape(&o.to_string())),+ None => {}+ }+ }+ if prefix.contains("%q") {+ re.push_str(")?");+ }+ re.push_str(r"\s*(?P<level>LOG|ERROR|FATAL|PANIC|WARNING|NOTICE|INFO|DEBUG[1-5]?|DETAIL|HINT|STATEMENT|CONTEXT|QUERY|LOCATION):\s{0,2}(?P<msg>.*)$");+ Regex::new(&re).expect("prefix regex")+}++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct Entry {+ pub ts: Option<DateTime<Utc>>,+ pub pid: Option<i64>,+ pub user: Option<String>,+ pub db: Option<String>,+ pub remote: Option<String>,+ pub app: Option<String>,+ pub query_id: Option<i64>,+ pub sqlstate: Option<String>,+ pub level: String,+ pub message: String,+ pub detail: Option<String>,+ pub hint: Option<String>,+ pub statement: Option<String>,+ pub context: Option<String>,+ pub query: Option<String>,+ /// Which field the last line went to, for tab-continuations.+ #[serde(skip)]+ last: Last,+}++#[derive(Debug, Clone, Copy, Default, PartialEq)]+enum Last {+ #[default]+ Message,+ Detail,+ Hint,+ Statement,+ Context,+ Query,+}++impl Entry {+ fn append(&mut self, text: &str) {+ let f = match self.last {+ Last::Message => &mut self.message,+ Last::Detail => self.detail.get_or_insert_with(String::new),+ Last::Hint => self.hint.get_or_insert_with(String::new),+ Last::Statement => self.statement.get_or_insert_with(String::new),+ Last::Context => self.context.get_or_insert_with(String::new),+ Last::Query => self.query.get_or_insert_with(String::new),+ };+ f.push('\n');+ f.push_str(text);+ }+}++/// Turns lines into complete entries. Keep one per log stream; serialise `pending`+/// into collector state between ticks.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct Assembler {+ pub pending: Option<Entry>,+}++fn parse_ts(s: &str) -> Option<DateTime<Utc>> {+ // "2026-08-27 18:22:49 UTC" or with .123 ms; RDS always logs UTC.+ let s = s.trim_end_matches(" UTC").trim_end_matches(" GMT");+ NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f")+ .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S"))+ .ok()+ .map(|n| n.and_utc())+}++impl Assembler {+ pub fn push(&mut self, re: &Regex, line: &str) -> Option<Entry> {+ let line = line.strip_suffix('\r').unwrap_or(line);+ if line.is_empty() {+ return None;+ }+ if line.starts_with('\t') || line.starts_with(" ") {+ if let Some(p) = &mut self.pending {+ p.append(line.trim_start_matches('\t'));+ }+ return None;+ }+ let Some(m) = re.captures(line) else {+ // Unparseable, treat as continuation (RDS sometimes wraps).+ if let Some(p) = &mut self.pending {+ p.append(line);+ }+ return None;+ };+ let level = m.name("level").map(|x| x.as_str()).unwrap_or("");+ let msg = m.name("msg").map(|x| x.as_str()).unwrap_or("").to_string();+ let pid = m.name("pid").and_then(|x| x.as_str().parse().ok());+ let secondary = matches!(+ level,+ "DETAIL" | "HINT" | "STATEMENT" | "CONTEXT" | "QUERY" | "LOCATION"+ );+ if secondary {+ if let Some(p) = &mut self.pending {+ if p.pid == pid || pid.is_none() {+ match level {+ "DETAIL" => {+ p.detail = Some(msg);+ p.last = Last::Detail;+ }+ "HINT" => {+ p.hint = Some(msg);+ p.last = Last::Hint;+ }+ "STATEMENT" => {+ p.statement = Some(msg);+ p.last = Last::Statement;+ }+ "CONTEXT" => {+ p.context = Some(msg);+ p.last = Last::Context;+ }+ "QUERY" => {+ p.query = Some(msg);+ p.last = Last::Query;+ }+ _ => {}+ }+ return None;+ }+ }+ return None; // orphan secondary line+ }+ let opt = |n: &str| {+ m.name(n)+ .map(|x| x.as_str().trim().to_string())+ .filter(|s| !s.is_empty())+ };+ let e = Entry {+ ts: m.name("ts").and_then(|x| parse_ts(x.as_str())).or_else(|| {+ m.name("epoch")+ .and_then(|x| x.as_str().parse::<f64>().ok())+ .and_then(|f| DateTime::from_timestamp((f) as i64, ((f.fract()) * 1e9) as u32))+ }),+ pid,+ user: opt("user"),+ db: opt("db"),+ remote: opt("remote").or_else(|| opt("host")),+ app: opt("app"),+ query_id: m+ .name("qid")+ .and_then(|x| x.as_str().parse().ok())+ .filter(|q| *q != 0),+ sqlstate: opt("sqlstate"),+ level: level.to_string(),+ message: msg,+ ..Default::default()+ };+ self.pending.replace(e)+ }++ pub fn flush(&mut self) -> Option<Entry> {+ self.pending.take()+ }+}++// ---------- classification ----------++#[derive(Debug, Clone, PartialEq)]+pub enum Record {+ Duration {+ duration_ms: f64,+ kind: String,+ query: Option<String>,+ },+ Plan {+ duration_ms: f64,+ query: Option<String>,+ plan: serde_json::Value,+ },+ Autovacuum(BTreeMap<String, serde_json::Value>),+ Checkpoint(BTreeMap<String, serde_json::Value>),+ LockWait {+ waiting_pid: i64,+ lock_type: String,+ target: String,+ wait_ms: f64,+ acquired: bool,+ },+ Deadlock,+ TempFile {+ size_bytes: i64,+ path: String,+ },+ Cancel {+ reason: String,+ },+ Connection {+ what: String,+ },+ Error,+ Other,+}++static DURATION: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"(?s)^duration: ([\d.]+) ms(?: (statement|execute [^:]*|bind [^:]*|parse [^:]*|plan): ?(.*))?$").unwrap()+});+static AUTOVAC: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r#"(?s)^automatic (aggressive )?(vacuum|analyze) of table "([^"]+)"(.*)$"#).unwrap()+});+static CHECKPOINT: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"^(checkpoint|restartpoint) complete: wrote (\d+) buffers \(([\d.]+)%\); (\d+) WAL file\(s\) added, (\d+) removed, (\d+) recycled; write=([\d.]+) s, sync=([\d.]+) s, total=([\d.]+) s; sync files=(\d+), longest=([\d.]+) s, average=([\d.]+) s; distance=(\d+) kB, estimate=(\d+) kB").unwrap()+});+static LOCKWAIT: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"^process (\d+) (still waiting for|acquired) (\w+) on (.+?) after ([\d.]+) ms$")+ .unwrap()+});+static TEMPFILE: Lazy<Regex> =+ Lazy::new(|| Regex::new(r#"^temporary file: path "([^"]+)", size (\d+)"#).unwrap());+static CANCEL: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"^canceling (?:statement|autovacuum task) due to (.+)$").unwrap());+static CONN: Lazy<Regex> = Lazy::new(|| {+ Regex::new(+ r"^(connection received|connection authorized|connection authenticated|disconnection)",+ )+ .unwrap()+});++fn num(re: &Regex, s: &str) -> Option<Vec<f64>> {+ re.captures(s).map(|c| {+ c.iter()+ .skip(1)+ .filter_map(|m| m.and_then(|m| m.as_str().parse().ok()))+ .collect()+ })+}++pub fn classify(e: &Entry) -> Record {+ let m = e.message.as_str();+ if let Some(c) = DURATION.captures(m) {+ let d: f64 = c[1].parse().unwrap_or(0.0);+ let kind = c+ .get(2)+ .map(|k| k.as_str().split(' ').next().unwrap_or("").to_string())+ .unwrap_or_default();+ let text = c.get(3).map(|t| t.as_str().to_string());+ if kind == "plan" {+ let plan = text+ .as_deref()+ .and_then(|t| serde_json::from_str::<serde_json::Value>(t.trim()).ok())+ .unwrap_or(serde_json::Value::Null);+ let q = plan+ .get("Query Text")+ .and_then(|v| v.as_str())+ .map(str::to_string);+ return Record::Plan {+ duration_ms: d,+ query: q,+ plan,+ };+ }+ return Record::Duration {+ duration_ms: d,+ kind,+ query: text,+ };+ }+ if let Some(c) = AUTOVAC.captures(m) {+ static PAGES: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"pages: (\d+) removed, (\d+) remain").unwrap());+ static TUPLES: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"tuples: (\d+) removed, (\d+) remain, (\d+) are dead but not yet removable")+ .unwrap()+ });+ static SCANS: Lazy<Regex> = Lazy::new(|| Regex::new(r"index scans: (\d+)").unwrap());+ static RATES: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"avg read rate: ([\d.]+) MB/s, avg write rate: ([\d.]+) MB/s").unwrap()+ });+ static BUF: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"buffer usage: (\d+) hits, (\d+) (?:misses|reads), (\d+) dirtied").unwrap()+ });+ static WAL: Lazy<Regex> = Lazy::new(|| {+ Regex::new(r"WAL usage: (\d+) records, (\d+) full page images, (\d+) bytes").unwrap()+ });+ static SYS: Lazy<Regex> = Lazy::new(|| {+ Regex::new(+ r"system usage: CPU: user: ([\d.]+) s, system: ([\d.]+) s, elapsed: ([\d.]+) s",+ )+ .unwrap()+ });+ static FROZEN: Lazy<Regex> = Lazy::new(|| {+ Regex::new(+ r"frozen: (\d+) pages from table \(([\d.]+)% of total\) had (\d+) tuples frozen",+ )+ .unwrap()+ });+ let rest = &c[4];+ let mut r = BTreeMap::new();+ let j = |v: f64| serde_json::json!(v);+ r.insert("kind".into(), serde_json::json!(&c[2]));+ r.insert("aggressive".into(), serde_json::json!(c.get(1).is_some()));+ r.insert("relation".into(), serde_json::json!(&c[3]));+ if let Some(v) = num(&SCANS, rest) {+ r.insert("index_scans".into(), j(v[0]));+ }+ if let Some(v) = num(&PAGES, rest) {+ r.insert("pages_removed".into(), j(v[0]));+ r.insert("pages_remain".into(), j(v[1]));+ }+ if let Some(v) = num(&TUPLES, rest) {+ r.insert("tuples_removed".into(), j(v[0]));+ r.insert("tuples_remain".into(), j(v[1]));+ r.insert("tuples_dead_not_removable".into(), j(v[2]));+ }+ if let Some(v) = num(&FROZEN, rest) {+ r.insert("pages_frozen".into(), j(v[0]));+ r.insert("tuples_frozen".into(), j(v[2]));+ }+ if let Some(v) = num(&RATES, rest) {+ r.insert("read_mb_s".into(), j(v[0]));+ r.insert("write_mb_s".into(), j(v[1]));+ }+ if let Some(v) = num(&BUF, rest) {+ r.insert("buffer_hits".into(), j(v[0]));+ r.insert("buffer_misses".into(), j(v[1]));+ r.insert("buffer_dirtied".into(), j(v[2]));+ }+ if let Some(v) = num(&WAL, rest) {+ r.insert("wal_records".into(), j(v[0]));+ r.insert("wal_fpi".into(), j(v[1]));+ r.insert("wal_bytes".into(), j(v[2]));+ }+ if let Some(v) = num(&SYS, rest) {+ r.insert("cpu_user_s".into(), j(v[0]));+ r.insert("cpu_system_s".into(), j(v[1]));+ r.insert("elapsed_s".into(), j(v[2]));+ }+ return Record::Autovacuum(r);+ }+ if let Some(v) = num(&CHECKPOINT, m) {+ let names = [+ "buffers_written",+ "buffers_pct",+ "wal_added",+ "wal_removed",+ "wal_recycled",+ "write_s",+ "sync_s",+ "total_s",+ "sync_files",+ "sync_longest_s",+ "sync_average_s",+ "distance_kb",+ "estimate_kb",+ ];+ let mut r: BTreeMap<String, serde_json::Value> = names+ .iter()+ .zip(v)+ .map(|(n, x)| (n.to_string(), serde_json::json!(x)))+ .collect();+ r.insert(+ "kind".into(),+ serde_json::json!(if m.starts_with("restartpoint") {+ "restartpoint"+ } else {+ "checkpoint"+ }),+ );+ return Record::Checkpoint(r);+ }+ if let Some(c) = LOCKWAIT.captures(m) {+ return Record::LockWait {+ waiting_pid: c[1].parse().unwrap_or(0),+ acquired: &c[2] == "acquired",+ lock_type: c[3].to_string(),+ target: c[4].to_string(),+ wait_ms: c[5].parse().unwrap_or(0.0),+ };+ }+ if m.starts_with("deadlock detected") {+ return Record::Deadlock;+ }+ if let Some(c) = TEMPFILE.captures(m) {+ return Record::TempFile {+ path: c[1].to_string(),+ size_bytes: c[2].parse().unwrap_or(0),+ };+ }+ if let Some(c) = CANCEL.captures(m) {+ return Record::Cancel {+ reason: c[1].to_string(),+ };+ }+ if let Some(c) = CONN.captures(m) {+ return Record::Connection {+ what: c[1].to_string(),+ };+ }+ if matches!(e.level.as_str(), "ERROR" | "FATAL" | "PANIC") {+ return Record::Error;+ }+ Record::Other+}++#[cfg(test)]+mod tests {+ use super::*;+ const PREFIX: &str = "%t:%r:%u@%d:[%p]:%Q:";++ #[test]+ fn parses_rds_style_lines_with_continuations() {+ let re = prefix_regex(PREFIX);+ let mut a = Assembler::default();+ let lines = [+ "2026-08-27 18:22:49 UTC:[local]:postgres@app:[132]:7519653867268795551:LOG: duration: 0.006 ms plan:",+ "\t{",+ "\t \"Query Text\": \"select 1\",",+ "\t \"Plan\": { \"Node Type\": \"Result\" }",+ "\t}",+ "2026-08-27 18:22:49 UTC:[local]:postgres@app:[132]:7519653867268795551:LOG: duration: 0.598 ms statement: select count(*) from t where id < 50",+ "2026-08-27 18:22:50 UTC:10.1.2.3(5000):app@app:[140]:0:ERROR: canceling statement due to statement timeout",+ "2026-08-27 18:22:50 UTC:10.1.2.3(5000):app@app:[140]:0:STATEMENT: update t set v = 'x'",+ "2026-08-27 18:22:51 UTC::@:[7]::LOG: checkpoint complete: wrote 12 buffers (0.1%); 0 WAL file(s) added, 0 removed, 1 recycled; write=1.001 s, sync=0.002 s, total=1.010 s; sync files=9, longest=0.001 s, average=0.001 s; distance=100 kB, estimate=100 kB",+ ];+ let mut out = Vec::new();+ for l in lines {+ if let Some(e) = a.push(&re, l) {+ out.push(e);+ }+ }+ if let Some(e) = a.flush() {+ out.push(e);+ }+ assert_eq!(out.len(), 4);+ match classify(&out[0]) {+ Record::Plan { query, plan, .. } => {+ assert_eq!(query.as_deref(), Some("select 1"));+ assert_eq!(plan["Plan"]["Node Type"], "Result");+ }+ r => panic!("{r:?}"),+ }+ assert_eq!(out[0].query_id, Some(7519653867268795551));+ match classify(&out[1]) {+ Record::Duration {+ duration_ms,+ kind,+ query,+ } => {+ assert_eq!(duration_ms, 0.598);+ assert_eq!(kind, "statement");+ assert!(query.unwrap().starts_with("select count"));+ }+ r => panic!("{r:?}"),+ }+ assert_eq!(out[2].level, "ERROR");+ assert_eq!(out[2].statement.as_deref(), Some("update t set v = 'x'"));+ assert_eq!(out[2].remote.as_deref(), Some("10.1.2.3(5000)"));+ assert!(matches!(classify(&out[2]), Record::Cancel { .. }));+ match classify(&out[3]) {+ Record::Checkpoint(r) => assert_eq!(r["buffers_written"], 12.0),+ r => panic!("{r:?}"),+ }+ }++ #[test]+ fn default_rds_prefix_and_autovacuum() {+ let re = prefix_regex("%t:%r:%u@%d:[%p]:");+ let mut a = Assembler::default();+ let l1 = "2026-08-27 18:22:49 UTC::@:[55]:LOG: automatic vacuum of table \"app.public.t\": index scans: 1";+ let l2 = "\tpages: 0 removed, 84 remain, 84 scanned (100.00% of total)";+ let l3 = "\ttuples: 15000 removed, 5000 remain, 0 are dead but not yet removable";+ let l4 = "\tbuffer usage: 200 hits, 3 misses, 90 dirtied";+ let l5 = "\tsystem usage: CPU: user: 0.01 s, system: 0.00 s, elapsed: 0.05 s";+ for l in [l1, l2, l3, l4, l5] {+ a.push(&re, l);+ }+ let e = a.flush().unwrap();+ match classify(&e) {+ Record::Autovacuum(r) => {+ assert_eq!(r["relation"], "app.public.t");+ assert_eq!(r["tuples_removed"], 15000.0);+ assert_eq!(r["elapsed_s"], 0.05);+ }+ r => panic!("{r:?}"),+ }+ }+}diff --git a/rust/pgcollector/src/main.rs b/rust/pgcollector/src/main.rsnew file mode 100644index 000000000000..d069a559458c--- /dev/null+++ b/rust/pgcollector/src/main.rs@@ -0,0 +1,168 @@+mod collector;+mod collectors;+mod config;+mod http;+mod logs;+mod pg;+mod scheduler;+mod sink;++use anyhow::Result;+use clap::Parser;+use std::path::PathBuf;+use std::sync::Arc;+use tracing_subscriber::EnvFilter;++#[derive(Parser, Debug)]+#[command(name = "pgcollector", about = "Postgres telemetry collector")]+struct Cli {+ /// Path to pgcollector.toml+ #[arg(+ short,+ long,+ env = "PGCOLLECTOR_CONFIG",+ default_value = "pgcollector.toml"+ )]+ config: PathBuf,+ /// Optional overlay directory of YAML collectors (defaults are compiled in)+ #[arg(long, env = "PGCOLLECTOR_COLLECTORS_DIR")]+ collectors_dir: Option<PathBuf>,+ /// Validate config + collectors and exit+ #[arg(long)]+ check: bool,+ /// Run every collector once against every server, print row counts, exit (no sink writes)+ #[arg(long)]+ once: bool,+ /// Parse a Postgres log file with --log-line-prefix and print what was classified, then exit+ #[arg(long)]+ parse_log: Option<PathBuf>,+ #[arg(long, default_value = "%t:%r:%u@%d:[%p]:")]+ log_line_prefix: String,+}++#[tokio::main]+async fn main() -> Result<()> {+ tracing_subscriber::fmt()+ .with_env_filter(+ EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,tokio_postgres=warn".into()),+ )+ .init();++ let cli = Cli::parse();+ if let Some(path) = &cli.parse_log {+ return parse_log(path, &cli.log_line_prefix);+ }+ let cfg = config::Config::load(&cli.config)?;+ let registry = collectors::Registry::load(cli.collectors_dir.as_deref())?;+ tracing::info!(+ servers = cfg.servers.len(),+ collectors = registry.len(),+ "loaded config"+ );++ if cli.check {+ for c in registry.iter() {+ let r = c.requires();+ let req = match (r.aurora, &r.extension) {+ (true, Some(e)) => format!("aurora, ext:{e}"),+ (true, None) => "aurora".into(),+ (false, Some(e)) => format!("ext:{e}"),+ _ => String::new(),+ };+ let off = if c.default_enabled() {+ ""+ } else {+ "[off by default] "+ };+ println!(+ "{:<24} {:<9} {:>6}s pg>={} per_instance={:<5} {req:<28} {off}{}",+ c.name(),+ format!("{:?}", c.scope()),+ c.interval().as_secs(),+ c.min_pg_version(),+ c.per_instance(),+ c.description()+ );+ }+ for s in &cfg.servers {+ println!(+ "server {:<16} instances={:?} databases={:?}",+ s.id,+ s.instances.keys().collect::<Vec<_>>(),+ cfg.databases_for(s)+ );+ }+ return Ok(());+ }++ let sink: Arc<dyn sink::Sink> = if cli.once {+ Arc::new(sink::StdoutSink)+ } else {+ Arc::new(sink::postgres::PostgresSink::connect(&cfg.sink).await?)+ };++ let ready = http::Readiness::default();+ if !cli.once {+ let (listen, ready) = (cfg.http.listen.clone(), ready.clone());+ tokio::spawn(async move {+ if let Err(e) = http::serve(listen, ready).await {+ tracing::error!(error = %e, "http server exited");+ }+ });+ }++ scheduler::run(Arc::new(cfg), Arc::new(registry), sink, ready, cli.once).await+}++fn parse_log(path: &std::path::Path, prefix: &str) -> Result<()> {+ use logs::parse::*;+ let re = prefix_regex(prefix);+ let text = std::fs::read_to_string(path)?;+ let mut asm = Assembler::default();+ let mut counts: std::collections::BTreeMap<String, usize> = Default::default();+ let mut unparsed = 0usize;+ let mut entries = Vec::new();+ for line in text.lines() {+ if !line.starts_with('\t') && !re.is_match(line) {+ unparsed += 1;+ }+ if let Some(e) = asm.push(&re, line) {+ entries.push(e);+ }+ }+ if let Some(e) = asm.flush() {+ entries.push(e);+ }+ for e in &entries {+ let name = match classify(e) {+ Record::Duration { .. } => "duration",+ Record::Plan { .. } => "plan",+ Record::Autovacuum(_) => "autovacuum",+ Record::Checkpoint(_) => "checkpoint",+ Record::LockWait { .. } => "lock_wait",+ Record::Deadlock => "deadlock",+ Record::TempFile { .. } => "temp_file",+ Record::Cancel { .. } => "cancel",+ Record::Connection { .. } => "connection",+ Record::Error => "error",+ Record::Other => "other",+ };+ *counts.entry(format!("{:<7} {name}", e.level)).or_default() += 1;+ }+ println!(+ "entries: {} lines not matching prefix (treated as continuation): {}",+ entries.len(),+ unparsed+ );+ for (k, v) in counts {+ println!("{v:>8} {k}");+ }+ for e in entries+ .iter()+ .filter(|e| matches!(classify(e), Record::Other))+ .take(5)+ {+ println!("other: {}", e.message.lines().next().unwrap_or(""));+ }+ Ok(())+}diff --git a/rust/pgcollector/src/pg.rs b/rust/pgcollector/src/pg.rsnew file mode 100644index 000000000000..f555f30c1d6d--- /dev/null+++ b/rust/pgcollector/src/pg.rs@@ -0,0 +1,166 @@+//! Connection handling for target servers: TLS (RDS requires it), session safety+//! settings, version and database discovery.++use anyhow::{Context, Result};+use std::time::Duration;+use tokio_postgres::Client;++/// TLS policy for a database URL. TLS is required unless the URL says otherwise:+/// `sslmode=disable` → plaintext (local dev), `sslmode=prefer` → try TLS, fall back.+/// RDS/Aurora always offer TLS, so production URLs never need a parameter.+pub fn tls_policy(url: &str) -> tokio_postgres::config::SslMode {+ use tokio_postgres::config::SslMode;+ let lower = url.to_ascii_lowercase();+ if lower.contains("sslmode=disable") {+ SslMode::Disable+ } else if lower.contains("sslmode=prefer") {+ SslMode::Prefer+ } else {+ SslMode::Require+ }+}++pub fn tls_connector() -> tokio_postgres_rustls::MakeRustlsConnect {+ let tls_cfg = rustls::ClientConfig::builder()+ .with_root_certificates(rustls::RootCertStore {+ roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),+ })+ .with_no_client_auth();+ tokio_postgres_rustls::MakeRustlsConnect::new(tls_cfg)+}++pub async fn connect(+ url: &str,+ statement_timeout: Duration,+ dbname: Option<&str>,+) -> Result<Client> {+ let mut cfg: tokio_postgres::Config = url.parse().context("parsing server url")?;+ if let Some(db) = dbname {+ cfg.dbname(db);+ }+ cfg.application_name("pgcollector");+ cfg.connect_timeout(Duration::from_secs(10));+ cfg.ssl_mode(tls_policy(url));++ let client = match cfg.get_ssl_mode() {+ tokio_postgres::config::SslMode::Disable => {+ let (client, connection) = cfg+ .connect(tokio_postgres::NoTls)+ .await+ .context("connecting")?;+ tokio::spawn(async move {+ if let Err(e) = connection.await {+ tracing::warn!(error = %e, "target connection closed");+ }+ });+ client+ }+ _ => {+ let (client, connection) = cfg.connect(tls_connector()).await.context("connecting")?;+ tokio::spawn(async move {+ if let Err(e) = connection.await {+ tracing::warn!(error = %e, "target connection closed");+ }+ });+ client+ }+ };++ // Safety rails: we must never be the thing that hurts production.+ let ms = statement_timeout.as_millis();+ client+ .batch_execute(&format!(+ "SET statement_timeout = {ms}; SET lock_timeout = 1000; \+ SET default_transaction_read_only = on; SET idle_in_transaction_session_timeout = 10000;"+ ))+ .await+ .context("applying session settings")?;+ quiet_session(&client).await;++ // Refuse transaction-pooled PgBouncer: our SET session settings would be lost and+ // the stats views need a stable backend. A pooler hands consecutive statements to+ // different server connections, so pid / setting must agree across two round trips.+ // (Can pass by luck on an idle pooler; deploy with `pgbouncer: false` regardless.)+ let pid1: i32 = client+ .query_one("SELECT pg_backend_pid()", &[])+ .await?+ .get(0);+ let t: String = client+ .query_one("SELECT current_setting('statement_timeout')", &[])+ .await?+ .get(0);+ let pid2: i32 = client+ .query_one("SELECT pg_backend_pid()", &[])+ .await?+ .get(0);+ if pid1 != pid2 || t != format!("{ms}ms") && t != format!("{}s", ms / 1000) {+ anyhow::bail!(+ "session settings do not persist across statements (backend pid {pid1} -> {pid2}, statement_timeout={t}); \+ this looks like a transaction-pooling PgBouncer — point pgcollector at Postgres directly (pgbouncer: false)"+ );+ }+ Ok(client)+}++/// Best effort: keep our own statements out of the server log (they'd otherwise be+/// ingested right back by the logs collector). Needs SET privilege on these GUCs;+/// silently ignored when the role doesn't have it.+pub async fn quiet_session(client: &Client) {+ for sql in [+ "SET log_min_duration_statement = -1",+ "SET log_min_duration_sample = -1",+ "SET auto_explain.log_min_duration = -1",+ "SET log_statement = 'none'",+ ] {+ if let Err(e) = client.simple_query(sql).await {+ tracing::debug!(sql, error = %e, "quiet_session setting not applied");+ }+ }+}++/// PG_VERSION_NUM, e.g. 160003.+pub async fn server_version(client: &Client) -> Result<u32> {+ let row = client+ .query_one("SELECT current_setting('server_version_num')::int", &[])+ .await?;+ Ok(row.get::<_, i32>(0) as u32)+}++/// Connectable, non-template, non-RDS-internal databases.+pub async fn discover_databases(client: &Client) -> Result<Vec<String>> {+ let rows = client+ .query(+ "SELECT datname FROM pg_database \+ WHERE datallowconn AND NOT datistemplate AND datname NOT IN ('rdsadmin') ORDER BY 1",+ &[],+ )+ .await?;+ Ok(rows.into_iter().map(|r| r.get(0)).collect())+}++/// Probe what this connection's server/database offers.+pub async fn capabilities(client: &Client) -> Result<crate::collector::Capabilities> {+ let mut caps = crate::collector::Capabilities::default();+ // aurora_version() only exists on Aurora. Postgres resolves functions at parse time,+ // so check pg_proc first rather than guarding the call with WHERE.+ let has_fn = client+ .query_opt(+ "SELECT 1 FROM pg_proc WHERE proname = 'aurora_version'",+ &[],+ )+ .await?+ .is_some();+ if has_fn {+ if let Ok(r) = client.query_one("SELECT aurora_version()::text", &[]).await {+ caps.aurora = true;+ caps.aurora_version = Some(r.get::<_, String>(0));+ }+ }+ for r in client+ .query("SELECT extname FROM pg_extension", &[])+ .await?+ {+ caps.extensions.insert(r.get::<_, String>(0));+ }+ Ok(caps)+}diff --git a/rust/pgcollector/src/scheduler.rs b/rust/pgcollector/src/scheduler.rsnew file mode 100644index 000000000000..dd82cae386fa--- /dev/null+++ b/rust/pgcollector/src/scheduler.rs@@ -0,0 +1,472 @@+//! Drives every (collector, target) pair on its own wall-clock-aligned tick.+//!+//! Per server:+//! * a discovery loop re-lists databases every `rediscover_interval` and starts/stops+//! database-scoped tick loops as databases appear and disappear;+//! * cluster-scoped collectors run against the writer and each `[servers.instances]`;+//! * heavy collectors (interval > 15s) are serialised per server via a semaphore, and+//! every tick loop owns its own connection so a slow `sizes` never delays sampling.++use crate::collector::{CollectCtx, Collector, Scope, State, Target};+use crate::collectors::Registry;+use crate::config::{Config, ServerConfig};+use crate::http::{Readiness, METRICS};+use crate::pg;+use crate::sink::{Run, Sink};+use anyhow::Result;+use chrono::Utc;+use std::collections::{BTreeSet, HashMap};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio::sync::Semaphore;+use tokio::task::JoinHandle;++pub const WRITER: &str = "writer";++pub async fn run(+ cfg: Arc<Config>,+ registry: Arc<Registry>,+ sink: Arc<dyn Sink>,+ ready: Readiness,+ once: bool,+) -> Result<()> {+ let mut handles = Vec::new();+ for server in &cfg.servers {+ let (cfg, registry, sink, server, ready) = (+ cfg.clone(),+ registry.clone(),+ sink.clone(),+ server.clone(),+ ready.clone(),+ );+ handles.push(tokio::spawn(async move {+ if let Err(e) = run_server(cfg, registry, sink, server.clone(), ready, once).await {+ tracing::error!(server = server.id, error = %format!("{e:#}"), "server loop exited");+ }+ }));+ }+ if !once {+ let sink = sink.clone();+ handles.push(tokio::spawn(async move {+ let mut t = tokio::time::interval(Duration::from_secs(3600));+ loop {+ t.tick().await;+ if let Err(e) = sink.maintain().await {+ tracing::warn!(error = %format!("{e:#}"), "sink maintenance failed");+ }+ }+ }));+ }+ futures::future::join_all(handles).await;+ Ok(())+}++/// One endpoint we can open connections to.+#[derive(Clone)]+struct Endpoint {+ instance: String,+ url: String,+}++async fn run_server(+ cfg: Arc<Config>,+ registry: Arc<Registry>,+ sink: Arc<dyn Sink>,+ server: ServerConfig,+ ready: Readiness,+ once: bool,+) -> Result<()> {+ let timeout = cfg.defaults.statement_timeout;+ let heavy = Arc::new(Semaphore::new(1));+ let server = Arc::new(server);++ let probe = pg::connect(&server.url, timeout, None).await?;+ let version = pg::server_version(&probe).await?;+ let wanted = cfg.databases_for(&server);+ let discover = matches!(wanted.as_slice(), [w] if w == "*");+ tracing::info!(+ server = server.id,+ version,+ discover,+ instances = server.instances.len(),+ "server ready"+ );+ ready.set(true);+ {+ let caps = pg::capabilities(&probe).await.unwrap_or_default();+ let sysid: Option<i64> = probe+ .query_one("SELECT system_identifier FROM pg_control_system()", &[])+ .await+ .ok()+ .map(|r| r.get(0));+ let version_str: String = probe+ .query_one("SELECT version()", &[])+ .await+ .map(|r| r.get(0))+ .unwrap_or_default();+ let databases = if discover {+ pg::discover_databases(&probe).await.unwrap_or_default()+ } else {+ wanted.clone()+ };+ let mut instances = vec![WRITER.to_string()];+ instances.extend(server.instances.keys().cloned());+ let info = crate::sink::ServerInfo {+ server_id: server.id.clone(),+ system_identifier: sysid,+ version_num: version as i32,+ version: version_str,+ aurora_version: caps.aurora_version,+ instances,+ databases,+ };+ if let Err(e) = sink.register_server(&info).await {+ tracing::warn!(error = %format!("{e:#}"), "register_server failed");+ }+ }+ drop(probe);++ let writer = Endpoint {+ instance: WRITER.into(),+ url: server.url.clone(),+ };+ let mut cluster_endpoints = vec![writer.clone()];+ cluster_endpoints.extend(server.instances.iter().map(|(n, u)| Endpoint {+ instance: n.clone(),+ url: u.clone(),+ }));++ // Cluster-scoped loops: fixed for the life of the process.+ let mut fixed: Vec<JoinHandle<()>> = Vec::new();+ for collector in registry.iter() {+ let eff = cfg.effective(&server, collector.name(), collector.default_enabled());+ if !eff.enabled+ || collector.min_pg_version() > version+ || collector.scope() != Scope::Cluster+ {+ continue;+ }+ let interval = eff.interval.unwrap_or(collector.interval());+ let endpoints: Vec<Endpoint> = if collector.per_instance() {+ cluster_endpoints.clone()+ } else {+ vec![writer.clone()]+ };+ for ep in endpoints {+ let target = Target {+ server_id: server.id.clone(),+ instance: ep.instance.clone(),+ datname: None,+ };+ fixed.push(spawn_loop(+ collector.clone(),+ target,+ ep.url,+ interval,+ version,+ timeout,+ sink.clone(),+ heavy.clone(),+ server.clone(),+ once,+ ));+ }+ }++ // Database-scoped loops: follow discovery.+ let mut running: HashMap<String, Vec<JoinHandle<()>>> = HashMap::new();+ loop {+ let current: BTreeSet<String> = if discover {+ match pg::connect(&server.url, timeout, None).await {+ Ok(c) => match pg::discover_databases(&c).await {+ Ok(dbs) => dbs.into_iter().collect(),+ Err(e) => {+ tracing::warn!(server = server.id, error = %e, "database discovery failed");+ running.keys().cloned().collect()+ }+ },+ Err(e) => {+ tracing::warn!(server = server.id, error = %e, "discovery connect failed");+ running.keys().cloned().collect()+ }+ }+ } else {+ wanted.iter().cloned().collect()+ };++ for gone in running+ .keys()+ .filter(|d| !current.contains(*d))+ .cloned()+ .collect::<Vec<_>>()+ {+ tracing::info!(+ server = server.id,+ database = gone,+ "database gone; stopping collectors"+ );+ for h in running.remove(&gone).unwrap() {+ h.abort();+ }+ }+ let new_dbs: Vec<String> = current+ .iter()+ .filter(|d| !running.contains_key(*d))+ .cloned()+ .collect();+ for db in &new_dbs {+ tracing::info!(+ server = server.id,+ database = db,+ "database found; starting collectors"+ );+ let mut hs = Vec::new();+ for collector in registry.iter() {+ let eff = cfg.effective(&server, collector.name(), collector.default_enabled());+ if !eff.enabled+ || collector.min_pg_version() > version+ || collector.scope() != Scope::Database+ {+ continue;+ }+ let interval = eff.interval.unwrap_or(collector.interval());+ let endpoints: Vec<Endpoint> = if collector.per_instance() {+ cluster_endpoints.clone()+ } else if collector.prefers_reader() && server.reader_url.is_some() {+ // Reader-preferring database collectors (sizes, schema) read data that is+ // identical across the cluster (shared storage / catalog); the reader is+ // only used to shed load, so the rows are still labelled as the writer's.+ vec![Endpoint {+ instance: WRITER.into(),+ url: server.reader_url.clone().unwrap(),+ }]+ } else {+ vec![writer.clone()]+ };+ for ep in endpoints {+ let target = Target {+ server_id: server.id.clone(),+ instance: ep.instance.clone(),+ datname: Some(db.clone()),+ };+ hs.push(spawn_loop(+ collector.clone(),+ target,+ ep.url,+ interval,+ version,+ timeout,+ sink.clone(),+ heavy.clone(),+ server.clone(),+ once,+ ));+ }+ }+ running.insert(db.clone(), hs);+ }+ METRICS+ .targets+ .with_label_values(&[&server.id])+ .set((fixed.len() + running.values().map(Vec::len).sum::<usize>()) as i64);++ if once {+ futures::future::join_all(fixed.drain(..)).await;+ futures::future::join_all(running.drain().flat_map(|(_, hs)| hs)).await;+ return Ok(());+ }+ tokio::time::sleep(cfg.defaults.rediscover_interval).await;+ }+}++#[allow(clippy::too_many_arguments)]+fn spawn_loop(+ collector: Arc<dyn Collector>,+ target: Target,+ url: String,+ interval: Duration,+ pg_version: u32,+ timeout: Duration,+ sink: Arc<dyn Sink>,+ heavy: Arc<Semaphore>,+ server: Arc<ServerConfig>,+ once: bool,+) -> JoinHandle<()> {+ tokio::spawn(async move {+ tick_loop(+ collector, target, url, interval, pg_version, timeout, sink, heavy, server, once,+ )+ .await+ })+}++#[allow(clippy::too_many_arguments)]+async fn tick_loop(+ collector: Arc<dyn Collector>,+ target: Target,+ url: String,+ interval: Duration,+ pg_version: u32,+ timeout: Duration,+ sink: Arc<dyn Sink>,+ heavy: Arc<Semaphore>,+ server: Arc<ServerConfig>,+ once: bool,+) {+ let mut state: Option<State> = sink+ .load_state(collector.name(), &target)+ .await+ .ok()+ .flatten();+ let is_heavy = interval > Duration::from_secs(15);+ let mut client: Option<tokio_postgres::Client> = None;+ let mut caps = crate::collector::Capabilities::default();+ let mut first = true;+ let mut unmet_logged: Option<String> = None;+ let labels = [collector.name().to_string(), target.server_id.clone()];++ loop {+ // First tick runs right away; later ticks align to wall-clock boundaries so+ // every server samples at the same instant.+ if !once && !first {+ tokio::time::sleep(until_next_boundary(interval)).await;+ }+ first = false;+ let _permit = if is_heavy {+ Some(heavy.acquire().await.unwrap())+ } else {+ None+ };++ if client.as_ref().map(|c| c.is_closed()).unwrap_or(true) {+ match pg::connect(&url, timeout, target.datname.as_deref()).await {+ Ok(c) => {+ match pg::capabilities(&c).await {+ Ok(cp) => caps = cp,+ Err(e) => {+ tracing::warn!(collector = collector.name(), error = %format!("{e:#}"), "capability probe failed")+ }+ }+ client = Some(c);+ }+ Err(e) => {+ tracing::warn!(collector = collector.name(), server = target.server_id, instance = target.instance, error = %format!("{e:#}"), "connect failed");+ METRICS+ .errors+ .with_label_values(&[&labels[0], &labels[1], "connect"])+ .inc();+ if once {+ return;+ }+ continue;+ }+ }+ }++ // Prerequisites (Aurora, extensions). Re-probed every 10 minutes so a later+ // CREATE EXTENSION is picked up without a restart.+ if let Some(reason) = collector.requires().unmet(&caps) {+ if unmet_logged.as_deref() != Some(&reason) {+ tracing::info!(+ collector = collector.name(),+ server = target.server_id,+ instance = target.instance,+ database = target.datname.as_deref().unwrap_or("-"),+ reason,+ "skipping: prerequisite not met"+ );+ unmet_logged = Some(reason);+ }+ if once {+ return;+ }+ drop(_permit);+ tokio::time::sleep(Duration::from_secs(600)).await;+ if let Some(c) = &client {+ if let Ok(cp) = pg::capabilities(c).await {+ caps = cp;+ }+ }+ continue;+ }+ unmet_logged = None;++ let started = Instant::now();+ let now = Utc::now();+ let cx = CollectCtx {+ target: target.clone(),+ server: &server,+ conn: client.as_ref().unwrap(),+ pg_version,+ caps: &caps,+ now,+ };+ let result = collector.collect(&cx, state.as_ref()).await;++ let mut run = Run {+ collector: collector.name().to_string(),+ target: target.clone(),+ started_at: now,+ duration_ms: started.elapsed().as_millis() as i64,+ rows: 0,+ error: None,+ };+ METRICS+ .tick_seconds+ .with_label_values(&[&labels[0], &labels[1]])+ .observe(started.elapsed().as_secs_f64());+ match result {+ Ok((snap, next)) => {+ run.rows = snap.rows.len() as i64;+ METRICS+ .rows+ .with_label_values(&[&labels[0], &labels[1]])+ .inc_by(run.rows as u64);+ if let Err(e) = sink.write(&snap).await {+ tracing::warn!(collector = collector.name(), error = %format!("{e:#}"), "sink write failed");+ METRICS+ .errors+ .with_label_values(&[&labels[0], &labels[1], "sink"])+ .inc();+ run.error = Some(format!("sink: {e:#}"));+ } else {+ state = Some(next);+ }+ }+ Err(e) => {+ tracing::warn!(collector = collector.name(), server = target.server_id, instance = target.instance, error = %format!("{e:#}"), "collect failed");+ METRICS+ .errors+ .with_label_values(&[&labels[0], &labels[1], "collect"])+ .inc();+ run.error = Some(format!("{e:#}"));+ }+ }+ if let Err(e) = sink.record_run(&run).await {+ tracing::debug!(error = %e, "record_run failed");+ }+ if is_heavy+ || collector.kind() == crate::collector::Kind::Snapshot+ || collector.name() == "logs"+ {+ if let Some(s) = &state {+ if let Err(e) = sink.save_state(collector.name(), &target, s).await {+ tracing::debug!(error = %e, "save_state failed");+ }+ }+ }+ if once {+ return;+ }+ }+}++/// Sleep until the next multiple of `interval` on the wall clock.+fn until_next_boundary(interval: Duration) -> Duration {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap();+ let i = interval.as_millis() as u64;+ let n = now.as_millis() as u64;+ Duration::from_millis(i - (n % i))+}diff --git a/rust/pgcollector/src/sink/mod.rs b/rust/pgcollector/src/sink/mod.rsnew file mode 100644index 000000000000..724d747a4403--- /dev/null+++ b/rust/pgcollector/src/sink/mod.rs@@ -0,0 +1,86 @@+pub mod postgres;++use crate::collector::{Snapshot, State, Target};+use anyhow::Result;+use async_trait::async_trait;++/// Where snapshots go. Collection code never knows.+#[async_trait]+pub trait Sink: Send + Sync {+ async fn write(&self, snap: &Snapshot) -> Result<()>;+ /// Record one collector tick (self-metrics).+ async fn record_run(&self, run: &Run) -> Result<()>;+ /// Persist/restore per-(collector,target) state across restarts.+ async fn save_state(&self, collector: &str, target: &Target, state: &State) -> Result<()>;+ async fn load_state(&self, collector: &str, target: &Target) -> Result<Option<State>>;+ /// Housekeeping: create upcoming partitions, drop expired ones.+ async fn maintain(&self) -> Result<()> {+ Ok(())+ }+ /// Upsert the server row (identity, version, instances) the API lists servers from.+ async fn register_server(&self, _info: &ServerInfo) -> Result<()> {+ Ok(())+ }+}++#[derive(Debug, Clone)]+pub struct ServerInfo {+ pub server_id: String,+ pub system_identifier: Option<i64>,+ pub version_num: i32,+ pub version: String,+ pub aurora_version: Option<String>,+ pub instances: Vec<String>,+ pub databases: Vec<String>,+}++#[derive(Debug, Clone)]+pub struct Run {+ pub collector: String,+ pub target: Target,+ pub started_at: chrono::DateTime<chrono::Utc>,+ pub duration_ms: i64,+ pub rows: i64,+ pub error: Option<String>,+}++/// `--once` mode: print what would be written.+pub struct StdoutSink;++#[async_trait]+impl Sink for StdoutSink {+ async fn write(&self, snap: &Snapshot) -> Result<()> {+ println!(+ "{:<24} {:<12} {:<8} {:<20} rows={:<6} events={} interval={:.0}s",+ snap.collector,+ snap.target.server_id,+ snap.target.instance,+ snap.target.datname.as_deref().unwrap_or("-"),+ snap.rows.len(),+ snap.events.len(),+ snap.interval_seconds+ );+ if let Some(r) = snap.rows.first() {+ println!(" first row: {}", serde_json::to_string(r)?);+ }+ for a in &snap.aux {+ Box::pin(self.write(a)).await?;+ }+ Ok(())+ }+ async fn record_run(&self, run: &Run) -> Result<()> {+ if let Some(e) = &run.error {+ println!(+ "{:<24} {:<12} ERROR {e}",+ run.collector, run.target.server_id+ );+ }+ Ok(())+ }+ async fn save_state(&self, _: &str, _: &Target, _: &State) -> Result<()> {+ Ok(())+ }+ async fn load_state(&self, _: &str, _: &Target) -> Result<Option<State>> {+ Ok(None)+ }+}diff --git a/rust/pgcollector/src/sink/postgres.rs b/rust/pgcollector/src/sink/postgres.rsnew file mode 100644index 000000000000..3cb183e543a1--- /dev/null+++ b/rust/pgcollector/src/sink/postgres.rs@@ -0,0 +1,505 @@+//! Postgres sink. Tier A tables are created/extended on the fly from the shape of+//! the rows; hand-written tables live in migrations/.++use super::{Run, ServerInfo, Sink};+use crate::collector::{Kind, Snapshot, State, Target, Value};+use crate::config::SinkConfig;+use anyhow::{Context, Result};+use async_trait::async_trait;+use chrono::{Duration as CDuration, Utc};+use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod};+use std::collections::{BTreeMap, HashSet};+use std::sync::Mutex;+use tokio_postgres::types::ToSql;++pub struct PostgresSink {+ pool: Pool,+ retention_days: u32,+ /// table → known columns, so we only hit the catalog when a new column shows up.+ schema_cache: Mutex<BTreeMap<String, HashSet<String>>>,+}++/// Columns the sink owns. A collector row carrying one of these (e.g. `datname` from+/// a cluster-scoped `pg_stat_database` query) supplies the identity value instead of+/// becoming a metric column.+const RESERVED: &[&str] = &[+ "server_id",+ "instance",+ "datname",+ "collected_at",+ "interval_seconds",+ "first_seen",+ "last_seen",+];++fn metric_cols(row: &crate::collector::Row) -> Vec<String> {+ row.keys()+ .filter(|k| !RESERVED.contains(&k.as_str()))+ .cloned()+ .collect()+}++fn datname_for(snap: &Snapshot, row: &crate::collector::Row) -> Option<String> {+ snap.target+ .datname+ .clone()+ .or_else(|| match row.get("datname") {+ Some(Value::Text(s)) => Some(s.clone()),+ _ => None,+ })+}++const MIGRATIONS: &[(&str, &str)] =+ &[("0001_base", include_str!("../../migrations/0001_base.sql"))];++impl PostgresSink {+ pub async fn connect(cfg: &SinkConfig) -> Result<Self> {+ let mut pg_cfg: tokio_postgres::Config =+ cfg.database_url.parse().context("parsing sink url")?;+ // TLS required unless the URL opts out (see pg::tls_policy).+ pg_cfg.ssl_mode(crate::pg::tls_policy(&cfg.database_url));+ let mgr = Manager::from_config(+ pg_cfg,+ crate::pg::tls_connector(),+ ManagerConfig {+ recycling_method: RecyclingMethod::Fast,+ },+ );+ let pool = Pool::builder(mgr)+ .max_size(8)+ .post_create(deadpool_postgres::Hook::async_fn(|client, _| {+ Box::pin(async move {+ crate::pg::quiet_session(client).await;+ Ok(())+ })+ }))+ .build()?;+ let sink = Self {+ pool,+ retention_days: cfg.retention_days,+ schema_cache: Mutex::new(BTreeMap::new()),+ };+ sink.migrate().await?;+ sink.maintain().await?;+ Ok(sink)+ }++ async fn migrate(&self) -> Result<()> {+ let c = self.pool.get().await?;+ c.batch_execute(+ "CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz DEFAULT now())",+ )+ .await?;+ for (name, sql) in MIGRATIONS {+ let done = c+ .query_opt("SELECT 1 FROM schema_migrations WHERE name = $1", &[name])+ .await?+ .is_some();+ if !done {+ tracing::info!(migration = name, "applying");+ c.batch_execute(sql)+ .await+ .with_context(|| format!("migration {name}"))?;+ c.execute("INSERT INTO schema_migrations (name) VALUES ($1)", &[name])+ .await?;+ }+ }+ Ok(())+ }++ /// Ensure `ts_<name>` / `cur_<name>` exists with every column the snapshot carries.+ async fn ensure_table(+ &self,+ c: &deadpool_postgres::Client,+ table: &str,+ snap: &Snapshot,+ ) -> Result<()> {+ let sample = match snap.rows.first() {+ Some(r) => r,+ None => return Ok(()),+ };+ let mut wanted: Vec<(String, &str)> = Vec::new();+ // (types borrowed from snap.types or inferred; both live as long as `snap`)+ for (col, v) in sample {+ if RESERVED.contains(&col.as_str()) {+ continue;+ }+ let ty = match snap.types.get(col) {+ Some(t) => t.as_str(),+ None => snap+ .rows+ .iter()+ .filter_map(|r| r.get(col))+ .find(|v| !matches!(v, Value::Null))+ .unwrap_or(v)+ .pg_type(),+ };+ wanted.push((col.clone(), ty));+ }++ let known = self.schema_cache.lock().unwrap().get(table).cloned();+ let known = match known {+ Some(k) if wanted.iter().all(|(c, _)| k.contains(c)) => return Ok(()),+ Some(k) => k,+ None => {+ let exists = c+ .query_opt(+ "SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = $1",+ &[&table],+ )+ .await?+ .is_some();+ if !exists {+ self.create_table(c, table, snap, &wanted).await?;+ }+ let cols = c+ .query(+ "SELECT column_name FROM information_schema.columns WHERE table_name = $1",+ &[&table],+ )+ .await?;+ cols.into_iter().map(|r| r.get::<_, String>(0)).collect()+ }+ };++ let mut known = known;+ for (col, ty) in &wanted {+ if !known.contains(col) {+ tracing::info!(table, column = col, r#type = ty, "adding column");+ c.batch_execute(&format!(+ "ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {} {ty}",+ q(col)+ ))+ .await?;+ known.insert(col.clone());+ }+ }+ self.schema_cache+ .lock()+ .unwrap()+ .insert(table.to_string(), known);+ Ok(())+ }++ async fn create_table(+ &self,+ c: &deadpool_postgres::Client,+ table: &str,+ snap: &Snapshot,+ cols: &[(String, &str)],+ ) -> Result<()> {+ let col_defs: Vec<String> = cols.iter().map(|(n, t)| format!("{} {t}", q(n))).collect();+ let sql = match snap.kind {+ Kind::Snapshot => {+ let pk: Vec<String> = ["server_id".to_string(), "instance".to_string(), "datname".to_string()].iter()+ .chain(snap.key.iter().filter(|k| !RESERVED.contains(&k.as_str()))).map(|k| q(k)).collect();+ format!(+ "CREATE TABLE IF NOT EXISTS {table} (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, {}, PRIMARY KEY ({}))",+ col_defs.join(", "),+ pk.join(", ")+ )+ }+ _ => format!(+ "CREATE TABLE IF NOT EXISTS {table} (server_id text NOT NULL, instance text NOT NULL, datname text, collected_at timestamptz NOT NULL, \+ interval_seconds real, {}) PARTITION BY RANGE (collected_at); \+ CREATE INDEX IF NOT EXISTS {table}_server_time_idx ON {table} (server_id, collected_at);",+ col_defs.join(", ")+ ),+ };+ tracing::info!(table, "creating table");+ // Several collector loops can see the same table missing at once (first tick+ // of every database); serialise the DDL so the losers see IF NOT EXISTS hit.+ let sql = sql.trim_end().trim_end_matches(';');+ c.batch_execute(&format!(+ "BEGIN; SELECT pg_advisory_xact_lock(hashtext('pgcollector:{table}')); {sql}; COMMIT;"+ ))+ .await+ .with_context(|| format!("creating {table}"))?;+ if snap.kind != Kind::Snapshot {+ self.ensure_partitions(c, table).await?;+ }+ Ok(())+ }++ async fn ensure_partitions(&self, c: &deadpool_postgres::Client, table: &str) -> Result<()> {+ let today = Utc::now().date_naive();+ for d in -1..=2i64 {+ let day = today + CDuration::days(d);+ let next = day + CDuration::days(1);+ let part = format!("{table}_{}", day.format("%Y%m%d"));+ c.batch_execute(&format!(+ "CREATE TABLE IF NOT EXISTS {part} PARTITION OF {table} FOR VALUES FROM ('{day}') TO ('{next}')"+ ))+ .await?;+ }+ Ok(())+ }++ async fn write_ts(+ &self,+ c: &deadpool_postgres::Client,+ table: &str,+ snap: &Snapshot,+ ) -> Result<()> {+ let cols = metric_cols(&snap.rows[0]);+ let mut all_cols = vec![+ "server_id".to_string(),+ "instance".to_string(),+ "datname".to_string(),+ "collected_at".to_string(),+ "interval_seconds".to_string(),+ ];+ all_cols.extend(cols.iter().cloned());+ let col_list = all_cols.iter().map(|c| q(c)).collect::<Vec<_>>().join(", ");++ // Multi-row VALUES in chunks; COPY is the upgrade path if this ever matters.+ for chunk in snap.rows.chunks(500) {+ let mut params: Vec<Box<dyn ToSql + Sync + Send>> = Vec::new();+ let mut tuples = Vec::new();+ let interval = snap.interval_seconds as f32;+ for row in chunk {+ let base = params.len();+ params.push(Box::new(snap.target.server_id.clone()));+ params.push(Box::new(snap.target.instance.clone()));+ params.push(Box::new(datname_for(snap, row)));+ params.push(Box::new(snap.collected_at));+ params.push(Box::new(interval));+ for col in &cols {+ params.push(to_sql(row.get(col).unwrap_or(&Value::Null)));+ }+ let ph: Vec<String> = (0..all_cols.len())+ .map(|i| format!("${}", base + i + 1))+ .collect();+ tuples.push(format!("({})", ph.join(", ")));+ }+ let sql = format!(+ "INSERT INTO {table} ({col_list}) VALUES {}",+ tuples.join(", ")+ );+ let refs: Vec<&(dyn ToSql + Sync)> = params+ .iter()+ .map(|p| -> &(dyn ToSql + Sync) { p.as_ref() })+ .collect();+ c.execute(&sql, &refs)+ .await+ .with_context(|| format!("inserting into {table}"))?;+ }+ Ok(())+ }++ async fn write_cur(+ &self,+ c: &deadpool_postgres::Client,+ table: &str,+ snap: &Snapshot,+ ) -> Result<()> {+ let cols = metric_cols(&snap.rows[0]);+ let mut all_cols = vec![+ "server_id".to_string(),+ "instance".to_string(),+ "datname".to_string(),+ "first_seen".to_string(),+ "last_seen".to_string(),+ ];+ all_cols.extend(cols.iter().cloned());+ let col_list = all_cols.iter().map(|c| q(c)).collect::<Vec<_>>().join(", ");+ let pk: Vec<String> = ["server_id", "instance", "datname"]+ .iter()+ .map(|s| s.to_string())+ .chain(+ snap.key+ .iter()+ .filter(|k| !RESERVED.contains(&k.as_str()))+ .cloned(),+ )+ .map(|k| q(&k))+ .collect();+ let updates: Vec<String> = cols+ .iter()+ .filter(|c| !snap.key.contains(c))+ .map(|c| format!("{0} = EXCLUDED.{0}", q(c)))+ .collect();+ let set = std::iter::once("last_seen = EXCLUDED.last_seen".to_string())+ .chain(updates)+ .collect::<Vec<_>>()+ .join(", ");++ for row in &snap.rows {+ let mut params: Vec<Box<dyn ToSql + Sync + Send>> = vec![+ Box::new(snap.target.server_id.clone()),+ Box::new(snap.target.instance.clone()),+ Box::new(datname_for(snap, row).unwrap_or_default()),+ Box::new(snap.collected_at),+ Box::new(snap.collected_at),+ ];+ for col in &cols {+ params.push(to_sql(row.get(col).unwrap_or(&Value::Null)));+ }+ let ph: Vec<String> = (1..=all_cols.len()).map(|i| format!("${i}")).collect();+ let sql = format!(+ "INSERT INTO {table} ({col_list}) VALUES ({}) ON CONFLICT ({}) DO UPDATE SET {set}",+ ph.join(", "),+ pk.join(", ")+ );+ let refs: Vec<&(dyn ToSql + Sync)> = params+ .iter()+ .map(|p| -> &(dyn ToSql + Sync) { p.as_ref() })+ .collect();+ c.execute(&sql, &refs)+ .await+ .with_context(|| format!("upserting into {table}"))?;+ }+ // Rows no longer present: mark by leaving last_seen stale; the API layer filters on it.+ Ok(())+ }+}++#[async_trait]+impl Sink for PostgresSink {+ async fn write(&self, snap: &Snapshot) -> Result<()> {+ for a in &snap.aux {+ Box::pin(self.write(a)).await?;+ }+ let c = self.pool.get().await?;+ for ev in &snap.events {+ c.execute(+ "INSERT INTO events (server_id, instance, datname, at, kind, subject, before, after) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)",+ &[&snap.target.server_id, &snap.target.instance, &snap.target.datname, &snap.collected_at, &ev.kind, &ev.subject, &ev.before, &ev.after],+ )+ .await?;+ }+ if snap.rows.is_empty() {+ return Ok(());+ }+ let table = match snap.kind {+ Kind::Snapshot => format!("cur_{}", snap.collector),+ _ => format!("ts_{}", snap.collector),+ };+ self.ensure_table(&c, &table, snap).await?;+ match snap.kind {+ Kind::Snapshot => self.write_cur(&c, &table, snap).await,+ _ => self.write_ts(&c, &table, snap).await,+ }+ }++ async fn record_run(&self, run: &Run) -> Result<()> {+ let c = self.pool.get().await?;+ c.execute(+ "INSERT INTO collector_runs (collector, server_id, instance, datname, started_at, duration_ms, rows, error) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)",+ &[&run.collector, &run.target.server_id, &run.target.instance, &run.target.datname, &run.started_at, &run.duration_ms, &run.rows, &run.error],+ )+ .await?;+ Ok(())+ }++ async fn save_state(&self, collector: &str, target: &Target, state: &State) -> Result<()> {+ let c = self.pool.get().await?;+ let dat = target.datname.clone().unwrap_or_default();+ c.execute(+ "INSERT INTO collector_state (collector, server_id, instance, datname, state, updated_at) VALUES ($1,$2,$3,$4,$5,now()) \+ ON CONFLICT (collector, server_id, instance, datname) DO UPDATE SET state = EXCLUDED.state, updated_at = now()",+ &[&collector, &target.server_id, &target.instance, &dat, &serde_json::to_value(state)?],+ )+ .await?;+ Ok(())+ }++ async fn load_state(&self, collector: &str, target: &Target) -> Result<Option<State>> {+ let c = self.pool.get().await?;+ let dat = target.datname.clone().unwrap_or_default();+ let row = c+ .query_opt(+ "SELECT state FROM collector_state WHERE collector = $1 AND server_id = $2 AND instance = $3 AND datname = $4",+ &[&collector, &target.server_id, &target.instance, &dat],+ )+ .await?;+ Ok(match row {+ Some(r) => Some(serde_json::from_value(r.get::<_, serde_json::Value>(0))?),+ None => None,+ })+ }++ async fn register_server(&self, info: &ServerInfo) -> Result<()> {+ let c = self.pool.get().await?;+ c.execute(+ "INSERT INTO cur_servers (server_id, system_identifier, version_num, version, aurora_version, instances, databases, first_seen, last_seen)+ VALUES ($1,$2,$3,$4,$5,$6,$7,now(),now())+ ON CONFLICT (server_id) DO UPDATE SET system_identifier = EXCLUDED.system_identifier, version_num = EXCLUDED.version_num,+ version = EXCLUDED.version, aurora_version = EXCLUDED.aurora_version, instances = EXCLUDED.instances, databases = EXCLUDED.databases, last_seen = now()",+ &[&info.server_id, &info.system_identifier, &info.version_num, &info.version, &info.aurora_version, &info.instances, &info.databases],+ ).await?;+ Ok(())+ }++ async fn maintain(&self) -> Result<()> {+ let c = self.pool.get().await?;+ let tables: Vec<String> = c+ .query(+ "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \+ WHERE n.nspname = 'public' AND c.relkind = 'p' AND c.relname LIKE 'ts\\_%'",+ &[],+ )+ .await?+ .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();+ for t in &tables {+ self.ensure_partitions(&c, t).await?;+ let parts = c+ .query(+ "SELECT inhrelid::regclass::text FROM pg_inherits WHERE inhparent = $1::text::regclass",+ &[t],+ )+ .await?;+ for p in parts {+ let name: String = p.get(0);+ if let Some(stamp) = name.rsplit('_').next() {+ if stamp.len() == 8 && stamp < cutoff.as_str() {+ tracing::info!(partition = name, "dropping expired partition");+ c.batch_execute(&format!("DROP TABLE IF EXISTS {name}"))+ .await?;+ }+ }+ }+ }+ Ok(())+ }+}++fn q(ident: &str) -> String {+ format!("\"{}\"", ident.replace('"', "\"\""))+}++/// A NULL that serialises into any column type.+#[derive(Debug)]+struct NullAny;+impl ToSql for NullAny {+ fn to_sql(+ &self,+ _: &tokio_postgres::types::Type,+ _: &mut bytes::BytesMut,+ ) -> std::result::Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>+ {+ Ok(tokio_postgres::types::IsNull::Yes)+ }+ fn accepts(_: &tokio_postgres::types::Type) -> bool {+ true+ }+ tokio_postgres::types::to_sql_checked!();+}++fn to_sql(v: &Value) -> Box<dyn ToSql + Sync + Send> {+ match v {+ Value::Null => Box::new(NullAny),+ Value::Bool(b) => Box::new(*b),+ Value::Int(i) => Box::new(*i),+ Value::Float(f) => Box::new(*f),+ Value::Text(s) => Box::new(s.clone()),+ Value::Timestamp(t) => Box::new(*t),+ Value::Json(j) => Box::new(j.clone()),+ }+}diff --git a/rust/pgcollector/test/aurora_stubs.sql b/rust/pgcollector/test/aurora_stubs.sqlnew file mode 100644index 000000000000..a703af5c6822--- /dev/null+++ b/rust/pgcollector/test/aurora_stubs.sql@@ -0,0 +1,51 @@+-- Stubs mimicking Aurora's functions with their documented column shapes, for pipeline tests.+CREATE OR REPLACE FUNCTION aurora_version() RETURNS text LANGUAGE sql AS $$ SELECT '16.4.0' $$;++CREATE OR REPLACE FUNCTION aurora_stat_wait_type() RETURNS TABLE(type_id int, type_name text) LANGUAGE sql AS $$+ VALUES (1,'LWLock'),(3,'Lock'),(6,'Client'),(10,'IO') $$;+CREATE OR REPLACE FUNCTION aurora_stat_wait_event() RETURNS TABLE(type_id int, event_id int, event_name text) LANGUAGE sql AS $$+ VALUES (1,100,'buffer_content'),(3,300,'transactionid'),(6,600,'ClientRead'),(10,1000,'XactSync') $$;+CREATE OR REPLACE FUNCTION aurora_stat_system_waits() RETURNS TABLE(type_id int, event_id int, waits bigint, wait_time bigint) LANGUAGE sql AS $$+ SELECT e.type_id, e.event_id, (extract(epoch from now())::bigint % 100000) * (e.event_id % 7 + 1), (extract(epoch from now())::bigint % 100000) * 13+ FROM aurora_stat_wait_event() e $$;+CREATE OR REPLACE FUNCTION aurora_stat_backend_waits(p int) RETURNS TABLE(type_id int, event_id int, waits bigint, wait_time bigint) LANGUAGE sql AS $$+ SELECT e.type_id, e.event_id, (p % 50)::bigint + e.event_id, (p % 50)::bigint * 10 + e.event_id FROM aurora_stat_wait_event() e $$;++CREATE OR REPLACE FUNCTION aurora_stat_get_db_commit_latency(dboid oid) RETURNS bigint LANGUAGE sql AS $$+ SELECT (extract(epoch from now())::bigint % 1000000) $$;+CREATE OR REPLACE FUNCTION aurora_stat_dml_activity(dboid oid)+ RETURNS TABLE(select_count bigint, select_latency_microsecs bigint, insert_count bigint, insert_latency_microsecs bigint,+ update_count bigint, update_latency_microsecs bigint, delete_count bigint, delete_latency_microsecs bigint)+ LANGUAGE sql AS $$ SELECT s.tup_returned, s.tup_returned*7, s.tup_inserted, s.tup_inserted*9, s.tup_updated, s.tup_updated*11, s.tup_deleted, s.tup_deleted*3+ FROM pg_stat_database s WHERE s.datid = dboid $$;++CREATE OR REPLACE FUNCTION aurora_replica_status()+ RETURNS TABLE(server_id text, session_id text, durable_lsn pg_lsn, highest_lsn_rcvd pg_lsn, current_read_lsn pg_lsn,+ cur_replay_latency_in_usec bigint, active_txns int, is_current bool, last_transport_error int,+ last_error_timestamp timestamptz, last_update_timestamp timestamptz, feedback_xmin xid, feedback_epoch int,+ replica_lag_in_msec float8, log_stream_speed_in_kib_per_second float8, log_buffer_sequence_number bigint,+ oldest_read_view_trx_id bigint, oldest_read_view_lsn pg_lsn, pending_read_ios bigint, read_ios bigint, iops int, cpu float8)+ LANGUAGE sql AS $$+ VALUES ('db-instance-1','MASTER_SESSION_ID','0/1'::pg_lsn,'0/1'::pg_lsn,'0/1'::pg_lsn,0::bigint,3,true,0,NULL::timestamptz,NULL::timestamptz,'100'::xid,0,NULL::float8,12.5::float8,1::bigint,0::bigint,'0/1'::pg_lsn,0::bigint,100::bigint,0,1.5::float8),+ ('db-instance-2','uuid-2','0/1'::pg_lsn,'0/1'::pg_lsn,'0/1'::pg_lsn,1500::bigint,1,true,0,NULL::timestamptz,now(),'100'::xid,0,13.0::float8,12.5::float8,1::bigint,0::bigint,'0/1'::pg_lsn,2::bigint,200::bigint,0,2.5::float8) $$;++CREATE OR REPLACE FUNCTION aurora_stat_memctx_usage() RETURNS TABLE(pid int, name text, allocated bigint, used bigint, instances int) LANGUAGE sql AS $$+ SELECT a.pid, c.name, c.alloc, c.alloc/2, 1 FROM pg_stat_activity a,+ LATERAL (VALUES ('CacheMemoryContext', 100*1024*1024::bigint), ('ExecutorState', 8192::bigint)) c(name, alloc)+ WHERE a.backend_type = 'client backend' $$;++CREATE OR REPLACE VIEW _aurora_stat_activity AS SELECT a.*, 424242::bigint AS plan_id FROM pg_stat_activity a;+CREATE OR REPLACE FUNCTION aurora_stat_activity() RETURNS SETOF _aurora_stat_activity LANGUAGE sql AS $$ SELECT * FROM _aurora_stat_activity $$;++CREATE OR REPLACE VIEW _aurora_stat_statements AS+ SELECT s.*, s.shared_blks_read AS storage_blks_read, 0::float8 AS orcache_blks_hit, s.blk_read_time AS storage_blk_read_time,+ 0::float8 AS local_blk_read_time, 0::float8 AS orcache_blk_read_time,+ 0::bigint AS total_plan_peakmem, 0::bigint AS min_plan_peakmem, 0::bigint AS max_plan_peakmem,+ (s.calls*65536)::bigint AS total_exec_peakmem, 65536::bigint AS min_exec_peakmem, 65536::bigint AS max_exec_peakmem+ FROM pg_stat_statements s;+CREATE OR REPLACE FUNCTION aurora_stat_statements(showtext bool) RETURNS SETOF _aurora_stat_statements LANGUAGE sql AS $$ SELECT * FROM _aurora_stat_statements $$;++CREATE OR REPLACE VIEW _aurora_stat_plans AS+ SELECT s.*, (s.queryid % 1000)::bigint AS planid, 'Seq Scan on t (cost=0.00..1.00)' AS explain_plan, 'estimate'::text AS plan_type, now() - interval '1 hour' AS plan_captured_time+ FROM _aurora_stat_statements s;+CREATE OR REPLACE FUNCTION aurora_stat_plans(showtext bool) RETURNS SETOF _aurora_stat_plans LANGUAGE sql AS $$ SELECT * FROM _aurora_stat_plans $$;diff --git a/rust/pgcollector/test/setup-local.sh b/rust/pgcollector/test/setup-local.shnew file mode 100755index 000000000000..42441e76dcef--- /dev/null+++ b/rust/pgcollector/test/setup-local.sh@@ -0,0 +1,34 @@+#!/usr/bin/env bash+# Throwaway PG16 target for local testing: pg_stat_statements, auto_explain, file+# logging (bind-mounted to $LOG_DIR), Aurora stub functions, pg_proctab if the+# image has it built (see docs/telemetry-sources.md).+#+# test/setup-local.sh [container-name] [port] [log-dir]+set -euo pipefail+NAME=${1:-pgcollector-test}+PORT=${2:-5499}+LOG_DIR=${3:-$PWD/.local/pglog}+IMAGE=${IMAGE:-postgres:16}+mkdir -p "$LOG_DIR"; chmod 777 "$LOG_DIR"++docker rm -f "$NAME" >/dev/null 2>&1 || true+docker run -d --name "$NAME" -p "$PORT:5432" -e POSTGRES_PASSWORD=test -v "$LOG_DIR:/var/log/pg" "$IMAGE" \+ -c shared_preload_libraries=pg_stat_statements,auto_explain -c compute_query_id=on -c track_io_timing=on \+ -c logging_collector=on -c log_directory=/var/log/pg -c log_filename=postgresql-%Y-%m-%d_%H%M%S.log \+ -c log_rotation_size=10MB -c log_rotation_age=1h \+ -c "log_line_prefix=%t:%r:%u@%d:[%p]:%Q:" \+ -c log_min_duration_statement=0 -c log_lock_waits=on -c deadlock_timeout=200ms \+ -c log_checkpoints=on -c log_autovacuum_min_duration=0 -c log_temp_files=0 -c log_connections=on -c log_disconnections=on \+ -c auto_explain.log_min_duration=0 -c auto_explain.log_format=json -c auto_explain.log_analyze=on -c auto_explain.sample_rate=1 \+ >/dev/null+for i in $(seq 1 30); do docker exec "$NAME" pg_isready -U postgres >/dev/null 2>&1 && break; sleep 1; done++psql() { docker exec -i "$NAME" psql -U postgres -v ON_ERROR_STOP=1 "$@"; }+psql -qc "create extension if not exists pg_stat_statements"+psql -qc "create database app" || true+psql -qc "create database pgcollector" || true+psql -d app -qc "create extension if not exists pg_stat_statements; create table if not exists t(id int primary key, v text); insert into t select g, md5(g::text) from generate_series(1,10000) g on conflict do nothing;"+docker cp "$(dirname "$0")/aurora_stubs.sql" "$NAME:/tmp/aurora_stubs.sql"+psql -qf /tmp/aurora_stubs.sql+psql -qc "create extension if not exists pg_proctab" 2>/dev/null || echo "pg_proctab not available in image (optional)"+echo "ready: postgres://postgres:test@localhost:$PORT/postgres?sslmode=disable (TLS is required unless sslmode=disable) logs in $LOG_DIR"