How to Validate Text-to-SQL Agents in PostgreSQL
Run each allowlisted text-to-SQL candidate and its reviewed reference on the same PostgreSQL staging snapshot with the same `as_of` value. Add a row at the exclusive cutoff so a missing end filter causes a mismatch, and block release on a mismatch, timeout, or execution failure.

A text-to-SQL agent can return the right rows in CI and still count orders that fall outside the requested window. If your fixture has no orders at the cutoff, a missing filter can pass unnoticed. Run the candidate and a reviewed reference against the same PostgreSQL staging snapshot, then add the row that makes them disagree.
Decide what should block release

CI maps one candidate to a reviewed SQL statement, binds the same as_of value for both queries, and compares their results. Repeatable read keeps concurrent commits from changing what the second query sees. The parameter fixes the business cutoff; it does not freeze the database clock.
| Check | Use it when | What to do with a failure |
|---|---|---|
| Allowlist | Every candidate, before database access | Reject unknown SQL; never execute it to see what happens. |
| Deterministic comparison | The prompt has a defined metric, schema, and ordering contract | Block release on a mismatch, timeout, or execution failure. |
| Advisory LLM review | The prompt leaves a business term or follow-up ambiguous | Ask a human to resolve intent; never override a failed check. |
A window function alone doesn't justify a judge. If you can specify the expected result and seed the cases that distinguish correct from incorrect SQL, deterministic checks are enough. For advisory review, send the prompt and metric definitions, not credentials or database rows.
1. Seed an isolated staging database
Create a dedicated sql_eval database on an isolated staging instance with no production data or credentials. Connect as its owner, run the following in psql, and set a password when prompted. Use the reader only for validation and the owner only for fixture changes.
CREATE ROLE eval_reader LOGIN;
\password eval_reader
CREATE SCHEMA fixture;
CREATE TABLE fixture.orders (
customer text NOT NULL,
created_at timestamptz NOT NULL,
amount numeric(12,2)
);
INSERT INTO fixture.orders VALUES
('acme', '2026-01-04 00:00+00', 12.50),
('acme', '2026-01-04 00:00+00', 12.50),
('beta', '2026-01-05 00:00+00', NULL);
GRANT CONNECT ON DATABASE sql_eval TO eval_reader;
GRANT USAGE ON SCHEMA fixture TO eval_reader;
GRANT SELECT ON fixture.orders TO eval_reader;2. Run one allowlisted candidate per check
Install the dependencies in a Python virtual environment. Replace the DSN placeholders and URL-encode the password. Test in staging first.
python -m pip install pandas sqlalchemy 'psycopg[binary]' scipy
export EVAL_DSN='postgresql+psycopg://eval_reader:ENCODED_PASSWORD@STAGING_HOST/sql_eval'Save this as validate.py. The task is to return customer and amount for every order in the seven days before as_of, with no ordering requirement. The comparator pairs rows one-to-one, so duplicates count and NULL never equals zero. Its matching matrix grows with both result sets; keep fixtures small.
import os
import sys
from datetime import datetime
from decimal import Decimal
import pandas as pd
from scipy.optimize import linear_sum_assignment
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
BASE = 'SELECT customer, amount FROM fixture.orders WHERE '
END = 'CAST(:as_of AS timestamptz)'
START = f"{END} - INTERVAL '168 hours'"
GOLD = BASE + f'created_at >= {START} AND created_at < {END}'
ALLOWED = {
'bounded': BASE + f'NOT (created_at < {START} OR created_at >= {END})',
'missing-end': BASE + f'created_at >= {START}', # negative control
}
SCHEMA = ('customer', 'amount') # str, nullable finite Decimal
ATOL, RTOL = Decimal('0.000001'), Decimal('0.00000001')
def valid(row):
customer, amount = row
return type(customer) is str and (
amount is None or (type(amount) is Decimal and amount.is_finite())
)
def same(left, right):
a, b = left[1], right[1]
return left[0] == right[0] and (
a is b if a is None or b is None else
abs(a - b) <= max(ATOL, RTOL * max(abs(a), abs(b)))
)
def equal(left, right, ordered=False):
if any(tuple(df.columns) != SCHEMA for df in (left, right)):
return False
a, b = [list(df.itertuples(index=False, name=None)) for df in (left, right)]
if len(a) != len(b) or not all(map(valid, a + b)):
return False
if ordered or not a:
return all(same(x, y) for x, y in zip(a, b))
costs = [[int(not same(x, y)) for y in b] for x in a]
rows, cols = linear_sum_assignment(costs)
return all(costs[i][j] == 0 for i, j in zip(rows, cols))
candidate = ALLOWED.get(sys.argv[1]) if len(sys.argv) == 2 else None
if candidate is None:
sys.exit('FAIL: candidate not allowlisted')
try:
engine = create_engine(os.environ['EVAL_DSN'], hide_parameters=True,
connect_args={'connect_timeout': 3})
with engine.begin() as conn:
conn.execute(text('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY'))
conn.execute(text("SET LOCAL statement_timeout = '2s'"))
params = {'as_of': datetime.fromisoformat('2026-01-08T00:00:00+00:00')}
actual, expected = [pd.read_sql_query(text(sql), conn, params=params,
coerce_float=False)
for sql in (candidate, GOLD)]
except (SQLAlchemyError, KeyError):
sys.exit('FAIL: staging configuration or query execution')
if not equal(actual, expected):
sys.exit('FAIL: result mismatch')
print('PASS: results match')For free-form agent output, map only exact matches to reviewed statements; reject everything else. Never send raw output to the database driver. For ranked results, give both statements an explicit ORDER BY with a deterministic tie-breaker and use ordered=True.
3. Make the wrong query fail

