---
title: "pgai mon sql reference (monitoring v4)"
sidebar_label: "SQL query reference"
slug: /monitoring/sql-reference
keywords:
  - "pgai mon sql"
  - "postgresai mon sql"
  - "pgai-mon"
  - "PostgresAI monitoring v4"
  - "DuckDB telemetry SQL"
  - "PostgreSQL observability SQL"
  - "pgai_samples"
  - "prom_rate"
---

# `pgai mon sql` reference (monitoring v4)

`npx pgai mon sql` runs one read-only DuckDB `SELECT` statement against a PostgresAI monitoring v4 (`pgai-mon`) metric store. You get full SQL access to time-series metrics, `pg_stat_statements` query texts, schema object history, PostgreSQL `jsonlog` entries, and `auto_explain` plans from one command.

Monitoring v4 replaces the v3 VictoriaMetrics + pgwatch + PromQL stack with a single Rust binary (`pgai-mon`) that stores telemetry in Parquet files on local disk or S3 and serves SQL through an embedded DuckDB engine. Every command in this reference works with both the `pgai` and `postgresai` CLI binaries (from the `postgresai` npm package, Node.js 18+ or Bun 1.0+).

`pgai mon sql` needs CLI version 4.0.0 or later. Until 4.0.0 is released, use `npx pgai@rc`: the npm `latest` version (0.18.x) has no `mon sql` command. To install a monitoring v4 box on a Linux machine with Docker, run `npx pgai@rc mon local-install`.

## Quickstart for AI agents

Orient yourself on an unfamiliar monitoring store in three commands. Always pass `--json` when parsing output programmatically, because `--json` preserves full 64-bit integer precision for `queryid` and `series_id`.

### 1. Discover views, columns, and collected metrics

List every public view and its columns from DuckDB catalog metadata:

```bash
npx pgai@rc mon sql --project my-db --json "
select v.view_name, c.column_name, c.data_type
from duckdb_views() v
join duckdb_columns() c on c.table_name = v.view_name
where not v.internal and v.view_name not like '\\_%' escape '\\'
order by v.view_name, c.column_index
"
```

List the metrics currently stored with their series counts and collection intervals:

```bash
npx pgai@rc mon sql --project my-db --json "
select md.metric, md.metric_group, md.interval_s, c.series
from metric_dict md
join (select metric, count(*) as series from series group by metric) c using (metric)
order by c.series desc
limit 50
"
```

### 2. Discover clusters, nodes, databases, and time bounds

Find every monitored cluster, node, and database in the store, including stopped or deleted clusters whose historical Parquet files remain within retention:

```bash
npx pgai@rc mon sql --project my-db --json "
select
  labels['cluster'] as cluster,
  labels['node_name'] as node_name,
  labels['dbname'] as source,
  labels['datname'] as datname,
  count(distinct metric) as metric_count,
  count(*) as series_count
from series
where metric like 'pgwatch_%'
group by all
order by cluster, node_name, datname
"
```

Find the last time each cluster reported data (look back 30 days using `prom_tlast_over_time` on `pgwatch_db_size_size_b`, which works on both local disk and S3 stores):

```bash
npx pgai@rc mon sql --project my-db --json "
select
  labels['cluster'] as cluster,
  labels['node_name'] as node_name,
  labels['datname'] as datname,
  to_timestamp(max(value)) as last_seen_utc
from prom_tlast_over_time(
  'pgwatch_db_size_size_b',
  [],
  epoch_ms(now()),
  epoch_ms(now()),
  300000,
  30 * 86400 * 1000
)
group by all
order by last_seen_utc desc
"
```

### 3. Run a scoped query with `--json`

Always pass an explicit `[start_ms, end_ms]` range and label matchers so `pgai-mon` prunes Parquet files and row groups before reading:

```bash
npx pgai@rc mon sql --project my-db --json "
select
  ts,
  labels['cluster'] as cluster,
  labels['node_name'] as node_name,
  labels['datname'] as datname,
  value as db_size_bytes
from pgai_samples(
  'pgwatch_db_size_size_b',
  [['cluster', '=', 'prod'], ['datname', '=', 'app']],
  epoch_ms(now() - interval 1 hour),
  epoch_ms(now())
)
where not stale
order by ts desc
limit 20
"
```

Check `"truncated": false` in the JSON reply before trusting any aggregation or ranking as complete.

## CLI reference (`npx pgai mon sql`)

The CLI runs queries in two modes: **remote Console mode** (default) and **local direct mode** (`--local`).

### How the two modes differ

Remote Console mode routes through PostgresAI Console so the platform never opens inbound connections to your monitoring box. Local direct mode speaks HTTP directly to `pgai-mon` on loopback with no platform round-trip.

| Behavior | Remote Console mode (default) | Local direct mode (`--local`) |
| --- | --- | --- |
| Transport | `POST /rpc/instance_query_enqueue` -> box `instance-jobs` polls -> local `pgai-mon POST /sql` -> `POST /rpc/instance_query_result` | Direct `POST http://127.0.0.1:8765/sql` (or `PGAI_MON_URL` / `PGAI_MON_PORT`) |
| Authentication | Console API token (`--api-key`, `PGAI_API_KEY`, or `~/.config/postgresai/config.json`) + org selector for global tokens | Bearer token `PGAI_MON_TOKEN` read from the install directory's `.env` |
| Target flags | `--project <id\|alias>`, `--instance <uuid>`, or `instance_id=` from local `.pgwatch-config` | None (rejects `--project` and `--instance`) |
| Default CLI wait timeout | Sized from server poll estimate: `clamp(ceil(estimate * 1.5) + 30, 60, 1800)` seconds; `11m` (660 s) fallback | `120s` |
| Max query text size | 64 KiB (65,536 bytes, valid UTF-8) | `pgai-mon` HTTP body limit |
| Max result payload size | 1,000,000 bytes JSONB text bound (enforced by `instance-jobs`; trailing rows dropped, `truncated: true`) | `http.max_bytes` (default 16 MiB) and `http.max_rows` (default 100,000) |
| Concurrency | 1 in-flight user query per monitoring instance by default (`PT409` if busy) | `http.max_concurrent` slots (default 1 per core, up to 4) with queue of 64 |
| String control characters | `instance-jobs` replaces control characters (including newlines) in cell strings with spaces | Preserved as returned by `pgai-mon` |

### Synopsis and options

```bash
npx pgai [--api-key <key>] [--api-base-url <url>] mon sql <query> [options]
```

| Flag | Scope | Description |
| --- | --- | --- |
| `<query>` | Positional (required) | One read-only DuckDB `SELECT` (or `WITH ... SELECT`) statement. |
| `--project <id\|alias>` | Remote mode | Resolve the monitoring instance UUID from a project ID, alias, or name (case-insensitive) via `v1.projects_list`. Fails if the project has zero or more than one active monitoring instance. Mutually exclusive with `--instance` and `--local`. |
| `--instance <uuid>` | Remote mode | Monitoring instance UUID. When omitted (along with `--project` and `--local`), the CLI reads `instance_id=` from `.pgwatch-config` in the local monitoring project directory. Mutually exclusive with `--project` and `--local`. |
| `--org <alias>` | Remote mode | Organization alias (overrides `PGAI_ORG`). Required when using a global token (`pai_global_...`). Mutually exclusive with `--org-id`. |
| `--org-id <id>` | Remote mode | Numeric organization ID (overrides `PGAI_ORG_ID`). Alternative to `--org`. Mutually exclusive with `--org`. |
| `--timeout <duration>` | Both modes | Wait timeout formatted as `<n>s`, `<n>m`, `<n>h`, or bare integer seconds (minimum `1`). Overrides the dynamic remote timeout or the `120s` local default. |
| `--json` | Both modes | Print the raw JSON result object on stdout instead of a formatted text table. |
| `--local` | Local mode | Query `pgai-mon` directly on the local host without a Console API key or `instance-jobs` container. |
| `--api-key <key>` | Root option (before `mon sql`) | Console API key. Overrides `PGAI_API_KEY` and stored config. |
| `--api-base-url <url>` | Root option (before `mon sql`) | Console API base URL. Overrides `PGAI_API_BASE_URL` and stored config. |

### Environment variables

Variables follow strict precedence: explicit CLI flag, then environment variable, then `~/.config/postgresai/config.json`, then legacy `.pgwatch-config`.

- **Remote Console mode:**
  - `PGAI_API_KEY`: Console API token (per-org token or global `pai_global_...` token).
  - `PGAI_API_BASE_URL`: Console API base URL.
  - `PGAI_ORG`: organization alias (mutually exclusive with `PGAI_ORG_ID`).
  - `PGAI_ORG_ID`: numeric organization ID (mutually exclusive with `PGAI_ORG`).
  - `XDG_CONFIG_HOME`: base directory for `postgresai/config.json` (defaults to `~/.config`).
- **Local direct mode (`--local`):**
  - `PGAI_MON_URL`: full base URL of `pgai-mon` (for example `http://127.0.0.1:8765`). Overrides `PGAI_MON_PORT`.
  - `PGAI_MON_PORT`: loopback port on `127.0.0.1` (defaults to `PGAI_MON_PORT` in the install `.env`, else `8765`).
  - `PGAI_PROJECT_DIR`: monitoring install directory where the CLI reads `.env` (for `PGAI_MON_TOKEN` and `PGAI_MON_PORT`) or `.pgwatch-config` (for `instance_id`).

