Skip to content

Fix sql.begin() sending BEGIN on an unreserved connection - #1218

Closed
v0idpwn wants to merge 2 commits into
porsager:masterfrom
v0idpwn:chore/fix-pipeline-boundary-check
Closed

v0idpwn wants to merge 2 commits into
porsager:masterfrom
v0idpwn:chore/fix-pipeline-boundary-check

Conversation

@v0idpwn

@v0idpwn v0idpwn commented Sep 9, 2026

Copy link
Copy Markdown

sql.begin() could send BEGIN to the server without reserving the
connection.

Depending on pool size, this errored with UNSAFE_TRANSACTION or
TypeError. The transaction stayed open on the server either way, and
the connection went back to the pool, so unrelated queries then ran
inside it.

With max_pipeline: 0 this error happened consistently. With the default
max_pipeline of 100 the same thing happened only when BEGIN was the
query that filled a connection's pipeline, which is why the failure was
intermittent.

The issue is in execute(): after writing the query it returns an &&
chain that states whether the connection can accept more queries, and
one of its terms is sent.length < max_pipeline. The onexecute hook,
which is how sql.begin() reserves the connection, was the last term of
that chain. Whenever the capacity term was false the chain
short-circuited and the hook never ran, even though BEGIN had already
been written. With max_pipeline: 0 that term is false for every query,
so the hook never ran at all.

Move the hook ahead of the capacity terms so it runs whenever the query
was written. Reserving the connection is a consequence of having sent
BEGIN, unrelated to the query limit in the connection.

Add tests for BEGIN at the pipeline boundary and with max_pipeline: 0.

Fixes #1189 #1210

sql.begin() could send BEGIN to the server without reserving the
connection.

Depending on pool size, this errored with UNSAFE_TRANSACTION or
TypeError.  The transaction stayed open on the server either way, and
the connection went back to the pool, so unrelated queries then ran
inside it.

With max_pipeline: 0 this error happened consistently.  With the default
max_pipeline of 100 the same thing happened only when BEGIN was the
query that filled a connection's pipeline, which is why the failure was
intermittent.

The issue is in execute(): after writing the query it returns an &&
chain that states whether the connection can accept more queries, and
one of its terms is sent.length < max_pipeline.  The onexecute hook,
which is how sql.begin() reserves the connection, was the last term of
that chain.  Whenever the capacity term was false the chain
short-circuited and the hook never ran, even though BEGIN had already
been written.  With max_pipeline: 0 that term is false for every query,
so the hook never ran at all.

Move the hook ahead of the capacity terms so it runs whenever the query
was written.  Reserving the connection is a consequence of having sent
BEGIN, unrelated to the query limit in the connection.

Add tests for BEGIN at the pipeline boundary and with max_pipeline: 0.

Fixes porsager#1189
execute() must keep returning a falsy value for BEGIN so the pool puts
the connection in the full queue rather than busy.  Otherwise a query
issued while BEGIN is in flight is pipelined behind it and runs inside
the transaction.
@Ruckus000

Copy link
Copy Markdown

