Repository navigation
Conversation
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.
|
A production data point for this fix, and for #970 / #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 |
|
+1 for this approach — we hit the same bug in our app and landed on Setup: postgres 3.4.8 (code unchanged in 3.4.9), Node 24.13, Drizzle, Why we need Then Our patch keeps the falsy return for queries carrying build(q)
const pipelinable = write(toBuffer(q))
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
return q.options.onexecute
? q.options.onexecute(connection)
: pipelinableOne small difference from this PR: we run the hook even when Results ( Happy to turn this into a test for |
|
Independent verification of this PR at
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 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 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. |
|
We carry this change as it is here. One more route to the pipeline boundary at the default 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 |
|
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),
Silent write loss: the session left
We applied this PR to 3.4.7:
We're carrying this PR as a pnpm patch on 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()
})() |
|
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 |
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