Skip to content

fix(db): disable prepared statements on Supabase pooler to prevent cross-connection statement-cache errors#270

Closed
notjbg wants to merge 1 commit into
garrytan:masterfrom
notjbg:fix-pooler-prepared-statements
Closed

fix(db): disable prepared statements on Supabase pooler to prevent cross-connection statement-cache errors#270
notjbg wants to merge 1 commit into
garrytan:masterfrom
notjbg:fix-pooler-prepared-statements

Conversation

@notjbg

@notjbg notjbg commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Problem

Users on the Supabase transaction pooler (port :6543 or pooler.supabase.com) hit sporadic prepared statement "abc123" does not exist errors under sustained gbrain load (sync, extract, embed, autopilot).

Root cause: pgbouncer in transaction mode recycles underlying Postgres connections between client queries. postgres.js caches prepared statements by name and reuses them — but the next query may land on a different underlying connection where that prepared-statement name is unknown. Postgres raises the error and the query fails.

Repro (bare postgres.js against Supabase pooler):

sql = postgres("postgresql://...@aws-1-us-west-1.pooler.supabase.com:6543/postgres", { max: 10 });
// Run enough parameterized queries to exhaust the pool and start reusing connections
// → "prepared statement 's1' does not exist"

Fix

Detect pooler URLs by regex on the connection string and pass prepare: false to postgres.js. Direct connections (port 5432, non-pooler hosts) keep prepare: true and retain plan-caching perf.

const isPooler = /pooler\.supabase\.com|:6543/i.test(url);
sql = postgres(url, {
  // ...
  prepare: !isPooler,
});

Applied at the two postgres(url, ...) call sites:

Empirical

Carried as a local patch for ~6 months against Supabase pooler on a ~31k-page brain. Without it, sustained load surfaces "prepared statement" errors within minutes. With it, zero occurrences across sync/extract/embed/autopilot over that span.

Impact

  • Pooler users: no more cross-connection statement-cache errors. Slight per-query overhead from skipping the prepared-statement optimization (negligible in practice).
  • Direct-Postgres users: zero change — isPooler evaluates false, prepare stays true.
  • Schema: no change.
  • Tests: none added. The fix is a config flag driven by URL inspection; the behavior is entirely in postgres.js.

Notes

  • Alternative: prepare: false unconditionally. Rejected because direct-Postgres users would pay the unnecessary perf cost.
  • Alternative: env-var opt-in (e.g. GBRAIN_POOLER_MODE=1). Rejected because pooler URLs are self-identifying — no reason to require manual configuration.
  • The regex matches both the Supabase-specific pooler hostname AND the generic :6543 transaction-mode port, covering self-hosted pgbouncer too.

If the regex approach feels too magical, happy to rework as an explicit {pooler: true} config option instead.

…repared statement does not exist" under load

Transaction-mode poolers (Supabase pgbouncer on :6543, or
pooler.supabase.com) invalidate server-side prepared statements between
connection releases. postgres.js caches prepared statements by default,
so a later query on a different underlying connection that reuses the
same prepared-statement name trips `prepared statement "xyz" does not
exist` and fails.

Detect pooler URLs via a regex on the connection string and pass
`prepare: false` in that case. Direct connections (port 5432, non-pooler
hosts) keep prepare=true and retain plan-caching.

Applied in two sites:
- src/core/db.ts connect() — the module-global singleton used by the CLI
- src/core/postgres-engine.ts connect() with config.poolSize — the
  instance pool used by worker isolation

Empirical: carried as a local patch for ~6 months against Supabase pooler
on a 31k-page brain. Without it, sustained gbrain sync/extract/embed load
surfaces "prepared statement ... does not exist" within minutes. With it,
zero occurrences.

