Repository navigation
fix(relay): stop a terminated checked-out PostgreSQL client from killing the cell - #21840
Conversation
…ing the cell pg-pool removes its own `error` listener when it hands a client out ([email protected] index.js:344) and only reattaches it in `_release` (index.js:385). Between acquire and release the client therefore has no `error` listener, so when Cloud SQL terminates that session mid-statement the emit becomes an unhandled 'error' event and the process exits. `absorbPostgresIdleClientErrors` cannot see it: pg-pool routes to `pool.on('error')` only from the idle listener. Attach a per-checkout `error` listener in the one seam every relay checkout passes through, log a single warn line, and release the client with the error so pg-pool destroys it instead of pooling a dead connection. The listener is removed on release so it cannot accumulate. The in-flight query still rejects, so existing failure reporting and the transaction retry ladder are unchanged. Claude-Session: https://claude.ai/session/ced32ebb-7155-4413-adad-1eccd14c2010
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (7)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe relay now attaches an error listener to checked-out PostgreSQL clients. It records and logs the first client failure, removes the listener during release, and forwards the failure to Priority: ➖ Normal 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |

ELI5
When the database hangs up on a connection the relay is actively using, the whole relay process dies. Every host on that cell is thrown off and they all come back at once. This makes the relay notice the hang-up, fail just that one request, and keep running.
What Changed
Before (what operators see): Cloud SQL drops one connection. The relay process crashes instantly, restarts ~17s later, and every host homed to that cell reconnects at the same time. On 2026-09-20 20:18:10Z on
production-gce-c28that was ~2,070 hosts stampeding into a 16-connection pool, saturating it for 15 minutes, and the director returned 7,750 HTTP 503s on/v1/assignin a single minute. The same signature took cells down on 08-22, 08-27, 08-29 (x9) and 09-01.After: the same hang-up logs one line —
[orca-relay] checked-out PostgreSQL client failed: <code> <message>— the single in-flight request fails and is retried by its normal caller, and the process stays up. No restart, no stampede, no 503 wave.Mechanism. node-postgres only routes client failures to
pool.on('error')for idle clients. Reading the installed[email protected]:_acquireClientcallsclient.removeListener('error', idleListener)when it hands a client out (index.js:344), and_releaseputs it back withclient.on('error', idleListener)(index.js:385). So for the entire time the relay holds a client — insidetransaction(), or insidequery()between acquire and release — the client has zeroerrorlisteners. Node's contract for anEventEmitterwith noerrorlistener is to throw, which is thethrow er; // Unhandled 'error' event/Error: Connection terminated unexpectedlyfromclient.js:199in the incident. Our existingabsorbPostgresIdleClientErrorsis structurally unable to catch it.The fix attaches a per-checkout
errorlistener inPostgresPoolPressure's acquire path — the one choke point bothquery()andtransaction()already await. On release the listener is removed (so it cannot accumulate on a reused client) and the recorded error is passed toclient.release(err), which is how you tell pg-pool to destroy the connection instead of returning a dead one to the pool. The in-flightclient.querystill rejects with the original error, soreportPostgresQueryFailureand the transaction retry ladder behave exactly as before — nothing is swallowed.Why
This is one of the two fixes the 2026-09-20 20:18Z c28 incident needs. The other is still open: finding which transaction sits idle inside a transaction for more than 5s and trips
idle_in_transaction_session_timeoutin the first place. That one removes the trigger; this one removes the blast radius, so a single database hiccup costs one request instead of a whole cell.Alternatives considered:
process.on('uncaughtException'). It would stop the crash, but it stops every crash — it converts unrelated real bugs into silent corrupt state, and it still leaves the dead connection in the pool for the next caller. Fixing it at the pool boundary keeps the blast radius at one connection and keeps the process's crash-on-bug behaviour honest everywhere else.idle_in_transaction_session_timeout. That timeout is load-bearing: it is what stops an abandoned transaction from pinning one of only 16 connections indefinitely. It is also not the only way a checked-out client dies — a failover, a restart, or a network drop does the same. Deliberately left unchanged.database.ts. Works, but it is two places to keep in sync and a third checkout site added later would silently reintroduce the crash.PostgresPoolPressure.connectis the single seam all checkouts already pass through.Linked Issue
N/A — incident-driven, no tracking issue filed.
Fixes #
Visual Proof
N/A— server-side crash handling in the relay cell; no UI or user-visible interaction changes.Testing
New
cloud/apps/relay/src/postgres-checked-out-client-error.test.tsdrives the realPostgresDatabase.transaction()over anEventEmitter-backed fake pool client (no live Postgres required, so it runs in the normal relay suite rather than the*-postgressuites):EventEmitterwith noerrorlistener throws, which is the production crash;erroron a checked-out client no longer throws, and the client has exactly 1errorlistener while checked out and 0 after release;releaseis called with that error (so pg-pool destroys the client), and a healthy transaction still releases with no error.Mutation check: with
guardCheckedOutClientremoved from the acquire path, the new test fails with the unhandled throw; restored, it passes.Four existing tests faked a pooled client as
{ query, release }. A realpg.PoolClientis always anEventEmitter, so those fixtures were under-specified; they now provideon/removeListener. No assertions were weakened.Commands run in
cloud/apps/relay:npx tsc -p tsconfig.json --noEmit→ exit 0 (this is the package'slintandtypecheckscript)npx vitest run→Test Files 75 passed | 24 skipped (99),Tests 764 passed | 124 skipped (888)npx oxlint <changed files>→ "No files found to lint":cloud/**is in the root.oxlintrc.jsonignorePatterns, as it is foroxfmt. Style was matched to the surrounding file by hand.Platforms: relay cell code is Linux-only server-side; no platform-dependent behaviour touched. The 24 skipped suites are the
*-postgres.test.tsfiles that needORCA_RELAY_TEST_POSTGRES_URL; they were not run.AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Security: the new warn line prints the error code and message of a client that is already past the TLS/auth handshake, so unlike the idle-client path it cannot carry a connection string or password.
absorbPostgresIdleClientErrorsand its redaction test are untouched.Backwards compatibility: no wire, schema, config, or protocol change; no change to
idle_in_transaction_session_timeout, statement timeout, or pool sizing. Behaviour differs only on a path that previously ended the process.Performance: one listener and one closure per checkout, both released on release. No added queries or round trips.
Cross-platform / SSH / mobile: relay cell server code only; untouched.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)