A production data point for this fix, and for #970 / #1210.

  • Setup: Next.js on Vercel, Supabase Supavisor in transaction mode (port 6543), postgres.js 3.4.8 via drizzle-orm, prepare: false, max: 3.
  • Symptom: a page that issued 8 concurrent queries hung until the platform's 300s timeout, on every load. The query that postgres.js had pipelined onto a busy connection never resolved, and PostgreSQL showed its backend active / wait event ClientRead.
  • Confirmation: raising max to 10, so nothing needed to pipeline, made the page load; that was the confirming test. We then shipped max_pipeline: 0 with max: 3.
  • Patch: we had to patch execute() to run onexecute unconditionally, because otherwise every sql.begin throws (sql.begin() always throws UNSAFE_TRANSACTION when max_pipeline is 0 #1210).

We run that patch in production. Its semantics match this PR: call the hook whenever the bytes were written, and keep a falsy return while it's present. In our local tests it passes concurrent transactions, savepoints and rollback at max_pipeline: 0, and keeps the transaction's connection out of ordinary pipelining at the default and at 1. (See my comment on #1211 for why that last part matters.)

@RotoPL

RotoPL commented Oct 2, 2026

Copy link
Copy Markdown

+1 for this approach — we hit the same bug in our app and landed on
the same semantics independently, so here's a second data point.

Setup: postgres 3.4.8 (code unchanged in 3.4.9), Node 24.13, Drizzle,
Supabase Supavisor transaction mode (port 6543), prepare: false.

Why we need max_pipeline: 0: once the pool saturates, a parameterless
query pipelined onto a busy connection is never answered by the transaction
pooler, and everything queued behind it on that socket wedges with it.
Minimal repro on max: 1: three concurrent sql`select 1 as a` etc. — the
first resolves, the rest never do, and later queries on that connection hang
too. Parameterized queries aren't affected (describeFirst stops them
pipelining), which made it look intermittent for us. (Supabase tracking:
supabase/supabase#50358.)

Then max_pipeline: 0 fails every sql.begin() with UNSAFE_TRANSACTION,
as described in #1210.

Our patch keeps the falsy return for queries carrying onexecute, like
this PR, so the connection is never offered for pipelining while BEGIN is in
flight:

build(q)
const pipelinable = write(toBuffer(q))
  && !q.describeFirst
  && !q.cursorFn
  && sent.length < max_pipeline
return q.options.onexecute
  ? q.options.onexecute(connection)
  : pipelinable

One small difference from this PR: we run the hook even when write()
returns false. As far as we can tell a false write() only means socket
backpressure — the BEGIN is still sent — so skipping the hook there would
reintroduce UNSAFE_TRANSACTION under backpressure, at any max_pipeline.
Worth considering, unless I'm misreading nextWrite.

Results (max: 3, max_pipeline: 0, against a live Supavisor
transaction pooler; read-only): 5 rounds × 41 concurrent operations — 8
sql.begin() transactions each with a nested savepoint, 1 transaction that
throws (rollback), 16 parameterized and 16 parameterless queries each
returning a distinct value. 205/205 resolved with their own values, no stalls,
no UNSAFE_TRANSACTION. Stock 3.4.8 on the same test: stalls at the default
max_pipeline, UNSAFE_TRANSACTION at 0. Same result through Drizzle's
db.transaction() (192 ops incl. rollbacks, 25-way parameterless contention
on max: 10).

Happy to turn this into a test for tests/index.js if useful — though our
verification was against Supavisor, not the plain-Postgres CI setup.

@evk-soft

evk-soft commented Oct 9, 2026

Copy link
Copy Markdown

Independent verification of this PR at 6007af7b7eb1a85f828f7422de0a28b0e17d2c1a, against upstream 411429e7bd7a3d61155ca9a70a97c111823702ea:

  • Windows x64, Node 24.21.0 and Bun 1.4.2; PostgreSQL 17.11 in a disposable container.
  • ESM and CommonJS (node transpile.cjs regenerated CommonJS at each revision).
  • Three focused cases per runtime/entry point: BEGIN behind an ordinary simple-protocol query at max_pipeline: 1; max_pipeline: 0; and BEGIN whose real socket write accepts the bytes but is made to return false.
  • All 12 baseline cases failed with the missing transaction-connection error; all 12 cases passed on this PR. Successful cases also verified an ordinary query after the transaction.

The last case deliberately forces the accepted-write/backpressure return value, rather than relying on natural OS buffer saturation: the real socket write still runs, BEGIN is padded past the driver's immediate-flush threshold, and a drain event is scheduled. This confirms that this revision runs onexecute even when write() returns false.

These are focused regression checks, not a claim that I ran the full upstream suite, Deno, or Cloudflare.

Standalone reproduction (save as repro-1218.mjs at the repository root)

Set REVIEW_DATABASE_URL to a disposable PostgreSQL database. Run each of boundary, zero, and backpressure with node repro-1218.mjs <case> esm; repeat with cjs after node transpile.cjs, and with bun instead of node. Each process asserts the fixed behavior; an unpatched checkout should exit nonzero.

import assert from 'node:assert/strict'
import net from 'node:net'
import { createRequire } from 'node:module'

const [scenario, entry = 'esm'] = process.argv.slice(2)
const imported = entry === 'cjs'
  ? createRequire(import.meta.url)('./cjs/src/index.js')
  : (await import('./src/index.js')).default
const postgres = imported.default ?? imported
const url = process.env.REVIEW_DATABASE_URL
assert.ok(url, 'Set REVIEW_DATABASE_URL to a disposable PostgreSQL server')
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
const deferred = () => {
  let resolve, reject
  const promise = new Promise((a, b) => { resolve = a; reject = b })
  return { promise, resolve, reject }
}
const timer = setTimeout(() => {
  console.error('FAIL: operation did not settle within 6 seconds')
  process.exit(2)
}, 6000)
const options = { max: 1, fetch_types: false, prepare: false, connect_timeout: 2, onnotice: () => {} }
const clients = []
const client = extra => {
  const sql = postgres(url, { ...options, ...extra })
  clients.push(sql)
  return sql
}
const observer = client()

async function pipeline() {
  const sql = client({ max_pipeline: scenario === 'zero' ? 0 : 1 })
  const [{ pid }] = await sql`select pg_backend_pid() as pid`
  let ordinary
  if (scenario === 'boundary') {
    ordinary = sql.unsafe('select pg_sleep(0.4)', [], { simple: true }).execute()
    for (;;) {
      const [state] = await observer`select wait_event from pg_stat_activity where pid = ${pid}`
      if (state?.wait_event === 'PgSleep') break
      await delay(5)
    }
  }
  const value = await sql.begin(async tx => (await tx`select 42 as value`)[0].value)
  await ordinary
  assert.equal(value, 42)
  const [state] = await observer`select state from pg_stat_activity where pid = ${pid}`
  assert.equal(state.state, 'idle', 'BEGIN must not leave an orphaned server transaction')
  assert.equal((await sql`select 43 as value`)[0].value, 43)
}

async function backpressure() {
  let armed = false, forced = 0
  const sql = client({ socket: async () => {
    const endpoint = new URL(url)
    const socket = net.createConnection({ host: endpoint.hostname, port: Number(endpoint.port) })
    await new Promise((resolve, reject) => { socket.once('connect', resolve); socket.once('error', reject) })
    const write = socket.write
    socket.write = function(chunk, ...rest) {
      const result = Reflect.apply(write, this, [chunk, ...rest])
      if (armed && chunk.includes(Buffer.from('begin '))) {
        armed = false
        forced++
        setImmediate(() => socket.emit('drain'))
        return false
      }
      return result
    }
    return socket
  } })
  await sql`select 1`
  armed = true
  // Force the BEGIN buffer through the immediate-write path (>= 1024 bytes).
  const value = await sql.begin(' '.repeat(1100), async tx => (await tx`select 42 as value`)[0].value)
  assert.equal(forced, 1, 'The accepted-write/backpressure seam must be exercised')
  assert.equal(value, 42)
  assert.equal((await sql`select 43 as value`)[0].value, 43)
}

try {
  if (scenario === 'boundary' || scenario === 'zero') await pipeline()
  else if (scenario === 'backpressure') await backpressure()
  else throw new Error('Choose boundary, zero, or backpressure')
  console.log(`PASS ${scenario} ${entry}`)
} catch (error) {
  console.error(`FAIL ${scenario} ${entry}:`, error)
  process.exitCode = 1
} finally {
  await Promise.allSettled(clients.map(sql => sql.end({ timeout: 0 })))
  clearTimeout(timer)
}

Prepared with Codex assistance; the results above come from executed checks.

@GrahamCampbell

Copy link
Copy Markdown
Contributor

We carry this change as it is here. One more route to the pipeline boundary at the default max_pipeline, and one that needs no timing: with max: 2, both connections reserved and 100 queries and then a sql.begin queued in the pool, releasing one reservation lets onopen (src/index.js:401-419) hand all 101 to that connection, so the BEGIN goes out with 100 ahead of it, skips onexecute and fails with UNSAFE_TRANSACTION, leaving its session idle in transaction for the pool to lend on, as #823 describes. With this change the same run's begin resolves and no session is left in a transaction.

import postgres from 'postgres'

// Server and credentials from PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE.
const sql = postgres({ max: 2, connection: { application_name: 'repro' } })
const held = [await sql.reserve(), await sql.reserve()]
const queued = Array.from({ length: 100 }, (_, i) => sql.unsafe(`select ${ i } as n`).execute())
const began = sql.begin(sql => sql`select 1`).then(() => 'resolved', e => 'rejected ' + e.code)
await new Promise(r => setTimeout(r, 50))
held[0].release()
await Promise.all(queued)
console.log('begin:', await began)
console.log(await held[1]`select state from pg_stat_activity where application_name = 'repro' order by state`)
held[1].release()
await sql.end({ timeout: 1 })

On 3.4.9 and on master (411429e) it prints begin: rejected UNSAFE_TRANSACTION and the states active and idle in transaction; with this change, begin: resolved and active and idle.

@snuff12

snuff12 commented Oct 22, 2026

Copy link
Copy Markdown

Another production data point, plus the consequence that worries us more than the error itself.

Setup: postgres 3.4.7 via drizzle-orm 0.40, Next.js on Vercel (Fluid compute), Supabase Supavisor in transaction mode (6543), prepare: false, max: 10.

Silent write loss: the session left idle in transaction goes back to the pool, so later non-transactional writes from unrelated callers run inside that open transaction. Their promises resolve successfully, but the writes are rolled back when the connection closes. Local repro on 3.4.7 / PostgreSQL 14 (max: 10, prepare: false, default max_pipeline):

  1. Saturate the pool with 1000 select pg_sleep(0.2).
  2. sql.begin() fails with UNSAFE_TRANSACTION.
  3. 200 plain inserts all resolve, but only about 170 rows remain after sql.end() (168–175 across our runs).

We applied this PR to 3.4.7:

  • It fixes the case above: begin resolves, 200/200 rows persist, and max_pipeline: 0 works too.
  • It keeps isolation: 300/300 inserts persist while 30 transactions that roll back run concurrently.
  • Run onexecute regardless of max_pipeline so begin() works at 0 #1211's variant loses 10/300 rows in the same test, which matches the regression noted there.

We're carrying this PR as a pnpm patch on src, cjs and cf until it lands.

Repro (silent write loss)
const postgres = require('postgres')
const URL = process.env.DATABASE_URL
;(async () => {
  const admin = postgres(URL, { max: 1 })
  await admin`drop table if exists t`
  await admin`create table t (id int)`
  const sql = postgres(URL, { max: 10, prepare: false })
  await Promise.all(Array.from({ length: 10 }, () => sql`select 1`))
  const bg = Array.from({ length: 1000 }, () => sql`select pg_sleep(0.2)`.catch(e => e))
  console.log('begin:', await sql.begin(tx => tx`select 1`).then(() => 'ok', e => e.code))
  await Promise.all(bg)
  const ok = await Promise.all(Array.from({ length: 200 }, (_, i) => sql`insert into t values (${ i })`.then(() => 1, () => 0)))
  await sql.end({ timeout: 1 })
  console.log('resolved:', ok.reduce((a, b) => a + b), 'persisted:', (await admin`select count(*)::int n from t`)[0].n)
  await admin.end()
})()

@porsager

Copy link
Copy Markdown
Owner

Thanks! This is part of v4 (06cf284), so I am closing it here. The changelog has the details: https://github.com/porsager/postgres/blob/master/CHANGELOG.md

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.

BEGIN can reach PostgreSQL without reserving the transaction connection

7 participants