### Output formats and lossless 64-bit integers

`pgai mon sql` supports two output modes:

- **Default text table:** prints space-padded columns, row values (`NULL` for SQL NULL, JSON strings for maps/arrays), a trailing `<N> row(s)` count, and a `⚠ TRUNCATED:` warning line when `truncated` is true.
- **`--json`:** prints a pretty-printed JSON payload to stdout:

```json
{
  "columns": ["queryid", "calls"],
  "types": ["BIGINT", "DOUBLE"],
  "rows": [[-8580166607628940136, 4210]],
  "row_count": 1,
  "truncated": false,
  "elapsed_ms": 12
}
```

In remote Console mode, the `instance-jobs` payload contains `columns`, `types`, `rows`, and `truncated` (`row_count` and `elapsed_ms` are omitted on the job channel). On an `s3://` store queried via `--local`, the payload may also include an `"s3"` object with `gets`, `bytes`, `demand_gets`, `footer_gets`, `exclusive`, and an optional `warning`.

Both the table renderer and `--json` use a lossless JSON parser (`lossless-json.ts`), so 64-bit integers such as `queryid` (`-8580166607628940136`) and `series_id` keep every digit instead of losing precision above `2^53`. Standard `JSON.parse()` in JavaScript rounds those numbers; when reading `queryid` in JS/TS scripts, cast `queryid::varchar` in SQL or use a lossless JSON parser.

The CLI has no `--csv` flag. If you need CSV or columnar/object JSON directly from a local `pgai-mon` server, call `POST /sql?format=csv` (or `rows`, `columnar`, `objects`) over HTTP with `Authorization: Bearer $PGAI_MON_TOKEN`.

### Exit codes, timeouts, and error handling

`npx pgai mon sql` exits `0` on a completed query and `1` on any error. Notice that a truncated result still exits `0`, so scripts and agents must inspect the `truncated` boolean in `--json` output.

Diagnostic lines (such as the slow-answer notice printed after 2 seconds in remote mode: `Queued as job <uuid>; ...`) go to stderr so stdout stays valid JSON under `--json`.

Common failure states:

- **Remote job timeout (`queued`):** no worker claimed the job before `--timeout`. Check that the `instance-jobs` container is running on the monitoring box (`npx pgai mon health`; enabled with `mon local-install --instance-jobs`), or wait if an initial collection is queued ahead of it.
- **Remote job timeout (`running`):** the box claimed the job and is still working on it. Re-run with a larger `--timeout` or narrow the query time window.
- **Concurrent query conflict (`PT409`):** another user query is already in flight on that monitoring instance (the platform enforces an in-flight cap of 1 user query per instance by default). Wait and retry.
- **SQL refused (`HTTP 403`):** `pgai-mon` rejected the statement as `not_read_only` (non-SELECT, DDL/DML, `SET`, or multiple statements) or `forbidden` (table function outside the allowlist, or a Parquet path outside the store).
- **SQL error (`HTTP 400`):** DuckDB reported `parse_error`, `binder_error`, `catalog_error`, `conversion_error`, or `invalid_input`.
- **Resource limit (`HTTP 408` / `413` / `429`):** `timeout` (15 s default in `pgai-mon`), `out_of_memory` (DuckDB limit of about 91.6 MiB or 192 MiB reader RSS cap), or `busy` (admission queue full or 30 s queue wait exceeded).

### Monitoring v3 (PromQL) vs. monitoring v4 (SQL)

The v4 CLI removed the `pgai promql` command. Running `pgai promql` exits `1` immediately without making any network request and prints:

```text
pgai promql was removed with VictoriaMetrics: query the metric store with 'pgai mon sql' instead (see 'pgai mon sql --help').
```

Cross-version behavior when a v4 CLI targets a v3 box (or vice versa):

- Running `pgai mon sql` against a **monitoring v3 (VictoriaMetrics)** box fails on the box with `failure_class = "unknown_kind"` (`this instance does not know this job kind`). Upgrade that monitoring box to v4 to query it with SQL.
- Sending legacy `promql_instant` or `promql_range` jobs to a **monitoring v4 (`pgai-mon`)** box fails with `failure_class = "not_supported"` (`not supported: use sql (the metric store answers SQL, not PromQL)`).

## Exploring archived and no-longer-existing clusters (including DBLab Forge)

Because `pgai-mon` writes immutable day-partitioned Parquet files indexed by `catalog.json` (on local disk or in an `s3://bucket/prefix` object store), telemetry survives after a monitored Postgres cluster is stopped, retired, or destroyed. This includes ephemeral DBLab Forge runs, short-lived benchmark clusters, staging environments, and decommissioned production replicas.

### How retention preserves historical data

Each data kind follows explicit retention rules in `pgai-mon`:

- **Time-series data (`samples`, `series`, `rollup_1h`, `rollup_1d`, `rollup_1h_month`, `logs`, `plan_events`):** kept for `store.retention_days`. The binary default is `0` (keep forever); the default Docker Compose config sets `14` days (`PGAI_MON_RETENTION_DAYS`).
- **Statement texts (`query_texts`):** kept for `store.texts_retention_days`. The binary default is `0` (keep forever); the default Docker Compose config sets `30` days (`PGAI_MON_TEXTS_RETENTION_DAYS`).
- **Permanent metadata (`series_reg`, `objects`, `plan_defs`):** never dropped by retention. Even after samples expire, the series registry still remembers which `(metric, labels)` existed, and `objects` retains schema definitions with their `valid_from` / `valid_to` ranges.

### Two cases: target cluster gone vs. monitoring box gone

How you connect depends on whether the **monitored Postgres cluster** is gone or the **monitoring box itself** is gone:

1. **Monitored cluster or DBLab Forge run is gone, while the monitoring box is still active:**
   Query it normally with `npx pgai mon sql --project <project>` or `--instance <uuid>`. All Parquet data collected while that cluster existed remains queryable in the store.
2. **Monitoring box itself is stopped, deleted, or deactivated (`is_active = false`):**
   Remote Console `npx pgai mon sql` cannot reach it today. The platform RPC `v1.projects_list` lists only active monitoring instances (`mi.is_active = true`), and `v1.instance_query_enqueue` refuses inactive instances with `PT409` (`This monitoring instance is not active.`). To inspect an archived S3 bucket or local disk store after the monitoring box is gone, start a read-only `pgai-mon serve` process against the store and query it with `--local` (or run a one-shot local `pgai-mon query`):

```bash
# Option A: serve an archived S3 or local store read-only and query with --local
export PGAI_MON_TOKEN=$(openssl rand -hex 24)
pgai-mon serve --store s3://my-bucket/pgai-mon/forge-run-42 \
  --listen 127.0.0.1:8765 \
  --metrics-yml mon/metrics.yml \
  --macros-sql mon/sql/macros.sql

# In another shell (point PGAI_MON_URL and ensure .env has matching PGAI_MON_TOKEN):
PGAI_MON_URL=http://127.0.0.1:8765 npx pgai mon sql --local --json "select metric, count(*) from series group by 1 order by 2 desc limit 10"

# Option B: one-shot offline query against a local store directory (no server)
pgai-mon query --store /var/lib/pgai-mon-archive \
  --metrics-yml mon/metrics.yml \
  "select labels['cluster'], count(*) from series group by 1"
```

### Why querying "now" returns empty for vanished clusters

A bare `prom_last('metric', matchers, epoch_ms(now()), epoch_ms(now()), 300000)` only looks back `300000` ms (5 minutes), or `metric_dict.interval_s * 1.125` for slow metrics collected more than 5 minutes apart. For a Forge run or retired cluster that stopped hours or days ago, querying `now()` returns zero rows.

Always use this two-step workflow for vanished clusters:

1. **Locate the cluster's exact labels and time window:**

```sql
-- Step 1a: list clusters/nodes in series and query_texts with their text observation bounds
select
  cluster,
  node_name,
  dbname,
  count(distinct queryid) as distinct_queries,
  min(first_seen) as earliest_text_utc,
  max(last_seen) as latest_text_utc
from query_texts
group by all
order by latest_text_utc desc
```

If the cluster had no `pg_stat_statements` texts (or you want exact sample boundaries), scan timestamps over a wide lookback (for example 14 days) with `prom_tlast_over_time`:

```sql
-- Step 1b: find last sample timestamp per cluster/node over the past 14 days
select
  labels['cluster'] as cluster,
  labels['node_name'] as node_name,
  to_timestamp(max(value)) as last_sample_utc,
  cast(max(value) * 1000 as bigint) as end_ms
from prom_tlast_over_time(
  'pgwatch_db_size_size_b',
  [],
  epoch_ms(now()),
  epoch_ms(now()),
  300000,
  14 * 86400 * 1000
)
group by all
order by last_sample_utc desc
```

2. **Query the historical window using explicit UTC timestamps:**

```sql
-- Step 2: inspect that vanished cluster's exact active window
select
  to_timestamp(t / 1000) as ts_utc,
  labels['datname'] as datname,
  value as tps
from prom_rate(
  'pgwatch_db_stats_xact_commit',
  [['cluster', '=', 'forge-run-2026-11-18'], ['node_name', '=', 'node-01']],
  epoch_ms(timestamptz '2026-11-18 14:00:00+00'),
  epoch_ms(timestamptz '2026-11-18 16:00:00+00'),
  60000,
  300000
)
order by t
```

