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
perf(server): stop the idle BYOA fleet from re-planning loadInbox and rewriting last_seen_at (#290)
yetone2054c873acdf
diff --git a/server/src/__integration__/resolve-device-touch.test.ts b/server/src/__integration__/resolve-device-touch.test.tsnew file mode 100644index 0000000..f004cee--- /dev/null+++ b/server/src/__integration__/resolve-device-touch.test.ts@@ -0,0 +1,72 @@+/** resolveDevice used to UPDATE computers.last_seen_at on every device-token+ * request — ~10% of production DB time at fleet scale for a column only read+ * at 90s granularity. It now writes at most once per RESOLVE_DEVICE_TOUCH_MS+ * per token and reads in between; revocation must still bite immediately. */+import { after, before, test } from 'node:test'+import assert from 'node:assert/strict'+import { pool } from '../db/pool.js'+import {+ issuePairingCode,+ pairComputer,+ resetDeviceTouches,+ resolveDevice,+ revokeComputer,+} from '../agents/computer/registry.js'+import { ensureSchemaOnce, seedCompanyWithAgent, teardownAll } from './_helpers.js'++async function lastSeen(computerId: string): Promise<string> {+ const { rows } = await pool.query<{ last_seen_at: string }>(+ `SELECT last_seen_at::text FROM computers WHERE id = $1`, [computerId],+ )+ return rows[0]?.last_seen_at ?? ''+}++async function pairFresh(): Promise<{ computerId: string; companyId: string; deviceToken: string }> {+ const { companyId } = await seedCompanyWithAgent()+ const { code } = await issuePairingCode({ companyId, ownerUserId: 'test-owner' })+ const paired = await pairComputer({ code, hostName: 'touch-test', engines: ['claude'], deferBroadcast: true })+ assert.ok(paired)+ return paired+}++before(async () => { await ensureSchemaOnce() })+after(async () => { await teardownAll() })++test('[integration] resolveDevice bumps last_seen_at once per window, not per request', async () => {+ resetDeviceTouches()+ const { computerId, companyId, deviceToken } = await pairFresh()+ // Age the row so the first resolve visibly moves it.+ await pool.query(`UPDATE computers SET last_seen_at = NOW() - interval '1 hour' WHERE id = $1`, [computerId])+ const aged = await lastSeen(computerId)++ const first = await resolveDevice(deviceToken)+ assert.deepEqual(first, { computerId, companyId })+ const afterFirst = await lastSeen(computerId)+ assert.notEqual(afterFirst, aged, 'first resolve in the window writes')++ // Age it again: a second resolve inside the window must NOT touch the row.+ await pool.query(`UPDATE computers SET last_seen_at = NOW() - interval '1 hour' WHERE id = $1`, [computerId])+ const agedAgain = await lastSeen(computerId)+ const second = await resolveDevice(deviceToken)+ assert.deepEqual(second, { computerId, companyId }, 'read path still resolves the computer')+ assert.equal(await lastSeen(computerId), agedAgain, 'second resolve in the window is a read')++ // Window expired (simulated by forgetting the memo): the next resolve writes.+ resetDeviceTouches()+ await resolveDevice(deviceToken)+ assert.notEqual(await lastSeen(computerId), agedAgain, 'resolve after the window writes again')+})++test('[integration] a revoked device is rejected on the very next request, even inside the window', async () => {+ resetDeviceTouches()+ const { computerId, companyId, deviceToken } = await pairFresh()+ assert.ok(await resolveDevice(deviceToken), 'primes the memo')+ assert.equal(await revokeComputer({ computerId, companyId }), true)+ assert.equal(await resolveDevice(deviceToken), null)+})++test('[integration] an unknown token never resolves and never writes', async () => {+ resetDeviceTouches()+ assert.equal(await resolveDevice('not-a-real-device-token'), null)+ assert.equal(await resolveDevice('not-a-real-device-token'), null)+})diff --git a/server/src/__integration__/status-avail-noop.test.ts b/server/src/__integration__/status-avail-noop.test.tsnew file mode 100644index 0000000..dda1ca9--- /dev/null+++ b/server/src/__integration__/status-avail-noop.test.ts@@ -0,0 +1,56 @@+/** setStatus('avail') on an already-avail participant must be a no-op: no row+ * write, no broadcast. Every BYOA daemon posts avail at the end of every idle+ * poll tick, so at fleet scale the redundant write + Redis fan-out was a+ * measurable share of production DB time. Busy statuses keep writing on+ * repeat because their status_updated_at is a lease. */+import { after, before, test } from 'node:test'+import assert from 'node:assert/strict'+import { pool } from '../db/pool.js'+import { setStatus } from '../status.js'+import { ensureSchemaOnce, seedCompanyWithAgent, teardownAll } from './_helpers.js'++async function statusRow(agentId: string): Promise<{ status: string; at: string }> {+ const { rows } = await pool.query<{ status: string; at: string }>(+ `SELECT status, status_updated_at::text AS at FROM participants WHERE id = $1`, [agentId],+ )+ return rows[0]+}++before(async () => { await ensureSchemaOnce() })+after(async () => { await teardownAll() })++test('[integration] re-asserting avail on an avail participant does not touch the row', async () => {+ const { agentId } = await seedCompanyWithAgent()+ await setStatus(agentId, 'avail')+ await pool.query(`UPDATE participants SET status_updated_at = NOW() - interval '1 hour' WHERE id = $1`, [agentId])+ const initial = await statusRow(agentId)+ assert.equal(initial.status, 'avail')++ await setStatus(agentId, 'avail')+ assert.deepEqual(await statusRow(agentId), initial, 'avail → avail wrote the row')+})++test('[integration] a real transition to avail still writes and stamps the row', async () => {+ const { agentId } = await seedCompanyWithAgent()+ await setStatus(agentId, 'thinking')+ await pool.query(`UPDATE participants SET status_updated_at = NOW() - interval '1 hour' WHERE id = $1`, [agentId])+ const busy = await statusRow(agentId)+ assert.equal(busy.status, 'thinking')++ await setStatus(agentId, 'avail')+ const landed = await statusRow(agentId)+ assert.equal(landed.status, 'avail')+ assert.notEqual(landed.at, busy.at, 'thinking → avail did not stamp status_updated_at')+})++test('[integration] repeating a busy status renews its lease', async () => {+ const { agentId } = await seedCompanyWithAgent()+ await setStatus(agentId, 'working')+ await pool.query(`UPDATE participants SET status_updated_at = NOW() - interval '1 hour' WHERE id = $1`, [agentId])+ const stale = await statusRow(agentId)++ await setStatus(agentId, 'working')+ const renewed = await statusRow(agentId)+ assert.equal(renewed.status, 'working')+ assert.notEqual(renewed.at, stale.at, 'working → working must renew the lease')+})diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex b408249..9f3b34c 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -590,17 +590,59 @@ export async function sweepOfflineComputers(staleMs = COMPUTER_STALE_MS): Promisfor (const r of rows) await broadcastComputerStatus(r.id, r.company_id, 'offline')}+/** How long resolveDevice trusts its own last_seen_at bump before writing+ * again. Every device-token request used to be an UPDATE; with ~870 daemons+ * each sending several requests a minute that row write (and its LWLock+ * wait) was ~10% of production DB time for a timestamp nobody reads at that+ * granularity: sweepOfflineComputers only asks "older than COMPUTER_STALE_MS+ * (90s)?", and the daemon's own 30s heartbeat bumps the column anyway. Kept+ * at a third of the stale window so a replica that only ever sees device+ * requests (no heartbeat) still keeps the computer online. */+export const RESOLVE_DEVICE_TOUCH_MS = 30_000+const deviceTouchedAt = new Map<string, number>()+const DEVICE_TOUCH_MAP_CAP = 10_000++function rememberDeviceTouch(hash: string, now: number): void {+ if (deviceTouchedAt.size >= DEVICE_TOUCH_MAP_CAP) {+ for (const [key, at] of deviceTouchedAt) if (now - at >= RESOLVE_DEVICE_TOUCH_MS) deviceTouchedAt.delete(key)+ if (deviceTouchedAt.size >= DEVICE_TOUCH_MAP_CAP) deviceTouchedAt.clear()+ }+ deviceTouchedAt.set(hash, now)+}++/** Test hook: forget every remembered bump so the next call writes again. */+export function resetDeviceTouches(): void {+ deviceTouchedAt.clear()+}+/** Resolve a device token (Bearer) to its computer. Rejects revoked devices.- * Bumps last_seen_at as a cheap liveness heartbeat. */+ * Bumps last_seen_at as a cheap liveness heartbeat, at most once per+ * RESOLVE_DEVICE_TOUCH_MS per token; in between it is a plain indexed read,+ * so revocation still takes effect on the very next request. */export async function resolveDevice(token: string): Promise<{ computerId: string; companyId: string } | null> {if (!token) return null+ const hash = hashToken(token)+ const now = Date.now()+ const touched = deviceTouchedAt.get(hash)+ if (touched !== undefined && now - touched < RESOLVE_DEVICE_TOUCH_MS) {+ const { rows } = await pool.query<{ id: string; company_id: string }>(+ `SELECT id, company_id FROM computers+ WHERE credential_hash = $1 AND revoked_at IS NULL`,+ [hash],+ )+ if (rows[0]) return { computerId: rows[0].id, companyId: rows[0].company_id }+ // Revoked or gone: drop the memo so a re-pair with the same secret bumps.+ deviceTouchedAt.delete(hash)+ return null+ }const { rows } = await pool.query<{ id: string; company_id: string }>(`UPDATE computers SET last_seen_at = NOW()WHERE credential_hash = $1 AND revoked_at IS NULLRETURNING id, company_id`,- [hashToken(token)],+ [hash],)if (!rows[0]) return null+ rememberDeviceTouch(hash, now)return { computerId: rows[0].id, companyId: rows[0].company_id }}diff --git a/server/src/agents/runtime/inproc-client.ts b/server/src/agents/runtime/inproc-client.tsindex b53cfe7..8057119 100644--- a/server/src/agents/runtime/inproc-client.ts+++ b/server/src/agents/runtime/inproc-client.ts@@ -139,8 +139,15 @@ export class InProcRuntimeClient implements AgentRuntimeClient {// Resolve membership through the normalized participant-led index, then// pull each conversation's unread tail with the message index. This avoids// both the old JSONB seq-scan and its dedicated enable_seqscan=off session.- const { rows } = await pool.query<InboxRow>(- `WITH requesting_agent AS MATERIALIZED (+ //+ // Named statement: this is the single hottest query in production (every+ // BYOA agent's idle poll lands here) and the text never changes, only $1.+ // Unnamed, Postgres re-parsed and re-planned it on every call and planning+ // was ~60% of its measured cost; a name lets each pooled connection keep+ // the parsed statement and plan across calls.+ const { rows } = await pool.query<InboxRow>({+ name: 'runtime_load_inbox',+ text: `WITH requesting_agent AS MATERIALIZED (SELECT company_idFROM participantsWHERE id = $1 AND kind = 'agent' AND departed_at IS NULL@@ -223,8 +230,8 @@ export class InProcRuntimeClient implements AgentRuntimeClient {LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = co.company_idORDER BY m.created_at ASC, m.id ASCLIMIT 200`,- [agentId],- )+ values: [agentId],+ })await refreshAttachmentUrls(rows)// NOTE: This used to call recordSeen() here to advance the freshness-// preflight boundary, but that fired for EVERY caller of loadInbox —diff --git a/server/src/status.ts b/server/src/status.tsindex 3cae73a..b33cb83 100644--- a/server/src/status.ts+++ b/server/src/status.ts@@ -22,12 +22,26 @@ function toIso(value: unknown): string {* tenant's connected clients see the transition.*/export async function setStatus(participantId: string, status: ParticipantStatus): Promise<void> {+ // `avail` carries no lease: `status_updated_at` only matters for the busy+ // statuses (routing-election reads it to tell "mid-turn" from "stale"), so+ // re-asserting avail on an already-avail row has nothing to record. Skipping+ // it matters because every BYOA daemon posts avail at the end of every idle+ // poll tick — at fleet scale that was ~180 row writes + Redis fan-outs per+ // second (each fan-out re-resolving the tenant's WS recipients on every+ // replica) to announce a status nobody changed. Busy statuses still always+ // write: a repeat is a lease renewal.const { rows } = await pool.query<{ company_id: string; status_updated_at: Date }>(- `UPDATE participants- SET status = $2,- status_updated_at = NOW()- WHERE id = $1- RETURNING company_id, status_updated_at`,+ status === 'avail'+ ? `UPDATE participants+ SET status = $2,+ status_updated_at = NOW()+ WHERE id = $1 AND status IS DISTINCT FROM $2+ RETURNING company_id, status_updated_at`+ : `UPDATE participants+ SET status = $2,+ status_updated_at = NOW()+ WHERE id = $1+ RETURNING company_id, status_updated_at`,[participantId, status],)for (const r of rows) {