Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Backend hotfix: a slow Swarm command logs its time by phase (#4560) (#3564)

0xken15cba89790a3c9
diff --git a/backend/integration/superTabCommandReads.test.ts b/backend/integration/superTabCommandReads.test.ts
index b56d842ad..4db164356 100644
--- a/backend/integration/superTabCommandReads.test.ts
+++ b/backend/integration/superTabCommandReads.test.ts
@@ -1,9 +1,10 @@
import { randomUUID } from 'node:crypto'
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
import type { Prisma, PrismaClient } from '@prisma/client'
import type { AuthUser } from '../src/lib/ssoAuth.js'
import { SuperTabStore } from '../src/superTabs/store.js'
+import { logger } from '../src/utils/logger.js'
import type { Command } from '../src/superTabs/commands.js'
import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'
import { loadMachineAccounts } from '../src/superTabs/parts/index.js'
@@ -164,3 +165,34 @@ describe('what a common command reads in a prod-sized Swarm (task #4368)', () =>
expect(machines.map(e => [e.planSummary, e.docsExamined])).toEqual([['IXSCAN { _id: 1 }', 1]])
})
})
+
+// Task #4560: commands waited ~3.5 s in prod with ~23 ms of DB time. A command over a second logs its time by phase.
+describe('a slow command names its phases', () => {
+ it('logs its type, total and each phase, never its words, and nothing for a fast one', async () => {
+ let now = 1_000_000, step = 0
+ // Each read of the clock moves it on by `step`: a command that reads it a few times takes seconds, with no wait in the test.
+ const store = new SuperTabStore(db, () => (now += step), null, { pushOrigin: async () => 'clean', repositoryReach: async () => undefined,
+ pullRequestFiles: async () => null, pullRequestReader: () => { throw new Error('No pull request is read here') } })
+ const tab = (await store.create(owner, randomUUID(), 'Phases', 'public')).id
+ const create = (title: string) => store.execute(owner, tab, { operationId: randomUUID(), command: { type: 'conversation.create', title, checks: [],
+ task: { goal: `${title}.`, changes: 'The change.', constraints: 'None.', owns: ['backend/a.ts'] } } as Command })
+ const warn = vi.spyOn(logger, 'warn')
+ try {
+ await create('Fast words')
+ expect(warn.mock.calls.filter(call => call[0] === 'Swarm command slow')).toEqual([])
+ step = 300
+ await create('Secret words')
+ const lines = warn.mock.calls.filter(call => call[0] === 'Swarm command slow')
+ expect(lines).toHaveLength(1)
+ const fields = lines[0]![1] as { totalMs: number; phases: Record<string, number> }
+ expect(fields).toMatchObject({ tabId: tab, type: 'conversation.create', byAgent: false })
+ expect(fields.totalMs).toBeGreaterThanOrEqual(1_000)
+ expect(Object.keys(fields.phases)).toEqual(expect.arrayContaining(['read:pushOrigin', 'read:repositoryReach', 'attempts', 'pool', 'body',
+ 'commit', 'stamps', 'afterCommit', 'other']))
+ expect(fields.phases.attempts).toBe(1)
+ expect(JSON.stringify(lines)).not.toContain('Secret words')
+ } finally {
+ warn.mockRestore()
+ }
+ })
+})
diff --git a/backend/src/superTabs/cache.ts b/backend/src/superTabs/cache.ts
index 271d68d73..027f26d93 100644
--- a/backend/src/superTabs/cache.ts
+++ b/backend/src/superTabs/cache.ts
@@ -15,6 +15,7 @@ import { recordCache, type ReloadReason } from './cacheStats.js'
import type { PartKind } from './parts/types.js'
import type { SwarmDelta } from './parts/load.js'
import { OVERLAP_MS } from './read/cursor.js'
+import { addPhase, phaseClock, timedPhase } from './commandTiming.js'
/** The stamps of one Swarm. A stamp only grows; one that never moved is 0. */
export interface Stamp { main: number; machine: number }
@@ -532,8 +533,27 @@ function owe(changes: Changes, tabId: string, scopes: Iterable<StampScope>, host
export async function swarmTransaction<T>(db: Pick<PrismaClient, '$transaction'>, body: (tx: Prisma.TransactionClient) => Promise<T>,
options?: { maxWait?: number; timeout?: number }): Promise<T> {
const changes: Changes = new Map()
- const result = await db.$transaction(tx => { changesOf.set(tx, changes); return body(tx) }, options)
- await announce(changes)
+ // A command's phases (commandTiming.ts): the wait for a connection before the body runs, the body, then the commit. An
+ // attempt that fails before its body spent all its time waiting to begin.
+ const clock = phaseClock()
+ const asked = clock?.()
+ let begun: number | undefined, ended: number | undefined
+ let result: T
+ try {
+ result = await db.$transaction(async tx => {
+ changesOf.set(tx, changes)
+ begun = clock?.()
+ try { return await body(tx) } finally { ended = clock?.() }
+ }, options)
+ } finally {
+ if (clock) {
+ const now = clock()
+ addPhase('pool', (begun ?? now) - asked!)
+ if (begun !== undefined) addPhase('body', (ended ?? now) - begun)
+ if (ended !== undefined) addPhase('commit', now - ended)
+ }
+ }
+ await timedPhase('stamps', () => announce(changes))
return result
}
diff --git a/backend/src/superTabs/commandTiming.test.ts b/backend/src/superTabs/commandTiming.test.ts
new file mode 100644
index 000000000..fcb5a03ac
--- /dev/null
+++ b/backend/src/superTabs/commandTiming.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import { addPhase, commandPhases, timeCommand, timedPhase, type CommandPhases } from './commandTiming.js'
+
+/** Runs [work] as one command on [clock], returning its result and what it reported. */
+async function timed<T>(clock: () => number, work: () => Promise<T>) {
+ let reported: { phases: CommandPhases; totalMs: number } | undefined
+ const result = await timeCommand(clock, work, (phases, totalMs) => { reported = { phases, totalMs } })
+ return { result, phases: reported!.phases, totalMs: reported!.totalMs }
+}
+
+// Task #4560: some commands wait ~3.5 s in prod with little DB or CPU time; each phase's time names the wait.
+describe('a command\'s phase timings', () => {
+ it('adds each phase\'s time on the command\'s own clock, sums repeats, and counts attempts', async () => {
+ let now = 0
+ const { result, phases, totalMs } = await timed(() => now, async () => {
+ await timedPhase('read:repositoryReach', async () => { now += 3_400 })
+ addPhase('pool', 5)
+ addPhase('pool', 7)
+ addPhase('attempts', 1)
+ addPhase('attempts', 1)
+ expect(commandPhases()).toMatchObject({ pool: 12 })
+ return 'done'
+ })
+ expect(result).toBe('done')
+ expect(phases).toEqual({ 'read:repositoryReach': 3_400, pool: 12, attempts: 2 })
+ expect(totalMs).toBe(3_400)
+ })
+
+ it('keeps a read\'s inner transaction out of the command\'s own phases, and records nothing outside a command', async () => {
+ let now = 0
+ const { phases } = await timed(() => now, async () => {
+ await timedPhase('read:pullRequestFiles', async () => { addPhase('body', 50); now += 80 })
+ addPhase('body', 20)
+ })
+ expect(phases).toEqual({ 'read:pullRequestFiles': 80, body: 20 })
+ addPhase('body', 1)
+ expect(commandPhases()).toBeUndefined()
+ expect(await timedPhase('stamps', async () => 'outside')).toBe('outside')
+ })
+
+ it('reports a command that failed, with its phases and total', async () => {
+ let now = 0, reported: { phases: CommandPhases; totalMs: number } | undefined
+ await expect(timeCommand(() => now, async () => { addPhase('backoff', 2_900); now += 3_500; throw new Error('busy') },
+ (phases, totalMs) => { reported = { phases, totalMs } })).rejects.toThrow('busy')
+ expect(reported).toEqual({ phases: { backoff: 2_900 }, totalMs: 3_500 })
+ })
+
+ it('still records a phase whose work failed', async () => {
+ let now = 0
+ const { phases } = await timed(() => now, async () => {
+ await timedPhase('read:verdictHead', async () => { now += 900; throw new Error('GitHub down') }).catch(() => undefined)
+ })
+ expect(phases).toEqual({ 'read:verdictHead': 900 })
+ })
+})
diff --git a/backend/src/superTabs/commandTiming.ts b/backend/src/superTabs/commandTiming.ts
new file mode 100644
index 000000000..0e8249c51
--- /dev/null
+++ b/backend/src/superTabs/commandTiming.ts
@@ -0,0 +1,44 @@
+/**
+ * A command's time by phase (task #4560): in prod some commands waited ~3.5 s with ~23 ms of DB time and ~140 ms of CPU, so
+ * the time is a wait somewhere in the command path. Each phase adds its time here, on the command's own clock, and a slow
+ * command's log line names them (store.ts execute). Phases carry names and milliseconds only, never content.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks'
+
+export type CommandPhases = Record<string, number>
+interface Timing { clock: () => number; phases: CommandPhases }
+const current = new AsyncLocalStorage<Timing>()
+
+/** Runs one command with its phases recorded on [clock], and hands [report] its phases and total time, failed or not. */
+export async function timeCommand<T>(clock: () => number, work: () => Promise<T>, report: (phases: CommandPhases, totalMs: number) => void): Promise<T> {
+ const timing: Timing = { clock, phases: {} }, started = clock()
+ try {
+ return await current.run(timing, work)
+ } finally {
+ report(timing.phases, clock() - started)
+ }
+}
+
+/** Adds [amount] (milliseconds, or a count such as attempts) to [phase] of the running command; outside one, nothing. */
+export function addPhase(phase: string, amount: number): void {
+ const timing = current.getStore()
+ if (timing) timing.phases[phase] = (timing.phases[phase] ?? 0) + amount
+}
+
+/** The running command's phases so far, or undefined outside one. */
+export const commandPhases = (): CommandPhases | undefined => current.getStore()?.phases
+
+/** Times [work] as one [phase], failed or not. What it does inside (its own transaction) counts only as this phase. */
+export async function timedPhase<T>(phase: string, work: () => Promise<T>): Promise<T> {
+ const timing = current.getStore()
+ if (!timing) return work()
+ const started = timing.clock()
+ try {
+ return await current.run({ clock: timing.clock, phases: {} }, work)
+ } finally {
+ addPhase(phase, timing.clock() - started)
+ }
+}
+
+/** The clock phases are timed on now, or undefined outside a command. */
+export const phaseClock = (): (() => number) | undefined => current.getStore()?.clock
diff --git a/backend/src/superTabs/retry.ts b/backend/src/superTabs/retry.ts
index 8ca5b5062..dcf1231ef 100644
--- a/backend/src/superTabs/retry.ts
+++ b/backend/src/superTabs/retry.ts
@@ -1,5 +1,6 @@
import { fail } from './model.js'
import { recordAttempt, recordBusy, recordRetry } from './retryStats.js'
+import { addPhase, timedPhase } from './commandTiming.js'
/** A Swarm's answers that say "try again" rather than "no": busy after its retries, or moving to its new store. */
export const RETRYABLE_SWARM_CODES: ReadonlySet<string> = new Set(['SWARM_BUSY', 'SWARM_MIGRATING'])
@@ -27,6 +28,7 @@ export async function retryTransient<T>(attempt: () => Promise<T>,
alsoRetry: (error: unknown) => boolean = () => false): Promise<T> {
for (let tries = 1; ; tries++) {
recordAttempt()
+ addPhase('attempts', 1)
try {
return await attempt()
} catch (error) {
@@ -39,7 +41,7 @@ export async function retryTransient<T>(attempt: () => Promise<T>,
fail('SWARM_BUSY', 'This Swarm is busy. Try again in a moment.', 503)
}
recordRetry(typeof errorCode(error) === 'string' ? errorCode(error) as string : 'transient')
- await sleep(Math.random() * Math.min(TRANSACTION_BACKOFF_CAP_MS, TRANSACTION_BACKOFF_MS * 2 ** (tries - 1)))
+ await timedPhase('backoff', () => sleep(Math.random() * Math.min(TRANSACTION_BACKOFF_CAP_MS, TRANSACTION_BACKOFF_MS * 2 ** (tries - 1))))
}
}
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 434209b9b..3bbdb5327 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,6 +1,7 @@
import { legacyAsks } from './boardRights.js'
import { canReadProject } from './projects.js'
import { proposalMeasures, proposalMessageMeasures } from './proposalMetrics.js'
+import { timeCommand, timedPhase, type CommandPhases } from './commandTiming.js'
import { advanceProposalCards, pmAcceptsMessage, legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk } from './proposalCards.js'
import { defaultBuddy } from './buddies.js'
import { refusalLogFields, type DeclaredClient } from './refusalLog.js'
@@ -326,9 +327,11 @@ export async function transaction<T>(db: Pick<PrismaClient, '$transaction'>, bod
// The cache's stamps are bumped, and awaited, once the attempt commits (cache.ts); after-commit work runs after them.
const run = () => swarmTransaction(db, tx => { committed = []; pendingCommits.set(tx, committed); return body(tx) }, TRANSACTION_OPTIONS)
const result = await (hintless ? withoutHints(run) : run())
- for (const callback of committed) {
- try { callback() } catch (error) { logger.warn('[super-tab] after-commit callback failed', { error: error instanceof Error ? error.message : String(error) }) }
- }
+ await timedPhase('afterCommit', async () => {
+ for (const callback of committed) {
+ try { callback() } catch (error) { logger.warn('[super-tab] after-commit callback failed', { error: error instanceof Error ? error.message : String(error) }) }
+ }
+ })
return result
} catch (error) {
// A read in this attempt named an index removed since the last listing (parts/indexed.ts): the next attempts name none.
@@ -340,6 +343,15 @@ export async function transaction<T>(db: Pick<PrismaClient, '$transaction'>, bod
/** The longest a failed claim's record may hold up the busy answer. */
const RECORD_FAILED_CLAIM_MS = 2_000
const TRANSACTION_OPTIONS = { maxWait: 5_000, timeout: 15_000 }
+/** A command this slow logs its phases (task #4560: commands waited ~3.5 s in prod while p50 stayed at 245 ms). */
+export const SLOW_COMMAND_MS = 1_000
+/** One line per slow command: its type and phases in milliseconds, whether an agent sent it; never its words or ids but the Swarm's. */
+function slowCommand(tabId: string, type: unknown, totalMs: number, phases: CommandPhases, byAgent: boolean): void {
+ if (totalMs < SLOW_COMMAND_MS) return
+ const timed = Object.entries(phases).reduce((sum, [phase, ms]) => phase === 'attempts' ? sum : sum + ms, 0)
+ logger.warn('Swarm command slow', { tabId, type: typeof type === 'string' ? type : 'unknown', totalMs, byAgent,
+ phases: { ...phases, other: Math.max(0, totalMs - timed) } })
+}
/** Each attempt's after-commit work, by that attempt's client: a retried attempt's list is dropped with its client. */
const pendingCommits = new WeakMap<Transaction, Array<() => void>>()
@@ -1656,7 +1668,8 @@ export class SuperTabStore {
async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
client?: DeclaredClient) {
try {
- const done = await this.executeOnce(user, tabId, input, asAgentId, hostMachineId)
+ const done = await timeCommand(this.now, () => this.executeOnce(user, tabId, input, asAgentId, hostMachineId),
+ (phases, totalMs) => slowCommand(tabId, input.command?.type, totalMs, phases, !!asAgentId))
// Buddy thread sessions' first warning (spec Design 4): starts, refusals by code and ends by reason, ids only, in the
// server log that prod watch reads.
if (input.command?.type === 'message.send' && input.command.newSession && done.result.startId) logger.info('Buddy session started', { tabId, startId: done.result.startId })
@@ -1849,9 +1862,13 @@ export class SuperTabStore {
private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
workspaceLeave = false, only: { overdue?: boolean; defaulted?: boolean; movedTo?: { machineId: string; ownerId: string }; asProjectPm?: string } = {}) {
const { operationId, command } = operationSchema.parse(input)
- const [pushOrigin, repositoryReach, pullRequestFiles, pullRequestMerges] = await Promise.all([this.pushOriginFor(user, tabId, command),
- this.repositoryReachFor(user, tabId, command), this.pullRequestFilesFor(user, tabId, command), this.pullRequestMergesFor(user, tabId, command),
- this.verdictHeadRead(user, tabId, command)])
+ // Each read before the transaction is its own phase (commandTiming.ts): several call GitHub.
+ const [pushOrigin, repositoryReach, pullRequestFiles, pullRequestMerges] = await Promise.all([
+ timedPhase('read:pushOrigin', () => this.pushOriginFor(user, tabId, command)),
+ timedPhase('read:repositoryReach', () => this.repositoryReachFor(user, tabId, command)),
+ timedPhase('read:pullRequestFiles', () => this.pullRequestFilesFor(user, tabId, command)),
+ timedPhase('read:pullRequestMerges', () => this.pullRequestMergesFor(user, tabId, command)),
+ timedPhase('read:verdictHead', () => this.verdictHeadRead(user, tabId, command))])
let ended: WorkHold[] = [], started: WorkHold[] = []
// With only PMs and Buddies, no dispatch pass can hand out work.
let hasWorkers = false
@@ -2532,7 +2549,7 @@ export class SuperTabStore {
// A write that may free a worker or open a task hands out work at once, not at the next 30-second sweep (dispatch.ts).
if (hasWorkers && freesOrOpens(command)) this.dispatchSoon(tabId)
// A task's Ready records its pull request's head as GitHub has it now, for the Reviewers it hands over to (task #3628).
- if (command.type === 'work.status' && command.status === 'review') await this.readyHeadRead(user, tabId, command)
+ if (command.type === 'work.status' && command.status === 'review') await timedPhase('read:readyHead', () => this.readyHeadRead(user, tabId, command))
return done
}
diff --git a/backend/src/superTabs/transaction.test.ts b/backend/src/superTabs/transaction.test.ts
index bcad3d9a1..3c0cdccb2 100644
--- a/backend/src/superTabs/transaction.test.ts
+++ b/backend/src/superTabs/transaction.test.ts
@@ -129,3 +129,30 @@ describe('work after a Swarm transaction commits', () => {
expect(() => afterCommit({} as never, () => {})).toThrow(/Swarm transaction/)
})
})
+
+// Task #4560: a command's wait is named by phase: the connection before its body runs, the body, the commit, each attempt and
+// the backoff between them, the cache stamps after the commit, and the after-commit work.
+describe('a Swarm transaction\'s phases', () => {
+ it('times the connection wait, body, commit, attempts, backoff, stamps and after-commit work of a command', async () => {
+ const { timeCommand } = await import('./commandTiming.js')
+ let now = 0
+ const failures: unknown[] = [conflict()]
+ const db = { $transaction: async (body: (tx: never) => Promise<unknown>) => {
+ now += 40 // waiting for a pool connection
+ const failure = failures.shift()
+ if (failure) { now += 10; throw failure }
+ const result = await body({} as never)
+ now += 25 // the commit
+ return result
+ } }
+ let phases: Record<string, number> = {}
+ const result = await timeCommand(() => now, () => transaction(db as never, async tx => {
+ now += 100
+ afterCommit(tx, () => { now += 7 })
+ return 'done'
+ }, async () => { now += 300 }), recorded => { phases = recorded })
+ expect(result).toBe('done')
+ // The first attempt failed before its body ran: all of its time was spent waiting to begin.
+ expect(phases).toEqual({ attempts: 2, pool: 90, body: 100, commit: 25, backoff: 300, stamps: 0, afterCommit: 7 })
+ })
+})
diff --git a/docs/plans/2026-11-07-command-phase-timing-plan.md b/docs/plans/2026-11-07-command-phase-timing-plan.md
new file mode 100644
index 000000000..79fefbe6d
--- /dev/null
+++ b/docs/plans/2026-11-07-command-phase-timing-plan.md
@@ -0,0 +1,35 @@
+# P0 #4560 step 1: a slow Swarm command logs its time by phase — Plan
+
+> Written by the Engineer and implemented by it, task by task, test first. No Execution Handoff.
+
+**Goal:** Name where the ~3.5 s wait inside some Swarm commands goes (Ken's 17:20 VN scan on v1.4.32: POST commands p95 3,574 ms,
+p50 245 ms, ~23 ms DB and ~140 ms main-thread CPU per command, the event loop not blocked), so the next prod scan names the phase.
+
+**Architecture:** `commandTiming.ts` keeps a command's phases in an AsyncLocalStorage on the store's clock. The store's `execute`
+times each command; the GitHub reads before the transaction and the head read after it, `swarmTransaction` (connection wait
+before the body, the body, the commit, the cache stamps), `retryTransient` (attempts, backoff) and the after-commit work each add
+their phase. A command over 1 s logs one `Swarm command slow` line: Swarm id, command type, total, phases, whether an agent sent it.
+
+**Tech Stack:** TypeScript backend, node:async_hooks, vitest.
+
+**Spec:** Task #4560 brief, step 1.
+
+## Global Constraints
+- Names and milliseconds only: no command words, message text or secrets in the line.
+- Hot path: the timing's own cost is measured per command.
+- Ships as a backend hotfix as soon as it is green; steps 2 and 3 follow from the numbers.
+
+## Review Focus
+- Every phase the brief lists is named; the line carries nothing but names and numbers.
+
+## Tasks
+
+### 1. Phase timing
+Files: `backend/src/superTabs/commandTiming.ts`, `commandTiming.test.ts`, `transaction.test.ts`
+- [ ] Failing test: phases add on the command's clock, a read's inner transaction counts only as that read, a failed command still reports; a transaction's pool, body, commit, attempts, backoff, stamps and after-commit are timed.
+- [ ] Code: `commandTiming.ts`; phases in `cache.ts swarmTransaction`, `retry.ts`, `store.ts transaction`.
+
+### 2. The slow-command line
+Files: `backend/src/superTabs/store.ts`, `backend/integration/superTabCommandReads.test.ts`
+- [ ] Failing test: a command over 1 s logs its type, total and phases without its words; a fast one logs nothing.
+- [ ] Code: `execute` times the command; each read before and after the transaction is its own phase; `slowCommand` logs.