On closed UTC days (older than today plus `compact_grace_s`, default 5 minutes), `pgai-mon` automatically serves `prom_*` queries from 1-hour (`rollup_1h`) and 1-day (`rollup_1d`) Parquet rollups instead of raw samples, making multi-day historical queries fast even on S3 stores.

## Gen4 data model and SQL functions

Consumers query only the 11 public views defined in `mon/schema/views.sql` and the `pgai_*` / `prom_*` table functions bound by `pgai-mon`. Internal `_raw_*` views are managed by the server and should not be queried directly.

### Public views

| View | Columns and DuckDB types | Notes |
| --- | --- | --- |
| `series` | `series_id UBIGINT`, `metric VARCHAR`, `labels MAP(VARCHAR, VARCHAR)` | One row per unique `(metric, labels)` ever seen (series registry + unregistered day tail). Filters on `metric` push down into Parquet. |
| `samples` | `ts TIMESTAMPTZ`, `series_id UBIGINT`, `value DOUBLE`, `stale BOOLEAN` | Every raw sample on a **local** store. **Raises an error on `s3://` stores**; use `pgai_samples(...)` or `prom_*` for portable queries. |
| `metrics` | `ts TIMESTAMPTZ`, `metric VARCHAR`, `labels MAP(VARCHAR, VARCHAR)`, `value DOUBLE` | Convenience join of `samples` and `series`. **Local store only** (raises an error on `s3://` stores). |
| `query_texts` | `queryid BIGINT`, `dbname VARCHAR`, `query VARCHAR`, `first_seen TIMESTAMPTZ`, `last_seen TIMESTAMPTZ`, `source VARCHAR`, `cluster VARCHAR`, `node_name VARCHAR` | `pg_stat_statements` texts deduplicated per `(queryid, dbname, query_hash, source, cluster, node_name)`. Snapshotted every `collector.query_texts_interval_s` (default 300 s). `source`/`cluster`/`node_name` may be `NULL` in older files. |
| `query_text_names` | `queryid BIGINT`, `dbname VARCHAR`, `query VARCHAR` | One query text per `(queryid, dbname)`, picking the newest text by `first_seen`. Prefer this view when joining labels in `pg_stat_statements` queries so a text change does not duplicate rows, and so result cache entries survive refresh-only text snapshots. |
| `logs` | `ts TIMESTAMPTZ`, `level VARCHAR`, `sqlstate VARCHAR`, `pid BIGINT`, `dbname VARCHAR`, `username VARCHAR`, `application VARCHAR`, `message VARCHAR`, `query_fingerprint VARCHAR`, `plan_hash VARCHAR`, `raw JSON`, `queryid BIGINT` | PostgreSQL `jsonlog` lines (parameter values dropped; `auto_explain` lines carry `plan_hash` and `queryid`). Empty unless `logs[]` tailing or `pgai-mon load-logs` is configured; managed services (RDS, Supabase, ClickHouse Cloud) do not populate this view. |
| `plans` | `plan_hash VARCHAR`, `queryid BIGINT`, `first_seen TIMESTAMPTZ`, `last_seen TIMESTAMPTZ`, `count BIGINT`, `total_ms DOUBLE`, `plan JSON` | Aggregated `auto_explain` normalized execution plans (literals redacted), one row per `(plan_hash, queryid)`. Empty unless `jsonlog` with `auto_explain` is ingested. |
| `plan_events` | `ts TIMESTAMPTZ`, `plan_hash VARCHAR`, `queryid BIGINT`, `dbname VARCHAR`, `total_ms DOUBLE`, `top_node VARCHAR`, `shared_hit BIGINT`, `shared_read BIGINT`, `shared_dirtied BIGINT`, `shared_written BIGINT`, `temp_read BIGINT`, `temp_written BIGINT` | One row per `auto_explain` execution for tracking plan latency and buffer shifts over time. |
| `objects` | `kind VARCHAR`, `schema VARCHAR`, `name VARCHAR`, `definition VARCHAR`, `valid_from TIMESTAMPTZ`, `valid_to TIMESTAMPTZ`, `dbname VARCHAR`, `source VARCHAR`, `cluster VARCHAR`, `node_name VARCHAR` | Table, index, constraint, view, and function definitions with validity intervals. Only changes are stored; `valid_to IS NULL` means current. Snapshotted every `collector.objects_interval_s` (default 600 s), so objects created and dropped within 10 minutes are missed. |
| `metric_dict` | `metric VARCHAR`, `metric_group VARCHAR`, `interval_s BIGINT`, `instance_level BOOLEAN`, `type VARCHAR`, `description VARCHAR` | Maps every collected metric in the store to its `metrics.yml` group, collection interval, scope, and `gauge`/`counter` flag. |
| `metric_dict_prefix` | `metric_group VARCHAR`, `prefix VARCHAR`, `interval_s BIGINT`, `instance_level BOOLEAN`, `gauges VARCHAR[]`, `description VARCHAR` | Raw prefix dictionary loaded from `metrics.yml` (one row per metric group). |

### Portable raw-sample and PromQL-shaped table functions

All time arguments (`start_ms`, `end_ms`, `step_ms`, `window_ms`) are **Unix epoch milliseconds (`BIGINT`)**, while matcher arguments are a list of `[label, operator, value]` triples where `operator` is `=`, `!=`, `=~`, or `!~` using anchored RE2 regular expressions (`[]` matches every series of the metric).

#### Raw sample reader

```sql
pgai_samples(metric, matchers, start_ms, end_ms)
-- returns: (series_id UBIGINT, labels MAP(VARCHAR, VARCHAR), ts TIMESTAMPTZ, value DOUBLE, stale BOOLEAN)
```

`pgai_samples` reads Parquet files directly through the Rust scanner, pruning files and row groups by series and time so it works identically on local disk and `s3://` object stores. Because output is unordered and includes staleness markers, add `ORDER BY ts` when order matters and filter `WHERE NOT stale` before aggregating raw samples.

#### Time-grid rollup functions (`prom_*`)

Every function below returns `(series_id UBIGINT, labels MAP(VARCHAR, VARCHAR), t BIGINT, value DOUBLE)`, except `prom_agg`, which returns `(labels MAP(VARCHAR, VARCHAR), t BIGINT, value DOUBLE)` where `t` is the step timestamp in Unix milliseconds (`to_timestamp(t / 1000)` converts it to `TIMESTAMPTZ`).

For an **instant query** at timestamp `T`, pass `start_ms = T`, `end_ms = T`, and `step_ms = 300000` (5 minutes). For `prom_rate` and `prom_irate`, pass `window_ms = 0` when you need no explicit `[d]` window. The evaluator then uses `step_ms`, widened to the scrape-interval lookback. `prom_last` and `prom_timestamp` take no window argument: a 6th argument causes a binder error.

| Function signature | Semantics (matched to VictoriaMetrics v1.140) |
| --- | --- |
| `prom_last(metric, matchers, start, end, step)` | Bare selector: last raw value at each step `t`. Respects staleness markers (`stale = true` hides the series immediately). For slow metrics (`interval_s > 300`), automatically extends lookback to `interval_s * 1.125`. |
| `prom_timestamp(metric, matchers, start, end, step)` | Raw sample timestamp in Unix **seconds** (`DOUBLE`) of the last sample in the lookback window. |
| `prom_rate(metric, matchers, start, end, step, window)` | Per-second counter rate over `(t - window, t]` with automatic counter-reset correction. Does not extrapolate past sample edges. |
| `prom_irate(metric, matchers, start, end, step, window)` | Instantaneous per-second rate from the last two samples in `(t - window, t]`, with reset correction. |
| `prom_increase(metric, matchers, start, end, step, window)` | Total counter increase over `(t - window, t]` with reset correction and VictoriaMetrics' "started near zero" heuristic for brand-new series. |
| `prom_increase_pure(metric, matchers, start, end, step, window)` | Counter increase over `(t - window, t]` where a series with no prior history always counts from `0`. Ideal for `pg_stat_statements` window totals. |
| `prom_delta(metric, matchers, start, end, step, window)` | Raw value change over `(t - window, t]` without counter-reset adjustment (use for gauges). |
| `prom_idelta(metric, matchers, start, end, step, window)` | Raw difference between the last two samples in `(t - window, t]` (gauges). |
| `prom_last_over_time(metric, matchers, start, end, step, window)` | Last non-NaN value in `(t - window, t]`. |
| `prom_tlast_over_time(metric, matchers, start, end, step, window)` | Timestamp in Unix **seconds** of the last sample in `(t - window, t]`. |
| `prom_first_over_time(metric, matchers, start, end, step, window)` | First non-NaN value in `(t - window, t]`. |
| `prom_avg_over_time(...)`, `prom_sum_over_time(...)`, `prom_min_over_time(...)`, `prom_max_over_time(...)`, `prom_count_over_time(...)`, `prom_stddev_over_time(...)` | Same 6 arguments as `prom_rate`. Population standard deviation (`stddev_pop`) for `stddev_over_time`. |
| `prom_quantile_over_time(phi, metric, matchers, start, end, step, window)` | Continuous quantile `phi` in `[0.0, 1.0]` over samples in `(t - window, t]`. |
| `prom_agg(op, fn, metric, matchers, start, end, step, window, p_by := [...])` | Streaming group aggregation in Rust: `op` in `'sum'`, `'avg'`, `'count'`, `'min'`, `'max'`; `fn` is any rollup name (such as `'rate'`, `'irate'`, `'last'`, `'last_over_time'`, `'max_over_time'`). Keeps memory low when aggregating thousands of series. |
| `prom_topk(k, fn, metric, matchers, start, end, step, window, p_den_metric := '', p_bottom := false, p_by := [])` | Streaming top-k (or bottom-k with `p_bottom := true`) per step in Rust. Set `p_den_metric` to rank ratios such as `exec_time / calls`. Set `p_by` to sum by label keys before ranking. |
| `prom_topk_expr(k, fn, terms, matchers, start, end, step, window, p_bottom := false, p_by := [])` | Streaming top-k over a multi-metric linear combination or ratio: `terms` is `[{'m': metric, 'n': num_coef, 'd': den_coef}, ...]`. |

