Skip to content

@prisma/adapter-pg: a transaction whose ROLLBACK timed out unsent goes back to the pool still open, so the next caller's write never commits #31144

Open

Description

@sohel-shekh-9spl

Bug description

With pg's query_timeout set, an interactive transaction whose reply arrives late goes back to
the pool still inside the transaction. The next caller on that connection runs inside the
abandoned transaction: an autocommit INSERT resolves with rowCount: 1 but never commits, and
is rolled back when the connection finally closes. If the server had already aborted the
transaction, the next caller gets 25P02 instead.

The window is a reply late by more than about two query_timeouts with the TCP connection still
alive: a network stall that heals, or a database host that stalls and recovers.

How it happens (@prisma/adapter-pg 7.10.1, @prisma/client 7.10.1, pg 8.23.0, pg-pool
3.14.0):

  1. The statement's reply is late, so pg's query_timeout rejects it (pg/lib/client.js:706-713).
    The statement stays active on the connection.
  2. The client engine closes the transaction with executeRaw(ROLLBACK), then rollback() in a
    finally (usePhantomQuery: false; on v7,
    packages/client-engine-runtime/src/transaction-manager/transaction-manager.ts:648-652).
    pg queues the ROLLBACK behind the active statement.
    The ROLLBACK's own query_timeout fires, and because it was never sent, pg removes it from
    the queue (pg/lib/client.js:719-722).
  3. PgTransaction.rollback() releases the client with no error. In 7.10.1 it calls
    this.client.release() directly, and commit() does the same. On v7 both now call close()
    (packages/adapter-pg/src/pg.ts:169-196), which since fix(adapter-pg): release the pool client at most once per transaction #29954 passes an error only while its own
    running-statement count is above zero. Here that count is 0: query_timeout has already rejected
    the statement and the ROLLBACK, though the statement is still active on the connection. So
    close() reaches this.client.release() with no error (:181).
    pg-pool destroys a released client when err is set (pg-pool/index.js:392-397). A queryable
    client released without one goes back to the idle list.
  4. The late reply arrives, the connection reads as idle, and the pool lends it to the next caller.

By my reading of the engine, a COMMIT that times out is followed by rollback() alone, which
would release the connection the same way (transaction-manager.ts:634-638 on v7). I have not
measured that variant.

Still present on v7 @ 93ad3696 (20 Nov), after #29954 and #30995, by reading. I have not
measured it there, because neither is in a release yet (latest is 7.10.1). #30995 makes a closing
transaction wait for its running statements, but only for promises still pending
(transaction-manager.ts:448), and here query_timeout has already settled the statement's promise.

How to reproduce

The script drives the adapter through the engine's close sequence. It goes through a TCP proxy
that holds server→client bytes for 2 s once the transaction's INSERT is sent. It creates and
drops a table, repro_late_reply.

npm i pg@8.23.0 pg-pool@3.14.0 @prisma/adapter-pg@7.10.1, then
node repro.mjs postgresql://USER:PASS@127.0.0.1:5432/DB [fixed | nohold]

// node repro.mjs postgresql://USER:PASS@127.0.0.1:5432/DB [fixed | nohold]
import net from 'node:net';
import pg from 'pg';
import { PrismaPg } from '@prisma/adapter-pg';

const QUERY_TIMEOUT_MS = 500;
const HOLD_MS = 2_000; // longer than the statement's query_timeout plus the ROLLBACK's
const db = new URL(process.argv[2]);
const fixed = process.argv[3] === 'fixed';
const nohold = process.argv[3] === 'nohold'; // control: the proxy passes everything through
const sql = (text) => ({ sql: text, args: [], argTypes: [] });
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const why = (e) => e.cause?.originalMessage ?? e.cause?.message ?? e.message;

