# pg_plan_guard [![CI](https://github.com/Manuelreyesbravo/pg_plan_guard/actions/workflows/ci.yml/badge.svg)](https://github.com/Manuelreyesbravo/pg_plan_guard/actions/workflows/ci.yml) **Detect when a query plan drifts away from the plan you approved.** PostgreSQL 19 added [`pg_plan_advice`](https://www.postgresql.org/docs/19/pgplanadvice.html) (generate advice for a plan, then force it) and [`pg_stash_advice`](https://www.postgresql.org/docs/19/pgstashadvice.html) (store advice per `query_id` and apply it automatically). Both are deliberate, manual acts: you decide a plan is good, and you pin it. Neither of them **watches**. There is no way to ask: > Is the plan for this query still the plan I approved? `pg_plan_guard` answers that question. ## Why it matters A plan regression does not fail. The query still answers -- it just stops using the index and starts scanning. Nothing errors, and with the default settings nothing is logged. The case this was built for: a vector similarity search backed by an approximate index (DiskANN, HNSW). If the planner stops choosing that index, the query still answers, in order: a sequential scan returns the exact nearest neighbours where the index returned approximate ones. Correct, and slow. You find out from a latency graph, if at all. ## Usage ```sql CREATE EXTENSION pg_plan_guard; -- Approve today's plan for a critical query. Here docs has a pgvector -- HNSW index, docs_emb_idx, on its embedding column. SELECT plan_guard.capture( 'semantic_search', 'SELECT id FROM docs ORDER BY embedding <=> ''[0.1, 0.7, 0.2]'' LIMIT 10', 'must use the HNSW index'); -- Later, on a schedule: has anything drifted? SELECT * FROM plan_guard.verify(); -- name | state | expected_advice | actual_advice -- -----------------+---------+------------------------------------------------------+-------------------------------- -- semantic_search | drifted | INDEX_SCAN(docs public.docs_emb_idx) NO_GATHER(docs) | SEQ_SCAN(docs) NO_GATHER(docs) ``` Run it from `pg_cron`, or from whatever already runs your checks: ```sql SELECT cron.schedule('plan-guard', '37 */6 * * *', $$SELECT * FROM plan_guard.verify()$$); ``` And point your monitoring at one view: ```sql SELECT * FROM plan_guard.status WHERE state <> 'ok'; ``` The monitoring role needs `USAGE` on the schema `plan_guard` and `SELECT` on the view. ## API | Function | Purpose | |---|---| | `plan_guard.capture(name, query_sql [, description])` | Approve the current plan as the baseline | | `plan_guard.verify([name])` | Re-plan every baseline and report drift | | `plan_guard.sync_stash(stash_name)` | Push approved advice into a `pg_stash_advice` stash | | `plan_guard.advice_for(query_sql)` | Plan advice for an arbitrary query | | `plan_guard.plan_text_for(query_sql)` | The plan of an arbitrary query, as `EXPLAIN` text | | `plan_guard.query_id_for(query_sql)` | `query_id` of a query, for stash operations | | `plan_guard.watch(name, query_sql [, note])` | Approve the plan as a living assertion (pg_living_assertions) | | Relation | Contents | |---|---| | `plan_guard.baselines` | The approved plan for each query | | `plan_guard.drift_log` | Append-only history of every detected drift | | `plan_guard.status` | Current state, worst first — the view a monitor polls | ## Design decisions These are the choices that make it usable rather than annoying, and the reasons behind them: **Advice is compared, not `EXPLAIN` output.** `EXPLAIN` text changes with row estimates and costs even when the plan shape is identical. Comparing it would make baselines drift constantly and train everyone to ignore the alerts. Advice describes the *shape* — which scan on which relation, which join order, which method — so it changes only when the planner's decision changes. **Capture is explicit, never automatic.** A baseline that captured itself would happily bless whatever plan happened to be in effect, including the regression you are hunting. **Drift is logged once per transition, not once per check.** A baseline that has been drifting for a week should not produce a row per cron run. **A broken baseline does not abort the run.** If a query no longer plans (table dropped, column renamed) it is reported as `error` and the remaining baselines are still checked. A monitor that dies on the first problem stops working exactly when something is wrong. **A baseline is re-planned against the tables its author meant.** The query is stored as text, so the names in it are resolved by a `search_path`. `capture()` records the capturing session's, and `verify()` and `sync_stash()` re-plan under it with `pg_temp` moved to the end. So a baseline captured with `SET search_path = app` plans the same from `pg_cron`, and a temporary table in the verifying session cannot answer for a watched one. The recorded path is applied only inside the sealed `EXPLAIN` described below, so the session that called `verify()` keeps its own. Baselines captured before 1.1.4 have no recorded path and are planned under the caller's, also with `pg_temp` last; capture them again to pin it. **The table is the source of truth, not shared memory.** `pg_stash_advice` keeps its stashes in shared memory and, by default, in a file in the data directory. `pg_dump` does not carry that file, so after a restore into a new cluster the pinning is gone, and queries keep working, just slowly. That is the failure this extension exists to catch, so the stash is treated as a cache that `sync_stash()` rebuilds from `plan_guard.baselines`. ## Requirements - PostgreSQL 19 or later, with `pg_plan_advice` available. - `sync_stash()` additionally requires `pg_stash_advice`, which needs **two** things to actually apply advice — and if either is missing, nothing is applied and nothing warns you: 1. `shared_preload_libraries` includes `pg_plan_advice` and `pg_stash_advice` 2. `pg_stash_advice.stash_name` is set (the default is empty) Diagnose with: ```sql SELECT name, setting FROM pg_settings WHERE name LIKE 'pg_stash%'; ``` Baselines are captured with `EXPLAIN (PLAN_ADVICE)`, which does not execute the query, but planning can run code: the planner folds an `IMMUTABLE` function called with constant arguments. So every `EXPLAIN` of stored text runs sealed, the way pg_living_assertions runs a check: in a subtransaction switched to read-only and always rolled back. What planning does is refused if it writes and undone if it does not. Some things are not writes to the database: `COPY ... TO PROGRAM`, `pg_switch_wal()`, a session advisory lock. For those, a baseline is planned as the role that wrote it. `baselines.captured_by` records that role: a trigger sets it to whoever writes or rewrites the query, and accepts another name only from a role that may `SET ROLE` to it. The `EXPLAIN` runs inside a temporary `SECURITY DEFINER` function owned by the author, created and rolled back inside the seal. There PostgreSQL refuses to change `role` or `session_authorization`, so a stored query can do no more than its author could do directly. Anything beyond that is that baseline's `error`, not an aborted `verify()`. Session advisory locks taken inside the seal are released. The role that runs `verify()` must be able to hand that function to each author: a superuser can; any other role needs to be able to `SET ROLE` to the author, and the author needs `TEMP` on the database. A baseline captured before 1.1.7 has no recorded author and is refused until it is captured again. `make check-audit` checks each of these against a control. A role that is not a superuser can run `capture()` and `verify()` once `pg_plan_advice` is in `shared_preload_libraries` (`LOAD` needs superuser). It needs `USAGE` on the schema `plan_guard`, `EXECUTE` on its functions (the entry points call internal helpers, so grant them all), `SELECT`, `INSERT` and `UPDATE` on `plan_guard.baselines`, and `INSERT` on `plan_guard.drift_log`. `sync_stash()` sets `compute_query_id`, which only a superuser can. ## Tested on PostgreSQL 19 only, and that is not conservatism: the extension reads plan advice through `pg_plan_advice`, which arrived in 19. Since 1.1.11 `CREATE EXTENSION` refuses anything older: ERROR: pg_plan_guard requires PostgreSQL 19 or later, this is 18.6 1.2.0 was tested by the CI on 2026-12-06 ([run 47606675262](https://github.com/Manuelreyesbravo/pg_plan_guard/actions/runs/47606675262)) on PostgreSQL 19.0: `make installcheck`, `ci/upgrade_check.sh` from every release on PGXN, and `make check-suites` (`check-pgtemp`, `check-audit`); all green. The CI runs the same on every push and every Monday. On 18 `CREATE EXTENSION` stops with the error above. ## Install It needs **PostgreSQL 19 with its contrib module `pg_plan_advice`** (a library, no `CREATE EXTENSION`; it ships with contrib, e.g. the `-contrib` package). Optional: `pg_stash_advice` (contrib too) for `sync_stash()`, and pg_living_assertions 0.5.6 or later (0.5.10 recommended) for `watch()`; every other function works without them. From [PGXN](https://pgxn.org/dist/pg_plan_guard/): ```sh pgxn install pg_plan_guard psql -c 'CREATE EXTENSION pg_plan_guard' ``` From source: ```sh make install PG_CONFIG=/path/to/pg_config psql -c 'CREATE EXTENSION pg_plan_guard' ``` Run the tests against a live server (as a superuser, or with `pg_plan_advice` in `shared_preload_libraries`): ```sh make installcheck PG_CONFIG=/path/to/pg_config ``` And the `search_path` and audit suites, in a throwaway cluster built from the same binaries and stopped afterwards (port 5493; `PGPORT` overrides): ```sh make check-suites PG_CONFIG=/path/to/pg_config ``` ## Limitations - A query with parameters (`$1`) is captured as the application sends it and planned with `EXPLAIN (GENERIC_PLAN)`: the plan a prepared statement uses once PostgreSQL settles on a generic one. With the default `plan_cache_mode`, the first five executions of a prepared statement get custom plans, made for the values given, and so does every later one while the generic plan looks costlier; `verify()` does not watch those. Capture with `$1` when the application sends `$1`: a literal gives the statement another query_id, and advice that `sync_stash()` stashes under it does not reach the application. - Advice names each partition it scans, so attaching a partition to a partitioned table is reported as drift. - Drift detection is only as good as the baseline: capturing a bad plan pins a bad plan. Review what `capture()` returns. - `capture()` and `verify()` run `EXPLAIN` on stored SQL, so execute rights are not granted to `PUBLIC`. - `verify()` plans with the settings of the session that runs it, not those of the application's role: a planner setting on that role (`enable_indexscan`, say) is not seen. - A query_id ignores constants, so two baselines of one statement with different literals share a stash slot, and the last `sync_stash()` writes wins. - A temporary table still answers for a name found nowhere on the recorded path: `pg_temp` goes last, not away. - A session advisory lock that the session running `verify()` already holds, and that a stored query takes again while it is planned, is held once more afterwards: `pg_locks` shows one row for a lock however often it was taken. ## License Apache License 2.0 -- see [LICENSE](LICENSE). Copyright 2026 Manuel Reyes Bravo. The name is not licensed with the code: see [TRADEMARK.md](TRADEMARK.md).