AI Dev Pipeline · 6 min read
Add plpgsql_check to CI Without Drowning in Legacy Errors
Background: why database functions need their own static check
AllyOS is the business system I built with Claude Code and a team of AI agents. It has one hard rule: the frontend never writes to tables directly. Every write goes through a database function written in PL/pgSQL. That keeps permissions and auditing in one place, but it means a lot of functions. Today (2026-11-30) I counted 1,626 PL/pgSQL function definition files in the repo's schema snapshot.
The catch is how PL/pgSQL works. In plain words: when you create a function, PostgreSQL checks the syntax, not whether the tables and columns it mentions still exist. The queries inside are planned the first time the function actually runs, and only then do you learn that a column is gone.
Think of it as a printer that proofreads a recipe for typos but never checks whether the ingredients are still in the fridge. You find out the day someone cooks it.
An AI-written codebase makes this worse. An agent writes a migration that drops a column, carefully updates the callers it can see, and misses the one function three schemas away that still names the old column. Tests only cover the paths a test actually calls.
Why not just turn the check on and fail the build?
plpgsql_check is an open-source PostgreSQL extension that acts like a compiler for PL/pgSQL. Without running a function, it tells you which ones reference missing columns, assign mismatched types, or declare unused variables.
But switching it on as a hard gate on day one, in a project with over a thousand functions, almost always fails. Nobody knows the existing count. If the first run reports 300 errors, every pull request goes red at once, and the usual ending is that someone disables the check.
So I did it in two steps, and that is the one idea this post is about: measure first, then enforce.
Step one: report only, and count what is already there
The first version did one thing. After CI builds the test database, check every PL/pgSQL function in the application schemas, write counts by category to the CI summary, write each error to the log, and pass regardless of findings.
Three design points mattered:
- Leave no trace. The whole check runs in one transaction: create the extension, check, read results, roll back. The extension never persists anywhere, and no migration has to install it.
- One failure doesn't stop the run. Each function is checked inside its own exception block. If the checker itself crashes on one, it is recorded as
check-failedand the loop moves on. - Trigger functions need a table. They can only be checked against a table that fires them; a trigger function no table uses is counted as skipped.
A simplified version (generalized for this post; the real one filters by schema and handles trigger functions separately):
begin;
create extension if not exists plpgsql_check;
create temp table findings(fn text, level text, msg text);
do $$ declare f regprocedure; begin
for f in select p.oid from pg_proc p join pg_language l on l.oid = p.prolang
where l.lanname = 'plpgsql' and p.prorettype <> 'trigger'::regtype loop
begin
insert into findings select f::text, level, message
from plpgsql_check_function_tb(f, fatal_errors => false);
exception when others then insert into findings values (f::text, 'check-failed', sqlerrm);
end;
end loop; end $$;
select level, count(*) from findings group by 1;
rollback;
The first CI run (2026-11-29) checked 1,632 functions and found 25 errors concentrated in 7 functions, plus 100 warnings (78 "target type is different than source type", 22 unused variables).
Twenty-five, not three hundred. That number shaped step two.
Step two: freeze the existing errors in a shrink-only baseline
With the count in hand, I reviewed all 7 functions:
- 5 were false positives or environment differences: a temp table the function body creates itself (invisible to the checker until the function runs), or an extension that was only ever installed by hand in production.
- 2 were real bugs: two early data-import functions, one writing to a column that no longer exists, one writing to a table that no longer exists. Each ran once before go-live and was never called again, so nobody noticed. Calling either would fail immediately.
The rule became: errors block, warnings are reported only, and those 7 functions go into a baseline file, each group with its reason. The file looks like this (generalized):
# signature<TAB>allowed error rows; every group states its reason
# false positive: temp table created inside the body
app.rebuild_report(integer) 7
# real bug, to be deleted: references a column that no longer exists
app.legacy_import(jsonb) 2
The key is that the baseline is a two-way ratchet:
def compare(found: dict, baseline: dict) -> list[str]:
problems = []
for fn in sorted(set(found) | set(baseline)):
have, allowed = found.get(fn, 0), baseline.get(fn, 0)
if have > allowed:
problems.append(f"{fn}: {have} errors, baseline allows {allowed}")
elif have < allowed:
problems.append(f"{fn}: baseline says {allowed}, found {have}; lower or delete the line")
return problems
- A new function with an error, or an old one with more errors: red.
- An old function with fewer errors: also red, so the same change has to lower or delete its baseline line.
Why fail on improvement? If the baseline were only a ceiling, every fix would leave unused headroom, and the next regression of the same kind could slip quietly into that slot. With a two-way ratchet, the baseline only ever gets shorter, until it reaches zero.
And the 2 real bugs? Both functions were dropped on 2026-11-29, the same day the baseline landed. The check paid for itself with two real fixes on day one.
Exit codes: separate "found a problem" from "didn't run"
Every guard in AllyOS follows one principle: if a precondition is missing, fail; never pass silently. This check has three outcomes:
- 0: errors match the baseline exactly (warnings never count).
- 1: an error outside the baseline, or a baseline line that no longer matches reality.
- 2: no verdict. The extension is unavailable, psql failed, the output lacks its completion line, or the baseline can't be read.
The third is the one teams forget. If "didn't run" counts as a pass, then one day the database image changes, the extension disappears, and the check stays green forever while checking nothing. So the output must end with a completion line ("checked N, skipped M"), and without it the verdict is "no verdict".
Measured numbers
| Metric | Value | How we measured |
|---|---|---|
| Functions checked on the first run | 1,632 | first CI run, 2026-11-29 |
| Errors | 25, in 7 functions | same run |
| Warnings (report only) | 100 (78 type mismatch, 22 unused) | same run |
| Real bugs among the 7 | 2, deleted the same day | commit history reviewed 2026-11-30 |
| PL/pgSQL function definition files today | 1,626 | counted in the schema snapshot, 2026-11-30 |
| Test cases for the checker itself | 17 | counted in its test file, 2026-11-30 |
| Baseline files in the repo (this one included, all tracked by the rot report) | 22 | counted in the rules folder and report script, 2026-11-30 |
| Step timeout | 4 minutes | CI configuration |
A checklist you can copy
- Start report-only: the first version of any new static check passes regardless, and counts the backlog by category.
- Leave no trace: create the extension and run the check inside a rolled-back transaction; no migration for tooling.
- Wrap each checked object in its own exception handler so one crash doesn't end the run.
- Review the backlog line by line: false positive, environment difference, or real bug. Schedule the real bugs.
- Freeze the backlog in a baseline file with a reason per group; any error outside it fails the build.
- Make the baseline a two-way ratchet: more errors is red, fewer errors is red too, so it only shrinks.
- Give "didn't run" its own exit code, require a completion line, and never treat it as a pass.
- Keep warnings report-only until errors reach zero, then consider tightening.
PostgreSQL's docs explain why PL/pgSQL queries are planned on first execution in PL/pgSQL Under the Hood, and the built-in extra compile-time checks in Tips for Developing in PL/pgSQL.
FAQ
My project has only a few database functions. Do I need this?
If you have few functions and tests call every one of them, the payoff is small. It earns its keep when you have many functions, change the schema often, and can't test every branch, especially when AI agents write your migrations, because a rename is exactly where an agent misses a distant reference.
Won't the baseline become a permanent exemption list?
That is exactly why it is a two-way ratchet. It can only get shorter: every fix deletes a line, and a newly added line stands out in review. My repo has 22 baseline files like this (this one included), and a code-rot report tracks how each one grows or shrinks.
Does this pattern only apply to plpgsql_check?
No. It works any time you add a new check to an existing codebase: type checking, dead-code detection, dependency-direction rules. Measure, freeze a baseline, ratchet it both ways. My earlier Python subprocess encoding check follows the same playbook. If you want this kind of AI development guardrail set up for your team, see services.