On October 15, a review of a cleanup job came back with one finding: "every pass picks the same oldest 500 expired drafts." If those 500 stayed blocked, the job would never try the newer ones. Claude Code had written the job in the hour before, in a subagent of my session. That night, the review of another subagent's sweep found the same mistake, with batches of 100. A third sweep had it, with batches of 50.
I run backend engineering at GoodBarber, an app platform. Since early November, the agent of our AI Extension Builder can create a database for an app, one per app, managed by us. Claude Code wrote the service behind those databases from mid-October on, along with background jobs for the builder's agent. In my session, two other models, OpenAI's Codex and Google's Gemini, reviewed the diffs, and each finding was checked in the code before anything was fixed. Quotes from French are my translations.
Four traps came out of code written in the week of October 15. All four traps passed the tests written with them. None reached a user: the GRANT race ran in production for about six hours, with only the deploy's checks and one test app calling it; the COPY ran there for one night, with nothing calling it; and the other two were never pushed.
1. The LIMIT came before the filter
The first sweep drops expired drafts in the data service. A draft is a short-lived copy of an app's tables, in a schema of its own. The cleanup runs every hour in a container I had asked for that afternoon in one line: "if you need cron, set up a container." The first version took the 500 longest-expired drafts, then tried to drop each one. A draft whose lock was held, or whose drop kept failing, stayed expired, and the next pass took the same 500 again.
The second walks a queue of deferred tasks in the studio, the Django service behind the AI Extension Builder's back-office screen. It took the 100 oldest due entries, then skipped those it wasn't allowed to run yet, such as the entries of an app the feature wasn't switched on for. Nothing moved a skipped entry, so 100 of them would have held every batch.
The third looks for answers that no worker picked up: when the builder's agent asks a question and the user answers, a job has to resume the run. It took the 50 oldest pending pages whose run was waiting or running, then kept the ones it could act on:
rows = (
Page.objects.filter(status=PENDING, run__state__in=(WAITING, RUNNING))
.order_by("updated_at")[:50] # LIMIT 50
)
lost = [row for row in rows if recoverable(row)]
The finding blamed pages waiting for their user's answer. The subagent that fixed it checked first: those have another status and never matched, but pages still on their first run, whether their job was alive or dead, did. Fifty of them would have hidden a lost answer for as long as they stayed.
The fix moved the cases into the query, before the limit.
The queue's fix put the app condition into its query. The draft cleanup couldn't: whether a lock is free, or a drop will succeed, is only known by trying. Its fix walks the expired drafts in the same order, 100 at a time, starting after the last one tried, dropped or left:
SELECT app, draft, expires_at FROM drafts
WHERE expires_at <= now() AND (expires_at, draft) > (%s, %s)
ORDER BY expires_at, draft
LIMIT 100;
A pass stops at 500 drops, 2,000 attempts or 10 minutes, and the next one starts again from the oldest, with no stored state. Enough blocked drafts at the head of that order can still fill a pass. None of the three sweeps was pushed before its fix, and Claude deployed the draft cleanup that evening, on my go-ahead.
2. md5(t::text) hashed a column
Each version of a section is kept, and for a section on the GoodBarber database, the data can come back too if its copy is less than 15 days old. To save disk, a new snapshot reuses the last copy of a table that hasn't changed: same columns, same fingerprint, which combines the row count with the md5 of each row.
The contract for snapshots, written by a planning subagent on the afternoon of October 15, computed it with md5(t::text), the table aliased t. The subagent that implemented it kept the expression, under a comment saying it covered all columns. In Postgres, a table alias used as a value stands for the current row, so t::text is the whole row as text, unless the table has a column named t. The documentation warns that "simple names are matched to column names before table names."
The builder's agent designs an app's tables from what the user asks for, and the service accepts column names of lowercase letters, digits and underscores, up to 63 characters. t is one. On such a table, the fingerprint hashed that column alone. An update to any other column left it unchanged, and the next snapshot reused the stale copy without saying so.
SELECT md5(t::text) FROM items t; -- the row, unless items has a column t
SELECT md5(ROW(t.*)::text) FROM items t; -- always the row
A row's text has no column names, and an integer prints like a bigint, so a copy is reused only if the list of column names and types matches too. The fingerprint also runs with TimeZone, DateStyle, IntervalStyle, extra_float_digits and bytea_output fixed, since they change how a row prints. (money, which depends on lc_monetary, isn't an accepted type.)
The third and last review round found it. The fix, with a test on a table that has a column t, NULL in one case and not NULL in the other, was pushed.
3. A GRANT per tenant, on objects every tenant shares
Each app's data lives in a schema of its own, with its own roles. Those roles also need privileges on objects every app shares: a shared schema, the trigger functions in it, and CONNECT on the database. Until October 15, each creation granted them in its own transaction. Review asked what happens when two creations run at once, and the subagent measured it on its local stack:
-- session 1
BEGIN;
GRANT USAGE ON SCHEMA shared TO tenant_a_owner;
-- session 2
BEGIN;
GRANT USAGE ON SCHEMA shared TO tenant_b_owner;
-- waits for session 1
COMMIT;
-- ERROR: tuple concurrently updated
A GRANT rewrites the object's row in the system catalog. The second session waited, then failed with SQLSTATE XX000 when the first committed, and went through when it rolled back. In a test of 30 calls sent three at a time, 10 answered 500.
The fix that day took one advisory lock for the whole service before those GRANTs. Nothing collided anymore. Creations waited for each other instead, and a draft held the lock while it was being filled.
Two days later, we replaced those GRANTs with a common role that holds the privileges, and made every new role inherit from it. A measurement on Postgres 18.6, in a throwaway container, shaped the design: while one transaction runs GRANT common TO x, a second GRANT common TO y waits until the first commits. A single common role would have queued creations as the lock did, so several gate roles sit in between, each a member of the common role, with no privilege of its own:
-- once
CREATE ROLE tenant_common NOLOGIN NOINHERIT;
GRANT USAGE ON SCHEMA shared TO tenant_common;
CREATE ROLE tenant_common_3 NOLOGIN NOINHERIT; -- one of the gates
GRANT tenant_common TO tenant_common_3 WITH INHERIT TRUE, SET FALSE;
-- per creation, in its transaction: the first free gate, from a starting gate set by app_id
SELECT pg_try_advisory_xact_lock(:gate_3_key);
GRANT tenant_common_3 TO tenant_a_owner WITH INHERIT TRUE, SET FALSE;
Privileges pass through both memberships because each has the INHERIT option, and SET FALSE keeps the new role from doing SET ROLE to the gate or the common role. Two creations take two gates and don't wait for each other. When all the gates are taken, one more at the same moment falls back on a blocking pg_advisory_xact_lock on its starting gate. The gates reached production on October 20, and since November 4, every app that creates its database goes through one.
4. COPY holds its connection
The last one belongs to psycopg. On October 16, we wrote an API call in the data service that reads a table with COPY ... TO STDOUT, compresses what it reads, and stores the result in 4 MiB chunks with an INSERT on the same connection, so that the chunks commit or roll back with the rest:
with conn.cursor() as cur, cur.copy("COPY (SELECT * FROM items) TO STDOUT (FORMAT csv)") as copy:
for data in copy:
chunks.write(compress(data)) # each full 4 MiB chunk: conn.execute("INSERT ...")
In psycopg 3.3.3, Cursor.copy() holds the connection's lock for the whole with block, and execute() takes the same lock, a threading.Lock, which isn't reentrant. The first time a chunk filled up during the COPY, the INSERT waited for a lock its own thread held, until gunicorn killed the worker at our 60-second timeout. Nothing was saved.
Our tests used small tables, whose output never filled a chunk during the COPY, so the only INSERT ran after it. Replayed on a local stack with 30,000 rows of md5 text and 64 KiB chunks, the call was still blocked 15 seconds after it started, its session idle in transaction.
The fix reads on a second connection and keeps writing on the first. The first transaction exports its snapshot, and the reader imports it before its first query, as pg_dump -j does, so both see the same committed data:
snapshot = conn.execute("SELECT pg_export_snapshot()").fetchone()[0]
with connect() as reader, reader.transaction():
reader.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
reader.execute(sql.SQL("SET TRANSACTION SNAPSHOT {}").format(sql.Literal(snapshot)))
with reader.cursor() as cur, cur.copy(statement) as copy:
... # each full chunk still goes through conn.execute(), in conn's transaction
A review a few days later found the freeze, and the fix was committed the same day. The frozen code had gone to production, with nothing calling it, and the fix followed the next day.
What the tests didn't have
None of the four was caught by the tests written with it. They had fewer blocked rows than one batch, no column named t, one creation at a time, and outputs smaller than one chunk. Review found all of them, the GRANTs through a measurement it asked for. Each fix came with the test that was missing, and each of those tests fails on the code it replaced.
Top comments (2)
The "what the tests didn't have" point hit close to home. I spent part of this week debugging a Postgres client bug in node-postgres where a mid-query FATAL left
client._queryableset to true until TCP close. Every single-connection unit test passed, and then on a real pool with immediaterelease(), the nextconnect()got a dead session 5 out of 5 times. The part I missed on my first patch was localizedlc_messages, where Postgres translates theSfield (likeFATALEin Italian) and only keepsFATALin the non-localizedVfield.Trap 3 with the gate roles is a neat workaround for catalog tuple collisions on
GRANT. Roughly how many gate roles did you end up putting in front oftenant_commonbefore falling back to blockingpg_advisory_xact_lock, and have you seen theSET TRANSACTION SNAPSHOTreader in trap 4 hold back vacuum or hit recovery conflicts on larger tables?The localized
Sfield is a nasty one: every test run in English passes.Gates: a small fixed number, set in code. A gate is only held for the transaction of one creation, so the count just has to cover how many databases get created at the very same moment.
The reader can't hold back more than the writer already does. It imports the writer's snapshot, so its xmin is the one the writer's open transaction pins anyway, and it closes first. Both connections go to the primary, so no recovery conflicts there. Every connection of the service also has a 45-second
transaction_timeout, under gunicorn's 60, which caps how long that horizon lasts. I haven't measured it on a really big table, though.