Repository navigation
Description
Bug
With B4_PG_SCHEMA set to a schema that does not exist yet, the first run of the vercel bundle always fails:
[b4:vercel] postgres store initialisation failed against postgres://127.0.0.1:5439/hashbrown — error: duplicate key value violates unique constraint "pg_namespace_nspname_index" (23505)
GET /readyz -> 503 {"checks":{"requestStores":{"error":"error: duplicate key value violates unique constraint \"pg_namespace_nspname_index\" (23505)","status":"failed"}},"status":"not_ready"}
The three generated stores (checkpointer, threads store, permissions store) each issue CREATE SCHEMA IF NOT EXISTS <schema> concurrently. IF NOT EXISTS is not concurrency-safe in Postgres: two concurrent CREATE SCHEMA statements race on pg_namespace and the loser raises 23505 rather than a benign no-op. (Same hazard as concurrent CREATE TABLE IF NOT EXISTS / CREATE INDEX IF NOT EXISTS.)
It is not self-healing within a run: after the failure the schema exists but is partly populated — I observed b4_checkpointer_migrations, b4_checkpoints, b4_writes created and the threads/permissions tables missing. A second run then succeeds and /readyz returns 200.
Repro
Built vercel bundle from main (0429cec2…acfc786f), plain local Postgres, no WebSocket proxy:
docker exec -i pg psql "$ADMIN_URL" -c "drop schema if exists preview_dogfood cascade;"
B4_PG_SCHEMA=preview_dogfood DATABASE_URL=postgres://…@127.0.0.1:5439/hashbrown \
node -e "const m=await import('./.vercel/output/functions/index.func/index.mjs'); console.log(await (await m.default.fetch(new Request('http://local/readyz'))).text())"
# -> 503, 23505
# repeat without dropping the schema -> 200 readyDeterministic: 3/3 cold starts failed, every warm start succeeded.
Impact
The first request to any freshly provisioned environment fails — exactly the preview/production separation #682 was added for. On a serverless target that is the first invocation after a deploy to a new environment.
Proposal
Serialise or make the schema bootstrap idempotent under concurrency, e.g.:
- create the schema once in shared wiring before the stores start, rather than once per store; and/or
- take the advisory lock that already guards the migrations around the
CREATE SCHEMA; and/or - catch
23505(and42P06) fromCREATE SCHEMA IF NOT EXISTSand treat it as success.
Also worth ensuring a partly-created schema from a failed bootstrap is retried cleanly on the next request.
Found while dog-fooding the fixes from #682 against the hashbrown invoicing example (https://invoicing.hashbrown.dev, source examples/invoicing), using a local build of main.
Activity
fix(postgres-storage): serialize shared schema creation on its own lock
fix(memory-pgvector): serialize schema init under an advisory lock (#727