Helper scalar macros loaded from `mon/sql/macros.sql` (when configured via `macros_sql`): `prom_match(labels, matchers)`, `prom_by(labels, keys)`, `prom_ms(ts)`, `prom_ts(ms)`, `fmt_bytes(bytes)`, `py_isoformat(epoch_s)`, `py_utc_z(epoch_s)`.

Not available in `pgai-mon`: `histogram_quantile(...)`, and native Rust `resets()` / `changes()` (computing resets over raw samples requires scanning raw points).

### Label conventions

Every Postgres metric emitted by `pgai-mon` carries these standard labels in `labels`:

- `cluster` and `node_name`: custom tags from the target configuration (`instances.yml` / `sources.yml`), used to group nodes and join `host_*` metrics.
- `dbname`: the **monitored source name** (the node/target alias in `sources.yml`), rather than the PostgreSQL database name.
- `datname`: the **PostgreSQL database name** (such as `postgres`, `app`, or `server_process` for background processes in `wait_events`).
- `real_dbname`: database name added by the collector on every series, which you need when filtering metrics such as `redundant_indexes` that do not emit a `tag_datname` column.
- `sys_id`: PostgreSQL `system_identifier` from `pg_control_system()` (empty if the role lacks `EXECUTE` on `pg_control_system()`).
- `job` and `instance`: default scrape labels (`job = 'pgwatch-prometheus'`, `instance = <source name>`). Each source with a `job` also writes the `up` series (`1` while healthy, `0` on failure/hang).

### Important note on `metric_dict.type` (counters vs. gauges)

In `mon/metrics.yml`, several cumulative PostgreSQL statistics views (`db_stats`, `pg_stat_statements`, `pg_stat_all_tables`, `pg_stat_all_indexes`, `pg_statio_all_tables`, `pg_statio_all_indexes`, `pg_stat_io`, `wal`) list their columns under `gauges` for pgwatch Prometheus sink compatibility. Because `metric_dict.type` derives directly from that `gauges` list, `metric_dict.type` reports `'gauge'` for cumulative counters such as `pgwatch_db_stats_xact_commit` and `pgwatch_pg_stat_statements_exec_time_total`.

Always choose `prom_rate` / `prom_increase_pure` vs. `prom_last` based on the **semantic type** in the catalog below, rather than `metric_dict.type` alone.

## Complete telemetry catalog

`mon/metrics.yml` defines **58 PostgreSQL metric groups**: **51** enabled in the default `full` preset, **2** in the `pg_index_pilot` preset, and **5** express-checkup-only snapshot groups (not scheduled in continuous monitoring). On top of those, `pgai-mon` emits `up`, **38** `pgai_mon_*` collector/store self-monitoring metrics, and up to **40** unified `host_*` metrics across RDS, Aurora, Supabase, and ClickHouse Managed Postgres.

Metric names follow the pattern `pgwatch_<prefix>_<column>`. All intervals below are from the `full` preset unless noted otherwise.

### 1. Query performance (`pg_stat_statements`)

- **`pg_stat_statements`** (`pgwatch_pg_stat_statements_*`, interval **30 s**, instance-level, top 100 queries per run with `calls >= 3` and `exec_time_total >= 1000` ms):
  - Labels: `datname`, `queryid` (text).
  - Cumulative counters (use `prom_rate` / `prom_irate` / `prom_increase_pure`): `calls`, `plans_total`, `exec_time_total` (ms), `plan_time_total` (ms), `rows`, `shared_bytes_hit_total` (bytes), `shared_bytes_read_total` (bytes), `shared_bytes_dirtied_total` (bytes), `shared_bytes_written_total` (bytes), `block_read_total` (ms), `block_write_total` (ms), `wal_records`, `wal_fpi`, `wal_bytes` (bytes), `temp_bytes_read` (bytes), `temp_bytes_written` (bytes).
  - Companion view: `query_texts` / `query_text_names` (snapshotted every **300 s**).

### 2. Active sessions, wait events (ASH), and locks

- **`wait_events`** (`pgwatch_wait_events_total`, interval **15 s**, instance-level, gauge): active session count per `(datname, query_id, wait_event_type, wait_event)`. Running on CPU is labeled `wait_event = 'CPU*'`, `wait_event_type = 'CPU*'`. Background processes use `datname = 'server_process'`. Notice the label name is `query_id` (with underscore).
- **`pg_stat_activity`** (`pgwatch_pg_stat_activity_*`, interval **15 s**, per-DB, gauge): `count`, `max_tx_duration` (seconds), labeled by `datname`, `application_name`, `state`.
- **`lock_waits`** (`pgwatch_lock_waits_*`, interval **30 s**, per-DB, gauge): `blocked_ms` (ms), `blocker_tx_ms` (ms), labeled by `blocked_pid`, `blocked_user`, `blocked_appname`, `blocked_table`, `blocked_query_id`, `blocker_pid`, `blocker_user`, `blocker_appname`, `blocker_table`, `blocker_query_id`, `blocked_mode`, `blocked_locktype`, `blocker_mode`, `blocker_locktype`.
- **`locks_mode`** (`pgwatch_locks_mode_count`, interval **30 s**, per-DB, gauge): lock count per `lockmode` (`AccessShareLock`, `RowExclusiveLock`, `AccessExclusiveLock`, etc.).
- **`pg_blocked`** (`pgwatch_pg_blocked_queries`, interval **30 s**, per-DB, gauge): count of blocked queries per `table`.
- **`pg_long_running_transactions`** (`pgwatch_pg_long_running_transactions_*`, interval **30 s**, per-DB, gauge): `transactions` (count), `age_in_seconds` (seconds).
- **`pg_stuck_idle_in_transaction`** (`pgwatch_pg_stuck_idle_in_transaction_queries`, interval **30 s**, per-DB, gauge): count of stuck idle-in-transaction sessions.

### 3. Database throughput, I/O, buffers, and SLRU

- **`db_stats`** (`pgwatch_db_stats_*`, interval **30 s**, per-DB):
  - Gauges: `numbackends`, `postmaster_uptime_s` (s), `in_recovery_int` (0/1), `invalid_indexes`, `checksum_last_failure_s` (s).
  - Cumulative counters: `xact_commit`, `xact_rollback`, `blks_read`, `blks_hit`, `tup_returned`, `tup_fetched`, `tup_inserted`, `tup_updated`, `tup_deleted`, `conflicts`, `temp_files`, `temp_bytes` (bytes), `deadlocks`, `blk_read_time` (ms), `blk_write_time` (ms), `checksum_failures`, `session_time` (ms), `active_time` (ms), `idle_in_transaction_time` (ms), `sessions`, `sessions_abandoned`, `sessions_fatal`, `sessions_killed`.
- **`db_size`** (`pgwatch_db_size_*`, interval **30 s**, per-DB, gauge): `size_b` (bytes), `catalog_size_b` (bytes).
- **`bgwriter`** (`pgwatch_bgwriter_*`, interval **30 s**, instance-level): cumulative counters `buffers_clean`, `maxwritten_clean`, `buffers_alloc` (plus checkpoint columns on PG &lt;17); gauge `last_reset_s` (s).
- **`checkpointer`** (`pgwatch_checkpointer_*`, interval **30 s**, PG 17+): cumulative counters `num_timed`, `num_requested`, `restartpoints_timed`, `restartpoints_req`, `restartpoints_done`, `write_time` (ms), `sync_time` (ms), `buffers_written`; gauge `last_reset_s` (s).
- **`pg_stat_io`** (`pgwatch_pg_stat_io_*`, interval **30 s**, instance-level, PG 16+): labeled by `backend_type`, `object`, `context`; cumulative counters `reads`, `writes`, `writebacks`, `extends`, `hits`, `evictions`, `reuses`, `fsyncs`, `read_time_ms`, `write_time_ms`, `writeback_time_ms`, `fsync_time_ms`, `read_bytes_mb`, `write_bytes_mb`, `writeback_bytes_mb`, `extend_bytes_mb`; gauge `stats_reset_s`.
- **`pg_stat_slru`** (`pgwatch_pg_stat_slru_*`, interval **30 s**, per-DB): labeled by `name` (SLRU cache name); cumulative counters `blks_zeroed`, `blks_hit`, `blks_read`, `blks_written`, `blks_exists`, `flushes`, `truncates`; gauge `stats_reset_epoch`.
- **`stats_reset`** (`pgwatch_stats_reset_*`, interval **3600 s**, per-DB, gauge): `stats_reset_epoch`, `seconds_since_reset`.

