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(search): don't cancel a search by pid alone
zhuangxialie6460e9628ca6
diff --git a/server/src/__integration__/search-cancel-recycled-connection.test.ts b/server/src/__integration__/search-cancel-recycled-connection.test.tsnew file mode 100644index 0000000..13e485e--- /dev/null+++ b/server/src/__integration__/search-cancel-recycled-connection.test.ts@@ -0,0 +1,130 @@+/**+ * The abandoned-search cancel must land on the search it was fired for.+ *+ * `searchMessagesBounded` captures a backend pid and, when the sidebar aborts+ * on the next keystroke, fires `pg_cancel_backend` from another connection.+ * Nothing awaits that cancel, so it can still be in flight when the abandoned+ * search finishes on its own and the connection goes back to the pool. The idle+ * pool is a LIFO stack: the next borrower gets that same backend, and a cancel+ * addressed only by pid lands on THEIR query.+ *+ * These run the race against a real Postgres rather than asserting on a string,+ * because every part of it — LIFO reuse, `set_config` reverting at COMMIT, what+ * a cancel does to a backend that has moved on — is the database's behaviour,+ * not ours.+ */+import { test, before, after } from 'node:test'+import assert from 'node:assert/strict'+import { readFile } from 'node:fs/promises'+import { randomUUID } from 'node:crypto'+import { ensureSchemaOnce, teardownAll } from './_helpers.js'+import { pool } from '../db/pool.js'+import { CANCEL_ABANDONED_SEARCH_SQL } from '../api/router.js'++before(async () => { await ensureSchemaOnce() })+after(async () => { await teardownAll() })++/** What `searchMessagesBounded` does to a connection, up to the point the+ * caller walks away: bound it, publish a token for it, then finish and let go. */+async function runAndReleaseSearch(token: string): Promise<number> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query('SET LOCAL statement_timeout = 3000')+ const { rows } = await client.query<{ pid: number }>(+ 'SELECT pg_backend_pid() AS pid, set_config($1, $2, true)',+ ['application_name', token],+ )+ await client.query('SELECT 1')+ await client.query('COMMIT')+ return rows[0].pid+ } finally {+ client.release()+ }+}++test('[integration] a late cancel does not kill the next borrower of the backend', async () => {+ const token = `cumora-search:${randomUUID()}`+ const pid = await runAndReleaseSearch(token)++ const next = await pool.connect()+ try {+ const nextPid = (await next.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')).rows[0].pid+ assert.equal(nextPid, pid, 'the pool did not hand the backend straight back — the race under test was not reproduced')++ // The cancel arrives now, while the new borrower is mid-query.+ const innocent = next.query('SELECT pg_sleep(0.5)')+ const fired = await pool.query(CANCEL_ABANDONED_SEARCH_SQL, [pid, token])+ assert.equal(fired.rowCount, 0, 'the guard matched a backend that is no longer running our search')+ await innocent++ // And the same moment with a pid-only cancel, so the guard is not merely+ // decorative: this is what it is standing in front of.+ const victim = next.query('SELECT pg_sleep(2)').then(() => null).catch((e: { code?: string }) => e.code)+ await new Promise((r) => setTimeout(r, 150))+ await pool.query('SELECT pg_cancel_backend($1)', [pid])+ assert.equal(await victim, '57014', 'a pid-only cancel was expected to kill the unrelated query')+ } finally {+ next.release()+ }+})++test('[integration] the guard still cancels the search it belongs to', async () => {+ const token = `cumora-search:${randomUUID()}`+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const pid = (await client.query<{ pid: number }>(+ 'SELECT pg_backend_pid() AS pid, set_config($1, $2, true)',+ ['application_name', token],+ )).rows[0].pid+ const search = client.query('SELECT pg_sleep(5)').then(() => null).catch((e: { code?: string }) => e.code)+ await new Promise((r) => setTimeout(r, 250))++ const started = Date.now()+ const fired = await pool.query(CANCEL_ABANDONED_SEARCH_SQL, [pid, token])+ assert.equal(fired.rowCount, 1)+ assert.equal(await search, '57014')+ assert.ok(Date.now() - started < 2_000, 'the cancel did not take effect promptly')+ await client.query('ROLLBACK').catch(() => {})+ } finally {+ client.release()+ }+})++test('[integration] the token lives exactly as long as the search transaction', async () => {+ // The guard rests entirely on this: `set_config(…, is_local => true)` must+ // revert when the transaction ends, or a released connection would keep+ // answering to a cancel meant for a search that is long over.+ const token = `cumora-search:${randomUUID()}`+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query('SELECT set_config($1, $2, true)', ['application_name', token])+ const during = (await client.query<{ application_name: string }>(+ 'SELECT application_name FROM pg_stat_activity WHERE pid = pg_backend_pid()')).rows[0].application_name+ assert.equal(during, token)+ await client.query('COMMIT')+ const after = (await client.query<{ application_name: string }>(+ 'SELECT application_name FROM pg_stat_activity WHERE pid = pg_backend_pid()')).rows[0].application_name+ assert.notEqual(after, token)+ } finally {+ client.release()+ }+})++test('[integration] the search route still names the search it cancels', async () => {+ // The three tests above pass just as well against a route that went back to a+ // bare `pg_cancel_backend($1)` — they exercise the SQL, not the caller. Read+ // the source so the caller cannot quietly stop using it.+ const source = await readFile(new URL('../api/router.ts', import.meta.url), 'utf8')+ const body = source.slice(source.indexOf('async function searchMessagesBounded'))+ const fn = body.slice(0, body.indexOf('\n}\n') + 2)++ assert.match(fn, /set_config/, 'the search no longer publishes a token for its backend')+ assert.match(fn, /CANCEL_ABANDONED_SEARCH_SQL/, 'the cancel no longer goes through the guarded statement')+ assert.doesNotMatch(+ fn, /pg_cancel_backend\(\$1\)/,+ 'the search is cancelling by pid alone again — a late cancel will hit whoever borrows the connection next',+ )+})diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex 066630a..2109e99 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -5029,7 +5029,24 @@ class QueryAbandonedError extends Error {}* a command). A cancelled or timed-out search resolves to no rows rather than* throwing: there is no longer anyone to show an error to, and a partial* dropdown is a better failure than a 500.+ *+ * A pid alone is not a safe thing to cancel. Nothing waits for that cancel — it+ * is fired with `void` — so it can still be in flight when the abandoned search+ * finishes on its own and `finally` hands the connection back. The idle pool is+ * a LIFO stack, so the very next borrower gets that same backend, and the+ * cancel lands on THEIR query. Measured against Postgres 16: it kills them with+ * 57014, which for another search means silently empty results and for anything+ * else a 500 — on a request that did nothing wrong.+ *+ * So the cancel names the search, not just the backend. Each search publishes a+ * unique token as its `application_name` for the life of its transaction+ * (`set_config(…, is_local => true)`, so it reverts at COMMIT/ROLLBACK exactly+ * like the timeout above), and the cancel only fires on a backend still+ * carrying that token. A cancel that arrives late now matches nothing.*/+export const CANCEL_ABANDONED_SEARCH_SQL = `SELECT pg_cancel_backend(pid) FROM pg_stat_activity+ WHERE pid = $1 AND application_name = $2 AND state = 'active'`+async function searchMessagesBounded(res: Response,params: unknown[],@@ -5038,13 +5055,16 @@ async function searchMessagesBounded(const client = await pool.connect()let backendPid: number | null = nulllet abandoned = false+ // Identifies THIS search on THIS backend, for exactly as long as it runs.+ const searchToken = `cumora-search:${randomUUID()}`const cancelIfRunning = (): void => {// `close` also fires on a normal, fully-written response — only an early// close means the caller is gone.if (res.writableEnded) returnabandoned = trueif (backendPid == null) return- void pool.query('SELECT pg_cancel_backend($1)', [backendPid]).catch(() => { /* best effort */ })+ void pool.query(CANCEL_ABANDONED_SEARCH_SQL, [backendPid, searchToken])+ .catch(() => { /* best effort */ })}res.on('close', cancelIfRunning)try {@@ -5052,7 +5072,12 @@ async function searchMessagesBounded(// SET LOCAL, not SET: the deadline dies with this transaction, so releasing// the connection cannot leak a 3s timeout onto the next borrower.await client.query(`SET LOCAL statement_timeout = ${SEARCH_MESSAGE_TIMEOUT_MS}`)- const pid = await client.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')+ // Both in one round trip — the token has to be published before we hand the+ // pid to a canceller, and SET takes no bind parameter, so set_config it is.+ const pid = await client.query<{ pid: number }>(+ 'SELECT pg_backend_pid() AS pid, set_config($1, $2, true)',+ ['application_name', searchToken],+ )backendPid = pid.rows[0]?.pid ?? nullif (abandoned) throw new QueryAbandonedError()const result = await client.query<{ body: string } & Record<string, unknown>>(sql, params)