// A TCP proxy that holds server->client bytes while `holdUntil` is in the future: a late reply
// (a network stall that heals, or a database host that stalls and recovers).
let holdUntil = 0;
const proxy = net.createServer((client) => {
  const server = net.connect(Number(db.port || 5432), db.hostname);
  client.pipe(server);
  server.on('data', (chunk) => {
    const wait = holdUntil - Date.now();
    if (wait <= 0) return void client.write(chunk);
    server.pause();
    setTimeout(() => (client.write(chunk), server.resume()), wait);
  });
  for (const [a, b] of [
    [client, server],
    [server, client],
  ]) {
    a.on('error', () => b.destroy());
    a.on('close', () => b.destroy());
  }
});
await new Promise((resolve) => proxy.listen(0, '127.0.0.1', resolve));
const viaProxy = new URL(db);
viaProxy.hostname = '127.0.0.1';
viaProxy.port = String(proxy.address().port);

const observer = new pg.Client({ connectionString: db.href });
await observer.connect();
await observer.query(
  'DROP TABLE IF EXISTS repro_late_reply; CREATE TABLE repro_late_reply (n int)',
);

const adapter = await new PrismaPg({
  connectionString: viaProxy.href,
  max: 1,
  query_timeout: QUERY_TIMEOUT_MS,
}).connect();

// The client engine's sequence for an interactive transaction that fails (usePhantomQuery: false).
const tx = await adapter.startTransaction(); // BEGIN
if (!nohold) holdUntil = Date.now() + HOLD_MS; // the reply to the next statement is late
await tx
  .executeRaw(sql('INSERT INTO repro_late_reply VALUES (1)'))
  .catch((e) => console.log('1. INSERT inside the transaction ->', why(e)));
// Queued in pg behind the INSERT it still considers active; times out; removed from the queue unsent.
await tx
  .executeRaw(sql('ROLLBACK'))
  .catch((e) => console.log('2. ROLLBACK                       ->', why(e)));
if (fixed) {
  // The suggested fix: the close did not complete, so release with an error and pg-pool destroys it.
  // (`client` is `protected` in the TypeScript types, but it is a plain field at runtime.)
  tx.client.release(new Error('transaction close did not complete'));
} else {
  await tx.rollback(); // PgTransaction.rollback(): client.release(), no error
}
await sleep(HOLD_MS); // the late reply arrives; the connection now reads as idle

// An unrelated caller on the same pool.
const rowCount = await adapter.executeRaw(sql('INSERT INTO repro_late_reply VALUES (2)'));
console.log('3. next caller INSERT (autocommit)  -> resolved, rowCount', rowCount);
const visible = await observer.query('SELECT count(*)::int AS n FROM repro_late_reply');
const states = await observer.query(
  `SELECT state FROM pg_stat_activity
    WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'`,
);
console.log(
  '4. rows another session sees:',
  visible.rows[0].n,
  '| pool backend:',
  states.rows.map((r) => r.state).join(', '),
);
await adapter.dispose();
await sleep(300);
const after = await observer.query('SELECT count(*)::int AS n FROM repro_late_reply');
console.log(`5. rows after the pool closes: ${after.rows[0].n} (the next caller's write is row 2)`);
await observer.query('DROP TABLE repro_late_reply');
await observer.end();
proxy.close();

Output on PostgreSQL 16.15 and Node 24.18.1. Each mode ran 3 times, with the same result each
time. In the first two modes, the INSERT and the ROLLBACK both print Query read timeout. In
all three, the next caller's INSERT resolves with rowCount 1.

mode rows another session sees pool backend rows after the pool closes
as shipped 0 idle in transaction 0
fixed: release(error) 1 idle 1
nohold: the proxy idles 1 idle 1

Expected behavior

When a transaction's COMMIT or ROLLBACK did not complete, its client should be released with
an error (this.client.release(err)). Then pg-pool destroys the connection instead of lending it
out still inside a transaction, and the server rolls the transaction back when the socket closes.
The fixed mode above does exactly that. A count of running statements can't make that call,
because pg settles a timed-out statement's promise while the statement is still running on the
connection. Whether the COMMIT or ROLLBACK itself resolved can.