### 4. Tables, indexes, bloat, and storage

- **`table_stats`** (`pgwatch_table_stats_*`, interval **30 s**, per-DB, top 100 tables + `'$other$'`):
  - Labels: `datname`, `schema`, `table_name`, `table_full_name`.
  - Gauges: `table_size_b`, `total_relation_size_b`, `toast_size_b`, `n_live_tup`, `n_dead_tup`, `seconds_since_last_vacuum`, `seconds_since_last_analyze`, `tx_freeze_age`, `mxid_freeze_age`, `last_seq_scan_s`.
  - Cumulative counters: `seq_scan`, `seq_tup_read`, `idx_scan`, `idx_tup_fetch`, `n_tup_ins`, `n_tup_upd`, `n_tup_del`, `n_tup_hot_upd`, `vacuum_count`, `autovacuum_count`, `analyze_count`, `autoanalyze_count`.
- **`table_size_detailed`** (`pgwatch_table_size_detailed_*`, interval **30 s**, per-DB, top 100 + `'$other$'`, gauge): byte breakdown across `table_main_size_b`, `table_fsm_size_b`, `table_vm_size_b`, `table_indexes_size_b`, `toast_main_size_b`, `toast_fsm_size_b`, `toast_vm_size_b`, `toast_indexes_size_b`, `total_relation_size_b`, `actual_data_size_b`, `metadata_size_b`, `total_indexes_size_b`, `total_toast_size_b`.
- **`pg_class`** (`pgwatch_pg_class_*`, interval **30 s**, per-DB, top 100 relations, gauge): `reltuples`, `relpages`, `relation_size_bytes`, `total_relation_size_bytes`.
- **`pg_total_relation_size`** (`pgwatch_pg_total_relation_size_bytes`, interval **30 s**, per-DB, top 100, gauge): total bytes per relation.
- **`pg_stat_all_tables`** (`pgwatch_pg_stat_all_tables_*`, interval **30 s**, per-DB): cumulative scan/tuple/vacuum/analyze counters plus `n_live_tup`, `n_dead_tup` gauges.
- **`pg_stat_all_indexes`** (`pgwatch_pg_stat_all_indexes_*`, interval **30 s**, per-DB): cumulative counters `idx_scan`, `idx_tup_read`, `idx_tup_fetch`.
- **`pg_statio_all_tables`** / **`pg_statio_all_indexes`** (`pgwatch_pg_statio_all_tables_*`, `pgwatch_pg_statio_all_indexes_*`, interval **30 s**, per-DB): cumulative heap, index, and TOAST block read/hit counters.
- **`pg_table_bloat`** (`pgwatch_pg_table_bloat_*`, interval **7200 s**, per-DB, top 100 + `'$other$'`, gauge): `real_size_mib` (MiB), `extra_size` (bytes), `extra_pct`, `fillfactor`, `bloat_size` (bytes), `bloat_pct` (%), `is_na`. Labels: `datname`, `schemaname`, `tblname`.
- **`pg_btree_bloat`** (`pgwatch_pg_btree_bloat_*`, interval **7200 s**, per-DB, top 100 + `'$other$'`, gauge): same bloat columns plus `table_size_mib`, labeled by `datname`, `schemaname`, `tblname`, `idxname`.
- **`unused_indexes`** (interval **7200 s**), **`rarely_used_indexes`** (interval **10800 s**), **`redundant_indexes`** (interval **10800 s**, filter on `real_dbname`), **`pg_invalid_indexes`** (interval **7200 s**), **`pg_not_valid_constraints`** (interval **7200 s**): periodic schema health gauges (`index_size_bytes`, `idx_scan`, etc.).

### 5. Autovacuum, xmin horizon, and wraparound risk

- **`pg_autovacuum_workers`** (`pgwatch_pg_autovacuum_workers_*`, interval **30 s**, instance-level, gauge): `active_workers`, `max_workers`, `free_slots`.
- **`pg_autovacuum_queue`** (`pgwatch_pg_autovacuum_queue_*`, interval **60 s**, per-DB, gauge): `n_dead_tup`, `n_live_tup`, `autovacuum_threshold`, `autovacuum_overdue_factor` (`dead_tup / threshold`; values `>= 1.0` are eligible for autovacuum). Labels: `datname`, `schemaname`, `relname`.
- **`pg_autovacuum_blocked`** (`pgwatch_pg_autovacuum_blocked_wait_seconds`, interval **30 s**, per-DB, gauge): seconds an autovacuum worker has waited on a lock; labels `worker_pid`, `blocker_pid`, `blocker_queryid`.
- **`pg_vacuum_progress`** (`pgwatch_pg_vacuum_progress_*`, interval **30 s**, per-DB, gauge): `pg_stat_progress_vacuum` columns including `index_vacuum_count`, `is_anti_wraparound`, labeled by `schema_name`, `table_name`, `vacuum_mode`.
- **`xmin_horizon`** (`pgwatch_xmin_horizon_*`, interval **30 s**, instance-level, gauge): `data_horizon_age_tx`, `catalog_horizon_age_tx`, `snapshot_xmin`, plus per-class ages and counts (`pg_stat_activity_*`, `pg_replication_slots_*`, `pg_replication_slots_catalog_*`, `pg_stat_replication_*`, `pg_prepared_xacts_*`).
- **`xmin_horizon_blockers`** (`pgwatch_xmin_horizon_blockers_age_tx`, interval **30 s**, instance-level, gauge): top xmin blocker per component, with rich labels (`component`, `horizon_type`, `blocker_database`, `blocker_user`, `blocker_appname`, `blocker_state`, `queryid`, `slot_name`, `slot_type`, `standby_name`, `prepared_gid`).
- **`pg_database_wraparound`** (`pgwatch_pg_database_wraparound_*`, interval **30 s**, per-DB, gauge): `age_datfrozenxid`, `age_datminmxid`.
- **`pg_table_wraparound`** (`pgwatch_pg_table_wraparound_*`, interval **300 s**, per-DB, top 50 by XID + top 50 by MultiXact, gauge): `xid_age`, `multixact_age`, `effective_freeze_max_age`, `effective_multixact_freeze_max_age`, `table_size_bytes`. Labels: `datname`, `schema_name`, `table_name`, `ranked_by`.
- **`pg_settings_wraparound`** (`pgwatch_pg_settings_wraparound_*`, interval **300 s**, instance-level, gauge): `autovacuum_freeze_max_age`, `autovacuum_multixact_freeze_max_age`, `vacuum_failsafe_age`, `vacuum_multixact_failsafe_age`.
- **`pg_txid`** (`pgwatch_pg_txid_*`, interval **30 s**, per-DB, gauge): `current`, `xmin`, `xmin_age`.
- **`multixact_size`** (`pgwatch_multixact_size_*`, interval **300 s**, per-DB, gauge): `members_bytes`, `offsets_bytes`, `status_code`.

### 6. WAL, archiving, replication, and server settings

- **`wal`** (`pgwatch_wal_*`, interval **30 s**, instance-level): cumulative counter `xlog_location_b` (LSN position in bytes; use `prom_rate` for WAL bytes/sec); gauges `timeline`, `in_recovery_int`, `postmaster_uptime_s`.
- **`pg_xlog_position`** (`pgwatch_pg_xlog_position_bytes`, interval **30 s**, per-DB, cumulative LSN byte offset).
- **`pg_wal_size`** (`pgwatch_pg_wal_size_*`, interval **30 s**, instance-level, gauge): `bytes` (total size of `pg_wal` directory), `status_code` (`0` = OK).
- **`archive_lag`** (`pgwatch_archive_lag_*`, interval **15 s**, per-DB): gauges `seconds_since_archive`, `wal_files_behind`, `current_lsn_numeric`, `archived_wal_finish_lsn_numeric`; cumulative counters `archived_count`, `failed_count`.
- **`pg_archiver`** (`pgwatch_pg_archiver_pending_wal_count`, interval **30 s**, per-DB, gauge): ready-to-archive WAL files.
- **`replication`** (`pgwatch_replication_*`, interval **30 s**, instance-level, gauge): `sent_lag_b`, `write_lag_b`, `flush_lag_b`, `replay_lag_b` (bytes); `write_lag_ms`, `flush_lag_ms`, `replay_lag_ms`, `reply_time_lag_ms` (ms); `backend_xmin_age_tx`, `is_sync_int`, `in_recovery_int`. Labels: `application_name`, `usename`, `client_info`.
- **`pg_stat_replication`** (`pgwatch_pg_stat_replication_*`, interval **30 s**, per-DB, gauge): raw LSNs and `reply_time_lag`.
- **`pg_stat_wal_receiver`** (`pgwatch_pg_stat_wal_receiver_*`, interval **30 s**, per-DB, standby-side WAL receiver state and LSNs).
- **`replication_slots`** (`pgwatch_replication_slots_*`, interval **30 s**, instance-level, gauge): `active` (0/1), `non_active_int` (0/1), `restart_lsn_lag_b` (bytes), `xmin_age_tx` (txs). Labels: `slot_name`, `plugin`.
- **`settings`** (`pgwatch_settings_*`, interval **300 s**, instance-level, gauge): `configured`, `numeric_value`, `setting_normalized`, `is_default_bool`. Labels: `setting_name`, `setting_value`, `unit`, `category`, `vartype`.

