AI
Why my AI agent measures before it recommends
An agent that tries each database fix on a sandbox and keeps only what proved faster.
Ask a language model why a Postgres query is slow and the answer sounds equally sure whether the fix helps, does nothing, or changes the rows the query returns. The README of Postgres Query Doctor shows a plausible wrong fix: swapping NOT EXISTS for NOT IN in one query returns 0 rows instead of 280, because its subquery returns NULLs, and NOT IN is never true against a list that contains a NULL.
So the agent follows one rule: it can only recommend a fix it has run and timed. The prompt asks for that too, but the code is what enforces it.
One tool, and a budget
The agent is built with Pydantic AI. Before the model is called, plain code in context.py collects the query's EXPLAIN ANALYZE plan plus the row count, column statistics and existing indexes of every table the query reads, and puts it all in the model's first message.
It then has one working tool, try_fix, which takes a list of CREATE INDEX statements and an optional rewritten query. Each call, up to a budget of 5 by default (MAX_TRIALS), becomes a numbered Trial. The tool hands the fix to the measuring lab, stores the lab's Comparison on the trial, and returns a text summary: the verdict, the median before and after, whether the rows matched, each index's size, and Proven: yes or Proven: no.
The answer has no field for a measurement
The final answer is a typed Diagnosis with three fields: problem (a string), recommended_trial (int | None) and explanation (a string). No field holds a timing or a speedup. The model points at a trial by id, and report.py formats the "Measured" line from that trial's stored Comparison.
A pointer can still point at the wrong thing, so an output validator in doctor.py checks it:
@agent.output_validator
def recommend_only_proven_trials(ctx: RunContext[Session], diagnosis: Diagnosis) -> Diagnosis:
if diagnosis.recommended_trial is None:
return diagnosis
trial = next((t for t in ctx.deps.trials if t.id == diagnosis.recommended_trial), None)
if trial is None:
raise ModelRetry(f"There is no trial {diagnosis.recommended_trial}.")
if not trial.proven:
raise ModelRetry(
f"You can't recommend trial {trial.id}; the lab didn't prove it. {summarize(trial)} "
"Recommend a trial the lab proved faster with identical rows, or none."
)
return diagnosisModelRetry sends that message back to the model, which has to answer again. A trial id that doesn't exist is refused, and so is any trial the lab didn't prove: one that failed, came out slower or returned different rows. The only answers that pass are a proven trial or None, which the report prints as "none proven". A test covers this path with a scripted model that recommends a wrong rewrite and gets refused.
What "proven" means
trial.proven reads a property on the lab's result in lab.py, so the model has no say in it:
@dataclass(frozen=True)
class Comparison:
# ... fields, and the speedup and results properties
@property
def verdict(self) -> Verdict:
if not all(index.usable for index in self.indexes):
return Verdict.INCONCLUSIVE
# Only call a winner when every run of one side beat every run of the other.
if max(self.after.samples_ms) < min(self.before.samples_ms):
saving_ms = self.before.median_ms - self.after.median_ms
return Verdict.FASTER if saving_ms >= MIN_SAVING_MS else Verdict.TOO_SMALL
if min(self.after.samples_ms) > max(self.before.samples_ms):
return Verdict.SLOWER
return Verdict.NO_CLEAR_DIFFERENCE
@property
def proven(self) -> bool:
"""Faster, and the rows didn't change: the only kind of fix worth recommending."""
return self.verdict == Verdict.FASTER and self.results == Results.IDENTICAL"Faster" means the slowest run with the fix beat the fastest run without it, and the median saving is at least 1 ms (MIN_SAVING_MS). Overlapping runs give "no clear difference". "Identical" means the same rows in the same order.
What the sandbox does
The core of lab.try_fix:
before = measure(conn, query, runs, timeout_s)
with _rolled_back(conn, timeout_s):
built = tuple(_build_index(conn, statement) for statement in indexes)
conn.execute("SET TRANSACTION READ ONLY") # From here on the query can't change anything.
after = _timed_runs(conn, query if rewrite is None else rewrite, runs)
return Comparison(before, after, built, rewritten=rewrite is not None)It times the original query, then opens a transaction that is always rolled back (conn.transaction(force_rollback=True)), builds the trial indexes for real, switches the transaction to read-only, and times the query again, or the rewrite if there is one. Each timed run is EXPLAIN (ANALYZE, TIMING OFF, SERIALIZE, FORMAT JSON), and the sample is planning time plus execution time. On each side the first run only warms the cache and isn't counted; the next five, by default, are. Then the query runs once more to fetch its rows for the comparison.
Index fixes must match a CREATE INDEX pattern. Every query and index statement the lab is given goes out as a prepared statement, which Postgres refuses if it contains more than one statement, so SELECT 1; COMMIT; DROP TABLE posts can't commit its way out of the rollback. Statements stop after 60 seconds by default, and results over 100,000 rows are refused instead of compared.
The lab doesn't create the sandbox. It runs against whatever database DATABASE_URL points to, and the rollback leaves that database as it was. It must still be a copy, never production: a trial index blocks writes to its table while the trial runs.
What the benchmark compares
bench/cases.toml holds 16 queries on a Stack Exchange data dump loaded with primary keys and no other indexes: 13 slow ones that an index or rewrite can fix and 3 controls that are already fine. Four systems answer each one: a fix I wrote by hand, Dexter (an index advisor that works from the planner's estimates), the same model with the same context asked once with no lab, and the doctor. Every suggested fix is judged by a fresh lab.try_fix run in bench.py. "Fixed" means faster by the lab's rule, at least 2x, with identical rows. For index-only fixes, the same query with other values must be proven too.
From the README's scorecard, two runs with gemini-3.5-flash-lite:
- Dexter fixed 7 of 13 and left all 3 controls alone.
- The single model answer fixed 12 of 13, then 13 of 13, and left 2 of 3 controls alone both times.
- The doctor fixed 13 of 13 and left all 3 controls alone, both times.
One model answer is a strong baseline. It fixed 25 of 26 and never returned wrong rows. Its misses were a partial index that made one query only 1.8x faster and, in both runs, an unneeded index on a 1,239-row tags table. Closing that gap cost about 2.9 model calls, 5.6K tokens and 7.7 seconds per query, against 1 call, 1.3K tokens and 1.6 seconds.
Where it stops
- The benchmark is small: one model, 16 queries, mostly about missing indexes, two runs, one laptop.
- A measurement holds for the data it ran on, with a warm cache. If the sandbox differs from production in size or distribution, the plan and the timings can differ too.
- The lab times one query. It reports each index's size and build time, but not what the index costs on writes or does to other queries.
- Rows are compared only for the literal values in the query. The benchmark re-tests index fixes with other values, but not rewrites, which are written for the original values.
- Timing noise got through once. On a 0.65 ms query, a trial passed "every run beat every run", and the benchmark's own re-measurement found the same index slower (0.8x). The 1 ms minimum was added after that.
- The
problemandexplanationfields are still model prose. Their descriptions ask for no numbers or timings, but nothing checks the text.
The model chooses what to try and which trial to point at. Which fixes count as proven, and every measurement in the report, come from the lab.