Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(db): keep readiness off the request pool (#325)

OKNOTOK2ba25952d9ba
diff --git a/server/src/__integration__/_helpers.ts b/server/src/__integration__/_helpers.ts
index 6b96586..f06989f 100644
--- a/server/src/__integration__/_helpers.ts
+++ b/server/src/__integration__/_helpers.ts
@@ -231,6 +231,10 @@ export async function teardownAll(server?: import('node:http').Server): Promise<
// the process is about to exit anyway. Catch swallows reentrant-end
// errors when multiple test files share the singleton.
try { await pool.end() } catch { /* ignore */ }
+ try {
+ const { healthPool } = await import('../db/pool.js')
+ await healthPool.end()
+ } catch { /* ignore */ }
try {
const { redis, sub } = await import('../redis.js')
redis.disconnect()
diff --git a/server/src/__tests__/database-pool.test.ts b/server/src/__tests__/database-pool.test.ts
new file mode 100644
index 0000000..583dee6
--- /dev/null
+++ b/server/src/__tests__/database-pool.test.ts
@@ -0,0 +1,31 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { readFile } from 'node:fs/promises'
+
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'test-key'
+
+const { databasePoolMax } = await import('../db/pool.js')
+
+test('DATABASE_POOL_MAX accepts an integer from 1 to 100', () => {
+ assert.equal(databasePoolMax(undefined), 20)
+ assert.equal(databasePoolMax(''), 20)
+ assert.equal(databasePoolMax('40'), 40)
+ assert.equal(databasePoolMax('0'), 20)
+ assert.equal(databasePoolMax('101'), 20)
+ assert.equal(databasePoolMax('nope'), 20)
+})
+
+test('readiness does not borrow the request pool, and runtime auth releases it before Redis', async () => {
+ const router = await readFile(new URL('../api/router.ts', import.meta.url), 'utf8')
+ const health = router.slice(router.indexOf("api.get('/health'"))
+ assert.match(health.slice(0, 500), /healthPool\.query\('SELECT 1'\)/)
+ assert.doesNotMatch(health.slice(0, 500), /pool\.query\('SELECT 1'\)/)
+
+ const auth = await readFile(new URL('../agents/runtime/authorization.ts', import.meta.url), 'utf8')
+ const fn = auth.slice(auth.indexOf('export async function withRuntimeConversationAuthorization'))
+ const commit = fn.indexOf("await client.query('COMMIT')")
+ const task = fn.indexOf('await args.task()')
+ const release = fn.indexOf('client.release()')
+ assert.ok(commit >= 0 && release > commit && task > release)
+})
diff --git a/server/src/agents/runtime/authorization.ts b/server/src/agents/runtime/authorization.ts
index 41ac26e..ba99545 100644
--- a/server/src/agents/runtime/authorization.ts
+++ b/server/src/agents/runtime/authorization.ts
@@ -80,10 +80,11 @@ export async function withRuntimeAgentRunAuthorization<T>(args: {
}
}
-/** Hold the current agent and every requested conversation membership stable
- * while an ephemeral Redis/pubsub side effect runs. Membership mutation uses
- * the same participant -> conversation lock order, so a revoke is linearized
- * either wholly before or wholly after the side effect. */
+/** Check the current agent and every requested conversation membership, then
+ * release the connection before the Redis side effect. Holding `FOR SHARE`
+ * across that publish pinned a pool slot and the membership rows for the
+ * whole round trip. A revoke that commits in the gap after this check can
+ * still observe one in-flight publish. */
export async function withRuntimeConversationAuthorization<T>(args: {
agentId: string
companyId: string
@@ -92,6 +93,7 @@ export async function withRuntimeConversationAuthorization<T>(args: {
}): Promise<{ authorized: boolean; result?: T }> {
const conversationIds = [...new Set(args.conversationIds)].sort()
const client = await pool.connect()
+ let authorized = false
try {
await client.query('BEGIN')
const participant = await client.query(
@@ -123,15 +125,17 @@ export async function withRuntimeConversationAuthorization<T>(args: {
return { authorized: false }
}
}
- const result = await args.task()
await client.query('COMMIT')
- return { authorized: true, result }
+ authorized = true
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
+ if (!authorized) return { authorized: false }
+ const result = await args.task()
+ return { authorized: true, result }
}
/** Authorize a read-cursor advance against the exact persisted message. The
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 66f761f..fcf1311 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -16,7 +16,7 @@ import {
storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,
storageKeyFromPublicUrl, messageAttachmentStorageKey,
} from '../storage.js'
-import { pool } from '../db/pool.js'
+import { healthPool, pool } from '../db/pool.js'
import { CH_MESSAGE_NEW, CH_REACTIONS, CH_CONVO_UPDATED, CH_DOCS, CH_TYPING, CH_CALENDAR_EVENTS, CH_BOARDS, CH_STATUS, CH_WORKSPACES, publish } from '../redis.js'
import { enqueueBroadcast, nudgeRealtimeOutbox, withOutboxTransaction } from '../realtime-outbox.js'
import { enqueueWorkspaceCleanup, nudgeWorkspaceCleanupWorker } from '../workspace-cleanup.js'
@@ -680,7 +680,7 @@ api.get('/livez', (_req, res) => { res.json({ ok: true, ts: Date.now() }) })
api.get('/health', async (_req, res) => {
try {
await Promise.race([
- pool.query('SELECT 1'),
+ healthPool.query('SELECT 1'),
new Promise((_, reject) => setTimeout(() => reject(new Error('health db check timed out')), 1000)),
])
res.json({ ok: true, ts: Date.now() })
diff --git a/server/src/db/pool.ts b/server/src/db/pool.ts
index 9bd6db8..e904a48 100644
--- a/server/src/db/pool.ts
+++ b/server/src/db/pool.ts
@@ -3,9 +3,19 @@ import { drizzle } from 'drizzle-orm/node-postgres'
import { env } from '../env.js'
import * as schema from './schema.js'
+/** Main request pool size. `DATABASE_POOL_MAX` overrides the default of 20.
+ * Values that are not an integer from 1 to 100 fall back to 20 so a bad
+ * env var cannot open an unbounded number of Cloud SQL connections. */
+export function databasePoolMax(raw = process.env.DATABASE_POOL_MAX): number {
+ if (raw == null || raw.trim() === '') return 20
+ const n = Number(raw)
+ if (!Number.isInteger(n) || n < 1 || n > 100) return 20
+ return n
+}
+
export const pool = new Pool({
connectionString: env.DATABASE_URL,
- max: 20,
+ max: databasePoolMax(),
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
// Defense-in-depth against connection-pool exhaustion. A single slow or stuck
@@ -24,4 +34,19 @@ pool.on('error', (err) => {
console.error('[pg] idle client error', err)
})
+/** Readiness uses its own single connection. `/api/health` must not wait
+ * behind the request pool it is supposed to report on. */
+export const healthPool = new Pool({
+ connectionString: env.DATABASE_URL,
+ max: 1,
+ idleTimeoutMillis: 30_000,
+ connectionTimeoutMillis: 1_000,
+ statement_timeout: 1_000,
+ idle_in_transaction_session_timeout: 30_000,
+})
+
+healthPool.on('error', (err) => {
+ console.error('[pg] health pool error', err)
+})
+
export const db = drizzle(pool, { schema })
diff --git a/server/src/index.ts b/server/src/index.ts
index 2309c80..fcba858 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -11,7 +11,7 @@ import { api } from './api/router.js'
import { storage, UPLOAD_DIR } from './storage.js'
import { attachWebSocket, resetHumanPresenceOnBoot } from './ws.js'
import { bootDocumentBus } from './documents/rooms.js'
-import { pool } from './db/pool.js'
+import { healthPool, pool } from './db/pool.js'
import { redis } from './redis.js'
import { startScanner } from './agents/scanner.js'
import { startScheduler } from './agents/scheduler.js'
@@ -385,6 +385,7 @@ async function main() {
stopRealtimeOutboxWorker()
stopWorkspaceCleanupWorker()
try { await pool.end() } catch { /* ignore */ }
+ try { await healthPool.end() } catch { /* ignore */ }
try { redis.disconnect() } catch { /* ignore */ }
process.exit(0)
}