### 7. Optional preset and express-only groups

- **`pg_index_pilot` preset** (only collected when that preset is enabled): `pg_index_pilot` (30 s) and `pg_index_pilot_config` (7200 s).
- **Express-checkup-only snapshot groups** (in `metrics.yml` with no continuous preset schedule): `pg_autovacuum_relopts`, `pg_autovacuum_worker_snapshot`, `pg_dead_tuples`, `pg_dead_tuples_keepup`, `xmin_horizon_snapshot`.

### 8. Unified host metrics (`host_*`)

For managed Postgres providers (Amazon RDS/Aurora, Supabase, ClickHouse Managed Postgres), `pgai-mon` normalizes OS and cloud metrics into a single `host_*` vocabulary keyed by `cluster` and `node_name` (and `provider` on `host_provider_info`). Self-managed nodes do not emit `host_*` unless pushed or scraped through rules.

- **Identity and limits:** `host_provider_info` (`provider` = `Amazon RDS`, `Supabase`, or `ClickHouse`), `host_instance_info` (RDS labels: `instance_class`, `engine`, `storage_type`, `multi_az`, `region`), `host_cpu_cores` (ClickHouse), `host_disk_size_bytes`, `host_disk_max_size_bytes` (RDS autoscaling ceiling), `host_disk_provisioned_iops` (RDS), `host_disk_provisioned_throughput_bytes_per_second` (RDS gp3).
- **CPU and load:** `host_cpu_utilization_percent`, `host_os_cpu_percent` (RDS EM), `host_os_cpu_user_percent`, `host_os_cpu_system_percent`, `host_os_cpu_iowait_percent`, `host_os_cpu_steal_percent`, `host_os_load1` (RDS EM), `host_db_load` (RDS/Aurora Performance Insights `db.load.avg`).
- **Memory:** `host_memory_available_bytes`, `host_os_memory_total_bytes`, `host_os_memory_free_bytes`, `host_os_memory_cached_bytes`, `host_os_memory_buffers_bytes`, `host_os_swap_used_bytes`, `host_os_process_max_rss_bytes` (RDS EM).
- **Storage, I/O, and network:** `host_disk_free_bytes`, `host_local_storage_free_bytes` (Aurora), `host_volume_used_bytes` (Aurora), `host_disk_read_iops`, `host_disk_write_iops`, `host_volume_read_iops` (Aurora), `host_volume_write_iops` (Aurora), `host_disk_read_bytes_per_second`, `host_disk_write_bytes_per_second`, `host_disk_read_latency_seconds`, `host_disk_write_latency_seconds`, `host_network_receive_bytes_per_second`, `host_network_transmit_bytes_per_second`.
- **AWS credit and burst balances (300 s):** `host_cpu_credit_balance`, `host_cpu_surplus_credit_balance`, `host_disk_burst_balance_percent`, `host_ebs_io_balance_percent`, `host_ebs_byte_balance_percent`.

### 9. Collector and `pgai-mon` self-monitoring (`pgai_mon_*` and `up`)

- **Target liveness and stats resets:** `up{job="pgwatch-prometheus", instance=...}` (1 = healthy, 0 = failed), `pgai_mon_source_up`, `pgai_mon_source_last_success_epoch_s`, `pgai_mon_connect_failures_total`, `pgai_mon_stats_reset_epoch_s{view, key}` (collected every **60 s** for `postmaster`, `pg_stat_database`, `pg_stat_bgwriter`, `pg_stat_archiver`, `pg_stat_slru`, `pg_stat_wal`, `pg_stat_replication_slots`, `pg_stat_statements_info`, `pg_stat_io`, `pg_stat_checkpointer`).
- **Collector diagnostics (per metric):** `pgai_mon_metric_duration_ms`, `pgai_mon_errors_total`, `pgai_mon_timeouts_total`, `pgai_mon_retries_total`, `pgai_mon_skipped_slots_total`, `pgai_mon_series_cut_total`, `pgai_mon_rows_cut_total`.
- **Store, reader, cache, and S3 health (every 15 s):** `pgai_mon_build_info`, `pgai_mon_ingest_samples_total`, `pgai_mon_ingest_records_total`, `pgai_mon_flushes_total`, `pgai_mon_late_flushes_total`, `pgai_mon_flush_duration_seconds`, `pgai_mon_compactions_total`, `pgai_mon_wal_bytes`, `pgai_mon_store_files`, `pgai_mon_store_parquet_bytes`, `pgai_mon_series_known`, `pgai_mon_process_resident_memory_bytes`, `pgai_mon_process_cpu_seconds_total`, `pgai_mon_reader_resident_memory_bytes`, `pgai_mon_reader_restarts_total`, `pgai_mon_reader_memory_kills_total`, `pgai_mon_admission_running`, `pgai_mon_admission_waiting`, `pgai_mon_admission_started_total`, `pgai_mon_admission_memory_deferred_total`, `pgai_mon_cache_hits_total`, `pgai_mon_cache_misses_total`, `pgai_mon_s3_last_commit_age_seconds`, `pgai_mon_s3_pending_files`, `pgai_mon_s3_pending_bytes`, `pgai_mon_s3_commits_total`, `pgai_mon_s3_upload_errors_total`.

## Agent SQL exploration cookbook

Every query below uses portable `pgai_samples` or `prom_*` calls so it runs identically on local disk and `s3://` stores. Replace `'prod'`, `'node-01'`, and `'app'` with the `cluster`, `node_name`, and `datname` values discovered in Quickstart step 2.

### Top slow queries (`pg_stat_statements` + query text)

Compute total execution time, calls, mean time per call, and shared buffer hit ratio over the last hour using `prom_increase_pure` (which handles counter resets and queries that first appeared mid-window), joined to `query_text_names`:

```sql
with stats as (
  select 'calls' as m, labels, value
  from prom_increase_pure(
    'pgwatch_pg_stat_statements_calls',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
  union all
  select 'exec_ms', labels, value
  from prom_increase_pure(
    'pgwatch_pg_stat_statements_exec_time_total',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
  union all
  select 'hit_b', labels, value
  from prom_increase_pure(
    'pgwatch_pg_stat_statements_shared_bytes_hit_total',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
  union all
  select 'read_b', labels, value
  from prom_increase_pure(
    'pgwatch_pg_stat_statements_shared_bytes_read_total',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
),
pivoted as (
  select
    labels['datname'] as datname,
    labels['queryid'] as queryid,
    coalesce(max(value) filter (where m = 'calls'), 0) as calls,
    coalesce(max(value) filter (where m = 'exec_ms'), 0) as exec_ms,
    coalesce(max(value) filter (where m = 'hit_b'), 0) as hit_b,
    coalesce(max(value) filter (where m = 'read_b'), 0) as read_b
  from stats
  where not isnan(value)
  group by all
)
select
  p.datname,
  p.queryid,
  round(p.exec_ms, 1) as total_exec_ms,
  round(p.calls, 0) as calls,
  round(case when p.calls > 0 then p.exec_ms / p.calls else 0 end, 2) as mean_exec_ms,
  round(case when p.hit_b + p.read_b > 0 then 100.0 * p.hit_b / (p.hit_b + p.read_b) else 100.0 end, 2) as hit_pct,
  left(regexp_replace(coalesce(qt.query, ''), '\s+', ' ', 'g'), 140) as query_snippet
from pivoted p
left join query_text_names qt
  on qt.queryid = try_cast(p.queryid as bigint)
 and qt.dbname = p.datname
order by p.exec_ms desc
limit 20
```

### Active Session History (ASH) and wait-event spikes

Calculate Average Active Sessions (AAS) per `(wait_event_type, wait_event)` in 5-minute buckets over the last hour by dividing `sum_over_time(pgwatch_wait_events_total)` by `sum_over_time(up)` (the number of scrapes in each bucket):

```sql
with w as (
  select
    coalesce(labels['instance'], '') as inst,
    coalesce(labels['wait_event_type'], '') as wait_event_type,
    coalesce(labels['wait_event'], '') as wait_event,
    t,
    sum(value) as total_samples
  from prom_sum_over_time(
    'pgwatch_wait_events_total',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01'], ['datname', '!=', 'server_process']],
    epoch_ms(now() - interval 1 hour), epoch_ms(now()), 300000, 300000
  )
  group by all
),
scrapes as (
  select coalesce(labels['instance'], '') as inst, t, sum(value) as n_scrapes
  from prom_sum_over_time(
    'up',
    [['job', '=', 'pgwatch-prometheus']],
    epoch_ms(now() - interval 1 hour), epoch_ms(now()), 300000, 300000
  )
  group by all
  having sum(value) > 0
)
select
  to_timestamp(w.t / 1000) as bucket_utc,
  w.wait_event_type,
  w.wait_event,
  round(sum(w.total_samples / s.n_scrapes), 2) as aas
from w
join scrapes s using (inst, t)
group by all
order by aas desc, bucket_utc desc
limit 30
```

To drill into which `query_id` drove a specific wait event (for example `LWLock` / `LockManager`), filter on `wait_event_type` and group by `labels['query_id']` (note the underscore), then `LEFT JOIN query_text_names` using `try_cast(labels['query_id'] as bigint)`.

