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(scanner): background scans must be claimed once, not run per replica (#219)

OKNOTOKc53989f18793
diff --git a/server/src/__integration__/agent-scanner.test.ts b/server/src/__integration__/agent-scanner.test.ts
index c4f078b..edc87f5 100644
--- a/server/src/__integration__/agent-scanner.test.ts
+++ b/server/src/__integration__/agent-scanner.test.ts
@@ -11,6 +11,7 @@ import { randomUUID } from 'node:crypto'
import { pool } from '../db/pool.js'
import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'
import {
+ __scannerCacheInternals,
__setBackgroundScannerWakeForTesting,
_resetBackgroundScannerForTests,
runBackgroundScans,
@@ -23,11 +24,11 @@ before(async () => {
beforeEach(async () => {
await resetAllTables()
- _resetBackgroundScannerForTests()
+ await _resetBackgroundScannerForTests()
})
after(async () => {
- _resetBackgroundScannerForTests()
+ await _resetBackgroundScannerForTests()
await teardownAll()
})
@@ -154,3 +155,48 @@ test('[integration] background scanner does not spend fingerprint or write audit
await runBackgroundScans()
assert.equal(attempts, 2, 'scanner must not wake again after successful scan')
})
+
+test('[integration] only one replica scans per tick', async () => {
+ await seedCompanyWithScannerAgent()
+ let attempts = 0
+ __setBackgroundScannerWakeForTesting(async () => {
+ attempts++
+ // Hold the pass open long enough that a concurrent caller is guaranteed to
+ // reach the lock while this one still owns it.
+ await new Promise((resolve) => setTimeout(resolve, 120))
+ return true
+ })
+
+ // Two passes in flight at once is exactly what N replicas do every 90s.
+ await Promise.all([runBackgroundScans(), runBackgroundScans()])
+ assert.equal(attempts, 1,
+ 'the replica that loses the advisory lock must do nothing, not repeat the pass')
+
+ // And the lock is released, not leaked — a later tick still works. It finds
+ // the Redis claim from the first pass and skips, which is the correct
+ // outcome and proves the lock did not wedge.
+ await runBackgroundScans()
+ assert.equal(attempts, 1)
+})
+
+test('[integration] a fresh process does not re-wake activity another replica already claimed', async () => {
+ const { agentId } = await seedCompanyWithScannerAgent()
+ let attempts = 0
+ __setBackgroundScannerWakeForTesting(async () => { attempts++; return true })
+
+ await runBackgroundScans()
+ assert.equal(attempts, 1)
+
+ // Simulate the lock moving to a replica that has never seen this activity:
+ // same database, same Redis, empty in-process cache. Before the claim
+ // existed, this re-woke the agent on every restart and on every leader move.
+ __scannerCacheInternals.clear()
+ await runBackgroundScans()
+ assert.equal(attempts, 1, 'the Redis claim must survive an empty local cache')
+
+ const { rows } = await pool.query(
+ `SELECT 1 FROM agent_log WHERE agent_id = $1 AND body LIKE 'background scan wake queued%'`,
+ [agentId],
+ )
+ assert.equal(rows.length, 1, 'exactly one audit row, not one per replica')
+})
diff --git a/server/src/__tests__/agents-scanner-budget-retry.test.ts b/server/src/__tests__/agents-scanner-budget-retry.test.ts
index 289063e..172cbf9 100644
--- a/server/src/__tests__/agents-scanner-budget-retry.test.ts
+++ b/server/src/__tests__/agents-scanner-budget-retry.test.ts
@@ -7,11 +7,16 @@ const { pool } = await import('../db/pool.js')
const {
__setBackgroundScannerWakeForTesting,
_resetBackgroundScannerForTests,
- runBackgroundScans,
+ scanOnce,
} = await import('../agents/scanner.js')
const originalQuery = pool.query.bind(pool)
+// Drives `scanOnce` rather than `runBackgroundScans`: this file stubs
+// `pool.query` to script the scan, and the leader lock in `runBackgroundScans`
+// takes a real connection via `pool.connect()`, which the stub cannot reach.
+// The lock is exercised for real in the integration suite instead.
+
after(async () => {
try { await pool.end() } catch { /* ignore */ }
try {
@@ -21,12 +26,12 @@ after(async () => {
} catch { /* ignore */ }
})
-beforeEach(() => {
- _resetBackgroundScannerForTests()
+beforeEach(async () => {
+ await _resetBackgroundScannerForTests()
})
-afterEach(() => {
- _resetBackgroundScannerForTests()
+afterEach(async () => {
+ await _resetBackgroundScannerForTests()
;(pool as unknown as { query: typeof originalQuery }).query = originalQuery
})
@@ -82,19 +87,19 @@ test('scanner does not spend fingerprint or record audit log when wake is droppe
})
// First pass: wake is dropped by budget
- await runBackgroundScans()
+ await scanOnce()
assert.equal(wakeCallCount, 1, 'wakeScannerAgent should have been attempted once')
assert.equal(auditLogs.length, 0, 'audit log must NOT be written when wake was dropped')
// Second pass with same messages: budget now permits (shouldDropWake = false).
// Because fingerprint was NOT spent, the agent must be re-evaluated and woken!
shouldDropWake = false
- await runBackgroundScans()
+ await scanOnce()
assert.equal(wakeCallCount, 2, 'scanner must retry dropped activity on next pass')
assert.equal(auditLogs.length, 1, 'audit log is recorded on successful wake')
// Third pass with same messages: already scanned and wake succeeded.
// Now fingerprint IS spent, so it should be skipped.
- await runBackgroundScans()
+ await scanOnce()
assert.equal(wakeCallCount, 2, 'scanner must not wake again once fingerprint was successfully spent')
})
diff --git a/server/src/__tests__/agents-scanner-cache-bound.test.ts b/server/src/__tests__/agents-scanner-cache-bound.test.ts
new file mode 100644
index 0000000..18eca3c
--- /dev/null
+++ b/server/src/__tests__/agents-scanner-cache-bound.test.ts
@@ -0,0 +1,60 @@
+/**
+ * The scanner's dedup cache must not grow with uptime.
+ *
+ * It was an unbounded `Set` of raw fingerprints, and a fingerprint carries up
+ * to 80 message ids (~3KB) — one entry per eligible pass per agent, retained
+ * for the lifetime of the process. Redis now holds the durable claim; this
+ * cache exists only to keep the common case off the network, so it stores
+ * fixed-width digests under a hard cap.
+ */
+import { beforeEach, test } from 'node:test'
+import assert from 'node:assert/strict'
+
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'mock-key'
+
+const { __scannerCacheInternals: cache } = await import('../agents/scanner.js')
+const { redis, sub } = await import('../redis.js')
+
+beforeEach(() => { cache.clear() })
+
+test.after(() => {
+ redis.disconnect()
+ sub.disconnect()
+})
+
+test('a fingerprint of any size is stored as a fixed-width digest', () => {
+ const short = cache.digest('co-1|agent-1|m1')
+ const long = cache.digest(`co-1|agent-1|${Array.from({ length: 80 }, (_, i) => `m-${'x'.repeat(34)}${i}`).join('|')}`)
+ assert.match(short, /^[a-f0-9]{64}$/)
+ assert.equal(long.length, short.length,
+ 'an 80-message fingerprint must cost exactly as much cache as a one-message fingerprint')
+ assert.notEqual(short, long)
+})
+
+test('the cache evicts at its limit instead of growing without bound', () => {
+ const { limit } = cache
+ for (let i = 0; i < limit + 50; i++) cache.remember(cache.digest(`fp-${i}`))
+
+ assert.equal(cache.size(), limit, 'the cache must never exceed its cap')
+ // The 50 oldest are gone; the newest survive.
+ assert.equal(cache.has(cache.digest('fp-0')), false)
+ assert.equal(cache.has(cache.digest('fp-49')), false)
+ assert.equal(cache.has(cache.digest(`fp-${limit + 49}`)), true)
+})
+
+test('a hit renews an entry, so a steadily-rescanned agent is not evicted by newcomers', () => {
+ const { limit } = cache
+ for (let i = 0; i < limit; i++) cache.remember(cache.digest(`lru-${i}`))
+ assert.equal(cache.size(), limit)
+
+ // Touch the oldest entry, then push one newcomer in.
+ assert.equal(cache.has(cache.digest('lru-0')), true)
+ cache.remember(cache.digest('lru-new'))
+
+ assert.equal(cache.size(), limit)
+ assert.equal(cache.has(cache.digest('lru-0')), true,
+ 'the renewed entry must survive — FIFO would have dropped it')
+ assert.equal(cache.has(cache.digest('lru-1')), false,
+ 'the genuinely-oldest entry is the one evicted')
+})
diff --git a/server/src/agents/scanner.ts b/server/src/agents/scanner.ts
index c14f2f6..108c28a 100644
--- a/server/src/agents/scanner.ts
+++ b/server/src/agents/scanner.ts
@@ -1,5 +1,6 @@
-import { randomUUID } from 'node:crypto'
+import { createHash, randomUUID } from 'node:crypto'
import { pool } from '../db/pool.js'
+import { redis } from '../redis.js'
import { wakeAgent } from './scheduler.js'
import type { AgentTurnOptions } from './turn.js'
@@ -19,7 +20,100 @@ interface BackgroundScanAgent {
company_id: string
}
-const PRECEDENT_SCANS = new Set<string>()
+/**
+ * Only one replica scans per tick.
+ *
+ * Every replica used to run the full pass every 90s: the agent roster query,
+ * an unread probe and a recent-activity query per agent, plus a roster load
+ * for each one that qualified — all of it duplicated R times for a result only
+ * one of them needed to produce. The dedup set below is per-process, so it
+ * could not stop the duplicate LLM wakes either.
+ *
+ * `pg_try_advisory_lock` is the same shape `llm-rollup.ts` uses for the same
+ * reason: no lease table, no leader election protocol, and a replica that dies
+ * mid-pass releases the lock with its session rather than blocking the next
+ * tick. Distinct from migrate's SCHEMA_LOCK_KEY (7_643_178_926_104n) and the
+ * rollup's ROLLUP_LOCK_KEY (7_643_178_926_211n).
+ */
+const SCANNER_LOCK_KEY = 7_643_178_926_318n
+
+const SCANNER_MIN_MESSAGES = 8
+const SCANNER_WINDOW_HOURS = 24
+
+/**
+ * Cross-replica dedup claim TTL. Matched to SCANNER_WINDOW_HOURS: a
+ * fingerprint names a specific set of recent messages, and once those age out
+ * of the window they can never be re-proposed, so the claim has nothing left
+ * to protect.
+ */
+const SCAN_CLAIM_TTL_SECONDS = SCANNER_WINDOW_HOURS * 3600
+
+/**
+ * Local accelerator only — Redis holds the truth.
+ *
+ * This was an unbounded `Set` of raw fingerprints, and a fingerprint carries up
+ * to 80 message ids (~3KB). At roughly 960 eligible passes per agent per day
+ * with nothing ever evicted, it grew for the lifetime of the process. Now it
+ * stores 64-char digests under a fixed cap, so the memory ceiling is ~32KB
+ * regardless of tenant count or uptime.
+ */
+const PRECEDENT_SCAN_CACHE_LIMIT = 512
+const PRECEDENT_SCANS = new Map<string, true>()
+
+/** Fingerprints are up to ~3KB of message ids; the digest is what we keep and
+ * what becomes the Redis key, so neither store scales with activity volume. */
+function scanDigest(fingerprint: string): string {
+ return createHash('sha256').update(fingerprint).digest('hex')
+}
+
+function precedentHas(digest: string): boolean {
+ if (!PRECEDENT_SCANS.has(digest)) return false
+ // Touch: Map preserves insertion order, so re-inserting moves this entry to
+ // the young end and the eviction below stays true LRU rather than FIFO.
+ PRECEDENT_SCANS.delete(digest)
+ PRECEDENT_SCANS.set(digest, true)
+ return true
+}
+
+function precedentRemember(digest: string): void {
+ PRECEDENT_SCANS.delete(digest)
+ PRECEDENT_SCANS.set(digest, true)
+ while (PRECEDENT_SCANS.size > PRECEDENT_SCAN_CACHE_LIMIT) {
+ const oldest = PRECEDENT_SCANS.keys().next()
+ if (oldest.done) break
+ PRECEDENT_SCANS.delete(oldest.value)
+ }
+}
+
+/**
+ * Has any replica already woken an agent for this exact activity?
+ *
+ * Fails OPEN: a Redis outage degrades dedup to the local cache, which the
+ * leader lock keeps meaningful — one scanner at a time means the worst case is
+ * a repeat after the lock moves to a different replica, not R simultaneous
+ * wakes. Refusing to scan instead would silently disable the feature for the
+ * duration of the outage.
+ */
+async function scanAlreadyClaimed(digest: string): Promise<boolean> {
+ try {
+ return (await redis.exists(`cumora:scan:${digest}`)) === 1
+ } catch (e) {
+ console.warn('[scanner] claim lookup failed — falling back to local cache',
+ e instanceof Error ? e.message : e)
+ return false
+ }
+}
+
+/** Recorded only after a wake is accepted, mirroring how the local cache and
+ * the audit row are spent — a dropped wake must stay retryable. */
+async function claimScan(digest: string): Promise<void> {
+ try {
+ await redis.set(`cumora:scan:${digest}`, '1', 'EX', SCAN_CLAIM_TTL_SECONDS)
+ } catch (e) {
+ console.warn('[scanner] claim write failed — other replicas may repeat this scan',
+ e instanceof Error ? e.message : e)
+ }
+}
type WakeScannerAgentFn = typeof wakeAgent
@@ -29,14 +123,29 @@ let scannerRunning = false
export function __setBackgroundScannerWakeForTesting(fn: WakeScannerAgentFn | null): void {
wakeScannerAgent = fn ?? wakeAgent
}
-const SCANNER_MIN_MESSAGES = 8
-const SCANNER_WINDOW_HOURS = 24
const BACKGROUND_SCAN_CAPABILITIES = ['background.scan']
-export function _resetBackgroundScannerForTests(): void {
+/** Async because the cross-replica claims outlive the process: a leftover
+ * 24h key from a previous run would otherwise make the next run's first pass
+ * silently skip the agent it is trying to assert on. */
+export async function _resetBackgroundScannerForTests(): Promise<void> {
PRECEDENT_SCANS.clear()
wakeScannerAgent = wakeAgent
scannerRunning = false
+ try {
+ const stale = await redis.keys('cumora:scan:*')
+ if (stale.length > 0) await redis.del(...stale)
+ } catch { /* no Redis in this test env — the local cache clear is enough */ }
+}
+
+/** Exported so a test can drive the eviction boundary without 512 real scans. */
+export const __scannerCacheInternals = {
+ limit: PRECEDENT_SCAN_CACHE_LIMIT,
+ digest: scanDigest,
+ has: precedentHas,
+ remember: precedentRemember,
+ clear: (): void => PRECEDENT_SCANS.clear(),
+ size: (): number => PRECEDENT_SCANS.size,
}
async function loadBackgroundScanAgents(): Promise<BackgroundScanAgent[]> {
@@ -180,7 +289,11 @@ async function recordScanWake(agent: BackgroundScanAgent, fingerprint: string):
)
}
-export async function runBackgroundScans(): Promise<void> {
+/**
+ * One scanning pass. Assumes the caller holds the leader lock — call
+ * `runBackgroundScans()` unless you are a test driving the pass directly.
+ */
+export async function scanOnce(): Promise<void> {
const agents = await loadBackgroundScanAgents()
const inFlight = new Set<string>()
for (const agent of agents) {
@@ -191,8 +304,16 @@ export async function runBackgroundScans(): Promise<void> {
if (recent.length < SCANNER_MIN_MESSAGES) continue
const fingerprint = `${agent.company_id}|${agent.id}|${recent.map((r) => r.message_id).sort().join('|')}`
- if (PRECEDENT_SCANS.has(fingerprint) || inFlight.has(fingerprint)) continue
- inFlight.add(fingerprint)
+ const digest = scanDigest(fingerprint)
+ if (precedentHas(digest) || inFlight.has(digest)) continue
+ // The local cache is empty on every fresh process, so without this a
+ // restart — or the lock simply moving to another replica — re-woke every
+ // agent for activity that had already been scanned.
+ if (await scanAlreadyClaimed(digest)) {
+ precedentRemember(digest)
+ continue
+ }
+ inFlight.add(digest)
try {
const roster = await loadRoster(agent.company_id)
@@ -210,10 +331,11 @@ export async function runBackgroundScans(): Promise<void> {
// so the next pass can re-evaluate as intended.
continue
}
- PRECEDENT_SCANS.add(fingerprint)
+ precedentRemember(digest)
+ await claimScan(digest)
await recordScanWake(agent, fingerprint)
} finally {
- inFlight.delete(fingerprint)
+ inFlight.delete(digest)
}
} catch (e) {
console.warn(`[scanner] background scan failed for ${agent.id}`, e)
@@ -221,6 +343,29 @@ export async function runBackgroundScans(): Promise<void> {
}
}
+/**
+ * Claim the scanner role for this tick, then scan. A replica that loses the
+ * race does nothing — the work is not sharded, so a second pass would only
+ * repeat queries the holder is already running.
+ */
+export async function runBackgroundScans(): Promise<void> {
+ const client = await pool.connect()
+ try {
+ const lock = await client.query<{ ok: boolean }>(
+ 'SELECT pg_try_advisory_lock($1) AS ok', [SCANNER_LOCK_KEY],
+ )
+ if (lock.rows[0]?.ok !== true) return
+ try {
+ await scanOnce()
+ } finally {
+ await client.query('SELECT pg_advisory_unlock($1)', [SCANNER_LOCK_KEY])
+ .catch(() => { /* session teardown releases it anyway */ })
+ }
+ } finally {
+ client.release()
+ }
+}
+
/** Periodic kick — call from server boot. */
export function startScanner(intervalMs: number): NodeJS.Timeout {
return setInterval(() => {
diff --git a/server/src/index.ts b/server/src/index.ts
index b342acb..c8420b7 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -255,8 +255,10 @@ async function main() {
// Start generic background scans for agents that explicitly have
// the background.scan capability.
- // In a multi-instance deploy you'd elect a leader (or use a job queue) so
- // only one instance runs the scan; for single-instance dev this is fine.
+ // Safe across replicas: each tick takes an advisory lock, so exactly one
+ // instance runs the pass, and wakes are claimed in Redis with a 24h TTL so
+ // the lock moving elsewhere doesn't re-wake agents for activity already
+ // scanned. See agents/scanner.ts.
if (process.env.ENABLE_SCANNER !== 'false') {
const handle = startScanner(env.SCANNER_INTERVAL_MS)
console.log(`[boot] background scanner running every ${env.SCANNER_INTERVAL_MS}ms`)