Skip to content

fix(pg-cache): keep the server alive when a checked-out connection drops - #2085

Merged
devin-ai-integration[bot] merged 1 commit into
mainfrom
fix/pg-cache-client-error-listener
Nov 26, 2026
Merged

devin-ai-integration[bot] merged 1 commit into
mainfrom
fix/pg-cache-client-error-listener

Conversation

@Zetazzz

@Zetazzz Zetazzz commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

pg-pool listens for errors only on idle clients. While a client is checked out, pg-pool removes its own listener and expects the caller to add one. PostGraphile's makePgService adds that listener to the pools it creates, and its source notes that a caller passing its own pool is responsible for doing the same ("If you pass your own pool, you're responsible for doing this yourself"). The GraphQL server passes pools from pg-cache, and pg-cache only handles the pool-level error event, which fires for idle clients.

PostgreSQL can end a checked-out connection at any time: a restart, a failover, a crashed backend, pg_terminate_backend. When it does, pg rejects the query in flight and also emits error on the client. Nothing listens, so Node treats the event as fatal and the process exits. Every other in-flight request is dropped, and every cached handler is lost.

Change

  • Listener: defaultPgPoolFactory gives every client a permanent error listener when the pool connects it (pool.on('connect', …)). PostGraphile does the same for its own pools.
  • Errors still surface: the listener only keeps the process alive. The code holding the client still gets the rejected query, the pool discards the broken client when it is released, and the request path still logs the failure (for example graphile:formatError).
  • Logging: errors on idle clients also reach the existing pool handler, so the new listener logs at debug level instead of reporting them twice.
  • Coverage: this covers every pool created by getPgPool with the default factory, which includes the GraphQL server, the explorer and the dev server. Factories registered with registerPgPoolFactory are unchanged.

Tests

  • pg-cache unit test (no database): a client the pool connects carries its own error listener, and an error event on it does not throw. It fails without the change.
  • graphql-server-test integration test: connection-loss.integration.test.ts terminates the backend serving an in-flight request through the real server. That request fails and the next one succeeds. Without the change, the suite fails with Unhandled error. (Error: Connection terminated unexpectedly …). In a running server, that unhandled event exits the process.

Evidence

The real server was run outside this repository, from main as of 2026-11-23 (postgres/pg-cache is unchanged since). It ran in production mode against a local PostgreSQL 18, and was tested in three server states. For each state, the connection was dropped three ways, twice each:

  • a graceful restart (fast shutdown);
  • pg_terminate_backend on the server's sessions;
  • SIGKILL of the postmaster.
Server state when the connection dropped main with this change
idle survived 6/6 survived 6/6
queries in flight crashed 6/6 survived 6/6
schema builds in flight crashed 6/6 survived 6/6

On main, the unhandled errors came from clients whose last statement was a request's rollback, the query itself, or the scoped introspection query. With the change, in-flight requests failed with an error, and all nine follow-up requests in each run succeeded without restarting the server.

Not changed

The observability-only diagnostics pool in graphql/server/src/diagnostics/debug-db-snapshot.ts creates its own pg.Pool without these handlers. It is only enabled in development on a loopback host, so it is left for a separate change.

Verification

  • pg-cache: 20/20 tests pass.
  • graphql-server-test: the new suite plus notify-listener, subscriber-pool-lifecycle, server, request-protection and handler-heap pass 58/58 locally against PostgreSQL 18.7.
  • Lint: eslint is clean on the changed files.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of database connection errors so a failed request is less likely to disrupt subsequent requests.

pg-pool listens for errors only on idle clients; while a client is
checked out, the caller is expected to listen. PostGraphile does that
for pools it creates and leaves it to callers that pass their own pool,
which is how the GraphQL server uses pg-cache's pools. When PostgreSQL
ended a checked-out connection (a restart, a failover,
pg_terminate_backend), pg emitted 'error' on the client with no
listener, and the whole process exited.

defaultPgPoolFactory now gives every client a permanent error listener
when the pool connects it. The owner still sees the rejected query, and
the pool discards the client when it is released. Idle-client errors
still reach the pool handler, so the new listener logs at debug level.

Adds a pg-cache unit test, and a graphql-server-test integration test
that terminates the backend of an in-flight request. Both fail without
the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@luxor-code-review

luxor-code-review Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Client error handler logs all errors at debug level (pg.ts:118) — The new client-level 'error' listener on checked-out connections logs every error at debug level (postgres/pg-cache/src/pg.ts:119-121).

This PR hardens pg-cache against backend connection loss by attaching per-client 'error' handlers so a terminated PostgreSQL backend no longer crashes the process, and adds tests proving the behavior.

Files Change
postgres/pg-cache/src/pg.ts Adds a pool-level error handler with 57P01-aware logging and a per-client 'error' listener attached on 'connect' to swallow errors on checked-out connections.
postgres/pg-cache/src/__tests__/client-errors.test.ts New unit tests asserting error listeners are attached and no unhandled error events escape.
graphql/server-test/__tests__/connection-loss.integration.test.ts New integration test terminating the probe's backend via pg_terminate_backend and verifying a GraphQL request still resolves gracefully.
graphql/server-test/__fixtures__/seed/connection-loss/probe.sql Seed SQL defining the probe function and granting anonymous access for the test.

Reviewed commit: 5ae8789

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The PostgreSQL pool now attaches a debug-logging error listener to each connected client. Tests cover a terminated backend during a GraphQL request and verify that a later request succeeds.

Changes: Connection-Loss Handling