### Lock contention and blockers

Find the worst lock-wait episodes in the last hour with blocked and blocker query IDs, tables, and durations:

```sql
select
  max(ts) as last_seen_utc,
  labels['datname'] as datname,
  labels['blocked_table'] as blocked_table,
  labels['blocked_mode'] as blocked_mode,
  labels['blocked_query_id'] as blocked_query_id,
  labels['blocker_user'] as blocker_user,
  labels['blocker_query_id'] as blocker_query_id,
  round(max(value) / 1000.0, 2) as max_blocked_s,
  count(*) as samples_seen
from pgai_samples(
  'pgwatch_lock_waits_blocked_ms',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now() - interval 1 hour),
  epoch_ms(now())
)
where not stale and not isnan(value)
group by all
order by max_blocked_s desc
limit 20
```

Check whether autovacuum workers were blocked by DDL or long transactions:

```sql
select
  max(ts) as last_seen_utc,
  labels['datname'] as datname,
  labels['worker_pid'] as worker_pid,
  labels['blocker_pid'] as blocker_pid,
  labels['blocker_queryid'] as blocker_queryid,
  round(max(value), 1) as max_wait_s
from pgai_samples(
  'pgwatch_pg_autovacuum_blocked_wait_seconds',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now() - interval 6 hour),
  epoch_ms(now())
)
where not stale and not isnan(value)
group by all
order by max_wait_s desc
limit 20
```

### Buffer cache hit ratio, shared I/O, and temp files

Check per-database buffer cache hit ratio, physical reads/sec, and temp-file spill rate over the last hour:

```sql
with m as (
  select 'hit' as k, labels['datname'] as datname, value
  from prom_increase_pure(
    'pgwatch_db_stats_blks_hit',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
  union all
  select 'read', labels['datname'], value
  from prom_increase_pure(
    'pgwatch_db_stats_blks_read',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
  union all
  select 'temp_b', labels['datname'], value
  from prom_increase_pure(
    'pgwatch_db_stats_temp_bytes',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
  union all
  select 'temp_f', labels['datname'], value
  from prom_increase_pure(
    'pgwatch_db_stats_temp_files',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(now()), epoch_ms(now()), 60000, 3600000
  )
)
select
  datname,
  round(case when sum(value) filter (where k in ('hit', 'read')) > 0
             then 100.0 * sum(value) filter (where k = 'hit')
                  / sum(value) filter (where k in ('hit', 'read'))
             else 100.0 end, 3) as cache_hit_pct,
  round(coalesce(sum(value) filter (where k = 'read'), 0) / 3600.0, 1) as blks_read_per_s,
  round(coalesce(sum(value) filter (where k = 'temp_b'), 0) / 1048576.0, 1) as temp_mib_1h,
  round(coalesce(sum(value) filter (where k = 'temp_f'), 0), 0) as temp_files_1h
from m
where not isnan(value)
group by datname
order by temp_mib_1h desc, blks_read_per_s desc
```

### Autovacuum pressure, bloat, xmin horizon, and wraparound risk

Check the most overdue tables in the autovacuum queue right now:

```sql
select
  labels['datname'] as datname,
  labels['schemaname'] || '.' || labels['relname'] as rel,
  round(value, 2) as overdue_factor
from prom_last(
  'pgwatch_pg_autovacuum_queue_autovacuum_overdue_factor',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 300000
)
where value >= 1.0
order by overdue_factor desc
limit 20
```

Check table bloat from the latest 2-hour snapshot (notice `prom_last` automatically widens its lookback to 2 h 15 m for `pg_table_bloat`):

```sql
with pct as (
  select labels['datname'] as datname, labels['schemaname'] as s, labels['tblname'] as t, value as bloat_pct
  from prom_last('pgwatch_pg_table_bloat_bloat_pct', [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
                 epoch_ms(now()), epoch_ms(now()), 300000)
),
sz as (
  select labels['datname'] as datname, labels['schemaname'] as s, labels['tblname'] as t, value as bloat_bytes
  from prom_last('pgwatch_pg_table_bloat_bloat_size', [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
                 epoch_ms(now()), epoch_ms(now()), 300000)
)
select
  pct.datname,
  pct.s || '.' || pct.t as table_name,
  round(pct.bloat_pct, 1) as bloat_pct,
  round(sz.bloat_bytes / 1048576.0, 1) as bloat_mib
from pct
join sz using (datname, s, t)
where pct.t <> '$other$'
order by sz.bloat_bytes desc
limit 20
```

Inspect active xmin horizon blockers and database/table XID wraparound age:

```sql
select
  labels['component'] as component,
  labels['horizon_type'] as horizon_type,
  coalesce(nullif(labels['slot_name'], ''), nullif(labels['standby_name'], ''), labels['blocker_appname']) as holder,
  labels['blocker_user'] as usr,
  labels['queryid'] as queryid,
  cast(value as bigint) as age_tx
from prom_last(
  'pgwatch_xmin_horizon_blockers_age_tx',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 300000
)
order by age_tx desc
limit 20
```

```sql
select
  labels['datname'] as datname,
  labels['schema_name'] || '.' || labels['table_name'] as table_name,
  cast(value as bigint) as xid_age
from prom_last(
  'pgwatch_pg_table_wraparound_xid_age',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 300000
)
order by xid_age desc
limit 20
```

### WAL generation, checkpoints, and replication lag

Measure WAL generation rate (MiB/s) in 5-minute steps over the last hour:

```sql
select
  to_timestamp(t / 1000) as ts_utc,
  round(value / 1048576.0, 2) as wal_mib_per_s
from prom_rate(
  'pgwatch_wal_xlog_location_b',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now() - interval 1 hour), epoch_ms(now()), 300000, 300000
)
order by t
```

Compare timed vs. requested checkpoints over the last 6 hours (PostgreSQL 17+ `checkpointer`; on PG 14–16 use `pgwatch_bgwriter_checkpoints_timed` and `pgwatch_bgwriter_checkpoints_req`):

```sql
select 'timed' as kind, round(sum(value), 0) as count_6h
from prom_increase_pure(
  'pgwatch_checkpointer_num_timed',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 60000, 6 * 3600000
)
union all
select 'requested', round(sum(value), 0)
from prom_increase_pure(
  'pgwatch_checkpointer_num_requested',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 60000, 6 * 3600000
)
```

Check streaming replication lag and inactive or lagging replication slots:

```sql
select
  labels['application_name'] as replica,
  labels['client_info'] as client,
  round(value / 1048576.0, 2) as replay_lag_mib
from prom_last(
  'pgwatch_replication_replay_lag_b',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 300000
)
order by replay_lag_mib desc
```

```sql
select
  labels['slot_name'] as slot_name,
  labels['plugin'] as plugin,
  round(value / 1048576.0, 2) as retained_wal_mib
from prom_last(
  'pgwatch_replication_slots_restart_lsn_lag_b',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 300000
)
order by retained_wal_mib desc
```

### Connections, TPS, rollbacks, and host CPU/RAM/disk

Check current connection counts by state and database:

```sql
select
  labels['datname'] as datname,
  labels['state'] as state,
  cast(sum(value) as bigint) as connections
from prom_last(
  'pgwatch_pg_stat_activity_count',
  [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
  epoch_ms(now()), epoch_ms(now()), 300000
)
group by all
having sum(value) > 0
order by connections desc
```

Compute commit TPS, rollback TPS, and deadlock count over the last hour:

```sql
with x as (
  select 'commit_tps' as m, labels['datname'] as datname, value
  from prom_rate('pgwatch_db_stats_xact_commit', [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
                 epoch_ms(now()), epoch_ms(now()), 60000, 3600000)
  union all
  select 'rollback_tps', labels['datname'], value
  from prom_rate('pgwatch_db_stats_xact_rollback', [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
                 epoch_ms(now()), epoch_ms(now()), 60000, 3600000)
  union all
  select 'deadlocks_1h', labels['datname'], value
  from prom_increase_pure('pgwatch_db_stats_deadlocks', [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
                          epoch_ms(now()), epoch_ms(now()), 60000, 3600000)
)
select
  datname,
  round(coalesce(max(value) filter (where m = 'commit_tps'), 0), 2) as commit_tps,
  round(coalesce(max(value) filter (where m = 'rollback_tps'), 0), 2) as rollback_tps,
  round(coalesce(max(value) filter (where m = 'deadlocks_1h'), 0), 0) as deadlocks_1h
from x
group by datname
order by commit_tps desc
```

Inspect host CPU, available RAM, free disk, and disk IOPS (RDS, Aurora, Supabase, or ClickHouse Managed Postgres):