python validate.py missing-end
# PASS: results matchIn the owner session, commit a row exactly at the exclusive cutoff. The next run sees a new fixture snapshot, but both queries still use the original as_of.
INSERT INTO fixture.orders VALUES ('acme', '2026-01-08 00:00+00', 99.00);python validate.py missing-end
# FAIL: result mismatch
python validate.py bounded
# PASS: results matchIllustrative scenario: spend less on judge calls

Suppose a SaaS team runs 1,000 cases per release and flags 100 for intent review. At an assumed 1,200 input and 300 output tokens per review, judging everything uses 1.2 million input and 300,000 output tokens. Routing only flagged cases uses 120,000 input and 30,000 output tokens: 90% less judge token spend at unchanged rates. The deterministic database work stays the same.
Roll back and verify
For a row mismatch, inspect cutoffs, join keys, and duplicate counts. For execution failures, check staging credentials, schema changes, and timeout signals in restricted diagnostics; keep raw database errors out of user output. If a regression ships, restore the last passing agent configuration and allowlist if they're compatible with the current schema. Otherwise, disable the affected query path until it passes staging again.
- Confirm the runner uses only the staging reader and rejects unknown candidates.
- Check that the positive case passes and the cutoff case fails the negative control.
- Rerun the suite against the schema you plan to deploy.
Next action: Add one high-risk prompt and a fixture row that separates its reference query from a plausible wrong answer.
Related resources
Frequently Asked Questions
Why compare results instead of SQL strings?
Different statements can answer the same question. Use the allowlist to control what runs and compare results to check correctness.
Does a shared snapshot make one fixture enough?
No. A shared snapshot keeps the comparison consistent, but you still need fixture rows that make plausible mistakes change the result.
How do you catch a missing end filter?
Add a row exactly at the exclusive cutoff and rerun with the same `as_of` value. The query with the missing end filter includes the row, but the reference excludes it.
When should you use advisory LLM review?
Use it when a business term or follow-up is ambiguous. Ask a human to resolve the intent, and never use advisory review to override a failed check.
Get the Weekly SMB AI & SaaS Brief
Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.