Repository navigation
Description
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):
- The statement's reply is late, so
pg'squery_timeoutrejects it (pg/lib/client.js:706-713).
The statement stays active on the connection. - The client engine closes the transaction with
executeRaw(ROLLBACK), thenrollback()in a
finally(usePhantomQuery: false; onv7,
packages/client-engine-runtime/src/transaction-manager/transaction-manager.ts:648-652).
pgqueues theROLLBACKbehind the active statement.
TheROLLBACK's ownquery_timeoutfires, and because it was never sent,pgremoves it from
the queue (pg/lib/client.js:719-722). PgTransaction.rollback()releases the client with no error. In 7.10.1 it calls
this.client.release()directly, andcommit()does the same. Onv7both now callclose()
(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_timeouthas already rejected
the statement and theROLLBACK, though the statement is still active on the connection. So
close()reachesthis.client.release()with no error (:181).
pg-pooldestroys a released client whenerris set (pg-pool/index.js:392-397). A queryable
client released without one goes back to the idle list.- 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
- Driver adapters: connection returned to pool with an open transaction (ROLLBACK never sent) when maxWait expires during startTransaction — "there is already a transaction in progress" #29719, fixed by fix(client-engine-runtime): send ROLLBACK when discarding a timed-out transaction start #29727: the same symptom on another path, a late
startTransactiondiscarded
with a barerollback(). That fix is in 7.10.1. This report is about the path after it. - Driver adapter (pg): after a database error inside an interactive transaction, subsequent queries on the same client receive other queries' responses #30374 / fix(adapter-pg): destroy pg connections after transaction database errors to prevent response leaking #30413: fix(adapter-pg): destroy pg connections after transaction database errors to prevent response leaking #30413 marks a transaction poisoned in
onErrorand releases it with an error.
performIOroutes everyclient.queryrejection throughonError,Query read timeout
included, so it would also cover this case. It would also evict after every database error,
including one the caller rolls back on purpose. It targets7.9.x. - Interactive transaction timeout during COMMIT double-releases the pg pool client with @prisma/adapter-pg (uncatchable process crash) #29952, fixed by fix(adapter-pg): release the pool client at most once per transaction #29954 (merged 10 Nov, not yet released):
close()releases with an error while
a statement is running, by the adapter's own count. By my reading it does not cover this case. By
the timerollback()runs,query_timeouthas rejected both the statement and theROLLBACK, so
the count reads 0. - fix(client): a statement can no longer run after its transaction has closed #30995 (merged 13 Nov, not yet released): once a transaction starts closing, no further
statement reaches the adapter, and the close waits up to 2 s for running ones. The close
sequence itself is unchanged (ROLLBACK, thenrollback()in afinally), and a statement
already rejected byquery_timeoutis not waited on.
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
prisma-asks commentedon Nov 20, 2026
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
joshuavivo commentedon Nov 29, 2026
Three new measurements on PostgreSQL 16.14, 5 runs per build, same result every run:
v7@ 4c3db4a, a later transaction'sCOMMITalso commits the row of the abandoned transaction, whoserollback()had already returned.COMMIT-timeout variant, which this issue does not measure, fails the same way on 7.10.1 andv7, 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).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 withpg_sleep(4)standing in for the late reply (INSERTid 1, timed-outpg_sleep,ROLLBACKthat 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.@prisma/adapter-pg7.10.1v7@ 4c3db4a#30947 and #30915 conflict with current
v7inpg.ts, so those results are from builds of their own heads (base 97ea359); only #31209 was built onv7@ 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: 1artefact: withmax: 5and 5 concurrent callers, the abandoned backend was lent once in each of 8 waves on 7.10.1 andv7, 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.
prisma-asks commentedon Nov 29, 2026
Thanks for reporting this. We're looking into it now: whether we can reproduce it and what impact it has.