```sql
with h as (
  select 'cpu_pct' as k, labels['cluster'] as c, labels['node_name'] as n, value
  from prom_avg_over_time('host_cpu_utilization_percent', [['cluster', '=', 'prod']], epoch_ms(now()), epoch_ms(now()), 60000, 3600000)
  union all
  select 'mem_avail_gib', labels['cluster'], labels['node_name'], value / 1073741824.0
  from prom_last('host_memory_available_bytes', [['cluster', '=', 'prod']], epoch_ms(now()), epoch_ms(now()), 300000)
  union all
  select 'disk_free_gib', labels['cluster'], labels['node_name'], value / 1073741824.0
  from prom_last('host_disk_free_bytes', [['cluster', '=', 'prod']], epoch_ms(now()), epoch_ms(now()), 300000)
  union all
  select 'read_iops', labels['cluster'], labels['node_name'], value
  from prom_avg_over_time('host_disk_read_iops', [['cluster', '=', 'prod']], epoch_ms(now()), epoch_ms(now()), 60000, 3600000)
  union all
  select 'write_iops', labels['cluster'], labels['node_name'], value
  from prom_avg_over_time('host_disk_write_iops', [['cluster', '=', 'prod']], epoch_ms(now()), epoch_ms(now()), 60000, 3600000)
)
select
  c as cluster,
  n as node_name,
  round(max(value) filter (where k = 'cpu_pct'), 1) as avg_cpu_pct_1h,
  round(max(value) filter (where k = 'mem_avail_gib'), 2) as mem_avail_gib,
  round(max(value) filter (where k = 'disk_free_gib'), 2) as disk_free_gib,
  round(max(value) filter (where k = 'read_iops'), 1) as avg_read_iops_1h,
  round(max(value) filter (where k = 'write_iops'), 1) as avg_write_iops_1h
from h
group by all
```

### Comparing two time windows (before/after migration or two Forge runs)

Compare per-query total execution time between a baseline window (`w_before`) and a post-change window (`w_after`) in one SQL statement. To compare two separate DBLab Forge runs instead of two windows on the same cluster, change the `cluster` matcher in `w_before` and `w_after`:

```sql
with w_before as (
  select labels['datname'] as datname, labels['queryid'] as queryid, value as exec_ms
  from prom_increase_pure(
    'pgwatch_pg_stat_statements_exec_time_total',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(timestamptz '2026-11-18 10:00:00+00'),
    epoch_ms(timestamptz '2026-11-18 10:00:00+00'),
    60000, 3600000
  )
),
w_after as (
  select labels['datname'] as datname, labels['queryid'] as queryid, value as exec_ms
  from prom_increase_pure(
    'pgwatch_pg_stat_statements_exec_time_total',
    [['cluster', '=', 'prod'], ['node_name', '=', 'node-01']],
    epoch_ms(timestamptz '2026-11-19 10:00:00+00'),
    epoch_ms(timestamptz '2026-11-19 10:00:00+00'),
    60000, 3600000
  )
)
select
  coalesce(a.datname, b.datname) as datname,
  coalesce(a.queryid, b.queryid) as queryid,
  round(coalesce(b.exec_ms, 0), 1) as before_ms,
  round(coalesce(a.exec_ms, 0), 1) as after_ms,
  round(coalesce(a.exec_ms, 0) - coalesce(b.exec_ms, 0), 1) as delta_ms,
  left(regexp_replace(coalesce(qt.query, ''), '\s+', ' ', 'g'), 100) as query_snippet
from w_after a
full outer join w_before b using (datname, queryid)
left join query_text_names qt
  on qt.queryid = try_cast(coalesce(a.queryid, b.queryid) as bigint)
 and qt.dbname = coalesce(a.datname, b.datname)
order by delta_ms desc
limit 20
```

### Schema changes (`objects`) and `auto_explain` plans

Find schema objects created, altered, or dropped in the past 7 days. A recent `valid_from` marks a new or changed definition. A recent `valid_to` marks a version that a later change replaced, or an object that was dropped. A drop has no later row for the same object.

```sql
select
  valid_from,
  valid_to,
  cluster,
  node_name,
  dbname,
  kind,
  schema || '.' || name as object_name,
  left(definition, 120) as def_preview
from objects
where valid_from >= now() - interval 7 day
   or valid_to >= now() - interval 7 day
order by coalesce(valid_to, valid_from) desc
limit 30
```

Find the slowest normalized `auto_explain` plans (populated when `jsonlog` tailing or `load-logs` is active):

```sql
select
  p.queryid,
  p.plan_hash,
  p.count as executions,
  round(p.total_ms, 1) as total_ms,
  round(p.total_ms / p.count, 2) as avg_ms,
  p.first_seen,
  p.last_seen
from plans p
order by p.total_ms desc
limit 20
```

## Query guardrails, limits, and pitfalls for agents

Respect these rules when generating SQL automatically to avoid timeouts, OOM errors, or subtle math bugs.

### Read-only enforcement and table function allowlist

`pgai-mon` parses every query with DuckDB's `json_serialize_sql` before execution, locks DuckDB configuration (`enable_external_access = false`, `lock_configuration = true`), and enforces strict rules:

- **Single `SELECT` only:** DDL, DML, `SET`, `COPY`, `ATTACH`, `INSTALL`, `LOAD`, `SHOW`, and multi-statement queries (even two `SELECT` statements separated by `;`) are refused with `HTTP 403` (`not_read_only`).
- **Allowed table functions:** `prom_*`, `pgai_*`, `parquet_*`, `read_parquet` (restricted to files inside the store directory), `range`, `generate_series`, `unnest`, `json_each`, `json_tree`, `duckdb_columns`, `duckdb_functions`, `duckdb_memory`, `duckdb_settings`, `duckdb_tables`, `duckdb_types`, and `duckdb_views`. Any other table function (`read_csv`, `read_text`, `glob`, `query`, etc.) is refused with `HTTP 403` (`forbidden`).
- **Store-wide visibility:** `pgai-mon` has no per-user or per-database ACL; a valid token can read every row in the store, including `query_texts` and `logs`.

### Resource limits and admission control

Default limits in `pgai-mon` (`http.*` config keys):

- **Query timeout (`http.timeout_ms`):** 15 s (`HTTP 408`, `timeout`).
- **Result row cap (`http.max_rows`):** 100,000 rows (`truncated: true` on JSON rows).
- **Result byte cap:** 16 MiB (`http.max_bytes`) in `--local` mode; **1,000,000 bytes** JSONB text bound in remote Console mode (`instance-jobs`). Always add `LIMIT` and select only needed columns.
- **DuckDB memory limit (`http.memory_limit`):** about 91.6 MiB (96,000,000 bytes; `HTTP 413`, `out_of_memory`).
- **SQL worker process RSS cap (`http.reader_rss_cap_mb`):** 192 MiB. A watchdog kills the isolated `pgai-mon sql-worker` child process above 192 MiB without harming metric collection, then retries in-flight queries once.
- **Disk spill cap (`http.max_temp_directory_size`):** about 1.86 GiB (2,000,000,000 bytes).
- **Admission queue:** up to 64 waiting queries (`http.queue_max`), max 30 s wait (`http.queue_wait_ms`), else `HTTP 429` (`busy`).

### Common pitfalls and how to avoid them

- **Always use `pgai_samples` or `prom_*` instead of `samples` / `metrics`:** the `samples` and `metrics` views work only on local disk stores and fail on `s3://` stores. `pgai_samples` and `prom_*` work everywhere, prune files by `(series_id, ts)`, and use 1 h / 1 d rollups on closed days.
- **Keep time bounds as scalar expressions, never subqueries:** `pgai_samples` and `prom_*` evaluate `start_ms` and `end_ms` during DuckDB table-function binding, so `epoch_ms(now() - interval 1 hour)` works while a scalar subquery fails to bind. Run a discovery query first when you need dynamic historical bounds.
- **Filter `WHERE NOT stale` on raw samples:** when a series ends (closed session, dropped index, removed target), `pgai-mon` appends a staleness marker with `stale = true` and `value = NaN`. Because `max()` and `avg()` propagate `NaN` and `NaN > 0` is `true` in DuckDB, always add `where not stale and not isnan(value)`.
- **Use `prom_rate` / `prom_increase_pure` for counters across resets:** raw `max(value) - min(value)` produces wrong or negative deltas when Postgres restarts or `pg_stat_statements_reset()` runs, whereas the `prom_*` counter functions detect drops and apply reset corrections automatically (and `pgai_mon_stats_reset_epoch_s` confirms whether a reset occurred inside your window).
- **Watch `queryid` types and label names:** `query_texts.queryid` is `BIGINT` while series labels are always `VARCHAR`, so cast with `try_cast(labels['queryid'] as bigint)` or `queryid::varchar` and check the exact label key per metric (`queryid` in `pg_stat_statements` and `xmin_horizon_blockers`, `query_id` in `wait_events`, `blocked_query_id` / `blocker_query_id` in `lock_waits`, `blocker_queryid` in `pg_autovacuum_blocked`).
- **Keep `dbname`, `datname`, and `real_dbname` straight:** in series labels, `dbname` is the monitored source name, `datname` is the PostgreSQL database name, and `real_dbname` is the database label used on `redundant_indexes`. In `query_texts` and `objects`, `dbname` is the PostgreSQL database name and `source` is the monitored source name.
- **Split heavy multi-day queries to stay under the DuckDB memory limit:** joining multiple wide `prom_*` calls over 7+ days at fine step sizes can exceed DuckDB's memory limit of about 91.6 MiB. Prefer `prom_agg` or `prom_topk` (which stream in Rust), widen `step_ms`, or split into per-metric queries.
- **Expect UTC timestamps and flush lag:** DuckDB's session timezone is locked to `UTC`, and newly scraped metrics appear in queries after the next flush (`store.flush_interval_s`, default **60 s**), or after the next upload commit on S3 readers (`store.s3.upload_interval_s`, default **300 s**).
