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(search): global search must not seq-scan every message body (#218)

OKNOTOK1e6b8816bd47
diff --git a/server/src/__integration__/search-trigram.test.ts b/server/src/__integration__/search-trigram.test.ts
new file mode 100644
index 0000000..6acda30
--- /dev/null
+++ b/server/src/__integration__/search-trigram.test.ts
@@ -0,0 +1,144 @@
+/**
+ * Integration tests for index-backed global message search (migration 0005).
+ *
+ * The contract under test is not "an index exists" — `schema-migrations.test.ts`
+ * already asserts every promotion-required index is valid/ready/live. It is
+ * that the planner can actually USE `idx_messages_body_trgm` for the predicate
+ * the search route issues, and that making the query index-backed did not
+ * change a single result.
+ */
+import { test, before, beforeEach, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { createServer, type Server } from 'node:http'
+import {
+ buildApiTestApp, ensureSchemaOnce, resetAllTables, seedUserMembership, teardownAll,
+} from './_helpers.js'
+import { pool } from '../db/pool.js'
+
+const ME_USER_ID = 'u-searcher'
+const COMPANY_ID = 'c-search-trgm'
+const CONVERSATION_ID = 'g-search-trgm'
+let server: Server
+let baseUrl = ''
+
+interface SearchResponse {
+ messages: Array<{ id: string; snippet: string }>
+ participants: Array<{ id: string }>
+}
+
+before(async () => {
+ await ensureSchemaOnce()
+ const app = await buildApiTestApp(ME_USER_ID)
+ await new Promise<void>((resolve) => {
+ server = createServer(app).listen(0, '127.0.0.1', () => {
+ const addr = server.address()
+ if (addr && typeof addr === 'object') baseUrl = `http://127.0.0.1:${addr.port}`
+ resolve()
+ })
+ })
+})
+
+beforeEach(async () => {
+ await resetAllTables()
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id)
+ VALUES ($1, 'Search Co', 'search-co', $2)`,
+ [COMPANY_ID, ME_USER_ID],
+ )
+ await seedUserMembership(ME_USER_ID, COMPANY_ID, { displayName: 'Searcher' })
+ await pool.query(
+ `INSERT INTO conversations (id, kind, title, members, company_id)
+ VALUES ($1, 'group', 'Search room', $2::jsonb, $3)`,
+ [CONVERSATION_ID, JSON.stringify([ME_USER_ID]), COMPANY_ID],
+ )
+})
+
+after(async () => { await teardownAll(server) })
+
+async function seedMessages(bodies: string[]): Promise<void> {
+ let sequence = 1
+ for (const body of bodies) {
+ await pool.query(
+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)
+ VALUES ($1, $2, $3, 'text', $4, $5, $6)`,
+ [`m-${sequence}`, CONVERSATION_ID, ME_USER_ID, body, sequence, COMPANY_ID],
+ )
+ sequence += 1
+ }
+}
+
+async function search(q: string): Promise<SearchResponse> {
+ const res = await fetch(`${baseUrl}/api/search?q=${encodeURIComponent(q)}`, {
+ headers: { 'x-company-id': COMPANY_ID },
+ })
+ assert.equal(res.status, 200)
+ return await res.json() as SearchResponse
+}
+
+test('[integration] the planner can serve a body ILIKE from the trigram index', async () => {
+ await seedMessages(['the quarterly contract is attached', 'unrelated chatter'])
+ // A handful of rows fits in one page, so a seq scan is genuinely the cheaper
+ // plan and the planner will (correctly) pick it. Disabling seq scans asks the
+ // question we actually care about: is this index a *usable* path for
+ // `body ILIKE '%…%'` at all? Before pg_trgm the answer was no at any size,
+ // and the query degraded to O(messages) on production-sized tables.
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ // TRUNCATE in resetAllTables() leaves stale reltuples behind; give the
+ // planner real numbers so the choice below is about path availability.
+ await client.query('ANALYZE messages')
+ await client.query('SET LOCAL enable_seqscan = off')
+ const { rows } = await client.query<{ 'QUERY PLAN': string }>(
+ `EXPLAIN SELECT id FROM messages
+ WHERE kind = 'text' AND body ILIKE $1 ESCAPE '\\'`,
+ ['%contract%'],
+ )
+ await client.query('COMMIT')
+ const plan = rows.map((r) => r['QUERY PLAN']).join('\n')
+ assert.match(plan, /idx_messages_body_trgm/,
+ `body ILIKE must be answerable from the trigram index. Plan was:\n${plan}`)
+ } finally {
+ client.release()
+ }
+})
+
+test('[integration] search results are unchanged by the index, including CJK and escapes', async () => {
+ await seedMessages([
+ 'the quarterly contract is attached',
+ '这是第一季度的合同草案',
+ 'literal 100% match rate',
+ 'unrelated chatter',
+ ])
+
+ const ascii = await search('contract')
+ assert.deepEqual(ascii.messages.map((m) => m.id), ['m-1'])
+
+ // A CJK term is three characters, so it has a complete trigram and rides the
+ // same index path as ASCII.
+ const cjk = await search('合同草案')
+ assert.deepEqual(cjk.messages.map((m) => m.id), ['m-2'])
+
+ // `%` is escaped, not treated as a wildcard: it must match the literal only.
+ const literalPercent = await search('100%')
+ assert.deepEqual(literalPercent.messages.map((m) => m.id), ['m-3'])
+
+ // A term nobody used returns nothing rather than everything.
+ const miss = await search('zzzznotpresent')
+ assert.deepEqual(miss.messages, [])
+})
+
+test('[integration] a single-character query skips the message bucket, not the whole search', async () => {
+ await seedMessages(['the quarterly contract is attached'])
+
+ const single = await search('S')
+ // One character yields no complete trigram, so the bucket would be a full
+ // scan whose top rows are just "the newest messages" — no answer to anything.
+ assert.deepEqual(single.messages, [], 'one character must not scan message bodies')
+ // The other buckets are small, indexed tables and stay useful.
+ assert.deepEqual(single.participants.map((p) => p.id), [ME_USER_ID])
+
+ // Two characters is the floor, because CJK terms are commonly that short.
+ const pair = await search('co')
+ assert.deepEqual(pair.messages.map((m) => m.id), ['m-1'])
+})
diff --git a/server/src/__tests__/schema-migrations.test.ts b/server/src/__tests__/schema-migrations.test.ts
index 58948c6..d47ccd6 100644
--- a/server/src/__tests__/schema-migrations.test.ts
+++ b/server/src/__tests__/schema-migrations.test.ts
@@ -16,6 +16,7 @@ const { computedBaselineMigrationChecksum } = await import('../db/migrate.js')
const { normalizedConversationMembersChecksum } = await import('../db/migrations/0002-normalized-conversation-members.js')
const { workspaceCleanupJobsChecksum } = await import('../db/migrations/0003-workspace-cleanup-jobs.js')
const { agentRuntimeAssignmentChecksum } = await import('../db/migrations/0004-agent-runtime-assignment.js')
+const { searchTrigramIndexChecksum } = await import('../db/migrations/0005-search-trigram-index.js')
const { verifySchemaCompatibility } = await import('../db/schema-version.js')
type SchemaVersionQueryable = import('../db/schema-version.js').SchemaVersionQueryable
@@ -37,6 +38,10 @@ test('the runtime assignment migration matches its immutable manifest checksum',
assert.equal(agentRuntimeAssignmentChecksum(), SCHEMA_MIGRATIONS[3].checksum)
})
+test('the search trigram migration matches its immutable manifest checksum', () => {
+ assert.equal(searchTrigramIndexChecksum(), SCHEMA_MIGRATIONS[4].checksum)
+})
+
test('the migration owner accepts an exact prefix and reports its pending suffix', () => {
const empty = validateMigrationHistory([], { allowPending: true })
assert.equal(empty.currentVersion, 0)
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index e05b084..870924c 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -4960,6 +4960,90 @@ api.post('/messages/:id/reactions', async (req, res) => {
* an agent (no humans). Messages live in the unified `messages` table.
*/
+/**
+ * Hard deadline for the message-body bucket of global search.
+ *
+ * `idx_messages_body_trgm` (migration 0005) answers most `%term%` patterns from
+ * the index, but a pattern shorter than three characters produces no complete
+ * trigram and still plans as a scan — two-character CJK queries are the common
+ * case. The pool's global 60s `statement_timeout` is far too generous for
+ * something the sidebar re-issues on every typing pause: a handful of those in
+ * flight is enough to hold every slot. Three seconds is well past a healthy
+ * indexed search and reaps the rest.
+ */
+const SEARCH_MESSAGE_TIMEOUT_MS = 3_000
+
+/**
+ * A single trigram needs three characters, so `%ab%` has none to look up and
+ * the planner falls back to a scan. Two-character queries are ordinary in CJK,
+ * so we still run them (bounded by the deadline above) — but a ONE-character
+ * pattern matches most of the corpus, meaning a full scan whose top-15 rows are
+ * effectively "the newest messages", which is not an answer to anything.
+ */
+const SEARCH_MESSAGE_MIN_LENGTH = 2
+
+/** Raised when the caller disconnects before the query is even issued. */
+class QueryAbandonedError extends Error {}
+
+/**
+ * Run the message-body search on its own connection under a bounded deadline,
+ * and actually cancel it when the caller walks away.
+ *
+ * The sidebar aborts its fetch on every keystroke after the debounce. Aborting
+ * the HTTP request does nothing to the query already executing in PostgreSQL —
+ * that backend keeps its pool slot until it finishes on its own. So we capture
+ * the backend pid up front and, if the response closes early, issue
+ * `pg_cancel_backend` from a *different* connection (the busy one cannot accept
+ * 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.
+ */
+async function searchMessagesBounded(
+ res: Response,
+ params: unknown[],
+ sql: string,
+): Promise<{ rows: Array<{ body: string } & Record<string, unknown>> }> {
+ const client = await pool.connect()
+ let backendPid: number | null = null
+ let abandoned = false
+ const cancelIfRunning = (): void => {
+ // `close` also fires on a normal, fully-written response — only an early
+ // close means the caller is gone.
+ if (res.writableEnded) return
+ abandoned = true
+ if (backendPid == null) return
+ void pool.query('SELECT pg_cancel_backend($1)', [backendPid]).catch(() => { /* best effort */ })
+ }
+ res.on('close', cancelIfRunning)
+ try {
+ await client.query('BEGIN')
+ // 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')
+ backendPid = pid.rows[0]?.pid ?? null
+ if (abandoned) throw new QueryAbandonedError()
+ const result = await client.query<{ body: string } & Record<string, unknown>>(sql, params)
+ await client.query('COMMIT')
+ return { rows: result.rows }
+ } catch (error) {
+ await client.query('ROLLBACK').catch(() => { /* connection may be dead */ })
+ // 57014 = query_canceled, raised by both statement_timeout and our own
+ // pg_cancel_backend. Everything else is a real fault worth surfacing.
+ const code = (error as { code?: unknown } | null)?.code
+ if (code === '57014' || error instanceof QueryAbandonedError) {
+ if (!abandoned) {
+ console.warn(`[search] message bucket exceeded ${SEARCH_MESSAGE_TIMEOUT_MS}ms and was cancelled`)
+ }
+ return { rows: [] }
+ }
+ throw error
+ } finally {
+ res.off('close', cancelIfRunning)
+ client.release()
+ }
+}
+
/**
* Universal search across the workspace.
*
@@ -5101,7 +5185,10 @@ api.get('/search', async (req, res) => {
// Skip `tool` / `system` rows — those bodies are machine output, not
// human-written content, and they'd flood the list with JSON snippets.
- const messagesP = pool.query(
+ // (`idx_messages_body_trgm` is partial on exactly this predicate.)
+ const messagesP = raw.length < SEARCH_MESSAGE_MIN_LENGTH
+ ? Promise.resolve({ rows: [] as Array<{ body: string } & Record<string, unknown>> })
+ : searchMessagesBounded(res, [tenant, me, contains],
`SELECT m.id,
m.conversation_id AS "conversationId",
CASE
@@ -5139,7 +5226,6 @@ api.get('/search', async (req, res) => {
AND m.body ILIKE $3 ESCAPE '\\'
ORDER BY m.created_at DESC
LIMIT ${M_LIMIT}`,
- [tenant, me, contains],
)
const [participants, rooms, groups, messages] = await Promise.all([
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index dcb691e..cfb8dd6 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -25,6 +25,12 @@ import {
AGENT_RUNTIME_ASSIGNMENT_SQL,
agentRuntimeAssignmentChecksum,
} from './migrations/0004-agent-runtime-assignment.js'
+import {
+ SEARCH_TRIGRAM_EXTENSION_SQL,
+ SEARCH_TRIGRAM_INDEX_NAME,
+ SEARCH_TRIGRAM_INDEX_SQL,
+ searchTrigramIndexChecksum,
+} from './migrations/0005-search-trigram-index.js'
/** Frozen data backfill embedded in migration 0001. Exported so its behavior
* can be exercised against PostgreSQL without replaying the whole migration. */
@@ -2366,6 +2372,15 @@ async function applyAgentRuntimeAssignment(client: import('pg').PoolClient): Pro
await client.query(AGENT_RUNTIME_ASSIGNMENT_SQL)
}
+/** Declared `transactional: false` below: PostgreSQL refuses CONCURRENTLY
+ * inside a transaction block. Both statements are idempotent, and
+ * `ensureConcurrentIndex` repairs an INVALID index left by an interrupted
+ * build, so an aborted run is safe to rerun. */
+async function applySearchTrigramIndex(client: import('pg').PoolClient): Promise<void> {
+ await client.query(SEARCH_TRIGRAM_EXTENSION_SQL)
+ await ensureConcurrentIndex(client, SEARCH_TRIGRAM_INDEX_NAME, SEARCH_TRIGRAM_INDEX_SQL)
+}
+
const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
{
...SCHEMA_MIGRATIONS[0],
@@ -2391,6 +2406,13 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
transactional: true,
up: applyAgentRuntimeAssignment,
},
+ {
+ ...SCHEMA_MIGRATIONS[4],
+ sourceChecksum: searchTrigramIndexChecksum(),
+ // CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
+ transactional: false,
+ up: applySearchTrigramIndex,
+ },
]
export async function applyPendingMigration(
@@ -2564,6 +2586,40 @@ async function ensureMessageClientIdIndex(client: import('pg').PoolClient): Prom
* stops promotion but cannot crash-loop application replicas because replicas
* never run this code.
*/
+/**
+ * Build one `CREATE INDEX CONCURRENTLY` idempotently.
+ *
+ * `IF NOT EXISTS` alone is not enough: an interrupted concurrent build leaves an
+ * INVALID index behind that `IF NOT EXISTS` would then skip forever, so the
+ * table keeps paying for an index no planner will use. Check the catalog first
+ * and drop the dead entry before rebuilding.
+ *
+ * MUST run outside any transaction block — PostgreSQL forbids CONCURRENTLY
+ * inside one. Callers from the versioned ledger therefore declare
+ * `transactional: false`.
+ */
+export async function ensureConcurrentIndex(
+ client: import('pg').PoolClient,
+ name: string,
+ create: string,
+): Promise<void> {
+ const { rows } = await client.query<{ indisvalid: boolean; indisready: boolean; indislive: boolean }>(
+ `SELECT i.indisvalid, i.indisready, i.indislive FROM pg_class c
+ JOIN pg_index i ON i.indexrelid = c.oid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = current_schema() AND c.relname = $1`,
+ [name],
+ )
+ if (rows[0] && (!rows[0].indisvalid || !rows[0].indisready || !rows[0].indislive)) {
+ console.warn(`[db] dropping invalid leftover index ${name} before rebuild`)
+ await client.query(`DROP INDEX CONCURRENTLY IF EXISTS ${name}`)
+ } else if (rows[0]) {
+ return
+ }
+ await client.query(create)
+ console.log(`[db] concurrent index ready: ${name}`)
+}
+
async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<void> {
const indexes: Array<{ name: string; create: string }> = [
{
@@ -2605,21 +2661,7 @@ async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<
},
]
for (const ix of indexes) {
- const { rows } = await client.query<{ indisvalid: boolean; indisready: boolean; indislive: boolean }>(
- `SELECT i.indisvalid, i.indisready, i.indislive FROM pg_class c
- JOIN pg_index i ON i.indexrelid = c.oid
- JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE n.nspname = current_schema() AND c.relname = $1`,
- [ix.name],
- )
- if (rows[0] && (!rows[0].indisvalid || !rows[0].indisready || !rows[0].indislive)) {
- console.warn(`[db] dropping invalid leftover index ${ix.name} before rebuild`)
- await client.query(`DROP INDEX CONCURRENTLY IF EXISTS ${ix.name}`)
- } else if (rows[0]) {
- continue
- }
- await client.query(ix.create)
- console.log(`[db] concurrent index ready: ${ix.name}`)
+ await ensureConcurrentIndex(client, ix.name, ix.create)
}
}
@@ -2640,6 +2682,7 @@ export const REQUIRED_SCHEMA_INDEXES = [
...BASELINE_REQUIRED_SCHEMA_INDEXES,
'conversation_members_conversation_ordinal_key',
'idx_conversation_members_participant',
+ SEARCH_TRIGRAM_INDEX_NAME,
] as const
/** Promotion gate: every required index must exist and be valid, ready, and
diff --git a/server/src/db/migrations/0005-search-trigram-index.ts b/server/src/db/migrations/0005-search-trigram-index.ts
new file mode 100644
index 0000000..9c416bb
--- /dev/null
+++ b/server/src/db/migrations/0005-search-trigram-index.ts
@@ -0,0 +1,46 @@
+import { createHash } from 'node:crypto'
+
+/**
+ * Migration 0005: make global message search index-backed.
+ *
+ * `GET /search` matched message bodies with `body ILIKE '%term%'`, which no
+ * btree can serve — a leading wildcard forces a sequential scan of every row
+ * the tenant/membership filter lets through. A rare or misspelled term reads
+ * the whole table, and the sidebar issues a fresh search on every typing
+ * pause, so a handful of concurrent searches were enough to hold the pool.
+ *
+ * `gin_trgm_ops` indexes the three-character shingles of each body, so the
+ * planner can answer `%term%` from the index instead. Partial on `kind =
+ * 'text'` for two reasons: the search route already excludes `tool` / `system`
+ * rows (machine output, not human-written), and every message INSERT pays the
+ * GIN maintenance cost, so keeping non-searchable kinds out of the index keeps
+ * that cost off the rows nobody will ever search.
+ *
+ * Known boundary: a pattern shorter than three characters yields no complete
+ * trigram, so a two-character query (common in CJK) still plans as a scan. The
+ * route bounds those with its own `statement_timeout` rather than refusing
+ * them — see the search handler in api/router.ts.
+ */
+export const SEARCH_TRIGRAM_INDEX_NAME = 'idx_messages_body_trgm'
+
+/** Runs before the concurrent build, and is transactional-safe on its own. */
+export const SEARCH_TRIGRAM_EXTENSION_SQL = `
+CREATE EXTENSION IF NOT EXISTS pg_trgm;
+`
+
+/**
+ * MUST run outside a transaction block. Built CONCURRENTLY because `messages`
+ * is the hottest write path in the product: a plain CREATE INDEX takes a
+ * SHARE lock and stalls every sender for the duration of the build.
+ */
+export const SEARCH_TRIGRAM_INDEX_SQL = `
+CREATE INDEX CONCURRENTLY IF NOT EXISTS ${SEARCH_TRIGRAM_INDEX_NAME}
+ ON messages USING gin (body gin_trgm_ops)
+ WHERE kind = 'text'
+`
+
+export function searchTrigramIndexChecksum(): string {
+ return createHash('sha256')
+ .update(SEARCH_TRIGRAM_EXTENSION_SQL + SEARCH_TRIGRAM_INDEX_SQL)
+ .digest('hex')
+}
diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.ts
index 6d933ac..010935e 100644
--- a/server/src/db/migrations/manifest.ts
+++ b/server/src/db/migrations/manifest.ts
@@ -37,12 +37,17 @@ export const SCHEMA_MIGRATIONS = [
name: '0004_agent_runtime_assignment',
checksum: '59956150df026c36238298603ed47438abf154cfc779034758d7141a79ae00b2',
},
+ {
+ version: 5,
+ name: '0005_search_trigram_index',
+ checksum: 'eac389304940a9af260ebc51e13b97f5d0d9d0148460debceaf328d8bbcd76f2',
+ },
] as const satisfies readonly MigrationMetadata[]
/** This build intentionally supports one exact schema range. Expand/contract
* releases may widen the range, but both bounds must remain explicit. */
-export const MIN_SUPPORTED_SCHEMA_VERSION = 4
-export const MAX_SUPPORTED_SCHEMA_VERSION = 4
+export const MIN_SUPPORTED_SCHEMA_VERSION = 5
+export const MAX_SUPPORTED_SCHEMA_VERSION = 5
function assertManifestShape(): void {
for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {
diff --git a/src/desktop/ConversationsPane.tsx b/src/desktop/ConversationsPane.tsx
index f0d79cb..e494640 100644
--- a/src/desktop/ConversationsPane.tsx
+++ b/src/desktop/ConversationsPane.tsx
@@ -649,6 +649,12 @@ export function ConversationsPane({ onResizeStart }: { onResizeStart?: (e: React
// Backend search: debounced API call with abort. We must not load every
// message into the client — the universal search hits SQL on each
// keystroke (after debounce) and returns four ranked buckets.
+ //
+ // 300ms, not 150: at typing speed the shorter window fired a second query
+ // before the first had returned, and each one occupies a connection for as
+ // long as the message-body bucket runs. The server now cancels an abandoned
+ // search (see `searchMessagesBounded`), but not issuing it at all is cheaper
+ // still, and the extra 150ms is imperceptible against the round trip.
const [results, setResults] = useState<ApiSearchResults | null>(null)
const [searching, setSearching] = useState(false)
useEffect(() => {
@@ -665,7 +671,7 @@ export function ConversationsPane({ onResizeStart }: { onResizeStart?: (e: React
console.warn('[search] failed', err)
setSearching(false)
})
- }, 150)
+ }, 300)
return () => { window.clearTimeout(handle); ctl.abort() }
}, [query])