Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(control-api): protect the shared PostgreSQL teardown boundary

Alfredo Lopez72c7a58bb414
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 641cde629..c57d40107 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.691",
+ "version": "0.1.692",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.691",
+ "version": "0.1.692",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 392a3831e..8acf89846 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.691",
+ "version": "0.1.692",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/helpers.realPostgresTeardown.test.ts b/control-api/test/helpers.realPostgresTeardown.test.ts
index 8dfd7fb5e..a0572825c 100644
--- a/control-api/test/helpers.realPostgresTeardown.test.ts
+++ b/control-api/test/helpers.realPostgresTeardown.test.ts
@@ -12,6 +12,8 @@ import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
// end() resolves at once and the test decides when each client finishes
// closing.
class FakeClient extends EventEmitter {
+ onClosed?: () => void
+
constructor(public _ended = false) {
super()
}
@@ -19,19 +21,38 @@ class FakeClient extends EventEmitter {
finishClosing(): void {
this._ended = true
this.emit('end')
+ this.onClosed?.()
}
}
-class FakePool {
- readonly end = vi.fn(async () => {})
- constructor(readonly _clients: unknown) {}
+class FakePool extends EventEmitter {
+ readonly end = vi.fn(async () => {
+ if (!Array.isArray(this._clients)) return
+ for (const client of this._clients.splice(0) as FakeClient[]) {
+ if (client._ended) this.emit('remove', client)
+ else client.onClosed = () => void this.emit('remove', client)
+ }
+ })
+
+ get totalCount(): number {
+ return Array.isArray(this._clients) ? this._clients.length : 0
+ }
+
+ constructor(readonly _clients: unknown) {
+ super()
+ }
}
async function settledAfterMicrotasks(promise: Promise<void>): Promise<boolean> {
let settled = false
- void promise.then(() => {
- settled = true
- })
+ void promise.then(
+ () => {
+ settled = true
+ },
+ () => {
+ settled = true
+ }
+ )
for (let i = 0; i < 10; i += 1) await Promise.resolve()
return settled
}
@@ -76,6 +97,61 @@ describe('endPoolAndWaitForClients', () => {
expect(client.listenerCount('end')).toBe(0)
})
+ it.each(['client closure', 'pool.end()'] as const)(
+ 'rejects within five seconds when %s never settles and removes its listeners and timer',
+ async phase => {
+ vi.useFakeTimers()
+ try {
+ const client = new FakeClient()
+ const pool = new FakePool([client])
+ if (phase === 'pool.end()') {
+ pool.end.mockImplementationOnce(() => new Promise<void>(() => {}))
+ }
+ const done = endPoolAndWaitForClients(pool as unknown as Pool)
+ const errorListeners = pool.listeners('error')
+ expect(errorListeners).toHaveLength(1)
+ const outcome = done.then(
+ () => undefined,
+ (error: unknown) => error
+ )
+
+ await vi.advanceTimersByTimeAsync(4_999)
+ expect(await settledAfterMicrotasks(done)).toBe(false)
+ expect(client.listenerCount('end')).toBe(1)
+
+ await vi.advanceTimersByTimeAsync(1)
+ expect(await settledAfterMicrotasks(done)).toBe(true)
+ expect(await outcome).toMatchObject({
+ message: 'Timed out after 5000ms waiting for pg pool clients to close',
+ })
+ expect(pool.end).toHaveBeenCalledTimes(1)
+ expect(client.listenerCount('end')).toBe(0)
+ expect(pool.listeners('error')).toEqual(errorListeners)
+ expect(vi.getTimerCount()).toBe(0)
+ client.finishClosing()
+ } finally {
+ vi.useRealTimers()
+ }
+ }
+ )
+
+ it('clears the deadline after a successful close or an end() rejection', async () => {
+ vi.useFakeTimers()
+ try {
+ const pool = new FakePool([])
+ await endPoolAndWaitForClients(pool as unknown as Pool)
+ expect(vi.getTimerCount()).toBe(0)
+
+ pool.end.mockRejectedValueOnce(new Error('pool end failed'))
+ await expect(endPoolAndWaitForClients(pool as unknown as Pool)).rejects.toThrow(
+ 'pool end failed'
+ )
+ expect(vi.getTimerCount()).toBe(0)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('throws before end() when pg-pool no longer keeps _clients as an array', async () => {
const pool = new FakePool(new Set([new FakeClient()]))
await expect(endPoolAndWaitForClients(pool as unknown as Pool)).rejects.toThrow(
@@ -89,6 +165,46 @@ describe('endPoolAndWaitForClients', () => {
await expect(endPoolAndWaitForClients(null)).resolves.toBeUndefined()
})
+ it('rejects an unexpected pool error during end and preserves the earlier observer', async () => {
+ const pool = new FakePool([])
+ const earlierObserver = vi.fn()
+ const error = Object.assign(new Error('unexpected pool failure'), { code: 'XX000' })
+ pool.on('error', earlierObserver)
+ pool.end.mockImplementationOnce(async () => {
+ pool.emit('error', error)
+ })
+
+ await expect(endPoolAndWaitForClients(pool as unknown as Pool)).rejects.toBe(error)
+ expect(earlierObserver).toHaveBeenCalledWith(error)
+ expect(pool.listeners('error')).toHaveLength(2)
+ expect(pool.listeners('error')[0]).toBe(earlierObserver)
+ })
+
+ it('keeps prior real-pool listeners, exposes unexpected errors, and adds no observer on a repeated end', async () => {
+ const pool = new Pool({ host: '127.0.0.1', port: 1, user: 'unused', database: 'unused' })
+ const earlierObserver = vi.fn()
+ pool.on('error', earlierObserver)
+ await endPoolAndWaitForClients(pool)
+ const listeners = pool.listeners('error')
+ expect(listeners).toHaveLength(2)
+ expect(listeners[0]).toBe(earlierObserver)
+
+ await expect(endPoolAndWaitForClients(pool)).rejects.toThrow(
+ 'Called end on pool more than once'
+ )
+ expect(pool.listeners('error')).toEqual(listeners)
+
+ const expected = Object.assign(new Error('backend terminated during teardown'), {
+ code: '57P01',
+ })
+ expect(() => pool.emit('error', expected)).not.toThrow()
+ expect(earlierObserver).toHaveBeenLastCalledWith(expected)
+ const unexpected = Object.assign(new Error('unexpected pool failure'), { code: 'XX000' })
+ expect(() => pool.emit('error', unexpected)).toThrow(unexpected)
+ expect(earlierObserver).toHaveBeenLastCalledWith(unexpected)
+ expect(pool.listeners('error')).toEqual(listeners)
+ })
+
it('ends a real pg Pool that never connected', async () => {
// Never connects: nothing checks a client out before end().
const pool = new Pool({ host: '127.0.0.1', port: 1, user: 'unused', database: 'unused' })
@@ -117,11 +233,14 @@ const READY_FOR_QUERY_IDLE = Buffer.from([0x5a, 0, 0, 0, 5, 0x49])
const TERMINATE = 0x58
async function startPgWireStub(
- options: { closeDelayMsByConnection: readonly number[] } | { dropEveryConnection: true }
+ options: { closeDelayMsByConnection: readonly (number | null)[] } | { dropEveryConnection: true }
): Promise<PgWireStub> {
let accepted = 0
let terminates = 0
+ const sockets = new Set<Socket>()
const server = net.createServer({ allowHalfOpen: true }, (socket: Socket) => {
+ sockets.add(socket)
+ socket.once('close', () => sockets.delete(socket))
const index = accepted
accepted += 1
if ('dropEveryConnection' in options) {
@@ -156,7 +275,9 @@ async function startPgWireStub(
pending = pending.subarray(1 + length)
if (type === TERMINATE) {
terminates += 1
- setTimeout(() => socket.end(), closeDelayMs)
+ // null deliberately holds this connection until fixture cleanup so
+ // a test can forward a late client error after the helper returns.
+ if (closeDelayMs !== null) setTimeout(() => socket.end(), closeDelayMs)
}
}
})
@@ -166,8 +287,12 @@ async function startPgWireStub(
return {
port,
terminates: () => terminates,
- close: () =>
- new Promise<void>((resolve, reject) => server.close(err => (err ? reject(err) : resolve()))),
+ close: () => {
+ for (const socket of sockets) socket.destroy()
+ return new Promise<void>((resolve, reject) =>
+ server.close(err => (err ? reject(err) : resolve()))
+ )
+ },
}
}
@@ -205,7 +330,48 @@ async function settleWithin(promise: Promise<void>, ms: number): Promise<'resolv
}
describe('endPoolAndWaitForClients against a real pg Pool and a PG wire stub', () => {
- it('resolves when a client still connecting at end() fails to connect (R4-M1)', async () => {
+ it.each(['57P01', 'XX000'])(
+ 'handles a removed client forwarding %s after the helper returns',
+ async code => {
+ const stub = await startPgWireStub({ closeDelayMsByConnection: [null, 0] })
+ const pool = stubPool(stub.port)
+ const emit = vi.spyOn(pool, 'emit')
+ try {
+ const removed = await pool.connect()
+ const held = await pool.connect()
+ held.release()
+ removed.release(true)
+ expect(pool.totalCount).toBe(1)
+
+ await endPoolAndWaitForClients(pool)
+
+ expect(pool.ended).toBe(true)
+ expect(pool.totalCount).toBe(0)
+ expect(socketOf(held).destroyed).toBe(true)
+ expect(socketOf(removed).destroyed).toBe(false)
+ emit.mockClear()
+ const error = Object.assign(new Error('late PostgreSQL client error'), { code })
+ // This is the real client's existing pg-pool idleListener. The emit
+ // spy passes through and adds no pool error listener that could hide
+ // missing helper protection. Unexpected errors must still escape.
+ const forward = (): void => {
+ removed.emit('error', error)
+ }
+ if (code === '57P01') expect(forward).not.toThrow()
+ else expect(forward).toThrow(error)
+
+ const forwarded = emit.mock.calls.filter(([event]) => event === 'error')
+ expect(forwarded).toHaveLength(1)
+ expect(forwarded[0]?.[1]).toBe(error)
+ expect(forwarded[0]?.[2]).toBe(removed)
+ } finally {
+ emit.mockRestore()
+ await stub.close()
+ }
+ }
+ )
+
+ it('resolves when a client still connecting at end() fails to connect', async () => {
const stub = await startPgWireStub({ dropEveryConnection: true })
try {
const pool = stubPool(stub.port)
@@ -230,7 +396,7 @@ describe('endPoolAndWaitForClients against a real pg Pool and a PG wire stub', (
}
})
- it('resolves only after every idle client has closed its socket (R4-M3)', async () => {
+ it('resolves only after every idle client has closed its socket', async () => {
const stub = await startPgWireStub({ closeDelayMsByConnection: [40, 120] })
try {
const pool = stubPool(stub.port)
@@ -255,7 +421,7 @@ describe('endPoolAndWaitForClients against a real pg Pool and a PG wire stub', (
}
})
- it('waits for the client it holds, not for one the pool removed before end() (R4-L12)', async () => {
+ it('waits for the client it holds, not for one the pool removed before end()', async () => {
const stub = await startPgWireStub({ closeDelayMsByConnection: [20, 300] })
try {
const pool = stubPool(stub.port)
diff --git a/control-api/test/helpers/realPostgresTeardown.ts b/control-api/test/helpers/realPostgresTeardown.ts
index 776885187..c8875cf39 100644
--- a/control-api/test/helpers/realPostgresTeardown.ts
+++ b/control-api/test/helpers/realPostgresTeardown.ts
@@ -10,6 +10,17 @@ interface ClosingClient {
off(event: 'end', listener: () => void): unknown
}
+// A removed client's pg-pool idleListener can still forward an error after
+// end() returns. Keep this shared observer on the ended pool for that late
+// teardown phase. Only PostgreSQL's expected backend-termination code is
+// handled; an unexpected error still escapes unchanged, including when an
+// earlier listener merely observed it. This function holds no pool reference.
+function handlePoolTeardownError(error: unknown): void {
+ if (error !== null && typeof error === 'object' && 'code' in error && error.code === '57P01')
+ return
+ throw error
+}
+
/**
* Ends a pg pool and resolves only after every client it held at end() has
* closed its connection.
@@ -18,17 +29,17 @@ interface ClosingClient {
* client.end() it started is still in flight. A real-Postgres teardown that
* then runs pg_terminate_backend can reach a client that is still closing; the
* 57P01 it receives is re-emitted on the pool and, with no pool `error`
- * listener, fails the run as an unhandled error (#946).
+ * listener, fails the run as an unhandled error.
*
* The helper snapshots the clients the pool holds before end() and waits for
* each one by identity. Counting pool `remove` events against `totalCount` is
* wrong both ways (pg-pool 3.13.0, `pg-pool/index.js`):
* - a client still connecting is in `_clients` (:242), but a failed connect
* (:271-274) or a rejected onConnect (:294-295) drops it without `_remove`,
- * so no `remove` is ever emitted and the wait never ends (R4-M1);
+ * so no `remove` is ever emitted and the wait never ends;
* - a client removed before end() (release(true), expiry, idle timeout) is no
* longer counted, yet `_remove` (:172-188) still emits its `remove` when its
- * connection closes, which stands in for a client still closing (R4-L12).
+ * connection closes, which stands in for a client still closing.
*
* pg 8.20.0 `pg/lib/client.js` sets `_ended` (:184) and emits `end` (:202-204)
* from the connection's `end` handler (:179), which `pg/lib/connection.js`
@@ -39,8 +50,13 @@ interface ClosingClient {
* before ending the pool, rather than wait on something it cannot read.
*
* Scope: a client the pool had already removed before end() is not in the
- * snapshot and is not waited for; a teardown that needs it closed must end it
- * before calling this helper.
+ * snapshot and is not waited for. Before ending the pool, the helper installs
+ * one retained error observer for the 57P01 such a client can still forward.
+ * Earlier listeners are preserved; unexpected errors remain visible/failing.
+ *
+ * The five-second deadline covers both pool.end() and client closure, below
+ * the ordinary ten-second test hook limit. A stuck close rejects explicitly;
+ * it does not authorize terminating a backend whose client is still open.
*
* A pool that was never created (setup failed first) is left alone, as the
* `pool?.end()` it replaces did.
@@ -51,6 +67,9 @@ export async function endPoolAndWaitForClients(pool: Pool | null | undefined): P
if (!Array.isArray(clients)) {
throw new Error('pg-pool internals changed: _clients is not an array')
}
+ if (!pool.listeners('error').includes(handlePoolTeardownError)) {
+ pool.on('error', handlePoolTeardownError)
+ }
const listeners: Array<[ClosingClient, () => void]> = []
const closed = (clients as ClosingClient[]).map(
client =>
@@ -64,10 +83,22 @@ export async function endPoolAndWaitForClients(pool: Pool | null | undefined): P
client.once('end', onEnd)
})
)
+ let timer: NodeJS.Timeout | undefined
try {
- await pool.end()
- await Promise.all(closed)
+ await Promise.race([
+ (async () => {
+ await pool.end()
+ await Promise.all(closed)
+ })(),
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Timed out after 5000ms waiting for pg pool clients to close')),
+ 5_000
+ )
+ }),
+ ])
} finally {
+ clearTimeout(timer)
for (const [client, onEnd] of listeners) client.off('end', onEnd)
}
}
diff --git a/control-api/test/realPostgresTeardown.guard.test.ts b/control-api/test/realPostgresTeardown.guard.test.ts
index a2c56720d..904b24337 100644
--- a/control-api/test/realPostgresTeardown.guard.test.ts
+++ b/control-api/test/realPostgresTeardown.guard.test.ts
@@ -2,46 +2,199 @@ import { describe, expect, it } from 'vitest'
import { readFileSync, readdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
+import * as ts from 'typescript'
// A real-Postgres suite that ends a pg pool with a plain `.end()` and later runs
// pg_terminate_backend against the same database can reach a client that is
// still closing: pg-pool's end() resolves before each client's connection has
// closed, and the 57P01 the terminate sends that client is re-emitted on the
-// pool as an unhandled error (#946). Such a pool must be ended through
+// pool as an unhandled error. Such a pool must be ended through
// endPoolAndWaitForClients. The only pool a suite may still end with a plain
// `.end()` is the one that runs the terminate: its own connection is excluded
// by `pid <> pg_backend_pid()` and nothing terminates it afterwards.
//
-// The rule is lexical and deliberately narrow: in each test/*.realPostgres*
-// suite that contains pg_terminate_backend, every argument-less `.end()` —
-// plain, optional-chained (`?.end()`) or on a parenthesised or indexed
-// receiver — whose receiver is not the identifier that issues the terminate
-// query is a violation, wherever it sits in the file (beforeAll, a test body,
-// afterAll). `.end(<arg>)` is an http request or stream, not a pg pool.
+// The scan uses TypeScript's local bindings, without loading dependencies or
+// following imports. It recognizes named pg Pool imports, typed/constructed
+// local pools, aliases, and destructured methods. Formatting, computed 'end'
+// access, and callback arguments do not change a pool's identity. HTTP/stream
+// ends are outside this rule. It does not resolve dynamic receivers, factory
+// returns without a Pool type, or cross-file/data-flow aliases. Terminate SQL
+// must contain a literal pg_terminate_backend in a direct query call.
+// The helper's retained error observer is proven behaviorally with a real pg
+// Pool and its removed-client forwarding listener in the helper test suite.
const testDir = dirname(fileURLToPath(import.meta.url))
const REAL_POSTGRES_SUITE = /\.realPostgres.*\.test\.ts$/
-const TERMINATE_QUERY = /\b(\w+)\.query(?:<[^>]*>)?\(\s*`[^`]*pg_terminate_backend/g
-const PLAIN_END = /([\w)\]]+)\??\.end\(\)/g
+type PoolBinding = ts.Symbol | ts.NewExpression
interface ScannedSuite {
file: string
terminators: string[]
- plainEnds: number
+ poolEnds: number
+ terminateQueries: number
+ parseErrors: string[]
+ unresolvedTerminators: string[]
violations: string[]
}
-function lineOf(source: string, index: number): number {
- return source.slice(0, index).split('\n').length
+function unwrap(expression: ts.Expression): ts.Expression {
+ while (
+ ts.isParenthesizedExpression(expression) ||
+ ts.isAsExpression(expression) ||
+ ts.isTypeAssertionExpression(expression) ||
+ ts.isNonNullExpression(expression) ||
+ ts.isSatisfiesExpression(expression)
+ )
+ expression = expression.expression
+ return expression
+}
+
+function memberReceiver(expression: ts.Expression, name: string): ts.Expression | undefined {
+ expression = unwrap(expression)
+ if (ts.isPropertyAccessExpression(expression) && expression.name.text === name) {
+ return expression.expression
+ }
+ if (
+ ts.isElementAccessExpression(expression) &&
+ ts.isStringLiteralLike(expression.argumentExpression) &&
+ expression.argumentExpression.text === name
+ )
+ return expression.expression
+ return undefined
}
function scanSource(file: string, source: string): ScannedSuite {
- const terminators = [...new Set([...source.matchAll(TERMINATE_QUERY)].map(match => match[1]))]
- const plainEnds = [...source.matchAll(PLAIN_END)]
- const violations = plainEnds
- .filter(match => !terminators.includes(match[1]))
- .map(match => `${file}:${lineOf(source, match.index)} ${match[0]}`)
- return { file, terminators, plainEnds: plainEnds.length, violations }
+ const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
+ const options: ts.CompilerOptions = { noLib: true, noResolve: true }
+ const host: ts.CompilerHost = {
+ ...ts.createCompilerHost(options),
+ getSourceFile: name => (name === file ? ast : undefined),
+ readFile: name => (name === file ? source : undefined),
+ fileExists: name => name === file,
+ }
+ const program = ts.createProgram([file], options, host)
+ const checker = program.getTypeChecker()
+ const importedPool = (node: ts.Node): boolean =>
+ checker.getSymbolAtLocation(node)?.declarations?.some(declaration => {
+ if (
+ !ts.isImportSpecifier(declaration) ||
+ (declaration.propertyName ?? declaration.name).text !== 'Pool'
+ )
+ return false
+ const importedFrom = declaration.parent.parent.parent
+ return (
+ ts.isImportDeclaration(importedFrom) &&
+ ts.isStringLiteral(importedFrom.moduleSpecifier) &&
+ importedFrom.moduleSpecifier.text === 'pg'
+ )
+ }) ?? false
+ const poolType = (type: ts.TypeNode): boolean =>
+ ts.isTypeReferenceNode(type)
+ ? importedPool(type.typeName)
+ : ts.isUnionTypeNode(type) && type.types.some(poolType)
+
+ function poolBinding(
+ expression: ts.Expression,
+ seen = new Set<ts.Symbol>()
+ ): PoolBinding | undefined {
+ expression = unwrap(expression)
+ if (ts.isNewExpression(expression) && importedPool(expression.expression)) return expression
+ if (!ts.isIdentifier(expression)) return undefined
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol || seen.has(symbol)) return undefined
+ seen.add(symbol)
+ const declaration = symbol.valueDeclaration
+ if (!declaration || (!ts.isVariableDeclaration(declaration) && !ts.isParameter(declaration)))
+ return undefined
+ if (declaration.initializer) {
+ const initial = unwrap(declaration.initializer)
+ if (ts.isNewExpression(initial) && importedPool(initial.expression)) return symbol
+ const alias = poolBinding(initial, seen)
+ if (alias) return alias
+ }
+ return declaration.type && poolType(declaration.type) ? symbol : undefined
+ }
+
+ function methodPool(
+ expression: ts.Expression,
+ method: string,
+ seen = new Set<ts.Symbol>()
+ ): PoolBinding | undefined {
+ expression = unwrap(expression)
+ const receiver = memberReceiver(expression, method)
+ if (receiver) return poolBinding(receiver)
+ if (!ts.isIdentifier(expression)) return undefined
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol || seen.has(symbol)) return undefined
+ seen.add(symbol)
+ const declaration = symbol.valueDeclaration
+ if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer) {
+ return methodPool(declaration.initializer, method, seen)
+ }
+ if (
+ declaration &&
+ ts.isBindingElement(declaration) &&
+ ts.isObjectBindingPattern(declaration.parent)
+ ) {
+ const property = declaration.propertyName ?? declaration.name
+ const variable = declaration.parent.parent
+ if (
+ (ts.isIdentifier(property) || ts.isStringLiteralLike(property)) &&
+ property.text === method &&
+ ts.isVariableDeclaration(variable) &&
+ variable.initializer
+ )
+ return poolBinding(variable.initializer)
+ }
+ return undefined
+ }
+
+ const calls: ts.CallExpression[] = []
+ function visit(node: ts.Node): void {
+ if (ts.isCallExpression(node)) calls.push(node)
+ ts.forEachChild(node, visit)
+ }
+ visit(ast)
+ const location = (node: ts.Node): string =>
+ `${file}:${ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1}`
+ const bindingName = (binding: PoolBinding): string =>
+ 'getName' in binding ? binding.getName() : '(new Pool)'
+ const terminationCalls = calls.filter(
+ call =>
+ memberReceiver(call.expression, 'query') &&
+ call.arguments.some(arg =>
+ ts.isStringLiteralLike(arg)
+ ? arg.text.includes('pg_terminate_backend')
+ : ts.isTemplateExpression(arg) &&
+ [arg.head, ...arg.templateSpans.map(span => span.literal)].some(part =>
+ part.text.includes('pg_terminate_backend')
+ )
+ )
+ )
+ const terminators = new Set<PoolBinding>()
+ const unresolvedTerminators: string[] = []
+ for (const call of terminationCalls) {
+ const pool = methodPool(call.expression, 'query')
+ if (pool) terminators.add(pool)
+ else unresolvedTerminators.push(location(call))
+ }
+ const ends = calls.flatMap(call => {
+ const pool = methodPool(call.expression, 'end')
+ return pool ? [{ call, pool }] : []
+ })
+ return {
+ file,
+ terminators: [...terminators].map(bindingName),
+ terminateQueries: terminationCalls.length,
+ poolEnds: ends.length,
+ parseErrors: program
+ .getSyntacticDiagnostics(ast)
+ .map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')),
+ unresolvedTerminators,
+ violations: ends
+ .filter(({ pool }) => !terminators.has(pool))
+ .map(({ call, pool }) => `${location(call)} ${bindingName(pool)}.end()`),
+ }
}
function scanSuites(): ScannedSuite[] {
@@ -50,12 +203,12 @@ function scanSuites(): ScannedSuite[] {
.sort()
.flatMap(file => {
const source = readFileSync(join(testDir, file), 'utf8')
- if (!source.includes('pg_terminate_backend')) return []
- return [scanSource(file, source)]
+ const suite = scanSource(file, source)
+ return suite.terminateQueries > 0 || suite.parseErrors.length > 0 ? [suite] : []
})
}
-describe('real-Postgres teardown guard (R4-L11)', () => {
+describe('real-Postgres teardown guard', () => {
it('ends every pool other than the terminating one through endPoolAndWaitForClients', () => {
const suites = scanSuites()
@@ -67,13 +220,17 @@ describe('real-Postgres teardown guard (R4-L11)', () => {
expect(suites.filter(suite => suite.terminators.length === 0).map(suite => suite.file)).toEqual(
[]
)
- expect(suites.reduce((sum, suite) => sum + suite.plainEnds, 0)).toBeGreaterThan(0)
+ expect(suites.flatMap(suite => suite.parseErrors)).toEqual([])
+ expect(suites.flatMap(suite => suite.unresolvedTerminators)).toEqual([])
+ expect(suites.reduce((sum, suite) => sum + suite.poolEnds, 0)).toBeGreaterThan(0)
expect(suites.flatMap(suite => suite.violations)).toEqual([])
})
- it('reports optional-chained, cast and chained ends, and allows the terminating pool (J2)', () => {
+ it('reports optional-chained, cast and chained ends, and allows the terminating pool', () => {
const source = [
+ "import { Pool } from 'pg'",
+ 'let adminPool: Pool, dbPool: Pool, pool: Pool, corePool: Pool',
'await adminPool.query(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity`)',
'await dbPool.end()',
'await pool?.end()',
@@ -88,10 +245,65 @@ describe('real-Postgres teardown guard (R4-L11)', () => {
// Witness: the terminate query named the pool that is allowed a plain end.
expect(suite.terminators).toEqual(['adminPool'])
expect(suite.violations).toEqual([
- 'fixture.realPostgres.test.ts:2 dbPool.end()',
- 'fixture.realPostgres.test.ts:3 pool?.end()',
- 'fixture.realPostgres.test.ts:4 Pool).end()',
- 'fixture.realPostgres.test.ts:5 corePool?.end()',
+ 'fixture.realPostgres.test.ts:4 dbPool.end()',
+ 'fixture.realPostgres.test.ts:5 pool.end()',
+ 'fixture.realPostgres.test.ts:6 dbPool.end()',
+ 'fixture.realPostgres.test.ts:7 corePool.end()',
])
})
+
+ it.each([
+ ['a split receiver', 'await appPool\n .end()'],
+ ['split arguments', 'await appPool.end(\n)'],
+ ['a computed method', "await appPool['end']()"],
+ ['a callback', 'appPool.end(() => {})'],
+ ['an optional callback', 'appPool?.end(() => {})'],
+ ['a destructured method', 'const { end } = appPool; end()'],
+ ['a renamed destructured method', 'const { end: close } = appPool; close()'],
+ ['a method alias', 'const close = appPool.end; close()'],
+ ['a shadowed administrative name', '{ const adminPool = appPool; await adminPool.end() }'],
+ ])('rejects a pool end through %s', (_name, end) => {
+ const source = [
+ "import { Pool } from 'pg'",
+ 'let adminPool: Pool',
+ 'let appPool: Pool',
+ 'await adminPool.query(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity`)',
+ end,
+ ].join('\n')
+
+ expect(scanSource('fixture.realPostgres.test.ts', source).violations).toHaveLength(1)
+ })
+
+ it('allows aliases of the terminating pool and real HTTP request ends', () => {
+ const source = [
+ "import { Pool as PgPool } from 'pg'",
+ "import * as http from 'node:http'",
+ 'const terminator = new PgPool()',
+ 'await terminator\n .query(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity`)',
+ 'const administrativeAlias = terminator',
+ 'await administrativeAlias.end(() => {})',
+ 'const req = http.request({})',
+ 'req.end()',
+ "req['end']('body')",
+ 'req.end(() => {})',
+ ].join('\n')
+
+ const suite = scanSource('fixture.realPostgres.test.ts', source)
+ expect(suite.parseErrors).toEqual([])
+ expect(suite.terminators).toEqual(['terminator'])
+ expect(suite.poolEnds).toBe(1)
+ expect(suite.violations).toEqual([])
+ })
+
+ it('reports parse errors and an unresolved terminating receiver instead of passing vacuously', () => {
+ const invalid = scanSource('fixture.realPostgres.test.ts', 'const pool = new Pool(')
+ expect(invalid.parseErrors.length).toBeGreaterThan(0)
+ const unresolved = scanSource(
+ 'fixture.realPostgres.test.ts',
+ 'pool.query(`SELECT pg_terminate_backend(pid)`)'
+ )
+ expect(unresolved.terminateQueries).toBe(1)
+ expect(unresolved.unresolvedTerminators).toEqual(['fixture.realPostgres.test.ts:1'])
+ expect(unresolved.terminators).toEqual([])
+ })
})
diff --git a/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts b/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts
index c6645c1aa..250b92bf1 100644
--- a/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts
+++ b/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts
@@ -45,7 +45,7 @@ describeRealPostgres('MCP Secret rollback permits on real PostgreSQL', () => {
afterAll(async () => {
// A concurrent consume test opens several pg clients. Wait for every one
- // of them to close before touching their backends (#946), then wait for
+ // of them to close before touching their backends, then wait for
// the backend rows to disappear before using the administrative fallback
// below.
await endPoolAndWaitForClients(pool)