Files
orca/cloud/apps/relay/src/postgres-session-end-release-postgres.test.ts
T
Jinwoo Hong 8f117e19b1 fix(relay): destroy a pooled client whose session the server ended (#29573)
* fix(relay): destroy a pooled client whose session the server ended, and mark work that never ran

pg keeps calling a client queryable until its socket's end arrives, so a client released after
57P01 (pg_terminate_backend, shutdown) or a dropped socket went back to the pool and failed the
next caller's statement with 'Connection terminated unexpectedly'. Such clients are now released
with the error, so pg-pool discards them.

Also marks failures where no statement of the operation reached the server (acquire, a failed
BEGIN, a client dead at checkout) so a caller can tell work safe to re-run.

* fix(relay): skip ROLLBACK on an ended session, drop unused nothing-ran marking

Adds 57P04/57P05 to the session-ended codes and covers 08xxx, a dropped
socket, an ordinary 23505, and a real pg_terminate_backend.

Claude-Session: f2fe8cb5
2026-10-16 11:46:22 -07:00

42 lines
1.4 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import pg from 'pg'
import { openRelayDatabase, type RelayDatabase } from './database.js'
const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL
const describePostgres = databaseUrl ? describe : describe.skip
describePostgres('PostgreSQL session terminated by the server', () => {
let database: RelayDatabase
let admin: pg.Client
beforeAll(async () => {
// One pooled client: the next caller gets the terminated one unless it was destroyed.
database = await openRelayDatabase({ databaseUrl, dataDir: '', poolMax: 1 })
admin = new pg.Client({ connectionString: databaseUrl })
await admin.connect()
})
afterAll(async () => {
await admin.end()
await database.close()
})
it('serves the next caller a live session after pg_terminate_backend', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
try {
const failure = await database
.transaction(async (tx) => {
const [row] = await tx.query('SELECT pg_backend_pid() AS pid')
await admin.query('SELECT pg_terminate_backend($1)', [row?.pid])
await tx.query('SELECT 1')
})
.catch((error: unknown) => error)
expect(failure).toBeInstanceOf(Error)
await expect(database.query('SELECT 1 AS ok')).resolves.toEqual([{ ok: 1 }])
} finally {
vi.restoreAllMocks()
}
})
})