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(idle): run the heartbeat on one replica (#322)

OKNOTOKf0873bc870c7
diff --git a/server/src/__tests__/idle-scheduler-lock.test.ts b/server/src/__tests__/idle-scheduler-lock.test.ts
new file mode 100644
index 0000000..f5bdae4
--- /dev/null
+++ b/server/src/__tests__/idle-scheduler-lock.test.ts
@@ -0,0 +1,75 @@
+/**
+ * The idle tick used to run on every replica. Two Pods meant two classifier
+ * calls and two agent turns per tenant. The tick now holds one advisory lock
+ * and refuses to overlap itself.
+ */
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'test-key'
+
+const { runIdleTick, startIdleScheduler } = await import('../agents/idle.js')
+const { pool } = await import('../db/pool.js')
+
+test('a replica that does not get the idle lock does no tenant work', async () => {
+ const originalConnect = pool.connect
+ const originalQuery = pool.query.bind(pool)
+ let companyQueries = 0
+ let unlocked = false
+ pool.connect = (async () => ({
+ async query(sql: string) {
+ if (sql.includes('pg_try_advisory_lock')) return { rows: [{ ok: false }] }
+ if (sql.includes('pg_advisory_unlock')) {
+ unlocked = true
+ return { rows: [] }
+ }
+ throw new Error(`unexpected client query: ${sql}`)
+ },
+ release() {},
+ })) as unknown as typeof pool.connect
+ pool.query = (async (sql: string) => {
+ if (String(sql).includes('FROM companies')) companyQueries += 1
+ return { rows: [] }
+ }) as unknown as typeof pool.query
+ try {
+ await runIdleTick()
+ } finally {
+ pool.connect = originalConnect
+ pool.query = originalQuery as typeof pool.query
+ }
+ assert.equal(companyQueries, 0)
+ assert.equal(unlocked, false)
+})
+
+test('the lock holder walks companies in id order and then unlocks', async () => {
+ const originalConnect = pool.connect
+ const originalQuery = pool.query.bind(pool)
+ const clientSql: string[] = []
+ let companySql = ''
+ pool.connect = (async () => ({
+ async query(sql: string) {
+ clientSql.push(sql)
+ if (sql.includes('pg_try_advisory_lock')) return { rows: [{ ok: true }] }
+ return { rows: [] }
+ },
+ release() {},
+ })) as unknown as typeof pool.connect
+ pool.query = (async (sql: string) => {
+ companySql = String(sql)
+ return { rows: [] }
+ }) as unknown as typeof pool.query
+ try {
+ await runIdleTick()
+ } finally {
+ pool.connect = originalConnect
+ pool.query = originalQuery as typeof pool.query
+ }
+ assert.match(companySql, /ORDER BY id/)
+ assert.equal(clientSql.filter((sql) => sql.includes('pg_advisory_unlock')).length, 1)
+})
+
+test('startIdleScheduler refuses a non-positive interval', () => {
+ assert.equal(startIdleScheduler(0), null)
+ assert.equal(startIdleScheduler(-1), null)
+})
diff --git a/server/src/agents/idle.ts b/server/src/agents/idle.ts
index 73bf7d2..f26f7ad 100644
--- a/server/src/agents/idle.ts
+++ b/server/src/agents/idle.ts
@@ -45,6 +45,12 @@ export function _resetIdleForTests(): void {
classifyAgenda = classifyAgendaActionable
}
+/** Session advisory lock. Distinct from the schema, rollup, and scanner keys.
+ * A replica that loses it skips the tick. The session releases the lock if
+ * this process dies mid-tick. */
+const IDLE_LOCK_KEY = 7_643_178_926_425n
+let idleTickRunning = false
+
interface IdleCandidate {
id: string
name: string
@@ -120,8 +126,26 @@ function agendaHasItems(agenda: AgentAgenda): boolean {
}
export async function runIdleTick(): Promise<void> {
+ const client = await pool.connect()
+ try {
+ const lock = await client.query<{ ok: boolean }>(
+ 'SELECT pg_try_advisory_lock($1) AS ok', [IDLE_LOCK_KEY],
+ )
+ if (lock.rows[0]?.ok !== true) return
+ try {
+ await runIdleTickUnlocked()
+ } finally {
+ await client.query('SELECT pg_advisory_unlock($1)', [IDLE_LOCK_KEY])
+ .catch(() => { /* session teardown releases it anyway */ })
+ }
+ } finally {
+ client.release()
+ }
+}
+
+async function runIdleTickUnlocked(): Promise<void> {
const { rows: tenants } = await pool.query<{ id: string }>(
- `SELECT id FROM companies`,
+ `SELECT id FROM companies ORDER BY id`,
)
for (const { id: companyId } of tenants) {
try {
@@ -212,6 +236,13 @@ export async function runIdleTick(): Promise<void> {
export function startIdleScheduler(intervalMs: number): NodeJS.Timeout | null {
if (intervalMs <= 0) return null
return setInterval(() => {
- runIdleTick().catch((e) => console.error('[idle]', e))
+ if (idleTickRunning) {
+ console.warn('[idle] previous tick still running — skipping')
+ return
+ }
+ idleTickRunning = true
+ runIdleTick()
+ .catch((e) => console.error('[idle]', e))
+ .finally(() => { idleTickRunning = false })
}, intervalMs)
}
diff --git a/server/src/index.ts b/server/src/index.ts
index 9a44d96..2309c80 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -269,7 +269,8 @@ async function main() {
// Idle scheduler — gives agents a chance to spontaneously initiate when
// nothing is incoming. Defaults to 15min cadence; set IDLE_INTERVAL_MS=0
- // to disable. See agents/idle.ts for what an idle tick actually does.
+ // to disable. Each tick takes an advisory lock, so a second replica does
+ // not run a second agenda classifier and a second agent turn. See agents/idle.ts.
if (process.env.ENABLE_IDLE !== 'false' && env.IDLE_INTERVAL_MS > 0) {
const handle = startIdleScheduler(env.IDLE_INTERVAL_MS)
if (handle) {