Layer / File(s) Summary
Connected-client error handling
postgres/pg-cache/src/pg.ts, postgres/pg-cache/src/__tests__/client-errors.test.ts
The pool attaches an error listener to each connected client and logs client errors at debug level. A unit test checks listener registration and error emission.
GraphQL connection-loss integration test
graphql/server-test/__fixtures__/seed/connection-loss/probe.sql, graphql/server-test/__tests__/connection-loss.integration.test.ts
The seeded probe sleeps for a requested duration. The integration test terminates the backend for a running probe, checks the failed response, and verifies that a subsequent probe succeeds.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: pyramation, luxor-code-review

Merge Risk: Minimal · up to 5ae87

This change keeps the process alive when PostgreSQL drops a connection, and queries still fail normally. No merge-blocking risk was found.

Security architecture risk: Low · up to 5ae87

The production change keeps a dropped database connection from taking down the server without hiding the failed request. The remaining risk is confined to testing: if the suite is configured to reuse a database, it can interrupt another matching session in that database.

Retained concerns

  • Low · reliability · inferred: The new integration test does not bind its termination target to the suite's own server session. If TEST_DB points multiple runs at the same database, the privileged harness can interrupt another matching session instead of the request under test. The default per-suite database contains this risk; the PR adds no production termination route.
Security review details

Security Blast Radius

  • inferred — The new termination action is bounded by the test database and the harness login's signaling privileges. The default unique database separates suites; reusing a database removes that separation without adding a session-ownership check.

Trust Boundaries and Controls

  • observed — The test server uses a separate nonsuperuser login without RLS bypass. The termination command runs on the harness connection, not under the anonymous GraphQL request role.

Resilience and Maintainability Implications

  • observed — The unchanged harness attempts teardown on seed failure. If later login or server setup fails before the teardown callback is returned, the suite's cleanup hook has no callback to invoke. The new fixture relies on the same database-level cleanup.

Hardening Proposals

  • proposed — Require a disposable database owned by the suite before seeding the probe, and verify that the target session belongs to the suite before issuing the termination command.
Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(pg-cache): keep the server alive when a checked-out connection drops" matches the main change. The PR adds a permanent client-level error listener in defaultPgPoolFactory (postgres/pg-c…
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.
Full details: Title check

Explanation

The title "fix(pg-cache): keep the server alive when a checked-out connection drops" matches the main change. The PR adds a permanent client-level error listener in defaultPgPoolFactory (postgres/pg-cache/src/pg.ts), which stops an unhandled 'error' event from terminating the Node process when PostgreSQL drops a checked-out connection. The title names the affected package and the behavior. The supporting test files and the SQL probe function cover the same change, so the title does not need to list them.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d5ef4f0 and 5ae8789.

Files selected for processing: 4

  • graphql/server-test/__fixtures__/seed/connection-loss/probe.sql
  • graphql/server-test/__tests__/connection-loss.integration.test.ts
  • postgres/pg-cache/src/__tests__/client-errors.test.ts
  • postgres/pg-cache/src/pg.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@blacksmith-sh

This comment has been minimized.

@Zetazzz

Zetazzz commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Responses to the automated reviews, plus the one CI failure:

  • Debug-level client listener (Luxor nit): intentional. An error on a checked-out client already reaches its owner: pg rejects the query in flight, and the request path logs that at error level. A failed request is logged as graphile:formatError, and a failed schema build as Failed to create PostGraphile[...]; both appeared in the outage runs. An error on an idle client still reaches the existing pool handler, which logs at error level (debug for 57P01). Logging at warn or error in the new listener would report each lost connection twice.
  • How the integration test picks the backend to terminate (CodeRabbit, low): left as is. Each run creates its own database, and only this suite's server runs connection_loss_probe in it. If TEST_DB points several runs at one database, seeding still runs for each of them, so a second run fails at CREATE FUNCTION ... connection_loss_probe (the function already exists) before it reaches the termination. notify-listener.integration.test.ts picks its backend the same way, by database and query text.
  • CI: the first run of pg-tests (pg-core) failed in pgpm/cli's init.test.ts. pgpm init spent about 69 s cloning constructive-io/pgpm-boilerplates from GitHub, longer than the test's 60 s limit. The second failure in that file was left over from the timed-out test (its foo/ files appeared in the next snapshot). pg-cache is not involved, and the re-run passed. Both new tests ran in CI: client-errors.test.ts in unit-tests (packages-core) and connection-loss.integration.test.ts in integration-tests (integration-graphql).

@devin-ai-integration
devin-ai-integration Bot merged commit b714bee into main Nov 26, 2026
40 of 41 checks passed
@devin-ai-integration
devin-ai-integration Bot deleted the fix/pg-cache-client-error-listener branch November 26, 2026 10:36
devin-ai-integration Bot pushed a commit that referenced this pull request Nov 28, 2026
…2101)

* fix(pgsql-test): keep a lost connection from ending the test process

node-postgres emits 'error' on a client whose connection the server ends
or drops (pg_terminate_backend, a restart, a crash). PgClient and the
pools that PgTestConnector.getPool creates had no listener for it, so
the event ended the whole test process instead of failing the test that
used the connection.

PgClient now listens on its underlying client. getPool's pools listen on
the pool, for idle connections, and on each client, for checked-out
connections. The listeners log and keep the process alive. Queries on
the broken connection still reject, and the pool discards it on release.
pg-cache's pools got the same listeners in #2085.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(pgsql-test): isolate the connection-loss cases and always release pooled clients

Run each case between the pg and db clients' beforeEach/afterEach hooks,
like the other pgsql-test suites. Release the pooled connections in
finally, so a failed check can't leave one checked out when the suite
ends its pools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Zetazzz <1872387+Zetazzz@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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