## How it works Today an LLM agent reaches PostgreSQL through an MCP server that holds a connection, hands the model a list of tools, and runs whatever the model asks. The model decides; the server obeys. Every guarantee lives in that server's code, outside the database, and the database never learns what was checked. `pg_agent_gate` moves the decision into PostgreSQL. An agent does not run SQL. It has seven verbs, and in a session that belongs to an agent **nothing else reaches the data** -- not `DELETE`, not `DO`, not `COPY`, not `PREPARE`. (`SHOW`, transaction control, `DISCARD`, `DEALLOCATE`, `RESET` and the settings an agent may `SET` still run: see [What it does not cover](limits.md#what-it-does-not-cover).) The database verifies every proposal against itself, runs it with the agent's own privileges, and keeps the record. ``` discover -> propose -> dry_run -> commit -> propose_and_commit (both in one call) acts, whoami ``` ## Verification The checks lean on PostgreSQL itself: its parser, analyzer, rewriter and planner. What the gate adds is the order, the verdict, its own DDL classification, and two hand-reviewed lists: the parameters an agent may set, and the volatile built-ins that only read. 1. **parses** -- PostgreSQL's own raw parser accepts it. 2. **single_statement** -- exactly one, so what was verified is what runs. `select 1; delete ...` dies here. 3. **kind_allowed** -- read, write or DDL, against what the agent may do. Transaction control is refused: the gate owns the transaction. 4. **no_writing_cte** -- PostgreSQL's analyzer and rewriter build the query tree (every table, column, type, operator and function must exist and fit, or the proposal fails `resolves` right here), and a CTE that changes data is refused. `max_rows` counts the rows of the statement, and a write hidden in a CTE under a `SELECT count(*)` is counted as one row: before 0.2.1 it deleted every row under a limit of 5. Propose each write as its own statement. 5. **keeps_its_context** -- `set_config()` anywhere in that tree (the `WHERE`, the `FROM`, a subquery, a CTE, an expanded view, schema-qualified or not) is refused. Inside the statement it moves, while the statement runs, the parameter a row-level policy reads; before 0.2.1, `... where set_config('app.tenant_id', '2', true) is not null` read another tenant's rows. Since 0.4.2 the same holds below the tree: in an agent's session, while its SQL runs, `set_config()` does not start wherever it is reached -- the SQL a function receives as text, the body of another function, a `CHECK`, a default, a domain's `CHECK`, an aggregate's transition function. **Code is judged where it starts (0.4.3):** the executor asks the gate before it runs any function, built-ins included, and the function manager asks for every user function C code calls through a cache -- a range type's support function, an RI check, a trigger (`tests/audit5.sh`, `tests/audit6.sh`). **In the whole session, and the context is the gate's (second review of 0.4.3):** a verb's parameter bound as an agent's domain ran the domain's `CHECK` before any verb started and switched the tenant for the rest of the session. The floor now stands in every agent session, not only while its SQL runs; a verb's argument must be of a built-in type; and the session's context -- `role`, `session_authorization`, `row_security`, `session_replication_role`, `search_path` and every placeholder parameter such as `app.tenant_id` -- is remembered when the session starts and checked when every verb starts, after the agent's SQL ran, and before a row is returned or a change kept. If it moved, the verb refuses (`tests/audit7.sh`). 6. **no_amplification**, **no_hidden_sql**, **no_opaque_function** -- on the same tree: a write whose cascade, trigger or rule the gate cannot vouch for; a call to a function that runs SQL it receives as text (`query_to_xml()` and the rest of the `*_to_xml()` family, `ts_stat()`, `ts_rewrite()`, tablefunc's `crosstab()` and `connectby()`, dblink), whose query no check sees (0.4.2); and a call to a user function that is volatile or `SECURITY DEFINER`, that the agent can alter -- its `STABLE` or `IMMUTABLE` is then its own claim -- or whose `SET` clause moves the context a policy reads: a placeholder -- a custom parameter no loaded module defines, such as `app.tenant_id` --, `agent_gate.*`, `role`, `session_authorization`, `row_security` or `session_replication_role` (`work_mem`, `jit`, `plan_cache_mode`, `search_path`, and a module's own parameter -- `pg_trgm.*`, `hnsw.*`, `plpgsql.*`: defined by a loaded module, or named after an installed extension -- only say how the body runs, and pass). An aggregate is judged by the functions it runs, its transition function first: `pg_proc` marks every aggregate `IMMUTABLE` (0.4.3). A function that runs SQL from a text, one the agent can alter and one with such a `SET` clause are also stopped wherever they are reached in an agent's session, as a `SECURITY DEFINER` one is since 0.2.7. Whose function it is, is asked of the agent's own role, not of the role PostgreSQL runs an RI check as (0.4.3), and by membership: a function the agent handed to a role it belongs to without `INHERIT` is still its own. **read_changes_nothing** / **changes_only_rows** -- a built-in that changes state outside the rows the gate counts is refused: in a read, any; in a write or a DDL, those that are not how a write numbers its rows, locks them until commit or tells a listener (`nextval()`, transaction advisory locks, `pg_notify()`). Which built-ins change state is PostgreSQL's own marking, not a list of what is forbidden: a `VOLATILE` built-in changes state unless it is on a reviewed list of those that only read, wait or draw a random number (`random()`, `clock_timestamp()`, `pg_sleep()`, `currval()`, `lo_get()`, sizes and statistics, ...), so a signal or administration function nobody named is refused by default -- `pg_terminate_backend()` passed as a read before (second review of 0.4.3). A `LANGUAGE internal` function is the built-in it names, and is judged as that one. The same rule stops them wherever they are reached: a domain's `CHECK` that called `nextval()` made a read advance a sequence. For an `allow_ddl` agent, the query of a `CREATE TABLE AS`, `SELECT INTO` or `CREATE MATERIALIZED VIEW` gets checks 4 to 6 too (0.4.2): up to 0.4.1 it was only run, and over a CTE that deletes it deleted rows no limit counted. 7. **resolves** -- only now `EXPLAIN` plans it, for the estimate. **The order is a guarantee (0.2.6):** planning runs functions -- it folds an `IMMUTABLE` call with constant arguments and estimates a `STABLE` one by calling it -- so up to 0.2.5, where `EXPLAIN` came first, a `SECURITY DEFINER` function ran as its owner before `no_opaque_function` refused it, and what it raised (a secret) came back in the check's detail. Now every refusal is decided on the analyzed tree, which runs nothing (`tests/plan_time.sh` counts the calls); and since 0.2.7 a `SECURITY DEFINER` function reached through a body the tree does not show -- a wrapper the planner folds -- is stopped before it runs. `estimated_rows` is given only when the agent could read in full every relation the analyzed tree AND the plan touch: `SELECT` on the whole table and no row-level security hiding rows from it. The statistics are gathered beneath the policy and beneath a view, and the estimate told another tenant's frequent value (34 rows) from an absent one (1) -- through the table (0.2.6), through a SQL function the planner inlines after the tree was built, and through a view that isolates tenants without row-level security (both 0.2.8). It errs on the withholding side: `SELECT` on a partitioned parent without its partitions, or on some columns only, withholds the estimate too, although nothing would leak. The agent's SQL never runs in a parallel worker (0.2.8): the backend runs the whole plan, where the gate's hooks see it. DDL (for agents allowed it) is verified instead by running it in a subtransaction that is rolled back -- as execution, under the same floor, and judged as a read: proposing changes nothing, so a DDL that would advance a sequence while it is only being checked is refused (0.4.3). A sequence the DDL itself creates may number its new column (`serial`, like an identity column: the rollback takes the sequence with it), one that existed before may not; a DBA's event-trigger code is judged as the DDL it runs for. **An agent's DDL changes only what the agent owns** (second review of 0.4.3): every object PostgreSQL drops for it -- by name, through a `CASCADE`, or as the owner of the schema -- must be one the agent could drop by name; a type it alters must not be what another role's table, domain or function is made of, and a function it redefines must not be what another role's index, constraint, generated column, view or function is built on (third review); what it creates -- an index or a trigger PostgreSQL makes on every partition of its table -- and a table it detaches must be its own; and it creates no temporary object, because PostgreSQL searches the temporary schema first for relation and type names and an agent's temporary table answered for a name a DBA's policy helper did not qualify. Checks 4 and 5 were found by an LLM proposing through the gate against a two-tenant database, with a superuser comparing the database before and after every case -- not by the suites in `tests/`, which were green with both holes open. Both now have cases there (`adversarial.sh`, `rls_isolation.sh`) that are red against 0.2.0. `commit` verifies **again**: a verification is a statement about the database at a moment. A proposal older than `agent_gate.proposal_ttl_seconds` (900) is refused outright.