Skip to content

fix(relay): stop a terminated checked-out PostgreSQL client from killing the cell - #21840

Merged
Jinwoo-H merged 1 commit into
mainfrom
relay-pg-checked-out-client-error
Sep 20, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
relay-pg-checked-out-client-error

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​111 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​106
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​39 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​37

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-c28 that 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/assign in 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]: _acquireClient calls client.removeListener('error', idleListener) when it hands a client out (index.js:344), and _release puts it back with client.on('error', idleListener) (index.js:385). So for the entire time the relay holds a client — inside transaction(), or inside query() between acquire and release — the client has zero error listeners. Node's contract for an EventEmitter with no error listener is to throw, which is the throw er; // Unhandled 'error' event / Error: Connection terminated unexpectedly from client.js:199 in the incident. Our existing absorbPostgresIdleClientErrors is structurally unable to catch it.

The fix attaches a per-checkout error listener in PostgresPoolPressure's acquire path — the one choke point both query() and transaction() already await. On release the listener is removed (so it cannot accumulate on a reused client) and the recorded error is passed to client.release(err), which is how you tell pg-pool to destroy the connection instead of returning a dead one to the pool. The in-flight client.query still rejects with the original error, so reportPostgresQueryFailure and 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_timeout in 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:

  • A global 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.
  • Dropping or raising 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.
  • Listening on each of the two checkout sites in 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.connect is 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.ts drives the real PostgresDatabase.transaction() over an EventEmitter-backed fake pool client (no live Postgres required, so it runs in the normal relay suite rather than the *-postgres suites):

  • a control case pinning Node's behaviour — an EventEmitter with no error listener throws, which is the production crash;
  • emitting error on a checked-out client no longer throws, and the client has exactly 1 error listener while checked out and 0 after release;
  • the transaction rejects with the original error object;
  • release is called with that error (so pg-pool destroys the client), and a healthy transaction still releases with no error.

Mutation check: with guardCheckedOutClient removed 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 real pg.PoolClient is always an EventEmitter, so those fixtures were under-specified; they now provide on/removeListener. No assertions were weakened.

Commands run in cloud/apps/relay:

  • npx tsc -p tsconfig.json --noEmit → exit 0 (this is the package's lint and typecheck script)
  • 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.json ignorePatterns, as it is for oxfmt. 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.ts files that need ORCA_RELAY_TEST_POSTGRES_URL; they were not run.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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. absorbPostgresIdleClientErrors and 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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…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
@pullfrog

pullfrog Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1ea5f243-0ade-47b8-ae39-2e53276e1a95

📥 Commits

Reviewing files that changed from the base of the PR and between 5b8b01b and 726d9b1.

📒 Files selected for processing (7)
  • cloud/apps/relay/src/cell-inventory-lock-contention.test.ts
  • cloud/apps/relay/src/database-postgres-timeout.test.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/postgres-checked-out-client-error.test.ts
  • cloud/apps/relay/src/postgres-pool-pressure.test.ts
  • cloud/apps/relay/src/postgres-pool-pressure.ts
  • cloud/apps/relay/src/postgres-query-failure.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The 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 pg-pool. PostgresDatabase is exported for direct testing. New tests cover terminated and healthy clients. Existing pool test doubles now expose the required EventEmitter methods.

Priority: ➖ Normal

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: preventing a terminated checked-out PostgreSQL client from crashing the relay process.
Description check ✅ Passed The description is detailed and covers the required explanation, changes, rationale, testing, platform impact, security, compatibility, performance, and checklist items. The Linked Issue section does …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Jinwoo-H
Jinwoo-H merged commit eb6068a into main Sep 20, 2026
26 of 27 checks passed
@Jinwoo-H
Jinwoo-H deleted the relay-pg-checked-out-client-error branch September 20, 2026 21:46
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.

1 participant