Zero-impact for users on direct Postgres (isPooler evaluates false, prepare
stays true). Zero schema change. No new tests — the fix is a one-line
config flag driven by URL inspection.
garrytan added a commit that referenced this pull request Apr 22, 2026
Without this, \`gbrain jobs work\` against a Supabase pooler URL hits
"prepared statement does not exist" under load even after the module
singleton was fixed in db.ts. Community PR #270 (@notjbg) caught this
second path that #284 had missed. Reuses the shared helper, no regex
duplication.

Co-Authored-By: Jonah Berg <jonah.berg.g@gmail.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
garrytan added a commit that referenced this pull request Apr 22, 2026
closes #284, #286, #270) (#301)

* fix(migrate): v0_13_0 shells out to `gbrain` shim, not `process.execPath`

On bun-installed trees, process.execPath is the bun runtime itself.
`bun extract links ...` got reinterpreted as `bun run extract` and
crashed the upgrade mid-Phase B. The canonical shim on PATH already
wraps the right runtime+entrypoint; trust it.

Regression-guarded by test/migrations-v0_13_0.test.ts which greps
the source for `process.execPath` and `bun` invocations. This was
Bug 1 of tonight's v0.13 → v0.14 upgrade-night postmortem.

* fix(autopilot): resolveGbrainCliPath prefers shim, never returns .ts

argv[1] check used to short-circuit on /cli.ts, so bun-source installs
got a .ts path back. spawn() then failed EACCES because TypeScript
source isn't executable, and autopilot silently lost its worker.

Reordered probes: which gbrain (shim) first, then compiled execPath,
then argv[1] only if it ends in /gbrain. Deleted the .ts branch
entirely — no valid case exists.

Rewrote the existing test that enshrined the buggy .ts return.
Critical regression guard: resolver MUST NEVER return a .ts path
across any combination of argv[1] + execPath + shim availability.
This was Bug 4 of tonight's v0.13 → v0.14 upgrade-night postmortem.

* chore: bump version and changelog (v0.15.3)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(db): resolvePrepare() helper for PgBouncer transaction-mode pools

Adds port-6543 auto-detect with a 4-level precedence chain:
GBRAIN_PREPARE env var → ?prepare= URL param → port auto-detect → default.
Wires into the module-singleton connect() so the main CLI path no longer
hits "prepared statement does not exist" against Supabase transaction
pooler. Returns boolean | undefined; undefined means omit the option and
let postgres.js default (true) stand.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(postgres-engine): honor resolvePrepare in worker-instance pool

Without this, \`gbrain jobs work\` against a Supabase pooler URL hits
"prepared statement does not exist" under load even after the module
singleton was fixed in db.ts. Community PR #270 (@notjbg) caught this
second path that #284 had missed. Reuses the shared helper, no regex
duplication.

Co-Authored-By: Jonah Berg <jonah.berg.g@gmail.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(doctor): pgbouncer_prepare check

URL-only check (no DB roundtrip) that reads the configured URL via
loadConfig() and flags the footgun: port 6543 with prepared statements
still enabled. Warns with the exact env override (GBRAIN_PREPARE=false)
and URL-query alternative (?prepare=false). Works for both the module
singleton and worker-instance engines.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: resolvePrepare precedence matrix + postgres-engine wiring guard

- test/resolve-prepare.test.ts: 11 cases covering env override, URL
  query param, port auto-detect, malformed URLs, postgres:// scheme,
  URL-encoded credentials. Uses bun:test — #284's original vitest file
  would never have run in this project.
- test/postgres-engine.test.ts: new source-level grep case asserting
  the worker-pool connect() branch calls db.resolvePrepare(url) and
  includes a typeof prepare === 'boolean' check. Mirrors the existing
  SET LOCAL regression guard. If anyone rips out the wiring, the build
  fails before shipping starts dropping rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump version and changelog (v0.15.4)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jonah Berg <jonah.berg.g@gmail.com>
@garrytan

Copy link
Copy Markdown
Owner

Closing — Prepared-statements-off shipped in #286 (v0.22.x).

Thanks for the report. If anything still reproduces on the latest release, please reopen with the version + repro.

@garrytan garrytan closed this May 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants