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 administrative fixture cleanup

Alfredo Lopezdf93ccf77559
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 8cd4a6784..fab665aa2 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.703",
+ "version": "0.1.704",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.703",
+ "version": "0.1.704",
"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 67e4cf3ee..04b010bb3 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.703",
+ "version": "0.1.704",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts b/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts
index d101e4bfc..1ec520c5d 100644
--- a/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts
+++ b/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts
@@ -48,12 +48,15 @@ describeRealPostgres('Codex subscription connection on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts b/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts
index eb1dab8f0..811477dd4 100644
--- a/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts
+++ b/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts
@@ -64,17 +64,20 @@ describeRealPostgres('listGrantsReferencingModel jsonb containment on real Postg
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
- FROM pg_stat_activity
- WHERE datname = $1
- AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
+ FROM pg_stat_activity
+ WHERE datname = $1
+ AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ } finally {
+ await adminPool?.end()
+ }
})
async function insertGrant(
diff --git a/control-api/test/db.llmProviderAttemptConnectionIntegrity.realPostgres.integration.test.ts b/control-api/test/db.llmProviderAttemptConnectionIntegrity.realPostgres.integration.test.ts
index bb915dd36..a3e6ad43b 100644
--- a/control-api/test/db.llmProviderAttemptConnectionIntegrity.realPostgres.integration.test.ts
+++ b/control-api/test/db.llmProviderAttemptConnectionIntegrity.realPostgres.integration.test.ts
@@ -75,12 +75,15 @@ describeRealPostgres('0114 llm_provider_attempts connection integrity on real Po
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts
index 028874521..ce82ffae5 100644
--- a/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts
+++ b/control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts
@@ -158,17 +158,20 @@ describeRealPostgres('Plugin Workload SDK runtime-contract upgrade on real Postg
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
- FROM pg_stat_activity
- WHERE datname = $1
- AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
+ FROM pg_stat_activity
+ WHERE datname = $1
+ AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index a54a7ebd6..be4d9bb61 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -140,17 +140,20 @@ describeRealPostgres('control-api real Postgres migrations', () => {
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
- FROM pg_stat_activity
- WHERE datname = $1
- AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
+ FROM pg_stat_activity
+ WHERE datname = $1
+ AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/entityChangeFeed.realPostgres.integration.test.ts b/control-api/test/entityChangeFeed.realPostgres.integration.test.ts
index 4513377c4..a0adee818 100644
--- a/control-api/test/entityChangeFeed.realPostgres.integration.test.ts
+++ b/control-api/test/entityChangeFeed.realPostgres.integration.test.ts
@@ -40,16 +40,19 @@ describeRealPostgres('entity change feed real PostgreSQL contract', () => {
})
afterAll(async () => {
- await endPoolAndWaitForClients(instancePool)
- await endPoolAndWaitForClients(replicaPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(instancePool)
+ await endPoolAndWaitForClients(replicaPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
index 56253d535..547f095d5 100644
--- a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
+++ b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
@@ -50,15 +50,18 @@ describeRealPostgres('GFS typed audit decision evidence', () => {
}, 60_000)
afterAll(async () => {
- await endPoolAndWaitForClients(pool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(pool)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('is additive, idempotent, and constrains the evidence vocabulary', async () => {
diff --git a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
index 2be7c4ea7..56f6f5777 100644
--- a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
+++ b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
@@ -36,15 +36,18 @@ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await endPoolAndWaitForClients(pool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(pool)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('applies 0071_gfs_immutable_blob_generations exactly once with named constraints, indexes, and writer ACL', async () => {
diff --git a/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts b/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts
index 466b1103d..7c73b0a77 100644
--- a/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts
+++ b/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts
@@ -102,16 +102,19 @@ describeRealPostgres('GFS blob reconciliation on real PostgreSQL + on-disk BlobS
})
afterAll(async () => {
- await endPoolAndWaitForClients(pool)
- await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(pool)
+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('reaps an orphaned generation blob: deletes the real bytes AND removes the manifest row', async () => {
diff --git a/control-api/test/gfsCopy.realPostgres.integration.test.ts b/control-api/test/gfsCopy.realPostgres.integration.test.ts
index 6b2de688c..90fe1e84b 100644
--- a/control-api/test/gfsCopy.realPostgres.integration.test.ts
+++ b/control-api/test/gfsCopy.realPostgres.integration.test.ts
@@ -155,16 +155,19 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem blo
}, 60_000)
afterAll(async () => {
- await endPoolAndWaitForClients(pool)
- await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(pool)
+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('publishes a recursive copy atomically, preserves the source, and records success in the publication transaction', async () => {
diff --git a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
index 48c12186f..6b8b4b0a9 100644
--- a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
@@ -63,20 +63,23 @@ describeRealPostgres('GFS reader and writer login isolation', () => {
}, 60_000)
afterAll(async () => {
- await endPoolAndWaitForClients(readerPool)
- await endPoolAndWaitForClients(writerPool)
- await pool?.query('ALTER ROLE gfs_controller NOLOGIN NOINHERIT').catch(() => undefined)
- await pool?.query('ALTER ROLE gfs_controller_reader NOLOGIN NOINHERIT').catch(() => undefined)
- await pool?.query(`DROP ROLE IF EXISTS ${quoteIdent(inheritedRole)}`).catch(() => undefined)
- await endPoolAndWaitForClients(pool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ await endPoolAndWaitForClients(readerPool)
+ await endPoolAndWaitForClients(writerPool)
+ await pool?.query('ALTER ROLE gfs_controller NOLOGIN NOINHERIT').catch(() => undefined)
+ await pool?.query('ALTER ROLE gfs_controller_reader NOLOGIN NOINHERIT').catch(() => undefined)
+ await pool?.query(`DROP ROLE IF EXISTS ${quoteIdent(inheritedRole)}`).catch(() => undefined)
+ await endPoolAndWaitForClients(pool)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('authenticates distinct DSNs as the exact NOINHERIT runtime identities', async () => {
diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
index 5609137a1..a230e7648 100644
--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
@@ -60,15 +60,18 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {
}, 60_000)
afterAll(async () => {
- await endPoolAndWaitForClients(pool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(pool)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('fails Control API readiness while the latest migration is absent', async () => {
diff --git a/control-api/test/gfsUploadFinalizer.realPostgres.integration.test.ts b/control-api/test/gfsUploadFinalizer.realPostgres.integration.test.ts
index 8445ff051..ef5a221a5 100644
--- a/control-api/test/gfsUploadFinalizer.realPostgres.integration.test.ts
+++ b/control-api/test/gfsUploadFinalizer.realPostgres.integration.test.ts
@@ -114,21 +114,26 @@ describeRealPostgres('GFS upload finalizer on real PostgreSQL + BlobStore', () =
}, 60_000)
afterAll(async () => {
- await pool?.query('DELETE FROM gfs_resources WHERE drive = $1', [drive]).catch(() => undefined)
- await pool
- ?.query('DELETE FROM gfs_upload_sessions WHERE drive = $1', [drive])
- .catch(() => undefined)
- await endPoolAndWaitForClients(pool)
- await rm(storageRoot, { recursive: true, force: true }).catch(() => undefined)
- await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await pool
+ ?.query('DELETE FROM gfs_resources WHERE drive = $1', [drive])
+ .catch(() => undefined)
+ await pool
+ ?.query('DELETE FROM gfs_upload_sessions WHERE drive = $1', [drive])
+ .catch(() => undefined)
+ await endPoolAndWaitForClients(pool)
+ await rm(storageRoot, { recursive: true, force: true }).catch(() => undefined)
+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
async function seedUpload(): Promise<{ upload: UploadSessionRow; uploadPart: UploadPartRow }> {
diff --git a/control-api/test/gfsUploadSession.realPostgres.integration.test.ts b/control-api/test/gfsUploadSession.realPostgres.integration.test.ts
index 0a8c370fa..88939d6cf 100644
--- a/control-api/test/gfsUploadSession.realPostgres.integration.test.ts
+++ b/control-api/test/gfsUploadSession.realPostgres.integration.test.ts
@@ -160,19 +160,22 @@ describeRealPostgres('GFS Upload v2 session engine on real PostgreSQL', () => {
})
afterAll(async () => {
- await pool
- ?.query('DELETE FROM gfs_upload_sessions WHERE drive = $1', [drive])
- .catch(() => undefined)
- await endPoolAndWaitForClients(pool)
- await rm(tempRoot, { recursive: true, force: true }).catch(() => undefined)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ try {
+ await pool
+ ?.query('DELETE FROM gfs_upload_sessions WHERE drive = $1', [drive])
+ .catch(() => undefined)
+ await endPoolAndWaitForClients(pool)
+ await rm(tempRoot, { recursive: true, force: true }).catch(() => undefined)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
+ }
})
it('serializes concurrent idempotent creates to one session and rejects a changed fingerprint', async () => {
diff --git a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
index f2b9b22e1..bde99eba6 100644
--- a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
@@ -116,15 +116,18 @@ describeRealPostgres(
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
index b3f2274c4..71017d311 100644
--- a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
@@ -55,15 +55,18 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts
index 4661bc785..0ee71d5b3 100644
--- a/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts
@@ -136,15 +136,18 @@ describeRealPostgres('dynamicClientStore install identity (real Postgres)', () =
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts
index d99b48b2f..13c5500a3 100644
--- a/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts
@@ -93,15 +93,18 @@ describeRealPostgres(
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts b/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
index 3e5ff9e8d..c929c2ccb 100644
--- a/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
@@ -73,15 +73,18 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
index b68a8f570..a9885ae92 100644
--- a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
@@ -60,15 +60,18 @@ describeRealPostgres('teardownMcpServerOAuthState — fenced by cr_uid (real Pos
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
@@ -275,15 +278,18 @@ describeRealPostgres('grant cr_uid sealing (D-T3, real Postgres)', () => {
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts b/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts
index da7a98e09..91acf0a2e 100644
--- a/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts
@@ -72,15 +72,18 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts
index 05808df92..3582dadca 100644
--- a/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts
@@ -86,15 +86,18 @@ describeRealPostgres(
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts b/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
index a358c6862..cc822e9f0 100644
--- a/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
@@ -75,15 +75,18 @@ describeRealPostgres('oauth reactive refresh — row-lock serialization (real Po
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts b/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts
index 3b4f91725..e17309be4 100644
--- a/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts
@@ -117,15 +117,18 @@ describeRealPostgres('grant readers fenced by the live installation uid (real Po
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts b/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
index 3976e885e..9e88e7587 100644
--- a/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
@@ -49,15 +49,18 @@ describeRealPostgres('oauth store — shared grants (real Postgres)', () => {
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts b/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts
index 6d56d6e9f..d0e86ba5c 100644
--- a/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts
@@ -55,15 +55,18 @@ describeRealPostgres('listUserOAuthGrants / listUserGrantsForServer (real Postgr
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
- WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
index ce5157e49..317c8387b 100644
--- a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
+++ b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
@@ -230,12 +230,15 @@ describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL',
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/pluginWorkloadSdkGrantUpdateNotify.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkGrantUpdateNotify.realPostgres.integration.test.ts
index 6394b2452..284c0f5fa 100644
--- a/control-api/test/pluginWorkloadSdkGrantUpdateNotify.realPostgres.integration.test.ts
+++ b/control-api/test/pluginWorkloadSdkGrantUpdateNotify.realPostgres.integration.test.ts
@@ -107,28 +107,31 @@ describeRealPostgres(
afterAll(async () => {
try {
- await listenClient?.query(`UNLISTEN ${sdk.PLUGIN_WORKLOAD_SDK_GRANT_UPDATE_CHANNEL}`)
- } catch {
- /* teardown */
- }
- listenClient?.release()
- await endPoolAndWaitForClients(listenPool)
- await endPoolAndWaitForClients(db?.pool)
- await endPoolAndWaitForClients(db?.rateLimitPool)
- if (previousPgConnectionString === undefined) {
- delete process.env.CONTROL_API_PG_CONNECTION_STRING
- } else {
- process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgConnectionString
- }
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
+ try {
+ await listenClient?.query(`UNLISTEN ${sdk.PLUGIN_WORKLOAD_SDK_GRANT_UPDATE_CHANNEL}`)
+ } catch {
+ /* teardown */
+ }
+ listenClient?.release()
+ await endPoolAndWaitForClients(listenPool)
+ await endPoolAndWaitForClients(db?.pool)
+ await endPoolAndWaitForClients(db?.rateLimitPool)
+ if (previousPgConnectionString === undefined) {
+ delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ } else {
+ process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgConnectionString
+ }
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts
index a52001d73..025f2259e 100644
--- a/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts
+++ b/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts
@@ -122,13 +122,16 @@ describeRealPostgres('Plugin Workload SDK Grok dual ledger on real PostgreSQL',
}, 60_000)
afterAll(async () => {
- config.grokSubscriptionEnabled = previousFlag
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ config.grokSubscriptionEnabled = previousFlag
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts
index 2e2464eae..d72386580 100644
--- a/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts
+++ b/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts
@@ -34,17 +34,21 @@ describeRealPostgres('Plugin Workload SDK policy review provenance on real Postg
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = $1
AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
it('re-fences complete-looking active rows without provenance and never reactivates them', async () => {
diff --git a/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts
index 35808cd86..8f572010e 100644
--- a/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts
+++ b/control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts
@@ -110,23 +110,26 @@ describeRealPostgres(
})
afterAll(async () => {
- await endPoolAndWaitForClients(db?.pool)
- await endPoolAndWaitForClients(db?.rateLimitPool)
- if (previousPgConnectionString === undefined) {
- delete process.env.CONTROL_API_PG_CONNECTION_STRING
- } else {
- process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgConnectionString
- }
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
+ try {
+ await endPoolAndWaitForClients(db?.pool)
+ await endPoolAndWaitForClients(db?.rateLimitPool)
+ if (previousPgConnectionString === undefined) {
+ delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ } else {
+ process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgConnectionString
+ }
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = $1
AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/realPostgresAdminCleanup.guard.test.ts b/control-api/test/realPostgresAdminCleanup.guard.test.ts
new file mode 100644
index 000000000..c16632265
--- /dev/null
+++ b/control-api/test/realPostgresAdminCleanup.guard.test.ts
@@ -0,0 +1,758 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync, readdirSync } from 'node:fs'
+import { dirname, join, relative } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import * as ts from 'typescript'
+
+const testDir = dirname(fileURLToPath(import.meta.url))
+type PoolBinding = ts.Symbol | ts.NewExpression
+type Callback = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration
+interface Problem {
+ file: string
+ line: number
+ reason: string
+}
+interface Audit {
+ file: string
+ hooks: number
+ callbacks: number
+ protectedCallbacks: number
+ adminPools: number
+ problems: Problem[]
+}
+
+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 descendants(node: ts.Node): ts.Node[] {
+ const found: ts.Node[] = []
+ function visit(child: ts.Node): void {
+ found.push(child)
+ ts.forEachChild(child, visit)
+ }
+ visit(node)
+ return found
+}
+
+function sqlPrefix(expression: ts.Expression): string {
+ expression = unwrap(expression)
+ if (ts.isStringLiteralLike(expression)) return expression.text
+ if (ts.isTemplateExpression(expression)) return expression.head.text
+ if (
+ ts.isBinaryExpression(expression) &&
+ expression.operatorToken.kind === ts.SyntaxKind.PlusToken
+ ) {
+ return sqlPrefix(expression.left)
+ }
+ return ''
+}
+
+// This is a conservative local control-flow proof, not a receiver-name rule.
+// Pools must come from pg constructors; admin identity comes from their bound
+// CREATE/DROP DATABASE queries. A close must be awaited in a guaranteed outer
+// finally, before anything there could fail, covering preceding cleanup.
+// Unresolved imports, receivers, callbacks or equivalent flow fail explicitly.
+// No dependency source, original module or database operation is executed.
+function auditSource(file: string, source: string): Audit {
+ const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
+ const options: ts.CompilerOptions = { noLib: true, noResolve: true }
+ const program = ts.createProgram([file], options, {
+ ...ts.createCompilerHost(options),
+ getSourceFile: name => (name === file ? ast : undefined),
+ readFile: name => (name === file ? source : undefined),
+ fileExists: name => name === file,
+ })
+ const checker = program.getTypeChecker()
+ const nodes = descendants(ast)
+ const problems: Problem[] = []
+ const problem = (node: ts.Node, reason: string): void => {
+ problems.push({
+ file,
+ line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
+ reason,
+ })
+ }
+ for (const diagnostic of program.getSyntacticDiagnostics(ast)) {
+ problems.push({
+ file,
+ line: ast.getLineAndCharacterOfPosition(diagnostic.start ?? 0).line + 1,
+ reason: `PARSE: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`,
+ })
+ }
+ const writes = new Map<ts.Symbol, number>()
+ function recordWrite(identifier: ts.Identifier): void {
+ const symbol = checker.getSymbolAtLocation(identifier)
+ if (symbol) writes.set(symbol, (writes.get(symbol) ?? 0) + 1)
+ }
+ for (const node of nodes) {
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer)
+ recordWrite(node.name)
+ if (ts.isFunctionDeclaration(node) && node.name) recordWrite(node.name)
+ if (
+ ts.isBinaryExpression(node) &&
+ ts.isIdentifier(node.left) &&
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
+ )
+ recordWrite(node.left)
+ }
+ function imported(
+ expression: ts.Expression,
+ module: string,
+ name: string,
+ seen = new Set<ts.Symbol>()
+ ): boolean {
+ expression = unwrap(expression)
+ if (!ts.isIdentifier(expression)) return false
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol || seen.has(symbol) || (writes.get(symbol) ?? 0) > 1) return false
+ seen.add(symbol)
+ return (
+ symbol.declarations?.some(declaration => {
+ if (ts.isImportSpecifier(declaration)) {
+ if ((writes.get(symbol) ?? 0) !== 0) return false
+ const origin = declaration.parent.parent.parent
+ return (
+ (declaration.propertyName ?? declaration.name).text === name &&
+ ts.isImportDeclaration(origin) &&
+ ts.isStringLiteral(origin.moduleSpecifier) &&
+ origin.moduleSpecifier.text === module
+ )
+ }
+ return (
+ ts.isVariableDeclaration(declaration) &&
+ !!declaration.initializer &&
+ imported(declaration.initializer, module, name, seen)
+ )
+ }) ?? false
+ )
+ }
+ const isPoolCreation = (expression: ts.Expression): expression is ts.NewExpression => {
+ expression = unwrap(expression)
+ return ts.isNewExpression(expression) && imported(expression.expression, 'pg', 'Pool')
+ }
+ const constructed = new Set<ts.Symbol>()
+ const creationSite = new Map<ts.Symbol, ts.Node>()
+ let currentCallback: Callback | undefined
+ function enclosingFunction(node: ts.Node): Callback | undefined {
+ for (let parent = node.parent; parent; parent = parent.parent) {
+ if (
+ ts.isArrowFunction(parent) ||
+ ts.isFunctionExpression(parent) ||
+ ts.isFunctionDeclaration(parent)
+ )
+ return parent
+ }
+ return undefined
+ }
+ for (const node of nodes) {
+ let identifier: ts.Identifier | undefined
+ if (
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.initializer &&
+ isPoolCreation(node.initializer)
+ )
+ identifier = node.name
+ if (
+ ts.isBinaryExpression(node) &&
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
+ ts.isIdentifier(node.left) &&
+ isPoolCreation(node.right)
+ )
+ identifier = node.left
+ if (identifier) {
+ const symbol = checker.getSymbolAtLocation(identifier)
+ if (symbol) {
+ constructed.add(symbol)
+ creationSite.set(symbol, node)
+ }
+ }
+ }
+ for (const symbol of constructed) if (writes.get(symbol) !== 1) constructed.delete(symbol)
+ function poolBinding(
+ expression: ts.Expression,
+ seen = new Set<ts.Symbol>()
+ ): PoolBinding | undefined {
+ expression = unwrap(expression)
+ if (isPoolCreation(expression)) return expression
+ if (!ts.isIdentifier(expression)) return undefined
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol || seen.has(symbol)) return undefined
+ if ((writes.get(symbol) ?? 0) > 1) return undefined
+ if (constructed.has(symbol)) return symbol
+ seen.add(symbol)
+ const declaration = symbol.valueDeclaration
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer)
+ return undefined
+ const alias = poolBinding(declaration.initializer, seen)
+ if (!alias || !('getName' in alias)) return alias
+ const created = creationSite.get(alias)
+ const scope = enclosingFunction(declaration)
+ // A top-level alias cannot capture a mutable pool that is assigned only
+ // when beforeAll runs. Aliases inside the actual cleanup callback, or
+ // after construction in the same executing scope, are resolvable.
+ return created &&
+ ((scope === enclosingFunction(created) && declaration.pos > created.pos) ||
+ (ts.isVariableDeclaration(created) && declaration.pos > created.pos) ||
+ (currentCallback &&
+ scope === currentCallback &&
+ beforeAllScopes.has(enclosingFunction(created)!)))
+ ? alias
+ : undefined
+ }
+ const calls = nodes.filter(ts.isCallExpression)
+ const beforeAllScopes = new Set<Callback>()
+ for (const call of calls) {
+ if (!imported(call.expression, 'vitest', 'beforeAll') || !call.arguments[0]) continue
+ const setup = callback(call.arguments[0])
+ if (setup) beforeAllScopes.add(setup)
+ }
+ const administrative = new Set<PoolBinding>()
+ const administrativeOrigin = new Map<PoolBinding, ts.Node>()
+ function resolvedSqlPrefix(expression: ts.Expression, seen = new Set<ts.Symbol>()): string {
+ expression = unwrap(expression)
+ if (!ts.isIdentifier(expression)) return sqlPrefix(expression)
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol || seen.has(symbol) || writes.get(symbol) !== 1) return ''
+ seen.add(symbol)
+ const declaration = symbol.valueDeclaration
+ return declaration &&
+ ts.isVariableDeclaration(declaration) &&
+ declaration.initializer &&
+ ts.isVariableDeclarationList(declaration.parent) &&
+ declaration.parent.flags & ts.NodeFlags.Const
+ ? resolvedSqlPrefix(declaration.initializer, seen)
+ : ''
+ }
+ for (const call of calls) {
+ const receiver = memberReceiver(call.expression, 'query')
+ if (
+ !receiver ||
+ !call.arguments[0] ||
+ !/^\s*(?:CREATE|DROP)\s+DATABASE\b/i.test(resolvedSqlPrefix(call.arguments[0]))
+ )
+ continue
+ const pool = poolBinding(receiver)
+ if (pool) {
+ administrative.add(pool)
+ administrativeOrigin.set(pool, call)
+ } else problem(call, 'UNRESOLVED administrative query receiver')
+ }
+ function callback(expression: ts.Expression, seen = new Set<ts.Symbol>()): Callback | undefined {
+ expression = unwrap(expression)
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) return expression
+ if (!ts.isIdentifier(expression)) return undefined
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol || seen.has(symbol) || (writes.get(symbol) ?? 0) > 1) return undefined
+ seen.add(symbol)
+ const declaration = symbol.valueDeclaration
+ if (declaration && ts.isFunctionDeclaration(declaration)) return declaration
+ return declaration && ts.isVariableDeclaration(declaration) && declaration.initializer
+ ? callback(declaration.initializer, seen)
+ : undefined
+ }
+ const isEnd = (call: ts.CallExpression, pool: PoolBinding): boolean => {
+ const receiver = memberReceiver(call.expression, 'end')
+ return !!receiver && poolBinding(receiver) === pool
+ }
+ function startsWithClose(expression: ts.Expression, pool: PoolBinding): boolean {
+ expression = unwrap(expression)
+ if (!ts.isCallExpression(expression)) return false
+ if (isEnd(expression, pool)) return expression.arguments.length === 0
+ // pg Pool.end is invoked before a recovery chain such as .catch(...)
+ // evaluates its arguments. Recovery does not bypass the administrative
+ // close; it preserves the fixture's existing error-handling semantics.
+ const receiver = memberReceiver(expression.expression, 'catch')
+ return !!receiver && startsWithClose(receiver, pool)
+ }
+ for (const node of nodes) {
+ if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
+ continue
+ const receiver = memberReceiver(node.left, 'end')
+ const pool = receiver && poolBinding(receiver)
+ if (pool && administrative.has(pool))
+ problem(node, 'UNRESOLVED administrative end method reassignment')
+ }
+ const contains = (container: ts.Node, node: ts.Node): boolean =>
+ container.pos <= node.pos && container.end >= node.end
+ function unshadowedUndefined(expression: ts.Expression): boolean {
+ expression = unwrap(expression)
+ return (
+ ts.isIdentifier(expression) &&
+ expression.text === 'undefined' &&
+ !checker.getSymbolAtLocation(expression)?.declarations?.length
+ )
+ }
+ function presentWhenPoolExists(expression: ts.Expression, pool: PoolBinding): boolean {
+ expression = unwrap(expression)
+ if (poolBinding(expression) === pool) return true
+ return (
+ ts.isBinaryExpression(expression) &&
+ (expression.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
+ expression.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsToken) &&
+ poolBinding(expression.left) === pool &&
+ (expression.right.kind === ts.SyntaxKind.NullKeyword || unshadowedUndefined(expression.right))
+ )
+ }
+ function pureExpression(expression: ts.Expression): boolean {
+ expression = unwrap(expression)
+ if (
+ ts.isStringLiteralLike(expression) ||
+ ts.isNumericLiteral(expression) ||
+ expression.kind === ts.SyntaxKind.TrueKeyword ||
+ expression.kind === ts.SyntaxKind.FalseKeyword ||
+ expression.kind === ts.SyntaxKind.NullKeyword ||
+ ts.isArrowFunction(expression) ||
+ ts.isFunctionExpression(expression)
+ )
+ return true
+ if (ts.isIdentifier(expression)) {
+ if (unshadowedUndefined(expression)) return true
+ const symbol = checker.getSymbolAtLocation(expression)
+ if (!symbol?.declarations?.length) return false
+ return symbol.declarations.every(
+ declaration =>
+ !ts.isVariableDeclaration(declaration) ||
+ enclosingFunction(declaration) !== currentCallback ||
+ declaration.pos < expression.pos
+ )
+ }
+ if (ts.isArrayLiteralExpression(expression))
+ return expression.elements.every(
+ element => !ts.isSpreadElement(element) && pureExpression(element)
+ )
+ if (ts.isObjectLiteralExpression(expression)) {
+ return expression.properties.every(property => {
+ if (ts.isSpreadAssignment(property)) return false
+ if (property.name && ts.isComputedPropertyName(property.name)) {
+ const key = unwrap(property.name.expression)
+ if (!ts.isStringLiteralLike(key) && !ts.isNumericLiteral(key)) return false
+ }
+ if (ts.isPropertyAssignment(property)) return pureExpression(property.initializer)
+ if (ts.isShorthandPropertyAssignment(property)) return pureExpression(property.name)
+ return (
+ ts.isMethodDeclaration(property) ||
+ ts.isGetAccessorDeclaration(property) ||
+ ts.isSetAccessorDeclaration(property)
+ )
+ })
+ }
+ return false
+ }
+ function safePrefix(statement: ts.Statement): boolean {
+ if (ts.isEmptyStatement(statement) || ts.isFunctionDeclaration(statement)) return true
+ if (ts.isBlock(statement)) return statement.statements.every(safePrefix)
+ if (ts.isVariableStatement(statement))
+ return statement.declarationList.declarations.every(
+ declaration =>
+ ts.isIdentifier(declaration.name) &&
+ (!declaration.initializer || pureExpression(declaration.initializer))
+ )
+ if (ts.isExpressionStatement(statement)) return pureExpression(statement.expression)
+ if (ts.isIfStatement(statement)) {
+ const condition = unwrap(statement.expression)
+ if (condition.kind === ts.SyntaxKind.FalseKeyword)
+ return !statement.elseStatement || safePrefix(statement.elseStatement)
+ if (condition.kind === ts.SyntaxKind.TrueKeyword) return safePrefix(statement.thenStatement)
+ }
+ return false
+ }
+ function safeWhenAbsent(expression: ts.Expression, pool: PoolBinding): boolean {
+ expression = unwrap(expression)
+ if (!ts.isCallExpression(expression)) return false
+ if (isEnd(expression, pool)) {
+ const member = expression.expression
+ if (
+ (ts.isPropertyAccessExpression(member) || ts.isElementAccessExpression(member)) &&
+ member.questionDotToken
+ )
+ return true
+ const created = 'getName' in pool ? creationSite.get(pool) : pool
+ return !!created && (ts.isNewExpression(created) || ts.isVariableDeclaration(created))
+ }
+ const receiver = memberReceiver(expression.expression, 'catch')
+ return !!receiver && safeWhenAbsent(receiver, pool)
+ }
+ function guaranteedClose(
+ statement: ts.Statement,
+ pool: PoolBinding,
+ knownPresent = false
+ ): boolean {
+ if (ts.isBlock(statement)) return guaranteedSequence(statement.statements, pool, knownPresent)
+ if (ts.isIfStatement(statement) && presentWhenPoolExists(statement.expression, pool))
+ return guaranteedClose(statement.thenStatement, pool, true)
+ if (!ts.isExpressionStatement(statement) || !ts.isAwaitExpression(statement.expression))
+ return false
+ const expression = unwrap(statement.expression.expression)
+ return startsWithClose(expression, pool) && (knownPresent || safeWhenAbsent(expression, pool))
+ }
+ function guaranteedSequence(
+ statements: ts.NodeArray<ts.Statement>,
+ pool: PoolBinding,
+ knownPresent = false
+ ): boolean {
+ for (const statement of statements) {
+ if (ts.isEmptyStatement(statement)) continue
+ if (
+ ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.every(
+ declaration =>
+ declaration.initializer &&
+ ts.isIdentifier(unwrap(declaration.initializer)) &&
+ poolBinding(declaration.initializer) === pool
+ )
+ )
+ continue
+ return guaranteedClose(statement, pool, knownPresent)
+ }
+ return false
+ }
+ let hooks = 0
+ let callbacks = 0
+ let protectedCallbacks = 0
+ let adminPools = 0
+ const closedByCallbacks = new Map<PoolBinding, number>()
+ for (const call of calls) {
+ const registered = imported(call.expression, 'vitest', 'afterAll')
+ const apparent = ts.isIdentifier(call.expression) && call.expression.text === 'afterAll'
+ if (!registered && !apparent) continue
+ hooks += 1
+ if (!registered) {
+ problem(call, 'UNRESOLVED afterAll registration')
+ continue
+ }
+ const cleanup = call.arguments[0] && callback(call.arguments[0])
+ if (!cleanup || !cleanup.body || !ts.isBlock(cleanup.body)) {
+ problem(call, 'UNRESOLVED afterAll callback')
+ continue
+ }
+ callbacks += 1
+ const callbackProblemsBefore = problems.length
+ if (
+ cleanup.parameters.some(
+ parameter => !ts.isIdentifier(parameter.name) || parameter.initializer
+ )
+ ) {
+ problem(call, 'UNPROVEN callback parameter evaluation before cleanup')
+ }
+ currentCallback = cleanup
+ const body = cleanup.body
+ const localNodes: ts.Node[] = []
+ function visitCleanup(node: ts.Node): void {
+ if (node !== body && ts.isFunctionLike(node)) return
+ localNodes.push(node)
+ ts.forEachChild(node, visitCleanup)
+ }
+ visitCleanup(body)
+ const subjects = new Set<PoolBinding>()
+ for (const node of localNodes) {
+ if (!ts.isIdentifier(node)) continue
+ const pool = poolBinding(node)
+ if (pool && administrative.has(pool)) subjects.add(pool)
+ }
+ if (subjects.size === 0) {
+ problem(call, 'UNRESOLVED administrative pool identity')
+ continue
+ }
+ adminPools += subjects.size
+ for (const pool of subjects) {
+ const poolProblemsBefore = problems.length
+ const ends = localNodes.filter(ts.isCallExpression).filter(end => isEnd(end, pool))
+ if (ends.length !== 1) {
+ problem(call, `Expected one administrative close, found ${ends.length}`)
+ continue
+ }
+ const outer = body.statements.find(
+ statement =>
+ ts.isTryStatement(statement) &&
+ statement.finallyBlock &&
+ guaranteedSequence(statement.finallyBlock.statements, pool)
+ )
+ if (!outer || !ts.isTryStatement(outer) || !outer.finallyBlock) {
+ problem(call, 'No guaranteed administrative close in an outer finally')
+ continue
+ }
+ const unprotected = localNodes
+ .filter(ts.isAwaitExpression)
+ .filter(
+ awaited =>
+ !contains(outer.tryBlock, awaited) &&
+ !(outer.catchClause && contains(outer.catchClause, awaited)) &&
+ !(contains(outer.finallyBlock!, awaited) && contains(awaited, ends[0]!))
+ )
+ for (const awaited of unprotected)
+ problem(awaited, 'Async cleanup is outside the administrative close guarantee')
+ const before = body.statements.slice(0, body.statements.indexOf(outer))
+ if (before.some(statement => !safePrefix(statement))) {
+ problem(
+ call,
+ 'UNPROVEN potentially throwing statement before the outer cleanup try/finally'
+ )
+ }
+ if (problems.length === poolProblemsBefore)
+ closedByCallbacks.set(pool, (closedByCallbacks.get(pool) ?? 0) + 1)
+ }
+ if (problems.length === callbackProblemsBefore) protectedCallbacks += 1
+ }
+ if (administrative.size > 0 && hooks === 0)
+ problem(ast, 'Administrative pool fixture has no resolved afterAll callback')
+ if (constructed.size > 0 && administrative.size === 0)
+ problem(ast, 'UNRESOLVED administrative cleanup for constructed pg pools')
+ for (const pool of administrative) {
+ const closures = closedByCallbacks.get(pool) ?? 0
+ if (closures !== 1)
+ problem(
+ administrativeOrigin.get(pool)!,
+ `Expected one globally guaranteed administrative callback close, found ${closures}`
+ )
+ }
+ return { file, hooks, callbacks, protectedCallbacks, adminPools, problems }
+}
+
+function discoverSuites(directory: string): string[] {
+ return readdirSync(directory, { withFileTypes: true })
+ .flatMap(entry => {
+ const path = join(directory, entry.name)
+ return entry.isDirectory()
+ ? discoverSuites(path)
+ : entry.isFile() &&
+ entry.name.includes('realPostgres') &&
+ entry.name.endsWith('.integration.test.ts')
+ ? [path]
+ : []
+ })
+ .sort()
+}
+
+function fixture(body: string): string {
+ return [
+ "import { afterAll as teardown, beforeAll } from 'vitest'",
+ "import { Pool as PgPool } from 'pg'",
+ 'const administrative = new PgPool()',
+ 'const appPool = new PgPool()',
+ 'beforeAll(async () => { await administrative.query(`CREATE DATABASE fixture`) })',
+ 'const owner = administrative',
+ `teardown(async () => { ${body} })`,
+ ].join('\n')
+}
+
+describe('real PostgreSQL administrative cleanup guard', () => {
+ it('proves administrative closure for every physically discovered real-PG afterAll callback', () => {
+ const files = discoverSuites(testDir)
+ const audits = files.map(path =>
+ auditSource(relative(testDir, path), readFileSync(path, 'utf8'))
+ )
+ // Reviewed inventory at 0a895015: 64 physical integrations / 65 hooks.
+ // New suites are discovered automatically; deliberate removals require
+ // explicit review of this lower-bound witness instead of silently passing.
+ expect(files.length).toBeGreaterThanOrEqual(64)
+ expect(new Set(files).size).toBe(files.length)
+ expect(audits.flatMap(audit => audit.problems)).toEqual([])
+ expect(audits.reduce((sum, audit) => sum + audit.hooks, 0)).toBeGreaterThanOrEqual(65)
+ expect(audits.reduce((sum, audit) => sum + audit.callbacks, 0)).toBe(
+ audits.reduce((sum, audit) => sum + audit.hooks, 0)
+ )
+ expect(
+ audits
+ .filter(audit => audit.callbacks > 0)
+ .every(audit => audit.adminPools >= audit.callbacks)
+ ).toBe(true)
+ expect(audits.reduce((sum, audit) => sum + audit.protectedCallbacks, 0)).toBe(
+ audits.reduce((sum, audit) => sum + audit.callbacks, 0)
+ )
+ })
+
+ it.each([
+ 'try { await appPool.query(`SELECT 1`) } finally { await administrative?.end() }',
+ "try { await appPool.query(`SELECT 1`) } finally { await (owner as PgPool)?.['end']() }",
+ 'try { await appPool.query(`SELECT 1`) } finally { if (owner) await owner.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { const closing = owner; await closing?.end() }',
+ 'const request = { end() {} }; try { request.end(); await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { await administrative?.end().catch(() => undefined) }',
+ 'try { await appPool.query(`SELECT 1`) } catch (error) { await appPool.query(`SELECT 2`); throw error } finally { await administrative.end() }',
+ 'if (false) { const previous = 1 } try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ ])('accepts a provably safe binding and close: %s', body => {
+ const audit = auditSource('fixture.realPostgres.test.ts', fixture(body))
+ expect(audit.callbacks).toBe(1)
+ expect(audit.adminPools).toBe(1)
+ expect(audit.problems).toEqual([])
+ })
+
+ it.each([
+ 'await appPool.query(`SELECT 1`); await administrative.end()',
+ 'await appPool.query(`SELECT 1`); try {} finally { await administrative.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { if (false) await administrative.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { await appPool.query(`SELECT 2`); await administrative.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { const administrative = appPool; await administrative.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { const request = { end() {} }; request.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { const { end } = administrative; await end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { administrative.end() }',
+ 'if (true) return; try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'administrative = appPool; try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'administrative.end = async () => {}; try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'try { await appPool.query(`SELECT 1`) } finally { await appPool.query(`SELECT 2`).catch(() => administrative.end()) }',
+ 'beforeThatCanThrow(); try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'const value = sourceWithGetter.property; try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'prepareCleanup(sourceWithGetter.property); try { await appPool.query(`SELECT 1`) } finally { await administrative.end() }',
+ 'const undefined = owner; try { await appPool.query(`SELECT 1`) } finally { if (owner !== undefined) await owner.end() }',
+ ])('rejects an unproven or unrelated administrative close: %s', body => {
+ expect(
+ auditSource('fixture.realPostgres.test.ts', fixture(body)).problems.length
+ ).toBeGreaterThan(0)
+ })
+
+ it('fails on parse errors, unknown pool construction and unresolved callback references', () => {
+ expect(
+ auditSource('fixture.realPostgres.test.ts', 'const broken = (').problems.length
+ ).toBeGreaterThan(0)
+ expect(
+ auditSource(
+ 'fixture.realPostgres.test.ts',
+ fixture('try {} finally { await administrative.end() }').replace(
+ 'new PgPool()',
+ 'makePool()'
+ )
+ ).problems.length
+ ).toBeGreaterThan(0)
+ expect(
+ auditSource(
+ 'fixture.realPostgres.test.ts',
+ fixture('try {} finally { await administrative.end() }').replace(
+ 'teardown(async () => {',
+ 'teardown(unknownCallback); void (async () => {'
+ )
+ ).problems.length
+ ).toBeGreaterThan(0)
+ })
+
+ it('rejects premature mutable aliases and unsafe absence handling while accepting cleanup-local aliases', () => {
+ const prefix = [
+ "import { afterAll, beforeAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'let administrative: Pool',
+ 'beforeAll(async () => { administrative = new Pool(); await administrative.query(`CREATE DATABASE fixture`) })',
+ ].join('\n')
+ const early = `${prefix}\nconst owner = administrative\nafterAll(async () => { try { await administrative.query(\`DROP DATABASE fixture\`) } finally { await owner?.end() } })`
+ expect(auditSource('fixture.realPostgres.test.ts', early).problems.length).toBeGreaterThan(0)
+ const absent = `${prefix}\nafterAll(async () => { try { await administrative.query(\`DROP DATABASE fixture\`) } finally { await administrative.end() } })`
+ expect(auditSource('fixture.realPostgres.test.ts', absent).problems.length).toBeGreaterThan(0)
+ const local = `${prefix}\nafterAll(async () => { const owner = administrative; try { await administrative.query(\`DROP DATABASE fixture\`) } finally { await owner?.end() } })`
+ expect(auditSource('fixture.realPostgres.test.ts', local).problems).toEqual([])
+ const late = [
+ "import { afterAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'let administrative: Pool',
+ 'afterAll(async () => { const owner = administrative; administrative = new Pool(); try { await administrative.query(`DROP DATABASE fixture`) } finally { await owner?.end() } })',
+ ].join('\n')
+ expect(auditSource('fixture.realPostgres.test.ts', late).problems.length).toBeGreaterThan(0)
+ })
+
+ it.each([
+ [
+ 'end argument evaluation',
+ fixture(
+ 'try { await appPool.query(`SELECT 1`) } finally { await administrative.end(beforeCloseThatThrows()) }'
+ ),
+ ],
+ [
+ 'omitted second administrative pool',
+ [
+ "import { afterAll, beforeAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'const administrative = new Pool(); const forgotten = new Pool()',
+ 'beforeAll(async () => { await administrative.query(`CREATE DATABASE fixture`); await forgotten.query(`CREATE DATABASE other_fixture`) })',
+ 'afterAll(async () => { try { await administrative.query(`DROP DATABASE fixture`) } finally { await administrative.end() } })',
+ ].join('\n'),
+ ],
+ [
+ 'SQL constant without a cleanup hook',
+ [
+ "import { Pool } from 'pg'",
+ 'const administrative = new Pool()',
+ "const sql = 'DROP DATABASE fixture'",
+ 'administrative.query(sql)',
+ ].join('\n'),
+ ],
+ [
+ 'reassigned callback',
+ [
+ "import { afterAll, beforeAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'const administrative = new Pool()',
+ 'beforeAll(async () => { await administrative.query(`CREATE DATABASE fixture`) })',
+ 'let cleanup = async () => { try { await administrative.query(`DROP DATABASE fixture`) } finally { await administrative.end() } }',
+ 'cleanup = async () => {}',
+ 'afterAll(cleanup)',
+ ].join('\n'),
+ ],
+ [
+ 'reassigned hook alias',
+ [
+ "import { afterAll, beforeAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'const administrative = new Pool()',
+ 'beforeAll(async () => { await administrative.query(`CREATE DATABASE fixture`) })',
+ 'let register = afterAll',
+ 'register = (_callback: unknown) => {}',
+ 'register(async () => { try { await administrative.query(`DROP DATABASE fixture`) } finally { await administrative.end() } })',
+ ].join('\n'),
+ ],
+ [
+ 'reassigned named function callback',
+ [
+ "import { afterAll, beforeAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'const administrative = new Pool()',
+ 'beforeAll(async () => { await administrative.query(`CREATE DATABASE fixture`) })',
+ 'async function cleanup() { try { await administrative.query(`DROP DATABASE fixture`) } finally { await administrative.end() } }',
+ 'cleanup = async () => {}',
+ 'afterAll(cleanup)',
+ ].join('\n'),
+ ],
+ ])('rejects reviewed unsafe shape: %s', (_name, source) => {
+ expect(
+ auditSource('fixture.realPostgres.integration.test.ts', source).problems.length
+ ).toBeGreaterThan(0)
+ })
+
+ it('resolves immutable administrative SQL and stable named callback aliases', () => {
+ const source = [
+ "import { afterAll as register, beforeAll } from 'vitest'",
+ "import { Pool } from 'pg'",
+ 'const administrative = new Pool()',
+ "const createSql = 'CREATE DATABASE fixture'",
+ "const dropSql = 'DROP DATABASE fixture'",
+ 'beforeAll(async () => { await administrative.query(createSql) })',
+ 'const cleanup = async () => { try { await administrative.query(dropSql) } finally { await administrative.end() } }',
+ 'register(cleanup)',
+ ].join('\n')
+ const audit = auditSource('fixture.realPostgres.integration.test.ts', source)
+ expect(audit.callbacks).toBe(1)
+ expect(audit.adminPools).toBe(1)
+ expect(audit.protectedCallbacks).toBe(1)
+ expect(audit.problems).toEqual([])
+ })
+})
diff --git a/control-api/test/realPostgresCleanup.contract.test.ts b/control-api/test/realPostgresCleanup.contract.test.ts
index 91a7b57dc..9f47adecf 100644
--- a/control-api/test/realPostgresCleanup.contract.test.ts
+++ b/control-api/test/realPostgresCleanup.contract.test.ts
@@ -232,3 +232,543 @@ describe('gfsStructuralIntegrity.realPostgres.integration.test.ts teardown contr
}
)
})
+
+describe('services.mcpSecretRollbackPermit.realPostgres.integration.test.ts teardown contract', () => {
+ const file = 'services.mcpSecretRollbackPermit.realPostgres.integration.test.ts'
+
+ it('closes the admin pool on helper rejection without probing, terminating or dropping', async () => {
+ const pool = {}
+ const error = new Error('rollback-permit client-close helper failed')
+ const helper = vi.fn().mockRejectedValueOnce(error)
+ const adminPool = { end: vi.fn().mockResolvedValue(undefined), query: vi.fn() }
+ const hook = afterAllCallback(file, {
+ pool,
+ adminPool,
+ endPoolAndWaitForClients: helper,
+ setImmediate,
+ })
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(helper).toHaveBeenCalledExactlyOnceWith(pool)
+ expect(adminPool.query).not.toHaveBeenCalled()
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+
+ it.each(['quiescent', 'still active'] as const)(
+ 'closes clients before observing %s backends and cleaning the database',
+ async state => {
+ const events: string[] = []
+ const pool = {}
+ const helper = vi.fn(async () => {
+ events.push('clients-closed')
+ })
+ const count = state === 'quiescent' ? '0' : '1'
+ const adminPool = {
+ query: vi.fn(async (sql: string) => {
+ events.push(
+ sql.includes('COUNT(*)')
+ ? 'probe'
+ : sql.includes('pg_terminate_backend')
+ ? 'terminate'
+ : 'drop'
+ )
+ return { rows: [{ count }] }
+ }),
+ end: vi.fn(async () => {
+ events.push('admin-closed')
+ }),
+ }
+ const hook = afterAllCallback(file, {
+ pool,
+ adminPool,
+ endPoolAndWaitForClients: helper,
+ setImmediate,
+ })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(helper).toHaveBeenCalledExactlyOnceWith(pool)
+ const probes = state === 'quiescent' ? 1 : 50
+ expect(adminPool.query).toHaveBeenCalledTimes(probes + (state === 'quiescent' ? 1 : 2))
+ expect(adminPool.query).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining('SELECT COUNT(*)::text AS count'),
+ ['teardown_contract']
+ )
+ if (state === 'still active') {
+ expect(adminPool.query).toHaveBeenNthCalledWith(
+ 51,
+ expect.stringContaining('SELECT pg_terminate_backend(pid)'),
+ ['teardown_contract']
+ )
+ }
+ expect(adminPool.query).toHaveBeenLastCalledWith(
+ 'DROP DATABASE IF EXISTS "teardown_contract"'
+ )
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ expect(events).toEqual([
+ 'clients-closed',
+ ...Array(probes).fill('probe'),
+ ...(state === 'still active' ? ['terminate'] : []),
+ 'drop',
+ 'admin-closed',
+ ])
+ }
+ )
+
+ it('closes the permit pool even when no admin pool exists', async () => {
+ const pool = {}
+ const helper = vi.fn().mockResolvedValue(undefined)
+ const hook = afterAllCallback(file, {
+ pool,
+ adminPool: undefined,
+ endPoolAndWaitForClients: helper,
+ setImmediate,
+ })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(helper).toHaveBeenCalledExactlyOnceWith(pool)
+ })
+
+ it.each(['probe', 'termination', 'DROP'] as const)(
+ 'closes the admin pool if %s SQL rejects',
+ async phase => {
+ const pool = {}
+ const error = new Error(`rollback-permit ${phase} SQL failed`)
+ const helper = vi.fn().mockResolvedValue(undefined)
+ const query = vi.fn()
+ if (phase === 'termination') {
+ for (let i = 0; i < 50; i += 1) query.mockResolvedValueOnce({ rows: [{ count: '1' }] })
+ } else if (phase === 'DROP') {
+ query.mockResolvedValueOnce({ rows: [{ count: '0' }] })
+ }
+ query.mockRejectedValueOnce(error)
+ const adminPool = { end: vi.fn().mockResolvedValue(undefined), query }
+ const hook = afterAllCallback(file, {
+ pool,
+ adminPool,
+ endPoolAndWaitForClients: helper,
+ setImmediate,
+ })
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(helper).toHaveBeenCalledExactlyOnceWith(pool)
+ expect(query).toHaveBeenCalledTimes(phase === 'probe' ? 1 : phase === 'termination' ? 51 : 2)
+ expect(query).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining('SELECT COUNT(*)::text AS count'),
+ ['teardown_contract']
+ )
+ if (phase === 'termination') {
+ expect(query).toHaveBeenLastCalledWith(
+ expect.stringContaining('SELECT pg_terminate_backend(pid)'),
+ ['teardown_contract']
+ )
+ } else if (phase === 'DROP') {
+ expect(query).toHaveBeenLastCalledWith('DROP DATABASE IF EXISTS "teardown_contract"')
+ }
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ }
+ )
+})
+
+describe('gfsReaderRole.realPostgres.integration.test.ts teardown contract', () => {
+ const file = 'gfsReaderRole.realPostgres.integration.test.ts'
+
+ // Only collaborator markers are constructed here. Role/SQL/helper order is
+ // supplied by the real source callback, never implemented by this fixture.
+ function readerTeardown() {
+ const readerPool = { identity: 'reader' }
+ const writerPool = { identity: 'writer' }
+ const pool = { query: vi.fn().mockResolvedValue(undefined) }
+ const helper = vi.fn().mockResolvedValue(undefined)
+ const adminPool = {
+ query: vi.fn().mockResolvedValue(undefined),
+ end: vi.fn().mockResolvedValue(undefined),
+ }
+ const collaborators = {
+ readerPool,
+ writerPool,
+ pool,
+ adminPool,
+ inheritedRole: 'teardown_inherited_role',
+ endPoolAndWaitForClients: helper,
+ }
+ return { readerPool, writerPool, pool, helper, adminPool, collaborators }
+ }
+
+ it.each(['reader', 'writer', 'core'] as const)(
+ 'closes the admin pool if the %s helper rejects',
+ async phase => {
+ const fixture = readerTeardown()
+ const error = new Error(`${phase} client-close helper failed`)
+ const events: string[] = []
+ const orderedPools = [fixture.readerPool, fixture.writerPool, fixture.pool]
+ const failedIndex = phase === 'reader' ? 0 : phase === 'writer' ? 1 : 2
+ fixture.helper.mockImplementation(async candidate => {
+ if (candidate === orderedPools[failedIndex]) {
+ events.push('helper-failed')
+ throw error
+ }
+ })
+ fixture.pool.query.mockImplementation(async () => {
+ events.push('role-cleanup')
+ })
+ fixture.adminPool.end.mockImplementation(async () => {
+ events.push('admin-closed')
+ })
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(fixture.helper).toHaveBeenCalledTimes(failedIndex + 1)
+ for (let i = 0; i <= failedIndex; i += 1)
+ expect(fixture.helper.mock.calls[i]?.[0]).toBe(orderedPools[i])
+ expect(fixture.pool.query).toHaveBeenCalledTimes(phase === 'core' ? 3 : 0)
+ expect(fixture.adminPool.query).not.toHaveBeenCalled()
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ expect(events.slice(events.indexOf('helper-failed') + 1)).toEqual(['admin-closed'])
+ }
+ )
+
+ it('preserves role isolation and helper/termination/DROP ordering', async () => {
+ const fixture = readerTeardown()
+ const events: string[] = []
+ fixture.helper.mockImplementation(async candidate => {
+ events.push(
+ candidate === fixture.readerPool
+ ? 'reader-closed'
+ : candidate === fixture.writerPool
+ ? 'writer-closed'
+ : 'core-closed'
+ )
+ })
+ fixture.pool.query.mockImplementation(async () => {
+ events.push('role-cleanup')
+ })
+ fixture.adminPool.query
+ .mockImplementationOnce(async () => {
+ events.push('terminate')
+ })
+ .mockImplementationOnce(async () => {
+ events.push('drop')
+ })
+ fixture.adminPool.end.mockImplementation(async () => {
+ events.push('admin-closed')
+ })
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(fixture.helper).toHaveBeenCalledTimes(3)
+ expect(fixture.helper.mock.calls[0]?.[0]).toBe(fixture.readerPool)
+ expect(fixture.helper.mock.calls[1]?.[0]).toBe(fixture.writerPool)
+ expect(fixture.helper.mock.calls[2]?.[0]).toBe(fixture.pool)
+ expect(fixture.pool.query).toHaveBeenCalledTimes(3)
+ expect(fixture.pool.query).toHaveBeenNthCalledWith(
+ 1,
+ 'ALTER ROLE gfs_controller NOLOGIN NOINHERIT'
+ )
+ expect(fixture.pool.query).toHaveBeenNthCalledWith(
+ 2,
+ 'ALTER ROLE gfs_controller_reader NOLOGIN NOINHERIT'
+ )
+ expect(fixture.pool.query).toHaveBeenNthCalledWith(
+ 3,
+ 'DROP ROLE IF EXISTS "teardown_inherited_role"'
+ )
+ expect(fixture.adminPool.query).toHaveBeenCalledTimes(2)
+ expect(fixture.adminPool.query).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining('SELECT pg_terminate_backend(pid)'),
+ ['teardown_contract']
+ )
+ expect(fixture.adminPool.query.mock.calls[0]?.[0]).toContain('pid <> pg_backend_pid()')
+ expect(fixture.adminPool.query).toHaveBeenNthCalledWith(
+ 2,
+ 'DROP DATABASE IF EXISTS "teardown_contract"'
+ )
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ expect(events).toEqual([
+ 'reader-closed',
+ 'writer-closed',
+ 'role-cleanup',
+ 'role-cleanup',
+ 'role-cleanup',
+ 'core-closed',
+ 'terminate',
+ 'drop',
+ 'admin-closed',
+ ])
+ })
+
+ it('closes every pool and attempts role isolation without an admin pool', async () => {
+ const fixture = readerTeardown()
+ const hook = afterAllCallback(file, { ...fixture.collaborators, adminPool: undefined })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(fixture.helper).toHaveBeenCalledTimes(3)
+ expect(fixture.helper.mock.calls[0]?.[0]).toBe(fixture.readerPool)
+ expect(fixture.helper.mock.calls[1]?.[0]).toBe(fixture.writerPool)
+ expect(fixture.helper.mock.calls[2]?.[0]).toBe(fixture.pool)
+ expect(fixture.pool.query).toHaveBeenCalledTimes(3)
+ expect(fixture.adminPool.query).not.toHaveBeenCalled()
+ expect(fixture.adminPool.end).not.toHaveBeenCalled()
+ })
+
+ it.each(['termination', 'DROP'] as const)(
+ 'closes the admin pool when reader cleanup %s SQL rejects',
+ async phase => {
+ const fixture = readerTeardown()
+ const error = new Error(`reader cleanup ${phase} SQL failed`)
+ if (phase === 'DROP') fixture.adminPool.query.mockResolvedValueOnce(undefined)
+ fixture.adminPool.query.mockRejectedValueOnce(error)
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(fixture.helper).toHaveBeenCalledTimes(3)
+ expect(fixture.pool.query).toHaveBeenCalledTimes(3)
+ expect(fixture.adminPool.query).toHaveBeenCalledTimes(phase === 'termination' ? 1 : 2)
+ expect(fixture.adminPool.query).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining('SELECT pg_terminate_backend(pid)'),
+ ['teardown_contract']
+ )
+ if (phase === 'DROP')
+ expect(fixture.adminPool.query).toHaveBeenLastCalledWith(
+ 'DROP DATABASE IF EXISTS "teardown_contract"'
+ )
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ }
+ )
+
+ it('preserves the existing best-effort role cleanup while still attempting every isolation query', async () => {
+ const fixture = readerTeardown()
+ fixture.pool.query.mockRejectedValue(new Error('role cleanup unavailable'))
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(fixture.pool.query).toHaveBeenCalledTimes(3)
+ expect(fixture.pool.query).toHaveBeenNthCalledWith(
+ 1,
+ 'ALTER ROLE gfs_controller NOLOGIN NOINHERIT'
+ )
+ expect(fixture.pool.query).toHaveBeenNthCalledWith(
+ 2,
+ 'ALTER ROLE gfs_controller_reader NOLOGIN NOINHERIT'
+ )
+ expect(fixture.pool.query).toHaveBeenNthCalledWith(
+ 3,
+ 'DROP ROLE IF EXISTS "teardown_inherited_role"'
+ )
+ expect(fixture.helper).toHaveBeenCalledTimes(3)
+ expect(fixture.adminPool.query).toHaveBeenCalledTimes(2)
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+})
+
+describe('actual spy-restoration failure cleanup', () => {
+ it.each([
+ { file: suites[0]!, spy: 'querySpy' },
+ { file: suites[0]!, spy: 'connectSpy' },
+ { file: suites[1]!, spy: 'querySpy' },
+ { file: suites[1]!, spy: 'connectSpy' },
+ { file: suites[2]!, spy: 'corePoolConnectSpy' },
+ ])('$file closes the admin pool when $spy restoration throws', async ({ file, spy }) => {
+ const error = new Error('spy restoration failed')
+ const restorations = {
+ querySpy: { mockRestore: vi.fn() },
+ connectSpy: { mockRestore: vi.fn() },
+ corePoolConnectSpy: { mockRestore: vi.fn() },
+ }
+ restorations[spy as keyof typeof restorations].mockRestore.mockImplementation(() => {
+ throw error
+ })
+ const helper = vi.fn().mockResolvedValue(undefined)
+ const wait = vi.fn()
+ const adminPool = { end: vi.fn().mockResolvedValue(undefined), query: vi.fn() }
+ const hook = afterAllCallback(file, {
+ ...restorations,
+ testPool: {},
+ adminPool,
+ endPoolAndWaitForClients: helper,
+ waitForDatabaseConnectionsToClose: wait,
+ })
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(
+ restorations[spy as keyof typeof restorations].mockRestore
+ ).toHaveBeenCalledExactlyOnceWith()
+ expect(helper).not.toHaveBeenCalled()
+ expect(wait).not.toHaveBeenCalled()
+ expect(adminPool.query).not.toHaveBeenCalled()
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+})
+
+describe('db.codexSubscriptionConnection.realPostgres.integration.test.ts teardown contract', () => {
+ const file = 'db.codexSubscriptionConnection.realPostgres.integration.test.ts'
+
+ it('closes the admin pool if the existing plain pool end rejects, without dropping', async () => {
+ const error = new Error('Codex pool end failed')
+ const pool = { end: vi.fn().mockRejectedValueOnce(error) }
+ const adminPool = { query: vi.fn(), end: vi.fn().mockResolvedValue(undefined) }
+ const hook = afterAllCallback(file, { pool, adminPool })
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(pool.end).toHaveBeenCalledExactlyOnceWith()
+ expect(adminPool.query).not.toHaveBeenCalled()
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+
+ it('preserves the intentional DROP recovery and still closes the admin pool', async () => {
+ const pool = { end: vi.fn().mockResolvedValue(undefined) }
+ const adminPool = {
+ query: vi.fn().mockRejectedValueOnce(new Error('DROP failed')),
+ end: vi.fn().mockResolvedValue(undefined),
+ }
+ const hook = afterAllCallback(file, { pool, adminPool })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(pool.end).toHaveBeenCalledExactlyOnceWith()
+ expect(adminPool.query).toHaveBeenCalledExactlyOnceWith(
+ 'DROP DATABASE IF EXISTS "teardown_contract"'
+ )
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+
+ it('drops and closes the admin pool when no application pool was created', async () => {
+ const adminPool = {
+ query: vi.fn().mockResolvedValue(undefined),
+ end: vi.fn().mockResolvedValue(undefined),
+ }
+ const hook = afterAllCallback(file, { pool: undefined, adminPool })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(adminPool.query).toHaveBeenCalledExactlyOnceWith(
+ 'DROP DATABASE IF EXISTS "teardown_contract"'
+ )
+ expect(adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+
+ it('still ends the application pool without an admin pool', async () => {
+ const pool = { end: vi.fn().mockResolvedValue(undefined) }
+ const hook = afterAllCallback(file, { pool, adminPool: undefined })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(pool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+})
+
+describe('routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts teardown contract', () => {
+ const file = 'routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts'
+ function routeTeardown() {
+ // process is a local collaborator: these callbacks never alter the real
+ // test runner's environment or execute the original module/beforeAll.
+ const env = { RESTORE_PRESENT: 'temporary', RESTORE_ABSENT: 'temporary' } as Record<
+ string,
+ string
+ >
+ const previousEnv = new Map<string, string | undefined>([
+ ['RESTORE_PRESENT', 'original'],
+ ['RESTORE_ABSENT', undefined],
+ ])
+ const corePool = { identity: 'core' }
+ const limiterPool = { identity: 'limiter' }
+ const helper = vi.fn().mockResolvedValue(undefined)
+ const adminPool = {
+ query: vi.fn().mockResolvedValue(undefined),
+ end: vi.fn().mockResolvedValue(undefined),
+ }
+ const collaborators = {
+ process: { env },
+ envKeys: [...previousEnv.keys()],
+ previousEnv,
+ corePool,
+ limiterPool,
+ adminPool,
+ endPoolAndWaitForClients: helper,
+ }
+ return { env, previousEnv, corePool, limiterPool, helper, adminPool, collaborators }
+ }
+
+ it('restores the environment and preserves existing helper recovery before SQL', async () => {
+ const fixture = routeTeardown()
+ fixture.helper.mockRejectedValue(new Error('caught client-close failure'))
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(fixture.env).toEqual({ RESTORE_PRESENT: 'original' })
+ expect(fixture.helper).toHaveBeenCalledTimes(2)
+ expect(fixture.helper.mock.calls[0]?.[0]).toBe(fixture.corePool)
+ expect(fixture.helper.mock.calls[1]?.[0]).toBe(fixture.limiterPool)
+ expect(fixture.adminPool.query).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining('SELECT pg_terminate_backend(pid)'),
+ ['teardown_contract']
+ )
+ expect(fixture.adminPool.query).toHaveBeenNthCalledWith(
+ 2,
+ 'DROP DATABASE IF EXISTS "teardown_contract"'
+ )
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+
+ it.each(['termination', 'DROP'] as const)(
+ 'restores the environment and closes admin on %s rejection',
+ async phase => {
+ const fixture = routeTeardown()
+ const error = new Error(`route ${phase} failed`)
+ if (phase === 'DROP') fixture.adminPool.query.mockResolvedValueOnce(undefined)
+ fixture.adminPool.query.mockRejectedValueOnce(error)
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(fixture.env).toEqual({ RESTORE_PRESENT: 'original' })
+ expect(fixture.helper).toHaveBeenCalledTimes(2)
+ expect(fixture.adminPool.query).toHaveBeenCalledTimes(phase === 'termination' ? 1 : 2)
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ }
+ )
+
+ it('closes admin and performs no helper/SQL work if environment restoration throws', async () => {
+ const fixture = routeTeardown()
+ const error = new Error('environment restoration failed')
+ vi.spyOn(fixture.previousEnv, 'get').mockImplementation(() => {
+ throw error
+ })
+ const hook = afterAllCallback(file, fixture.collaborators)
+
+ await expect(hook()).rejects.toBe(error)
+
+ expect(fixture.helper).not.toHaveBeenCalled()
+ expect(fixture.adminPool.query).not.toHaveBeenCalled()
+ expect(fixture.adminPool.end).toHaveBeenCalledExactlyOnceWith()
+ })
+
+ it('restores the environment and closes both application pools without admin', async () => {
+ const fixture = routeTeardown()
+ fixture.helper.mockRejectedValue(new Error('caught client-close failure'))
+ const hook = afterAllCallback(file, { ...fixture.collaborators, adminPool: undefined })
+
+ await expect(hook()).resolves.toBeUndefined()
+
+ expect(fixture.env).toEqual({ RESTORE_PRESENT: 'original' })
+ expect(fixture.helper).toHaveBeenCalledTimes(2)
+ expect(fixture.adminPool.query).not.toHaveBeenCalled()
+ expect(fixture.adminPool.end).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-api/test/routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts b/control-api/test/routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts
index 23f6b6e21..3b1ba053e 100644
--- a/control-api/test/routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts
+++ b/control-api/test/routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts
@@ -114,21 +114,25 @@ describeRealPostgres('external GFS rate limiter backend (real PostgreSQL)', () =
}, 60_000)
afterAll(async () => {
- for (const key of envKeys) {
- const value = previousEnv.get(key)
- if (value === undefined) delete process.env[key]
- else process.env[key] = value
- }
- await endPoolAndWaitForClients(corePool).catch(() => {})
- await endPoolAndWaitForClients(limiterPool).catch(() => {})
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ for (const key of envKeys) {
+ const value = previousEnv.get(key)
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ await endPoolAndWaitForClients(corePool).catch(() => {})
+ await endPoolAndWaitForClients(limiterPool).catch(() => {})
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
it('U1: the limiter pool runs with synchronous_commit off and a 3 s statement timeout; the core pool keeps the defaults', async () => {
diff --git a/control-api/test/routes.externalGfsRateLimitStress.realPostgres.integration.test.ts b/control-api/test/routes.externalGfsRateLimitStress.realPostgres.integration.test.ts
index 3d0669558..4b3a837e0 100644
--- a/control-api/test/routes.externalGfsRateLimitStress.realPostgres.integration.test.ts
+++ b/control-api/test/routes.externalGfsRateLimitStress.realPostgres.integration.test.ts
@@ -221,22 +221,26 @@ describeRealPostgres('external GFS rate limits under concurrent load (real Postg
})
afterAll(async () => {
- vi.useRealTimers()
- for (const key of envKeys) {
- const value = previousEnv.get(key)
- if (value === undefined) delete process.env[key]
- else process.env[key] = value
- }
- await endPoolAndWaitForClients(corePool).catch(() => {})
- await endPoolAndWaitForClients(limiterPool).catch(() => {})
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ vi.useRealTimers()
+ for (const key of envKeys) {
+ const value = previousEnv.get(key)
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ await endPoolAndWaitForClients(corePool).catch(() => {})
+ await endPoolAndWaitForClients(limiterPool).catch(() => {})
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
/**
diff --git a/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts b/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts
index 44fbfd4f9..a721da6d6 100644
--- a/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts
+++ b/control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts
@@ -167,19 +167,23 @@ describeRealPostgres('llm-model reductor ↔ grant upsert serialization (R1-H3 f
}, 60_000)
afterAll(async () => {
- if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING
- else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv
- await endPoolAndWaitForClients(racePool).catch(() => {})
- await endPoolAndWaitForClients(corePool).catch(() => {})
- await endPoolAndWaitForClients(limiterPool).catch(() => {})
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv
+ await endPoolAndWaitForClients(racePool).catch(() => {})
+ await endPoolAndWaitForClients(corePool).catch(() => {})
+ await endPoolAndWaitForClients(limiterPool).catch(() => {})
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
beforeEach(async () => {
diff --git a/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts b/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts
index 313266df2..2604bc9da 100644
--- a/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts
+++ b/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts
@@ -171,19 +171,23 @@ describeRealPostgres('llm-model reductor ↔ host referencer serialization (R1-H
}, 60_000)
afterAll(async () => {
- if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING
- else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv
- // Drain the module pool's connections first so DROP DATABASE has no live users.
- await endPoolAndWaitForClients(corePool).catch(() => {})
- await endPoolAndWaitForClients(limiterPool).catch(() => {})
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv
+ // Drain the module pool's connections first so DROP DATABASE has no live users.
+ await endPoolAndWaitForClients(corePool).catch(() => {})
+ await endPoolAndWaitForClients(limiterPool).catch(() => {})
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
beforeEach(async () => {
diff --git a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
index 26baaf9cf..a1ab0f17b 100644
--- a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
+++ b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
@@ -52,15 +52,18 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts
index ff1277bf9..2b24080b8 100644
--- a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts
+++ b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts
@@ -114,16 +114,19 @@ describeRealPostgres('legacy grants seen by the broker, gate and sweep (real Pos
})
afterAll(async () => {
- testDb.pool = undefined
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ testDb.pool = undefined
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/routes.mcpServerUninstall.repairRequired.realPostgres.integration.test.ts b/control-api/test/routes.mcpServerUninstall.repairRequired.realPostgres.integration.test.ts
index bde468a6c..fcb92d63d 100644
--- a/control-api/test/routes.mcpServerUninstall.repairRequired.realPostgres.integration.test.ts
+++ b/control-api/test/routes.mcpServerUninstall.repairRequired.realPostgres.integration.test.ts
@@ -82,16 +82,19 @@ describeRealPostgres('generic McpServer uninstall — repair_required (real Post
})
afterAll(async () => {
- dbHolder.target = null
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ dbHolder.target = null
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/routes.rateLimitProcessMemory.realPostgres.integration.test.ts b/control-api/test/routes.rateLimitProcessMemory.realPostgres.integration.test.ts
index c2fcc04b5..0c17c231f 100644
--- a/control-api/test/routes.rateLimitProcessMemory.realPostgres.integration.test.ts
+++ b/control-api/test/routes.rateLimitProcessMemory.realPostgres.integration.test.ts
@@ -111,21 +111,25 @@ describeRealPostgres('rateLimitMiddleware process-memory mode (real PostgreSQL)'
}, 60_000)
afterAll(async () => {
- for (const key of envKeys) {
- const value = previousEnv.get(key)
- if (value === undefined) delete process.env[key]
- else process.env[key] = value
- }
- await endPoolAndWaitForClients(corePool).catch(() => {})
- await endPoolAndWaitForClients(limiterPool).catch(() => {})
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ for (const key of envKeys) {
+ const value = previousEnv.get(key)
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ await endPoolAndWaitForClients(corePool).catch(() => {})
+ await endPoolAndWaitForClients(limiterPool).catch(() => {})
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
async function seedUser(): Promise<string> {
diff --git a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts
index 112f117a7..96d18c764 100644
--- a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts
+++ b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts
@@ -138,16 +138,19 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)
})
afterAll(async () => {
- dbHolder.target = null
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ dbHolder.target = null
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts b/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts
index 403c18b45..deaf2d265 100644
--- a/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts
+++ b/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts
@@ -46,15 +46,18 @@ describeRealPostgres('resolveConnectorsForAgents tri-state (real Postgres)', ()
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts
index 0dde8b506..474b23a82 100644
--- a/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts
+++ b/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts
@@ -45,15 +45,18 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.adminAuthDelete.realPostgres.integration.test.ts b/control-api/test/services.adminAuthDelete.realPostgres.integration.test.ts
index 54da2bab6..e442fa9d3 100644
--- a/control-api/test/services.adminAuthDelete.realPostgres.integration.test.ts
+++ b/control-api/test/services.adminAuthDelete.realPostgres.integration.test.ts
@@ -74,9 +74,9 @@ describeRealPostgres('deleteControlAdmin on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- querySpy?.mockRestore()
- connectSpy?.mockRestore()
try {
+ querySpy?.mockRestore()
+ connectSpy?.mockRestore()
await endPoolAndWaitForClients(testPool)
if (!adminPool) return
await waitForDatabaseConnectionsToClose(adminPool, database)
diff --git a/control-api/test/services.codexSubscriptionCatalog.realPostgres.integration.test.ts b/control-api/test/services.codexSubscriptionCatalog.realPostgres.integration.test.ts
index 79b9b0c6f..824a51361 100644
--- a/control-api/test/services.codexSubscriptionCatalog.realPostgres.integration.test.ts
+++ b/control-api/test/services.codexSubscriptionCatalog.realPostgres.integration.test.ts
@@ -40,12 +40,15 @@ describeRealPostgres('Codex subscription catalog on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.codexSubscriptionLifecycle.realPostgres.integration.test.ts b/control-api/test/services.codexSubscriptionLifecycle.realPostgres.integration.test.ts
index 0481a2050..281301928 100644
--- a/control-api/test/services.codexSubscriptionLifecycle.realPostgres.integration.test.ts
+++ b/control-api/test/services.codexSubscriptionLifecycle.realPostgres.integration.test.ts
@@ -143,12 +143,15 @@ describeRealPostgres('Codex subscription grant lifecycle on real PostgreSQL', ()
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts b/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts
index 6594ec474..fb4b4ee22 100644
--- a/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts
+++ b/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts
@@ -51,12 +51,15 @@ describeRealPostgres('Codex subscription OAuth on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.codexSubscriptionRefreshRejected.realPostgres.integration.test.ts b/control-api/test/services.codexSubscriptionRefreshRejected.realPostgres.integration.test.ts
index ea884386a..d2f1f228d 100644
--- a/control-api/test/services.codexSubscriptionRefreshRejected.realPostgres.integration.test.ts
+++ b/control-api/test/services.codexSubscriptionRefreshRejected.realPostgres.integration.test.ts
@@ -104,12 +104,15 @@ describeRealPostgres('Codex refresh rejected by the vendor on real PostgreSQL (#
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
index 4b351bf6a..e41744ffd 100644
--- a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
+++ b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
@@ -181,9 +181,9 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
}, 60_000)
afterAll(async () => {
- querySpy?.mockRestore()
- connectSpy?.mockRestore()
try {
+ querySpy?.mockRestore()
+ connectSpy?.mockRestore()
await endPoolAndWaitForClients(testPool)
if (!adminPool) return
await waitForDatabaseConnectionsToClose(adminPool, database)
diff --git a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
index da9569d77..9e6c8a4ee 100644
--- a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
+++ b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
@@ -57,8 +57,8 @@ describeRealPostgres('retireDesktopUser on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- corePoolConnectSpy?.mockRestore()
try {
+ corePoolConnectSpy?.mockRestore()
await endPoolAndWaitForClients(testPool)
if (!adminPool) return
await waitForDatabaseConnectionsToClose(adminPool, database)
diff --git a/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts b/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts
index e64ff7ff9..e70a03596 100644
--- a/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts
+++ b/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts
@@ -62,13 +62,16 @@ describeRealPostgres('Grok ticket redemption on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- config.grokSubscriptionEnabled = previousFlag
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ config.grokSubscriptionEnabled = previousFlag
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.grokProviderAttemptRedemption.refresh.realPostgres.integration.test.ts b/control-api/test/services.grokProviderAttemptRedemption.refresh.realPostgres.integration.test.ts
index 0e060a87e..dcaaccdb9 100644
--- a/control-api/test/services.grokProviderAttemptRedemption.refresh.realPostgres.integration.test.ts
+++ b/control-api/test/services.grokProviderAttemptRedemption.refresh.realPostgres.integration.test.ts
@@ -78,14 +78,17 @@ describeRealPostgres('Grok ticket redemption with token refresh on real PostgreS
}, 60_000)
afterAll(async () => {
- config.grokSubscriptionEnabled = previousFlag
- config.oauthEncryptionKey = previousEncryptionKey
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ config.grokSubscriptionEnabled = previousFlag
+ config.oauthEncryptionKey = previousEncryptionKey
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts b/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
index 02df77e63..83e672125 100644
--- a/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
+++ b/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
@@ -149,12 +149,15 @@ describeRealPostgres('Grok subscription connection on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.llmCatalogSync.realPostgres.integration.test.ts b/control-api/test/services.llmCatalogSync.realPostgres.integration.test.ts
index b9b8d5478..bb7e85274 100644
--- a/control-api/test/services.llmCatalogSync.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmCatalogSync.realPostgres.integration.test.ts
@@ -212,17 +212,21 @@ describeRealPostgres('syncDiscoveredModels on real PostgreSQL (#654 image_input)
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = $1
AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
it('counts exactly the enabled rows whose image_input changed and republishes once', async () => {
diff --git a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts
index f5ca923ea..350d7912c 100644
--- a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts
@@ -140,12 +140,15 @@ describeRealPostgres('Codex provider-attempt authorization on real PostgreSQL',
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts
index 481a82d32..467d2757f 100644
--- a/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts
@@ -90,12 +90,15 @@ describeRealPostgres('Codex attempt finalization on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.llmProviderAttemptRedemption.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptRedemption.realPostgres.integration.test.ts
index 544bcba64..b624b15ed 100644
--- a/control-api/test/services.llmProviderAttemptRedemption.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmProviderAttemptRedemption.realPostgres.integration.test.ts
@@ -54,12 +54,15 @@ describeRealPostgres('Codex ticket redemption on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.llmProviderAttemptStore.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptStore.realPostgres.integration.test.ts
index a9db18729..8c1b52cad 100644
--- a/control-api/test/services.llmProviderAttemptStore.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmProviderAttemptStore.realPostgres.integration.test.ts
@@ -58,12 +58,15 @@ describeRealPostgres('LLM provider-attempt ledger on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts b/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts
index 250b92bf1..fb75ed3f4 100644
--- a/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts
+++ b/control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts
@@ -44,34 +44,37 @@ describeRealPostgres('MCP Secret rollback permits on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- // A concurrent consume test opens several pg clients. Wait for every one
- // 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)
- if (!adminPool) return
- let activeConnections = 0
- for (let attempt = 0; attempt < 50; attempt += 1) {
- const active = await adminPool.query<{ count: string }>(
- `SELECT COUNT(*)::text AS count
+ try {
+ // A concurrent consume test opens several pg clients. Wait for every one
+ // 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)
+ if (!adminPool) return
+ let activeConnections = 0
+ for (let attempt = 0; attempt < 50; attempt += 1) {
+ const active = await adminPool.query<{ count: string }>(
+ `SELECT COUNT(*)::text AS count
FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- activeConnections = Number(active.rows[0]?.count ?? 0)
- if (activeConnections === 0) break
- await new Promise<void>(resolve => setImmediate(resolve))
- }
- if (activeConnections > 0) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
+ [database]
+ )
+ activeConnections = Number(active.rows[0]?.count ?? 0)
+ if (activeConnections === 0) break
+ await new Promise<void>(resolve => setImmediate(resolve))
+ }
+ if (activeConnections > 0) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
+ [database]
+ )
+ }
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ } finally {
+ await adminPool?.end()
}
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
})
it('grants the runtime role the exact DML needed to issue and consume a permit', async () => {
diff --git a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts
index 6366278a1..0535e1339 100644
--- a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts
+++ b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts
@@ -122,15 +122,18 @@ describeRealPostgres('proactive refresh sweep — installation identity (real Po
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts
index ebf26bba9..2731cb8e8 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts
@@ -71,17 +71,20 @@ describeRealPostgres('Plugin Workload SDK finalization on real PostgreSQL', () =
})
afterAll(async () => {
- await endPoolAndWaitForClients(dbPool)
- if (adminPool) {
- await adminPool.query(
- `SELECT pg_terminate_backend(pid)
+ try {
+ await endPoolAndWaitForClients(dbPool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = $1
AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ }
+ } finally {
+ await adminPool?.end()
}
})
diff --git a/control-api/test/services.rateLimiter.realPostgres.integration.test.ts b/control-api/test/services.rateLimiter.realPostgres.integration.test.ts
index 775a2e770..714863304 100644
--- a/control-api/test/services.rateLimiter.realPostgres.integration.test.ts
+++ b/control-api/test/services.rateLimiter.realPostgres.integration.test.ts
@@ -40,16 +40,20 @@ describeRealPostgres('rate limiter atomicity on real PostgreSQL', () => {
}, 60_000)
afterAll(async () => {
- await pool?.query('DELETE FROM rate_limit_buckets WHERE bucket_key = $1', [bucketKey])
- await endPoolAndWaitForClients(pool)
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ await pool?.query('DELETE FROM rate_limit_buckets WHERE bucket_key = $1', [bucketKey])
+ await endPoolAndWaitForClients(pool)
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
it('returns distinct post-increment counts under concurrent requests', async () => {
diff --git a/control-api/test/services.rateLimiterPoolSaturation.realPostgres.integration.test.ts b/control-api/test/services.rateLimiterPoolSaturation.realPostgres.integration.test.ts
index b0d699132..d411b282c 100644
--- a/control-api/test/services.rateLimiterPoolSaturation.realPostgres.integration.test.ts
+++ b/control-api/test/services.rateLimiterPoolSaturation.realPostgres.integration.test.ts
@@ -134,21 +134,25 @@ describeRealPostgres('rate limiter under pool saturation', () => {
}, 60_000)
afterAll(async () => {
- for (const key of poolEnvKeys) {
- const value = previousEnv.get(key)
- if (value === undefined) delete process.env[key]
- else process.env[key] = value
- }
- await endPoolAndWaitForClients(corePool).catch(() => {})
- await endPoolAndWaitForClients(limiterPool).catch(() => {})
- if (!adminPool) return
- await adminPool.query(
- `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ try {
+ for (const key of poolEnvKeys) {
+ const value = previousEnv.get(key)
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ await endPoolAndWaitForClients(corePool).catch(() => {})
+ await endPoolAndWaitForClients(limiterPool).catch(() => {})
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = $1 AND pid <> pg_backend_pid()`,
- [database]
- )
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- await adminPool.end()
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ }
+ } finally {
+ await adminPool?.end()
+ }
})
it('runs against the production pool bounds', () => {
diff --git a/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts b/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts
index 3f42266b2..1802ab1b2 100644
--- a/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts
+++ b/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts
@@ -304,12 +304,15 @@ describeRealPostgres('Subscription catalog sync cron on real PostgreSQL', () =>
}, 60_000)
afterAll(async () => {
- await pool?.end()
- if (adminPool) {
- await adminPool
- .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
- .catch(() => undefined)
- await adminPool.end()
+ try {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ }
+ } finally {
+ await adminPool?.end()
}
})