Related, but a different trigger

Workaround

We wrap the adapter factory. Each transaction tracks whether the last COMMIT or ROLLBACK sent
through executeRaw resolved. If it did not, commit() and rollback() release the checkout with
an error. The wrapper depends on PgTransaction.client, which is protected, and on
usePhantomQuery: false, so a fix in the adapter would let us drop it.

Environment & setup

  • OS: Linux (Ubuntu 24.04)
  • Database: PostgreSQL 16.15
  • Node.js: 24.18.1

Prisma Version

prisma, @prisma/client and @prisma/adapter-pg 7.10.1; pg 8.23.0; pg-pool 3.14.0.
Also read against v7 @ 93ad3696 (20 Nov 2026), which includes #29954 and #30995.

Activity

  1. prisma-asks commented on Nov 20, 2026

    @prisma-asks

    Thanks for reporting this. We're looking into it now: whether we can reproduce it and what impact it has.

    You can follow where this stands here: https://asks.prisma.cool/public/asks/01a18c62-67c2-726a-b3f1-46f7f225810a

  2. joshuavivo commented on Nov 29, 2026

    @joshuavivo

    Three new measurements on PostgreSQL 16.14, 5 runs per build, same result every run:

    1. On 7.10.1 and v7 @ 4c3db4a, a later transaction's COMMIT also commits the row of the abandoned transaction, whose rollback() had already returned.
    2. The COMMIT-timeout variant, which this issue does not measure, fails the same way on 7.10.1 and v7, and does not on fix(adapter-pg): discard the connection when a transaction query fails with a non-server error #30947, fix(adapter-pg): destroy the connection when a transaction's COMMIT or ROLLBACK did not resolve #30915 or fix(adapter-pg): evict connection on failed close or unsettled query_timeout #31209 (each on its own head).
    3. v7 @ 4c3db4a, which includes fix(adapter-pg): release the pool client at most once per transaction #29954 and fix(client): a statement can no longer run after its transaction has closed #30995 (aimed at a double release and at statements after close, not at this), still reproduces. The issue says this by reading; this is a measurement.

    Setup: Node 26.3.0, max: 1, query_timeout: 1000. I ran this report's close sequence with pg_sleep(4) standing in for the late reply (INSERT id 1, timed-out pg_sleep, ROLLBACK that times out and is never sent, rollback(), then an unrelated caller), and also this report's own proxy script. Both gave the same result on every build.

    build the next caller gets ids committed after a later transaction commits
    @prisma/adapter-pg 7.10.1 the same backend, still inside the old transaction 1, 2
    v7 @ 4c3db4a same 1, 2
    #30947, #30915, #31209 (each on its own head) a fresh connection 2

    #30947 and #30915 conflict with current v7 in pg.ts, so those results are from builds of their own heads (base 97ea359); only #31209 was built on v7 @ 4c3db4a.

    Versions: 7.10.1 loaded pg 8.23.1 and pg-pool 3.14.0. The source builds load pg 8.16.3 and pg-pool 3.10.1 by default; forced onto pg 8.23.1 and pg-pool 3.14.0, the results were the same.

    Two limits on the first finding: the later transaction is driven by hand through the adapter API, not through the engine, and I did not run Prisma Client end to end. It is not a max: 1 artefact: with max: 5 and 5 concurrent callers, the abandoned backend was lent once in each of 8 waves on 7.10.1 and v7, and never on the three PRs.

    Not tested: other PostgreSQL versions, adapter-neon.

    Thanks to @sohel-shekh-9spl (#31144, #30914), @Kyte4 (#30946, #30947), @RagedPanda (#30915) and @Asadshah7950 (#31209).

    Script and raw output: https://gist.github.com/joshuavivo/826051a29bcffe5fa1c82b1166452703. Tested with Claude's help.

  3. prisma-asks commented on Nov 29, 2026

    @prisma-asks

    Thanks for reporting this. We're looking into it now: whether we can reproduce it and what impact it has.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions