Skip to content

bug(platform): a Postgres server process that dies under an open transaction crashes the backend (postgres.js null-socket write) #4041

Closed

Description

@yannickmonney

Summary

A backend process (api or worker) crashes when a PostgreSQL server process ends abruptly while the process has a transaction open: sql.begin, which is also what transactSerializable uses. The process dies with an uncaught

TypeError: Cannot read properties of null (reading 'write')
    at Immediate.nextWrite (node_modules/postgres/src/connection.js:250:22)

Error tracking receives it as a fatal event (auto.node.onuncaughtexception), and the process exits 1.

This is a postgres.js bug, and it is still unfixed upstream:

It reproduces on 3.4.7 (our pin) and on 3.4.9 (latest).

Found while testing the boot wait of #4031 (TALE-406). It predates that PR: every head and main behave the same.

Reproduction (local, isolated PostgreSQL 16.14, Node 22.21.1)

Minimal, 3 runs out of 3: postgres.js alone. sql.begin(async (t) => t\SELECT pg_sleep(20)`), then kill -9` the server process running it.

  • The transaction rejects CONNECTION_CLOSED.
  • One tick later the uncaught TypeError above ends the process with exit 1.

In the platform backend (ROLE=all, a migration held open with SELECT pg_sleep(25)):

Cut Result
kill -9 of the migration's own server process uncaught TypeError, fatal event, exit 1 (both heads of #4031 tested)
kill -9 of another session's server process (the server restarts every session; in PG 14+ the others get a 57P02 WARNING and a closed socket) the same crash in our process
pg_terminate_backend (57P01, a fast shutdown's signal) no crash: the FATAL message arrives before the socket closes

A fast shutdown is what docker compose restart db sends, and it does not trigger the crash: in TALE-406's rounds S1 and S6, 6 fast stops with 161 transactions cut caused 0 crashes.

Mechanism

  1. connection.js closed() sets socket = null first, then rejects the pending query with CONNECTION_CLOSED.
  2. begin's scope catch then writes ROLLBACK on the same connection.
  3. write defers through setImmediate(nextWrite), so the write is scheduled after closed() has already cleared the timer.
  4. nextWrite then calls socket.write on null.

On the 57P01 path the error arrives before the close, and closed() cancels the pending write.

Impact

Any of these makes every backend process with a transaction open at that moment crash:

  • a crash of any PostgreSQL server process: a segfault, a PANIC in an extension, or the kernel's OOM killer;
  • an immediate shutdown;
  • docker kill, or Docker's SIGKILL after stop_grace_period;
  • likely also a connection closed cleanly by something in between, such as a proxy failover (not tested).

Docker then restarts the process. With #4031 its boot waits out the crash recovery ("the database system is in recovery mode") instead of reporting and exiting again.

Options (needs a decision)

  1. Patch postgres.js with the upstream guard (Customer list combines name and email in a single column instead of showing them separately #1209) through Bun's patchedDependencies, with a regression test built from the minimal repro. This is the smallest fix.
  2. Upgrade once upstream ships a fix.

Not an uncaughtException filter: that would hide other defects.

Related, for whoever fixes this

Once this crash is gone, a migration that crashes PostgreSQL would be rerun by #4031's boot wait every 1–5 s for about a minute. Under a transaction, postgres.js reports an administrator's shutdown and a crash the same way (CONNECTION_CLOSED / ECONNRESET, never 57P01), so the two cannot be told apart. A rule that would not wait out such a loss under the migration lock was tried on #4031 and dropped, because it failed a routine restart mid-migration (TALE-406 probe p2new). Capping the reruns after the lock is taken (for example to one) would bound the risk without that cost.

Refs #4031.

Activity

  1. yannickmonney commented on Oct 1, 2026

    @yannickmonney
    ContributorAuthor

    Manager decision: pursue option 1, a narrowly reviewed patch for the pinned postgres.js dependency, with independent local regression proof before merging.

    I read the current upstream PR porsager/postgres#1209 (still open, head a2588b3073b5bd125f0fb3b419bdc9f2e8524291) and its patch. It guards the null socket and settles pending work as a connection failure; a guard that merely drops the write is insufficient because callers can hang. This source review is not independent confirmation of the author's runtime results.

    Keep the patch small and pinned through Bun's supported dependency-patch mechanism. Do not switch to an unpinned fork or upgrade unrelated dependencies. Determine every package entry point actually shipped by our API/worker/builds, including any separate CommonJS output; prove the normal frozen install and production image build contain the intended change. Record the upstream link, exact adapted patch and removal condition when a verified upstream release replaces it.

    Acceptance: run the unpatched and patched dependency in child processes with an owned local Postgres/proxy. Observe the socket close/readiness explicitly rather than trusting a fixed sleep. Cover clean close, reset, a reserved connection, rollback after a transaction loses its connection, and healthy query/transaction controls. The failed operation must settle with a catchable connection error within a bound; prove no uncaught crash, hung promise, successful acknowledgement of a failed operation or leaked child/pool. Preserve the original failing evidence. Retain strict uncaught-exception handling, safe retry semantics and normal CI/image checks.

    Migration retry behavior is a separate decision: after this driver patch, exercise a local repeated mid-migration loss and an ordinary announced restart. If the existing boot retry can repeatedly rerun the same crashing migration, bound that retry using actual migration/lock state and the existing overall deadline, with negative and recovery controls. Do not guess a universal retry count, suppress crashes, or restart non-idempotent work with unknown commit outcome. Coordinate with TALE-416/#4031 and use an independent reviewer; no production failure injection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugservice: platform

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions