Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: crash guard, crash restarts with backoff, staggered reruns, honest stall diagnostics, bounded caches (#6175)
Milind Sonid4108c8b05ac
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 0047afadcb..20877c402d 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1122,9 +1122,11 @@ boot id while its pids start again from 1, so the lease names its pidnamespace and its process's start time too), and runs two children as `maus`: theserver on `127.0.0.1:8799` (webhooks on `127.0.0.1:8800`) and Caddy on`:8080`. It stays a small root supervisor: if either child exits, both stop-and Fly restarts the machine. The one exception: after a restore commits-(a backup restored in Settings), the server exits with code 75-(`server/restart.ts`) and the launcher starts only the server again.+and Fly restarts the machine. Two exceptions (`server/restart.ts`): after a restore+commits (a backup restored in Settings), the server exits with code 75 and the+launcher starts only the server again; after a crash (exit 70 from+`server/crash-guard.ts`, or killed by the system, as out of memory) it starts the+server again after 1, 2, 5, 15 and 30 s, then gives up so Fly restarts the machine.The machine's secrets (`OMB_CLOUD_BOOTSTRAP_SECRET` and the relay tokens`OMB_CLOUD_BOAT_TOKEN`, `OMB_CLOUD_VOICE_TOKEN`, `OMB_CLOUD_DECIDER_TOKEN`, `OMB_CLOUD_X_TOKEN`,diff --git a/server/app-settings/registry-config.ts b/server/app-settings/registry-config.tsindex a66687426a..e09b659c90 100644--- a/server/app-settings/registry-config.ts+++ b/server/app-settings/registry-config.ts@@ -115,10 +115,10 @@ export function configEntries(deps: Pick<RegistryDeps, "cfg" | "saveConfig" | "bcurrent: () => cfg().features?.shareLearnedSkills ?? "off", patch: (shareLearnedSkills) => ({ features: { shareLearnedSkills } }),}),section({- id: "threads.eventLogMaxBytes", label: "Thread log size limit", help: "The most bytes each conversation's event log keeps; null keeps it all.", where: "Settings → Data",+ id: "threads.eventLogMaxBytes", label: "Thread log size limit", help: "The most bytes each conversation's event log keeps; null keeps up to 256 MiB, the default ceiling.", where: "Settings → Data",synonyms: ["log size", "storage", "event log", "cleanup"], value: z.number().int().min(MIN_THREAD_EVENT_LOG_BYTES).max(MAX_THREAD_EVENT_LOG_BYTES).nullable(),- allowed: `${MIN_THREAD_EVENT_LOG_BYTES} to ${MAX_THREAD_EVENT_LOG_BYTES} bytes, or null for no limit`,- current: () => cfg().threads?.eventLogMaxBytes ?? null, read: () => display(cfg().threads?.eventLogMaxBytes ?? "no limit"), patch: (eventLogMaxBytes) => ({ threads: { eventLogMaxBytes } }),+ allowed: `${MIN_THREAD_EVENT_LOG_BYTES} to ${MAX_THREAD_EVENT_LOG_BYTES} bytes, or null for the default ceiling (256 MiB)`,+ current: () => cfg().threads?.eventLogMaxBytes ?? null, read: () => display(cfg().threads?.eventLogMaxBytes ?? "256 MiB (default ceiling)"), patch: (eventLogMaxBytes) => ({ threads: { eventLogMaxBytes } }),}),feature("appearance.toolCalls", "Show tool calls", "Show each tool a bot runs in the conversation.", "Settings → Appearance", ["tool calls", "tools", "show tools"], "showToolCalls", false,"Show each tool a bot runs in its conversation", "Hide tool runs from conversations"),diff --git a/server/atomic.ts b/server/atomic.tsindex 909b6e3f4f..e01e64b6ca 100644--- a/server/atomic.ts+++ b/server/atomic.ts@@ -15,6 +15,8 @@ import {writeFileSync,} from "node:fs";+import { timeBlocking } from "./perf/loop-stalls.ts";+export type AtomicWriteOptions = {mode?: number;/** false skips the fsync. Default true. */@@ -49,6 +51,10 @@ export function renameWithRetry(}export function writeFileAtomic(path: string, data: string | Uint8Array, options: AtomicWriteOptions = {}): void {+ timeBlocking("saves", () => writeWhole(path, data, options));+}++function writeWhole(path: string, data: string | Uint8Array, options: AtomicWriteOptions): void {const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;let fd: number | null = null;try {diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 87142eed47..58f00a84bd 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -52,7 +52,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_SIGNIN_SMTP_URL", "OMB_SKILLS_DIR", "OMB_SMOKE_BUNDLED_CUA", "OMB_SMOKE_CUA", "OMB_SMOKE_KEEP_OPEN","OMB_SMOKE_TEST", "OMB_SSE_HEARTBEAT_MS", "OMB_STATIC_DIR", "OMB_SYNC_ROOT", "OMB_TAILNET_ADDRESSES", "OMB_TAILNET_NAME", "OMB_TAILNET_SERVED", "OMB_TEAM_AWAY_WINDOW_MS","OMB_TEAM_PRESENCE_GRACE_MS", "OMB_TEST_INTERNAL_CAPABILITY_KEY", "OMB_TEST_ORG_LIBRARY_KEY",- "OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE",+ "OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_THREAD_CACHE_MB", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE","OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURN_STALL_MS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL","OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET","OMB_WORKERS_AI_TOKEN", "OMB_XAI_TTS_API",diff --git a/server/bot-limit.test.ts b/server/bot-limit.test.tsnew file mode 100644index 0000000000..92ccd81bb7--- /dev/null+++ b/server/bot-limit.test.ts@@ -0,0 +1,16 @@+import { expect, it } from "vitest";++import { botLimitRefusal } from "./bot-limit.ts";+import { threadEventLogMaxBytes, type AppConfig } from "./config.ts";+import { DEFAULT_THREAD_EVENT_LOG_MAX_BYTES, threadLogCapOrDefault } from "./thread-log-rotation.ts";++it("a workspace at its bot limit says the limit and what to do about it", () => {+ expect(botLimitRefusal(100)).toMatch(/already has 100 bots.*To add another, delete a bot you no longer need, or create the new bots in another workspace\./);+});++it("event logs are trimmed past a default ceiling where no limit is set, and past the person's limit where one is", () => {+ const none = {} as AppConfig, set = { threads: { maxConcurrentPerBot: 2, eventLogMaxBytes: 1024 * 1024 } } as AppConfig;+ expect(threadEventLogMaxBytes(none)).toBeNull();+ expect(threadLogCapOrDefault(threadEventLogMaxBytes(none))).toBe(DEFAULT_THREAD_EVENT_LOG_MAX_BYTES);+ expect(threadLogCapOrDefault(threadEventLogMaxBytes(set))).toBe(1024 * 1024);+});diff --git a/server/bot-limit.ts b/server/bot-limit.tsnew file mode 100644index 0000000000..81b6936027--- /dev/null+++ b/server/bot-limit.ts@@ -0,0 +1,4 @@+/** What a workspace at its bot limit answers: the limit, and what the person can do about it. */+export const botLimitRefusal = (max: number): string =>+ `This workspace already has ${max} bots, the most one workspace holds (bots in the archive count too). ` ++ "To add another, delete a bot you no longer need, or create the new bots in another workspace.";diff --git a/server/cli.ts b/server/cli.tsindex 2471157e8e..ad4c8ee3ee 100644--- a/server/cli.ts+++ b/server/cli.ts@@ -27,7 +27,7 @@ import { bindDecisionRetention, decisionRetentionDays } from "./decision-log.ts"import { hostedWorkspaceConfigured } from "./enterprise.ts";import { reportableServerVersion, serverVersion } from "./environment.ts";import { resolveLoopbackTrust } from "./request-auth.ts";-import { restartPolicy } from "./restart.ts";+import { CRASH_EXIT_CODE, crashed, restartLine, restartPolicy } from "./restart.ts";import { writeFileAtomic } from "./atomic.ts";import { ensureCaddy, normalizeDomainOption, startCaddy, type RunningCaddy } from "./caddy.ts";import { runServiceCommand } from "./service-cli.ts";@@ -776,7 +776,7 @@ export async function runServe(options: CliOptions, log: (line: string) => voidlet exited: number | null = null;const childExit = new Promise<number>((done) => {child.once("error", () => { exited = 1; done(1); });- child.once("exit", (code, signal) => { exited = code ?? (signal === "SIGTERM" || signal === "SIGINT" ? 0 : 1); done(exited); });+ child.once("exit", (code, signal) => { exited = code ?? (signal === "SIGTERM" || signal === "SIGINT" ? 0 : crashed(null, signal) ? CRASH_EXIT_CODE : 1); done(exited); });});let tunnel: RunningTunnel | null = null;let caddy: RunningCaddy | null = null;@@ -900,7 +900,7 @@ export async function serveUntilStopped(options: CliOptions, run: (options: CliOfor (;;) {const code = await run(launch);if (!policy.again(code)) return code;- console.log("\nOpenMausBot is starting again to finish installing a copy from the desktop app…");+ console.log(`\n${restartLine(code, policy.delayMs())}`); if (policy.delayMs() > 0) await new Promise((resume) => setTimeout(resume, policy.delayMs()));launch = { ...options, pair: false, open: false };}}diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex 473ecae4b2..805a957207 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -15,7 +15,7 @@ import { procHidepid } from "./bot-box/hidepid.ts";import { boxMemory, heapSizeArgs } from "./box-memory.ts";import { clearRecordsFromOtherMachines } from "./data-dir-lease.ts";import { OOM_SCORE, protectInit, protectSupervisor, spawnWithOomScore } from "./oom-score.ts";-import { restartPolicy } from "./restart.ts";+import { restartLine, restartPolicy } from "./restart.ts";const SERVICE_USER = "maus";const SECRETS_FD = 3;@@ -436,28 +436,32 @@ export function startCloudHome(processEnv: NodeJS.ProcessEnv = process.env) {// Names only, never values: what the server does not get from here.if (dropped.length) console.log(`cloud home: not passed to the server: ${dropped.join(", ")}`);const children: ChildProcess[] = [];- let stopping = false;+ let stopping = false, restartTimer: ReturnType<typeof setTimeout> | undefined;const stop = (failed: boolean) => {if (stopping) return;stopping = true;+ if (restartTimer) clearTimeout(restartTimer);process.exitCode = failed ? 1 : 0;for (const child of children) if (child.exitCode === null) child.kill("SIGTERM");const force = setTimeout(() => { for (const child of children) if (child.exitCode === null) child.kill("SIGKILL"); }, 20_000);force.unref();};- const watch = (child: ChildProcess, again?: (code: number | null) => boolean) => {+ const watch = (child: ChildProcess, again?: (code: number | null, signal: NodeJS.Signals | null) => boolean) => {children.push(child);child.once("error", () => stop(true));- child.once("exit", (code) => {+ child.once("exit", (code, signal) => {children.splice(children.indexOf(child), 1);- if (!again?.(code)) stop(true);+ if (!again?.(code, signal)) stop(true);});};const policy = restartPolicy();const runServer = () => {- watch(spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids)), (code) => {- if (!policy.again(code, stopping)) return false;- runServer();+ if (stopping) return;+ watch(spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids)), (code, signal) => {+ if (!policy.again(code, stopping, signal)) return false;+ console.warn(`cloud home: ${restartLine(code, policy.delayMs())}`);+ if (policy.delayMs() > 0) restartTimer = setTimeout(runServer, policy.delayMs());+ else runServer();return true;});};diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex 4499e15361..d7ecc0e3e6 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -592,13 +592,16 @@ it("ships an edge and a Fly template that keep the server private", () => {expect(fly).not.toContain("OMB_HOSTED_");});-it("the Cloud launcher starts the server again only when it asks to after a restore, and only a few times in a row", () => {+it("the Cloud launcher starts the server again when it asks to after a restore or after a crash (with a pause), and only a few times in a row", () => {const launcher = readFileSync(join(import.meta.dirname, "cloud-home-start.ts"), "utf8");expect(launcher).toContain("const policy = restartPolicy();");// The volume is prepared (and the previous machine's lease cleared) through one helper, as `maus`, before any child starts.expect(launcher).toContain("const prepare = () => prepareCloudHomeData(home, cloudHomeDataDir(env, home), config.machineId);");- expect(launcher.indexOf("prepared = prepare();")).toBeLessThan(launcher.indexOf("runServer();"));- expect(launcher).toContain("if (!policy.again(code, stopping)) return false;");+ expect(launcher.indexOf("prepared = prepare();")).toBeLessThan(launcher.indexOf("\n runServer();"));+ expect(launcher).toContain("if (!policy.again(code, stopping, signal)) return false;");+ expect(launcher).toContain("if (policy.delayMs() > 0) restartTimer = setTimeout(runServer, policy.delayMs());");+ // A stop during the pause ends the wait, so a stopped home exits at once.+ expect(launcher).toContain("if (restartTimer) clearTimeout(restartTimer);");for (const code of [0, 1, null]) expect(restartPolicy().again(code)).toBe(false);expect(restartPolicy().again(RESTART_EXIT_CODE, true)).toBe(false);const policy = restartPolicy(() => 0);diff --git a/server/cloud-team-private-default.e2e.test.ts b/server/cloud-team-private-default.e2e.test.tsindex 0868e73b72..8220f701e8 100644--- a/server/cloud-team-private-default.e2e.test.ts+++ b/server/cloud-team-private-default.e2e.test.ts@@ -326,7 +326,7 @@ describe("the team's bot limit", () => {expect(adminToo.status, `${all} bots: ${JSON.stringify(adminToo.body)}`).toBe(409);const refused = await as("rui", "POST", "/api/bots", { name: "One more" });expect([refused.status, refused.body.error]).toEqual([409, adminToo.body.error]);- expect(refused.body.error).toMatch(/limited to 100 bots/);+ expect(refused.body.error).toMatch(/already has 100 bots.*delete a bot you no longer need/);}, hostTimeout(240_000));});diff --git a/server/crash-guard.test.ts b/server/crash-guard.test.tsnew file mode 100644index 0000000000..d5abd83115--- /dev/null+++ b/server/crash-guard.test.ts@@ -0,0 +1,148 @@+import { EventEmitter } from "node:events";+import { afterEach, describe, expect, it, vi } from "vitest";++import { crashVerdict, currentTurn, FATAL_EXIT_DEADLINE_MS, installCrashGuard, runInTurn, STORM_LIMIT, STORM_WINDOW_MS, withTurnScope } from "./crash-guard.ts";+import type { ProviderInstance } from "./contracts.ts";+import { CRASH_EXIT_CODE } from "./restart.ts";++const peerGone = (code: string) => Object.assign(new Error("socket hang up"), { code });++function rig(turnRunning = true) {+ const events = new EventEmitter();+ const calls = { failed: [] as string[], shutdown: [] as number[], exit: [] as number[], log: [] as string[] };+ let clock = 0;+ installCrashGuard({+ failTurn: (turn) => { calls.failed.push(turn.threadId); return turnRunning; },+ shutdown: (code) => calls.shutdown.push(code),+ exit: (code) => calls.exit.push(code),+ log: (line) => calls.log.push(line),+ redact: (text) => text.replaceAll("sk-secret", "[redacted]"),+ now: () => clock,+ on: (event, listener) => events.on(event, listener),+ });+ return { calls, raise: (kind: "uncaughtException" | "unhandledRejection", error: unknown) => events.emit(kind, error), tick: (ms: number) => { clock += ms; } };+}++afterEach(() => { vi.useRealTimers(); });++describe("the crash guard's rule", () => {+ it("stops only the turn an error came from, keeps the server up for a rejection or a peer gone, and closes for anything else", () => {+ const turn = { botId: "b", threadId: "t" };+ expect(crashVerdict("exception", new TypeError("x"), turn, 1)).toBe("fail-turn");+ expect(crashVerdict("rejection", new TypeError("x"), turn, 1)).toBe("fail-turn");+ expect(crashVerdict("rejection", new TypeError("x"), undefined, 1)).toBe("keep");+ expect(crashVerdict("exception", peerGone("EPIPE"), undefined, 1)).toBe("keep");+ expect(crashVerdict("exception", peerGone("ECONNRESET"), undefined, 1)).toBe("keep");+ expect(crashVerdict("exception", new TypeError("x"), undefined, 1)).toBe("exit");+ expect(crashVerdict("exception", new RangeError("Maximum call stack size exceeded"), turn, 1)).toBe("exit");+ expect(crashVerdict("rejection", new TypeError("x"), turn, STORM_LIMIT + 1)).toBe("exit");+ });++ it("knows the turn an error came from across a timer and a promise started inside it", async () => {+ const seen: Array<string | undefined> = [];+ await runInTurn({ botId: "b", threadId: "t1" }, async () => {+ await new Promise((resolve) => setTimeout(resolve, 1));+ seen.push(currentTurn()?.threadId);+ await Promise.resolve().then(() => seen.push(currentTurn()?.threadId));+ });+ seen.push(currentTurn()?.threadId);+ expect(seen).toEqual(["t1", "t1", undefined]);+ });+});++describe("installCrashGuard", () => {+ it("stops the turn and keeps the server up when a turn's own work throws or rejects", async () => {+ const { calls, raise } = rig();+ await runInTurn({ botId: "b", threadId: "t1" }, async () => {+ await Promise.resolve();+ raise("uncaughtException", new TypeError("cannot read properties of undefined (sk-secret)"));+ raise("unhandledRejection", new Error("later"));+ });+ expect(calls.failed).toEqual(["t1", "t1"]);+ expect(calls.shutdown).toEqual([]);+ expect(calls.exit).toEqual([]);+ expect(calls.log[0]).toContain("uncaught exception in the turn of bot b thread t1: TypeError: cannot read properties of undefined ([redacted])");+ expect(calls.log[0]).not.toContain("sk-secret");+ });++ it("closes when the turn an error is filed under is no longer running: nothing was stopped, so nothing is known to be whole", async () => {+ vi.useFakeTimers();+ const { calls, raise } = rig(false);+ await runInTurn({ botId: "b", threadId: "warm" }, async () => { raise("uncaughtException", new TypeError("late callback")); });+ expect(calls.failed).toEqual(["warm"]);+ expect(calls.shutdown).toEqual([CRASH_EXIT_CODE]);+ expect(calls.log[1]).toContain("no running turn of thread warm to stop");+ });++ it("files only a driver's own work under a turn: what it hands the server through its events runs outside the turn", async () => {+ const seen: Array<string | undefined> = [];+ let emit: (event: never) => void = () => {};+ const instance = withTurnScope({ adapter: {+ sendTurn: async () => { seen.push(currentTurn()?.threadId); await Promise.resolve(); setTimeout(() => emit({} as never), 1); },+ onEvent: (listener: (event: never) => void) => { emit = listener; return () => {}; },+ } } as unknown as Pick<ProviderInstance, "adapter">);+ instance.adapter.onEvent(() => seen.push(currentTurn()?.threadId ?? "outside"));+ await instance.adapter.sendTurn({ threadId: "t9", botId: "b" } as never);+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(seen).toEqual(["t9", "outside"]);+ });++ it("logs a rejection outside any turn and a peer that went away, and stays up", () => {+ const { calls, raise } = rig();+ raise("unhandledRejection", new Error("fetch failed"));+ raise("uncaughtException", peerGone("EPIPE"));+ expect(calls.log).toHaveLength(2);+ expect(calls.log[1]).toContain("[EPIPE]");+ expect(calls.shutdown).toEqual([]);+ });++ it("closes cleanly with the crash code on an error it cannot place, and exits anyway if the close hangs or fails again", () => {+ vi.useFakeTimers();+ const { calls, raise } = rig();+ raise("uncaughtException", new TypeError("x is not a function"));+ expect(calls.shutdown).toEqual([CRASH_EXIT_CODE]);+ expect(calls.exit).toEqual([]);+ vi.advanceTimersByTime(FATAL_EXIT_DEADLINE_MS);+ expect(calls.exit).toEqual([CRASH_EXIT_CODE]);+ raise("unhandledRejection", new Error("during the close"));+ expect(calls.exit).toEqual([CRASH_EXIT_CODE, CRASH_EXIT_CODE]);+ expect(calls.shutdown).toHaveLength(1);+ });++ it("closes when errors keep coming, even ones it would survive alone; a quiet minute resets the count", () => {+ vi.useFakeTimers();+ const { calls, raise, tick } = rig();+ for (let i = 0; i < STORM_LIMIT; i++) raise("unhandledRejection", new Error(`e${i}`));+ tick(STORM_WINDOW_MS + 1);+ for (let i = 0; i < STORM_LIMIT; i++) raise("unhandledRejection", new Error(`f${i}`));+ expect(calls.shutdown).toEqual([]);+ raise("unhandledRejection", new Error("one too many"));+ expect(calls.shutdown).toEqual([CRASH_EXIT_CODE]);+ });+});++describe("the crash guard in a real process", () => {+ const run = async (body: string) => {+ const { spawn } = await import("node:child_process");+ const guard = new URL("./crash-guard.ts", import.meta.url).href;+ const script = `import { installCrashGuard, runInTurn } from ${JSON.stringify(guard)};+ installCrashGuard({ failTurn: (turn) => { console.log("failed " + turn.threadId); return true; }, shutdown: (code) => { console.log("closing"); setTimeout(() => process.exit(code), 10); }, log: (line) => console.log(line.split("\\n")[0]) });+ ${body}`;+ const child = spawn(process.execPath, ["--experimental-strip-types", "--input-type=module", "-e", script], { stdio: ["ignore", "pipe", "pipe"] });+ let out = "";+ child.stdout.on("data", (chunk) => { out += chunk; });+ const code = await new Promise<number | null>((resolve) => child.once("exit", resolve));+ return { code, out };+ };++ it("stays up through a turn's own error and exits after its work, and closes with the crash code on an error outside any turn", async () => {+ const survived = await run(`runInTurn({ botId: "b", threadId: "t" }, () => setTimeout(() => { throw new TypeError("boom"); }, 5)); setTimeout(() => { console.log("still up"); }, 50);`);+ expect(survived.code).toBe(0);+ expect(survived.out).toContain("failed t");+ expect(survived.out).toContain("still up");+ const fatal = await run(`setTimeout(() => { throw new TypeError("boom"); }, 5); setTimeout(() => console.log("never"), 5_000);`);+ expect(fatal.code).toBe(CRASH_EXIT_CODE);+ expect(fatal.out).toContain("closing");+ expect(fatal.out).not.toContain("never");+ }, 30_000);+});diff --git a/server/crash-guard.ts b/server/crash-guard.tsnew file mode 100644index 0000000000..6c4f5925eb--- /dev/null+++ b/server/crash-guard.ts@@ -0,0 +1,126 @@+// What the server does with an error nothing caught. Without this, one bad callback ended the server with every turn+// in flight; the launcher did not start it again, and the turns it reran at the next start failed if it fell again.+//+// The rule:+// - A promise rejection nobody handled is survivable: the operation it belonged to is over, and what it changed before+// failing was written step by step. It is logged, and the turn it ran for (if any) is stopped.+// - An exception thrown by an engine driver's own code while it runs a turn is that turn's: the turn is stopped and its+// resources freed, the server stays up. Only driver code runs in a turn's scope (withTurnScope wraps sendTurn); what a+// driver hands the server (its events) runs outside it, so an error in shared server code is never filed as a turn's.+// If that turn is no longer running (a warm process or timer outlived it), nothing can be stopped: that is fatal.+// - An exception from a socket or pipe whose other end went away (EPIPE, ECONNRESET, ...) is survivable: it is logged.+// - Anything else (an exception outside any turn, a stack overflow, an internal assertion) may have left shared state+// half-changed: the server marks its running turns cut (so the next start reruns them), flushes nothing else it+// holds in memory (the files keep their last whole state), and exits with CRASH_EXIT_CODE; its launcher starts it+// again after a pause.+// - More than STORM_LIMIT errors within STORM_WINDOW_MS is treated as the last kind, so a failing loop cannot keep the+// server up and broken.+import { AsyncLocalStorage } from "node:async_hooks";++import type { ProviderInstance } from "./contracts.ts";+import { CRASH_EXIT_CODE } from "./restart.ts";++export interface TurnScope { botId: string; threadId: string }++const scope = new AsyncLocalStorage<TurnScope>();++/** Runs a turn's work so that an error nothing catches inside it, however late, is known to be that turn's. */+export const runInTurn = <T>(turn: TurnScope, run: () => T): T => scope.run(turn, run);+export const currentTurn = (): TurnScope | undefined => scope.getStore();+/** Runs server code a driver calls into (its event listeners) outside any turn's scope. */+export const outsideTurn = <T>(run: () => T): T => scope.exit(run);++/** A driver's sendTurn runs in the turn's scope, and its events reach the server's listeners outside it. */+export function withTurnScope<I extends Pick<ProviderInstance, "adapter">>(instance: I): I {+ const adapter = instance.adapter;+ (instance as { adapter: ProviderInstance["adapter"] }).adapter = {+ ...adapter,+ sendTurn: (input) => runInTurn({ botId: input.botId ?? "", threadId: input.threadId }, () => adapter.sendTurn(input)),+ onEvent: (listener) => adapter.onEvent((event) => outsideTurn(() => listener(event))),+ };+ return instance;+}++/** What the person is told in a turn the guard stopped. */+export const SERVER_ERROR_CAUSE = "turn stopped — the server hit an unexpected error (details in the server log)";++export const STORM_LIMIT = 10;+export const STORM_WINDOW_MS = 60_000;+/** Closing after a fatal error may take this long before the process exits anyway. */+export const FATAL_EXIT_DEADLINE_MS = 20_000;++const PEER_GONE = new Set(["EPIPE", "ECONNRESET", "ECONNABORTED", "ENOTCONN", "ETIMEDOUT", "ERR_STREAM_DESTROYED", "ERR_STREAM_WRITE_AFTER_END", "ERR_STREAM_PREMATURE_CLOSE"]);++export type CrashVerdict = "fail-turn" | "keep" | "exit";++const codeOf = (error: unknown): string | undefined => {+ const code = (error as { code?: unknown } | null)?.code;+ return typeof code === "string" ? code : undefined;+};++export function crashVerdict(kind: "exception" | "rejection", error: unknown, turn: TurnScope | undefined, inWindow: number): CrashVerdict {+ if (inWindow > STORM_LIMIT) return "exit";+ if (error instanceof RangeError && /call stack/i.test(error.message)) return "exit";+ if (codeOf(error) === "ERR_INTERNAL_ASSERTION") return "exit";+ if (turn) return "fail-turn";+ if (kind === "rejection") return "keep";+ return PEER_GONE.has(codeOf(error) ?? "") ? "keep" : "exit";+}++/** The error as one log line and its stack, with nothing from the process's environment. */+export function crashLine(kind: "exception" | "rejection", error: unknown, turn: TurnScope | undefined, verdict: CrashVerdict, redact: (text: string) => string): string {+ const name = error instanceof Error ? error.name : typeof error;+ const message = error instanceof Error ? error.message : String(error);+ const where = turn ? `in the turn of bot ${turn.botId} thread ${turn.threadId}` : "outside any turn";+ const what = verdict === "exit" ? "the server closes and starts again" : verdict === "fail-turn" ? "that turn is stopped, the server stays up" : "the server stays up";+ const stack = error instanceof Error && error.stack ? `\n${error.stack.split("\n").slice(1, 9).join("\n")}` : "";+ return redact(`crash guard: ${kind === "exception" ? "uncaught exception" : "unhandled rejection"} ${where}${codeOf(error) ? ` [${codeOf(error)}]` : ""}: ${name}: ${message.slice(0, 500)} — ${what}${stack}`);+}++export interface CrashGuardDeps {+ /** Stops the turn and frees what it holds; false when the turn had already ended. */+ failTurn(turn: TurnScope, detail: string): boolean;+ /** The close after a fatal error: mark running turns cut, flush nothing else, process.exit(code). */+ shutdown(code: number): void;+ log?: (line: string) => void;+ redact?: (text: string) => string;+ now?: () => number;+ exit?: (code: number) => void;+ on?: (event: "uncaughtException" | "unhandledRejection", listener: (error: unknown) => void) => void;+}++export function installCrashGuard(deps: CrashGuardDeps) {+ const log = deps.log ?? ((line: string) => console.error(line)), redact = deps.redact ?? ((text: string) => text);+ const now = deps.now ?? Date.now, exit = deps.exit ?? ((code: number) => process.exit(code));+ const recent: number[] = [];+ let closing = false;+ const handle = (kind: "exception" | "rejection") => (error: unknown) => {+ try {+ const at = now();+ while (recent.length && at - recent[0]! > STORM_WINDOW_MS) recent.shift();+ recent.push(at);+ const turn = currentTurn();+ let verdict = closing ? "exit" : crashVerdict(kind, error, turn, recent.length);+ log(crashLine(kind, error, turn, verdict, redact));+ if (verdict === "fail-turn" && turn) {+ let stopped = false;+ try { stopped = deps.failTurn(turn, error instanceof Error ? error.name : "error"); } catch (failure) { log(redact(`crash guard: stopping the turn failed: ${String(failure)}`)); }+ if (stopped) return;+ log(`crash guard: no running turn of thread ${turn.threadId} to stop — the server closes and starts again`);+ verdict = "exit";+ }+ if (verdict !== "exit") return;+ if (closing) { exit(CRASH_EXIT_CODE); return; }+ closing = true;+ // Ref'd on purpose: a close that hangs still ends here.+ setTimeout(() => exit(CRASH_EXIT_CODE), FATAL_EXIT_DEADLINE_MS);+ deps.shutdown(CRASH_EXIT_CODE);+ } catch {+ exit(CRASH_EXIT_CODE);+ }+ };+ const on = deps.on ?? ((event, listener) => { process.on(event, listener); });+ on("uncaughtException", handle("exception"));+ on("unhandledRejection", handle("rejection"));+ return { closing: () => closing };+}diff --git a/server/graceful-shutdown.ts b/server/graceful-shutdown.tsindex 3c0c0fa264..4e0da34af1 100644--- a/server/graceful-shutdown.ts+++ b/server/graceful-shutdown.ts@@ -14,9 +14,10 @@ export function createGracefulShutdown({cleanup,exit,timeoutMs = SHUTDOWN_DEADLINE_MS,-}: GracefulShutdownOptions): () => void {+}: GracefulShutdownOptions): (code?: number) => void {let started = false;- return () => {+ /** `code`: what the process exits with once closed (server/crash-guard.ts passes CRASH_EXIT_CODE); 0 by default. */+ return (code = 0) => {if (started) return;started = true;@@ -30,7 +31,7 @@ export function createGracefulShutdown({void Promise.race([settled, deadline]).finally(() => {if (timer) clearTimeout(timer);- exit(0);+ exit(code);});};}diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex b41b39e458..efd1b63de6 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -8,6 +8,7 @@ import { withEngineHomes } from "../engine-homes/engine-homes.ts";import { withLocalContext } from "../drivers/local-inject.ts";import { engineStatusFile, snapshotFrom } from "./engine-status-file.ts";import { withUnaskedStops } from "./unasked-stop.ts";+import { withTurnScope } from "../crash-guard.ts";import { withWslNotice } from "./wsl-launch.ts";import { modelManifest, startModelManifestRefresh } from "../model-manifest/manifest.ts";export { engineMemory } from "../engine-memory.ts";@@ -193,13 +194,13 @@ export class ProviderRegistry {// The RAW config: decodeConfig fills in the driver default, which would flag every instance as overridden.const rawCli = cliOfRaw(entry.config);if (rawCli) this.cliByInstance.set(instanceId, rawCli);- const live = withLocalContext(withUnaskedStops(withEngineHomes(withEngineMemory(await driver.create({+ const live = withLocalContext(withUnaskedStops(withEngineHomes(withEngineMemory(withTurnScope(await driver.create({instanceId,displayName: entry.displayName ?? driver.metadata.displayName,environment: entry.environment ?? {},enabled: entry.enabled ?? true,config,- })))));+ }))))));this.shareSnapshot(live);return { instanceId, live: decorate ? decorate(live) : live };} catch (e) {diff --git a/server/host/thread-maps.test.ts b/server/host/thread-maps.test.tsnew file mode 100644index 0000000000..4b2cf45aa2--- /dev/null+++ b/server/host/thread-maps.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";++import { createThreadMaps, keepThreadEntry } from "./thread-maps.ts";++describe("per-conversation maps", () => {+ it("forgets a deleted conversation at once, and an archived or gone one at the sweep, but never one that runs or is open", () => {+ const maps = createThreadMaps();+ const triggers = maps.track(new Map<string, string>()), noticed = maps.track(new Set<string>());+ for (const threadId of ["open", "archived", "running", "gone", "main", "room", "deleted"]) { triggers.set(threadId, "x"); noticed.add(threadId); }+ maps.forget("deleted");+ expect(triggers.has("deleted") || noticed.has("deleted")).toBe(false);+ const tasks: Record<string, { archivedAt?: number }> = { open: {}, archived: { archivedAt: 1 }, running: { archivedAt: 1 }, main: { archivedAt: 1 } };+ const keep = keepThreadEntry({+ botByThread: (threadId) => threadId in tasks ? { id: "bot", threadId: "main" } : null,+ taskByThread: (_botId, threadId) => tasks[threadId],+ groupByThread: (threadId) => threadId === "room" ? {} : undefined,+ }, (_botId, threadId) => threadId === "running");+ maps.sweep(keep);+ expect([...triggers.keys()].sort()).toEqual(["main", "open", "room", "running"]);+ expect([...noticed].sort()).toEqual(["main", "open", "room", "running"]);+ expect(maps.entries()).toBe(8);+ });+});diff --git a/server/host/thread-maps.ts b/server/host/thread-maps.tsnew file mode 100644index 0000000000..15a6f55b35--- /dev/null+++ b/server/host/thread-maps.ts@@ -0,0 +1,43 @@+// Per-conversation maps the server keeps in memory (a turn's trigger, the model a session reported, a room's queue, ...)+// were never emptied: with many bots they grow for as long as the server runs. Each such map is tracked here; a deleted+// conversation's entries go at once, and a sweep drops those of conversations that are archived or gone.+type ThreadKeyed = { delete(threadId: string): unknown; keys(): IterableIterator<string> };++export const THREAD_MAPS_SWEEP_MS = 10 * 60_000;++export function createThreadMaps() {+ const maps: ThreadKeyed[] = [];+ let timer: ReturnType<typeof setInterval> | undefined;+ const forget = (threadId: string) => { for (const map of maps) map.delete(threadId); };+ /** Drops every entry whose conversation `keep` no longer wants: archived, deleted, and not running. */+ const sweep = (keep: (threadId: string) => boolean) => {+ for (const map of maps) for (const threadId of Array.from(map.keys())) if (!keep(threadId)) map.delete(threadId);+ };+ return {+ track<T extends ThreadKeyed>(map: T): T { maps.push(map); return map; },+ forget,+ sweep,+ start(keep: (threadId: string) => boolean, everyMs = THREAD_MAPS_SWEEP_MS) {+ if (timer) return;+ timer = setInterval(() => { try { sweep(keep); } catch (error) { console.warn("thread maps: sweep failed", error); } }, everyMs);+ timer.unref?.();+ },+ stop() { if (timer) clearInterval(timer); timer = undefined; },+ entries: () => maps.reduce((sum, map) => sum + Array.from(map.keys()).length, 0),+ };+}++export interface KeepStore {+ botByThread(threadId: string): { id: string; threadId: string } | null | undefined;+ taskByThread(botId: string, threadId: string): { archivedAt?: number } | undefined;+ groupByThread(threadId: string): unknown;+}++/** A conversation's entries stay while it runs, is open (not archived) or belongs to a room; otherwise they go. */+export const keepThreadEntry = (store: KeepStore, busy: (botId: string, threadId: string) => boolean) => (threadId: string): boolean => {+ const bot = store.botByThread(threadId);+ if (!bot) return Boolean(store.groupByThread(threadId));+ if (busy(bot.id, threadId) || bot.threadId === threadId) return true;+ const task = store.taskByThread(bot.id, threadId);+ return task !== undefined && task.archivedAt === undefined;+};diff --git a/server/index.ts b/server/index.tsindex 300b915246..695bd1000e 100644--- a/server/index.ts+++ b/server/index.ts@@ -281,7 +281,7 @@ import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, typimport { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";import { createCloudMoveRoutes } from "./cloud-move-http.ts";-import { RESTART_EXIT_CODE } from "./restart.ts";+import { RESTART_EXIT_CODE } from "./restart.ts"; import { installCrashGuard, SERVER_ERROR_CAUSE } from "./crash-guard.ts"; import { markRequestArrival } from "./perf/loop-stalls.ts"; import { createThreadMaps, keepThreadEntry } from "./host/thread-maps.ts"; import { botLimitRefusal } from "./bot-limit.ts";import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createResearchAvailability } from "./research.ts";import { CloudCreditProvider } from "./cloud-credit-provider.ts";import { createCreditMoves } from "./cloud-credit-moves.ts"; import { createRoutineHoldsHost } from "./host/routine-holds-host.ts"; import { tellTurnedBackOn } from "./host/routines-turned-back-on.ts";@@ -479,7 +479,7 @@ import { OutboundRequestService } from "./outbound-requests.ts";import { createOutboundHold, OUTBOUND_HOLD_MS, type OutboundHoldAnswer } from "./outbound-hold.ts";import { connectorCallsIn, outboundCallsIn } from "../shared/outbound.ts";import { connectorAccessDecision, describeConnectorScopes } from "../shared/connector-scopes.ts";-import { bindThreadLogCapProvider } from "./thread-log-rotation.ts";+import { bindThreadLogCapProvider, threadLogCapOrDefault } from "./thread-log-rotation.ts";import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"; import { createBotApiHost } from "./bot-api-host.ts"; import { BotApiManager } from "./bot-api.ts"; import { BOT_API_PARTS, BOT_API_REFUSAL, BOT_API_TOOLS, botApiRouteRefused } from "./bot-api-fence.ts";import { addressFor } from "./webhook-address.ts";import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";@@ -797,7 +797,7 @@ if (hostedModels) {if (selection.instanceId && JSON.stringify(selection) !== JSON.stringify(cfg.defaultModelSelection)) saveConfig({ defaultModelSelection: selection });cfg.defaultModelSelection = selection;}-bindThreadLogCapProvider(() => threadEventLogMaxBytes(cfg));+bindThreadLogCapProvider(() => threadLogCapOrDefault(threadEventLogMaxBytes(cfg)));bindDecisionRetention(() => decisionRetentionDays(cfg.decisions?.retentionDays));bindSafetyFloor(() => cfg);const decider = createDecider({ config: () => cfg, dataDir: DATA_DIR }); const extractor = createExtractor({ config: () => cfg, timeZone: () => proactive.brief.timeZone() });@@ -823,7 +823,7 @@ const supportsApprovalMode = createApprovalModeSupport(registry);registerEnginesBinDir(); const engineUpdates = engineUpdatesFor({ drivers: BUILT_IN_DRIVERS, turnRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()), configuredClis: () => Object.values(providerConfigs()).flatMap((entry) => { const cli = (entry.config as { cli?: unknown } | undefined)?.cli; return typeof cli === "string" && cli ? [cli] : []; }), updated: () => { registry.forgetSnapshots(); broadcast({ kind: "config", ...configStatus() }); } });// Set only when a turn is admitted, never on queue or steer, so a second person's words cannot re-book the first person's turn.-const turnTriggers = new Map<string, UsageTrigger>();+const threadMaps = createThreadMaps(); const turnTriggers = threadMaps.track(new Map<string, UsageTrigger>());const NOBODY_PROFILE: MemberProfile = { name: "", email: "", aboutMe: "" };/** What a signed-in person is called on their lines, cards and reactions: on a Team Cloud the name they chose first. */@@ -3761,7 +3761,7 @@ const channelTaskBlocked = (group: GroupRecord) =>);// Load coordination state before registering store listeners or recovering routines: recovery can emit room changes synchronously.-const groupQueues = new Map<string, Promise<void>>();+const groupQueues = threadMaps.track(new Map<string, Promise<void>>());const personalReach = createPersonalReach({ privateTo: (threadId) => teamHost.privateTo(threadId), personKey: (email) => personKey({ id: "", email }), personBehind: (botId, threadId) => teammatePrompts.personBehind(botId, threadId), actingFor: (threadId, generation) => actingPeople.requester(threadId, generation), level: (bot, email) => { const role = (teamOwners.people?.list() ?? []).find((one) => one.email === email)?.role; return visibleTo(role === "owner" || role === "admin" ? { kind: "all", email } : { kind: "member", email }).level(bot.id); } }); const { roomRootProblem, roomHandoffProblem, roomHandoffTarget, roomSetupPending, roomTalks, laneRoomThread } = createRoomAccess({ store, privateTo: (threadId) => teamHost.privateTo(threadId), personalReach: () => personalReach, lookedAfterBy: (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null) });const roomJobs = createRoomJobs({ store, coordinator: { active: () => coordinator.active() }, cfg, laneRoomThread,operations: groupId => groupTurnOperations.get(groupId) ?? [], speakerOf: threadId => groupSpeakers.get(threadId)?.botId });@@ -4535,7 +4535,7 @@ store.onChange((change) => {case "thread.deleted":directRequestOwners.delete(change.threadId);for (const botId of computerControl.forgetThread(change.threadId)) announceControl(botId);- stoppedTurns.delete(change.threadId);+ stoppedTurns.delete(change.threadId); threadMaps.forget(change.threadId);turnStops.forget(change.threadId);repeats.settle(change.threadId);routines?.forgetRoutineRequestReceiptsForThread(change.threadId);@@ -4957,13 +4957,13 @@ function requestBehavior(value: unknown): "allow" | "deny" | "answer" | null {return value === "allow" || value === "deny" || value === "answer" ? value : null;}-const lastReply = new Map<string, string>();+const lastReply = threadMaps.track(new Map<string, string>());const stoppedTurns = new Map<string, string | undefined>(), personStops = new PersonStops();// The turn each thread runs, from its start to its end, and nothing once the thread is idle: what Stop and the rescue check.const liveTurns = new LiveTurns((threadId) => { const owner = store.botByThread(threadId); return owner ? threadBusy(owner.id, threadId) : groupSpeakers.has(threadId); });const settlingTurns = new Set<string>();-const sessionModelByThread = new Map<string, string>();-const nativeReviewNoticed = new Set<string>();+const sessionModelByThread = threadMaps.track(new Map<string, string>());+const nativeReviewNoticed = threadMaps.track(new Set<string>());const providerLabel = (provider: string): string => {const bare = provider.replace(/Agent$/, "");return bare.charAt(0).toUpperCase() + bare.slice(1);@@ -5016,10 +5016,10 @@ const watchdog = new TurnWatchdog({const bot = botForThread(turn.botId, turn.threadId);const routineRun = activeRoutineRunForThread(turn.threadId);void runningTurnInstance(bot, turn.threadId)?.adapter.interruptTurn(turn.threadId).catch(() => {});- const minutes = Math.round(silentMs / 60_000), notice = stallNotice(turn, silentMs, Date.now(), reason), stallCause = chatNotice(notice.key, notice.params), cause = engineMemory.stallCause(turn.threadId, stallCause);+ const minutes = Math.round(silentMs / 60_000), notice = stallNotice(turn, silentMs, Date.now(), reason), stallCause = chatNotice(notice.key, notice.params), cause = reason === "server-error" ? SERVER_ERROR_CAUSE : engineMemory.stallCause(turn.threadId, stallCause);const stalled = stoppedTurnText(turn.threadId, liveTurnByThread.get(turn.threadId), cause);if (routineRun?.target === "bot") {- routines?.failThread(turn.threadId, engineMemory.stallCause(turn.threadId, reason === "engine-exited" ? stallCause : `No activity for ${minutes} minutes — the routine was stopped`), { cause: "stalled" });+ routines?.failThread(turn.threadId, reason === "server-error" ? cause : engineMemory.stallCause(turn.threadId, reason === "engine-exited" ? stallCause : `No activity for ${minutes} minutes — the routine was stopped`), { cause: "stalled" });}store.appendMessage(turn.threadId, {role: "bot",@@ -7478,7 +7478,7 @@ function stopScreenPoller(botId: string, threadId?: string) {}}-const settledScreenHashes = new Map<string, string>();+const settledScreenHashes = threadMaps.track(new Map<string, string>());function shownScreenHash(threadId: string): string | undefined {const known = settledScreenHashes.get(threadId);@@ -12533,7 +12533,7 @@ ROUTES.push(createLiveRoutes({const toolResults = new ToolResults();const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {- if (CLOUD_TEAM) holdBodyDeadline(req, res);+ markRequestArrival(); if (CLOUD_TEAM) holdBodyDeadline(req, res);let url: URL;try {url = new URL(req.url ?? "/", `http://localhost:${PORT}`);@@ -14080,7 +14080,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 429, { error: `You can create at most ${MAX_CREATED_BOTS_PER_TURN} bots in one turn. Use the team you have before adding more.` });}if (store.bots.length >= MAX_WORKSPACE_BOTS) {- return json(res, 409, { error: `this workspace is limited to ${MAX_WORKSPACE_BOTS} bots` });+ return json(res, 409, { error: botLimitRefusal(MAX_WORKSPACE_BOTS) });}const fields = createBotFields(body, chief, store.bots);if ("error" in fields) return json(res, fields.status, { error: fields.error });@@ -14118,7 +14118,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (internalCapability.createdBots >= MAX_CREATED_BOTS_PER_TURN) {return json(res, 429, { error: `You can create at most ${MAX_CREATED_BOTS_PER_TURN} bots in one turn. Use the team you have before adding more.` });}- if (store.bots.length >= MAX_WORKSPACE_BOTS) return json(res, 409, { error: `this workspace is limited to ${MAX_WORKSPACE_BOTS} bots` });+ if (store.bots.length >= MAX_WORKSPACE_BOTS) return json(res, 409, { error: botLimitRefusal(MAX_WORKSPACE_BOTS) });const recheck = body.copyFromBotId === undefined ? fields : createBotFields(body, chief, store.bots); if ("error" in recheck) return json(res, recheck.status, { error: recheck.error }); const duplicate = store.bots.find((candidate) =>!candidate.hidden &&@@ -15423,7 +15423,7 @@ const gracefulShutdown = createGracefulShutdown({catch {// An uncleared marker makes saved sessions require sign-in next boot: never label failed persistence a clean shutdown.console.error("Session persistence failed during shutdown; account sign-in will be required again.");- exitCode = 1;+ exitCode ||= 1;}flushLaterSaves(); closeMessageDb();mcpOAuth.dispose();@@ -15441,6 +15441,5 @@ const gracefulShutdown = createGracefulShutdown({},});-for (const signal of ["SIGINT", "SIGTERM"] as const) {- process.on(signal, gracefulShutdown);-}+for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, () => gracefulShutdown());+installCrashGuard({ failTurn: (turn) => watchdog.fail(turn.threadId), redact: redactSecretsInText, shutdown: (code) => { /* Fatal: no flush of what memory holds (ledgers, journals, sessions, bus, registries); running turns stay "running" in the runtime store, so the next start reruns them. Engines are stopped so none is orphaned. */ companyShutdown = true; try { noteTurnsCutByShutdown(); } catch { /* best effort */ } void Promise.race([registry.disposeAll(), new Promise((done) => setTimeout(done, 5_000))]).catch(() => {}).finally(() => { releaseDataDirLeaseAtExit(); process.exit(code); }); } }); threadMaps.start(keepThreadEntry(store, threadBusy));diff --git a/server/perf/loop-stalls.test.ts b/server/perf/loop-stalls.test.tsnew file mode 100644index 0000000000..3646085694--- /dev/null+++ b/server/perf/loop-stalls.test.ts@@ -0,0 +1,80 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { setTimeout as delay } from "node:timers/promises";+import { describe, expect, it } from "vitest";++import { writeFileAtomic } from "../atomic.ts";+import { createLoopStalls, markRequestArrival, requestArrivedBefore, stallStats, timeBlocking } from "./loop-stalls.ts";+import { PERF_HEALTH_MAX_BYTES, perfHealth, stallLines } from "./perf-report.ts";++const tally = { n: 0, ms: 0, maxMs: 0 };+const minute = (count: number, points: Array<[number, number]>) => ({ count, points, maxMs: points.at(-1)![1], saves: tally, runtimeReads: tally });++describe("loop stall percentiles", () => {+ it("weighs each minute by its samples, so one bad minute shows in the hour's tail and not its middle", () => {+ const quiet = minute(3000, [[0, 0.1], [60, 0.2], [99, 0.5], [100, 1]]);+ const bad = minute(30, [[0, 0.1], [50, 0.3], [90, 900], [100, 2500]]);+ const hour = stallStats([quiet, quiet, bad])!;+ expect(hour.p50).toBe(0.2);+ expect(hour.max).toBe(2500);+ expect(hour.over1s).toBe(3);+ expect(hour.over100ms).toBe(15);+ expect(stallStats([bad])).toMatchObject({ p50: 0.3, p95: 2500, p99: 2500, max: 2500 });+ expect(stallStats([])).toBeNull();+ });+});++describe("the loop stall recorder", () => {+ it("sees a stall the once-a-minute sampler would miss, and counts whole-file saves", async () => {+ const stalls = createLoopStalls({ minuteMs: 60_000 });+ const dir = mkdtempSync(join(tmpdir(), "loop-stalls-"));+ stalls.start();+ try {+ await delay(60);+ const before = stalls.report().saves.m1.n;+ writeFileAtomic(join(dir, "a.json"), "{}");+ timeBlocking("runtimeReads", () => { const until = Date.now() + 300; while (Date.now() < until) { /* the stall */ } });+ await delay(60);+ const report = stalls.report();+ expect(report.m1!.max).toBeGreaterThanOrEqual(250);+ expect(report.m1!.over100ms).toBeGreaterThanOrEqual(1);+ expect(report.m1!.p50).toBeLessThan(5);+ expect(report.h1!.max).toBe(report.m1!.max);+ expect(report.saves.m1.n).toBe(before + 1);+ expect(report.runtimeReads.m1).toMatchObject({ n: 1 });+ expect(report.runtimeReads.m1.maxMs).toBeGreaterThanOrEqual(290);+ stalls.roll();+ const rolled = stalls.report();+ expect(rolled.m1!.max).toBe(report.m1!.max);+ expect(rolled.runtimeReads.h1.n).toBe(1);+ expect(stallLines(rolled)[0]).toMatch(/^Event loop stalls, measured all the time: last minute p50 .* max \d/);+ } finally {+ stalls.stop();+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("starts a message's wait when its request arrived, only for that request and only if recent", async () => {+ expect(requestArrivedBefore(Date.now())).toBeUndefined();+ await (async () => {+ markRequestArrival(1_000);+ await Promise.resolve();+ expect(requestArrivedBefore(3_500)).toBe(1_000);+ expect(requestArrivedBefore(500)).toBeUndefined();+ expect(requestArrivedBefore(1_000 + 120_000)).toBeUndefined();+ })();+ });++ it("fits the health report's budget with the rest of the timings, and holds numbers only", () => {+ const stalls = createLoopStalls();+ const report = stalls.report();+ const body = perfHealth({ hour: { turns: 0, failed: 0, phases: {}, slow: [], partial: false }, day: { turns: 0, failed: 0, slow: [], phases: {}, tools: [], retries: { n: 0, turns: 0, backoffMs: 0, why: {} }, limits: {}, failovers: 0 } as never,+ live: [], limits: null, process: null, stalls: report });+ expect(JSON.stringify(body).length).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);+ expect(body.stalls).toEqual(report);+ const strings: string[] = [];+ JSON.stringify(report, (_key, value) => { if (typeof value === "string") strings.push(value); return value; });+ expect(strings).toEqual([]);+ });+});diff --git a/server/perf/loop-stalls.ts b/server/perf/loop-stalls.tsnew file mode 100644index 0000000000..f3801b6c36--- /dev/null+++ b/server/perf/loop-stalls.ts@@ -0,0 +1,137 @@+// How long the event loop could not answer, measured all the time (perf_hooks.monitorEventLoopDelay), and the blocking+// work the server times itself: whole-file saves and runtime-store reads. The process sampler's own "timer late" reads+// one timer once a minute, so it missed 2–3 s stalls a probe saw; this does not. Numbers only, no names or content.+import { AsyncLocalStorage } from "node:async_hooks";+import { monitorEventLoopDelay, performance, type IntervalHistogram } from "node:perf_hooks";++export type BlockingKind = "saves" | "runtimeReads";+export interface Tally { n: number; ms: number; maxMs: number }+const zero = (): Tally => ({ n: 0, ms: 0, maxMs: 0 });++let current: Record<BlockingKind, Tally> = { saves: zero(), runtimeReads: zero() };++export function noteBlocking(kind: BlockingKind, ms: number): void {+ const tally = current[kind];+ tally.n += 1;+ tally.ms += ms;+ if (ms > tally.maxMs) tally.maxMs = ms;+}++/** Runs synchronous work that blocks the server and counts its time. */+export function timeBlocking<T>(kind: BlockingKind, run: () => T): T {+ const at = performance.now();+ try {+ return run();+ } finally {+ noteBlocking(kind, performance.now() - at);+ }+}++// When the request a person's message came in on arrived: a turn's queue clock starts there, not after the work the+// server did before storing the message. Set at the top of the request handler for the rest of that request.+const arrival = new AsyncLocalStorage<number>();+export const markRequestArrival = (at = Date.now()): void => arrival.enterWith(at);+/** The current request's arrival, if it came within `withinMs` of `at`. */+export function requestArrivedBefore(at: number, withinMs = 60_000): number | undefined {+ const arrived = arrival.getStore();+ return arrived !== undefined && arrived <= at && at - arrived <= withinMs ? arrived : undefined;+}++/** A distribution as monitorEventLoopDelay gives it: [percentile, delay ms] in rising order, and how many samples. */+interface Minute { count: number; points: Array<[number, number]>; maxMs: number; saves: Tally; runtimeReads: Tally }++export interface StallStats { p50: number; p95: number; p99: number; max: number; over100ms: number; over1s: number }+export interface StallsReport {+ /** The loop's delays over the last minute and the last hour, ms. */+ m1: StallStats | null;+ h1: StallStats | null;+ /** Whole-file saves and runtime-store reads: how many, their total and longest ms. */+ saves: { m1: Tally; h1: Tally };+ runtimeReads: { m1: Tally; h1: Tally };+}++/** The histogram holds the time between its timer's firings: the delay is what exceeds the timer's own interval. */+const lateMs = (ns: number, resolutionMs: number) => Math.max(0, Math.round(ns / 1e5) / 10 - resolutionMs);++function minuteOf(histogram: Pick<IntervalHistogram, "count" | "max" | "percentiles">, tallies: Record<BlockingKind, Tally>, resolutionMs: number): Minute {+ const points = [...histogram.percentiles].map(([percentile, ns]) => [percentile, lateMs(ns, resolutionMs)] as [number, number]).sort((a, b) => a[0] - b[0]);+ return { count: histogram.count, points, maxMs: histogram.count ? lateMs(histogram.max, resolutionMs) : 0, saves: { ...tallies.saves }, runtimeReads: { ...tallies.runtimeReads } };+}++/** The share of a minute's samples at or under `value`. */+function shareAtOrUnder(minute: Minute, value: number): number {+ let share = 0;+ for (const [percentile, delay] of minute.points) {+ if (delay > value) break;+ share = percentile / 100;+ }+ return share;+}++/** Percentiles over several minutes together, each weighted by its samples: exact to the histograms' own precision. */+export function stallStats(minutes: readonly Minute[]): StallStats | null {+ const used = minutes.filter((minute) => minute.count > 0);+ const total = used.reduce((sum, minute) => sum + minute.count, 0);+ if (!total) return null;+ const values = [...new Set(used.flatMap((minute) => minute.points.map(([, delay]) => delay)))].sort((a, b) => a - b);+ const atOrUnder = (value: number) => used.reduce((sum, minute) => sum + minute.count * shareAtOrUnder(minute, value), 0) / total;+ const quantile = (q: number) => {+ let low = 0, high = values.length - 1;+ while (low < high) {+ const mid = (low + high) >> 1;+ if (atOrUnder(values[mid]!) >= q) high = mid; else low = mid + 1;+ }+ return values[low] ?? 0;+ };+ const over = (value: number) => Math.round(used.reduce((sum, minute) => sum + minute.count * (1 - shareAtOrUnder(minute, value)), 0));+ return { p50: quantile(0.5), p95: quantile(0.95), p99: quantile(0.99), max: Math.max(...used.map((minute) => minute.maxMs)), over100ms: over(100), over1s: over(1000) };+}++const sum = (tallies: readonly Tally[]): Tally => tallies.reduce((all, tally) => ({ n: all.n + tally.n, ms: all.ms + tally.ms, maxMs: Math.max(all.maxMs, tally.maxMs) }), zero());+const rounded = (tally: Tally): Tally => ({ n: tally.n, ms: Math.round(tally.ms), maxMs: Math.round(tally.maxMs * 10) / 10 });++export const STALL_RESOLUTION_MS = 20;+export const MINUTE_MS = 60_000;+const MINUTES_KEPT = 60;++export function createLoopStalls(options: { histogram?: IntervalHistogram; minuteMs?: number; resolutionMs?: number } = {}) {+ const resolutionMs = options.resolutionMs ?? STALL_RESOLUTION_MS;+ const histogram = options.histogram ?? monitorEventLoopDelay({ resolution: resolutionMs });+ const minuteMs = options.minuteMs ?? MINUTE_MS;+ const minutes: Minute[] = [];+ let timer: ReturnType<typeof setInterval> | undefined;+ const roll = () => {+ minutes.push(minuteOf(histogram, current, resolutionMs));+ if (minutes.length > MINUTES_KEPT) minutes.shift();+ histogram.reset();+ current = { saves: zero(), runtimeReads: zero() };+ };+ return {+ start() {+ if (timer) return;+ histogram.enable();+ timer = setInterval(roll, minuteMs);+ timer.unref?.();+ },+ stop() {+ if (timer) clearInterval(timer);+ timer = undefined;+ histogram.disable();+ },+ /** Rolls the minute now (tests). */+ roll,+ /** The last full minute (or the one under way, before the first ends) and the last hour including the minute under way. */+ report(): StallsReport {+ const live = minuteOf(histogram, current, resolutionMs);+ const last = minutes.at(-1);+ const m1 = last && last.count ? last : live;+ const hour = [...minutes.slice(-(MINUTES_KEPT - 1)), live];+ return {+ m1: stallStats([m1]), h1: stallStats(hour),+ saves: { m1: rounded(m1.saves), h1: rounded(sum(hour.map((minute) => minute.saves))) },+ runtimeReads: { m1: rounded(m1.runtimeReads), h1: rounded(sum(hour.map((minute) => minute.runtimeReads))) },+ };+ },+ };+}+export type LoopStalls = ReturnType<typeof createLoopStalls>;diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex 70ed8a440a..6c6a0678d2 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -5,6 +5,7 @@ import { join } from "node:path";import type { EngineLimitsReport } from "../../shared/limit-reset.ts";import type { RuntimeEvent } from "../contracts.ts";import type { StoreChange } from "../store.ts";+import { createLoopStalls, requestArrivedBefore, type LoopStalls } from "./loop-stalls.ts";import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth } from "./perf-report.ts";import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";import type { FailoverWhy } from "./turn-record.ts";@@ -28,6 +29,8 @@ export interface PerfHostDeps {timer?: false;now?: () => number;sampler?: ProcessSampler;+ /** Tests: the event-loop delay recorder. */+ stalls?: LoopStalls;/** The engine processes the server tracks, with the threads each runs (engine-memory, on a Cloud home). */engines?: () => ReadonlyArray<{ pid: number; threads: readonly string[] }>;}@@ -63,7 +66,7 @@ export function createPerfHost(deps: PerfHostDeps) {const guarded = <T>(what: string, read: () => T, fallback: T): T => {try { return read(); } catch (error) { say(`failed:${what}`, `the performance recorder failed (${what}): ${error instanceof Error ? error.name : "error"}`); return fallback; }};- deps.store.onChange((change) => { if (change.type === "message") guarded("message", () => timings.noteMessage(change.threadId, change.message), undefined); });+ deps.store.onChange((change) => { if (change.type === "message") guarded("message", () => timings.noteMessage(change.threadId, change.message, requestArrivedBefore(change.message.at)), undefined); });deps.bus.subscribe((event) => guarded("event", () => timings.noteEvent(event), undefined));/** The limit clock is made after this host; until it is, there are no limits to read. */@@ -83,8 +86,10 @@ export function createPerfHost(deps: PerfHostDeps) {stalled: (ms) => say("loop", `event loop stalled: the ${linux ? 60 : 300}s sampler fired ${duration(ms)} late`), afterSample: watchHolds,});if (deps.timer !== false && !windows) sampler.start();+ const stalls = deps.stalls ?? createLoopStalls();+ if (deps.timer !== false) stalls.start();- const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report() });+ const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null) });return {timings,sampler,@@ -103,7 +108,7 @@ export function createPerfHost(deps: PerfHostDeps) {return guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE).join("\n");},/** The graceful shutdown: no more samples, and the turns since the last save written now. */- stop() { sampler.stop(); guarded("save", () => timings.flush(), undefined); },+ stop() { sampler.stop(); stalls.stop(); guarded("save", () => timings.flush(), undefined); },};}export type PerfHost = ReturnType<typeof createPerfHost>;diff --git a/server/perf/perf-privacy.test.ts b/server/perf/perf-privacy.test.tsindex fe320dd1ec..193622c3b2 100644--- a/server/perf/perf-privacy.test.ts+++ b/server/perf/perf-privacy.test.ts@@ -10,7 +10,7 @@ import type { StoreChange } from "../store.ts";import { createPerfHost, PERF_FILE } from "./perf-host.ts";import { PERF_HEALTH_MAX_BYTES, perfHealth } from "./perf-report.ts";import { createProcessSampler, type ProcessList } from "./process-sampler.ts";-import { createTurnTimings } from "./turn-timings.ts";+import { createTurnTimings, RING_CAP } from "./turn-timings.ts";const START = 1_800_000_000_000;const SECRETS = [@@ -209,7 +209,7 @@ describe("the recorder's cost", () => {console.log(`recorder: ${perEventUs.toFixed(2)} µs per event over ${turns * (events.length + 2)} events; window()+day() ${reportMs.toFixed(2)} ms`);expect(perEventUs).toBeLessThan(50);expect(reportMs).toBeLessThan(50);- expect(timings.recent()).toHaveLength(200);+ expect(timings.recent()).toHaveLength(RING_CAP);expect(timings.live()).toHaveLength(0);});});diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.tsindex e707aa2b26..33a4879210 100644--- a/server/perf/perf-report.ts+++ b/server/perf/perf-report.ts@@ -5,8 +5,9 @@ import type { EngineLimitsReport } from "../../shared/limit-reset.ts";import type { DayAggregate } from "./day-ledger.ts";import { SLOW_TURN_MS } from "./day-ledger.ts";import { PHASES, type Phase, type PhaseStats } from "./phases.ts";+import type { StallsReport, StallStats, Tally } from "./loop-stalls.ts";import type { ProcessReport } from "./process-sampler.ts";-import type { LiveTurnView, WindowStats } from "./turn-timings.ts";+import { RING_CAP, type LiveTurnView, type WindowStats } from "./turn-timings.ts";import type { TurnTiming } from "./turn-record.ts";/** The health report's `perf` field is at most this many bytes of JSON; parts are dropped, least useful first, to fit. */@@ -24,6 +25,8 @@ export interface PerfSources {live: LiveTurnView[];limits: EngineLimitsReport | null | undefined;process: ProcessReport | null;+ /** The loop's delays measured all the time, and the blocking work the server times (loop-stalls.ts). */+ stalls?: StallsReport | null;}/** Engines refusing work, or within 10 points of their limit: driver kind, window, use and reset time only. */@@ -47,16 +50,27 @@ export function perfHealth(sources: PerfSources) {live: sources.live.slice(0, LIVE_SHOWN),holds: limitHolds(sources.limits),process: sources.process,+ stalls: sources.stalls ?? null,};const size = () => JSON.stringify(body).length;if (size() > PERF_HEALTH_MAX_BYTES && body.process) body.process = { ...body.process, buckets: body.process.buckets.slice(0, 6) };if (size() > PERF_HEALTH_MAX_BYTES) body.h24.tools = body.h24.tools.slice(0, 4);if (size() > PERF_HEALTH_MAX_BYTES) body.live = body.live.slice(0, 2);if (size() > PERF_HEALTH_MAX_BYTES) body.process = null;+ if (size() > PERF_HEALTH_MAX_BYTES) body.stalls = null;return body;}export type PerfHealth = ReturnType<typeof perfHealth>;+const stallLine = (stats: StallStats | null) => stats+ ? `p50 ${duration(stats.p50)} p95 ${duration(stats.p95)} p99 ${duration(stats.p99)} max ${duration(stats.max)}, ${stats.over100ms} over 100ms, ${stats.over1s} over 1s` : "not measured yet";+const tallyLine = (tally: Tally) => `${tally.n} taking ${duration(tally.ms)} (longest ${duration(tally.maxMs)})`;+export const stallLines = (stalls: StallsReport): string[] => [+ `Event loop stalls, measured all the time: last minute ${stallLine(stalls.m1)}; last hour ${stallLine(stalls.h1)}`,+ ` Whole-file saves: last minute ${tallyLine(stalls.saves.m1)}; last hour ${tallyLine(stalls.saves.h1)}`,+ ` Runtime store reads: last minute ${tallyLine(stalls.runtimeReads.m1)}; last hour ${tallyLine(stalls.runtimeReads.h1)}`,+];+/** 850ms, 14s, 6m12s, 1h03m. */export function duration(ms: number): string {if (ms < 1000) return `${Math.round(ms)}ms`;@@ -90,7 +104,7 @@ export function turnLine(turn: TurnTiming): string {export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], recentTitle: string): string[] {const { hour, day } = sources;const lines = ["## Performance (timings only: no messages, names, files or addresses)"];- lines.push(`Last hour: ${plural(hour.turns, "turn")}, ${hour.failed} failed${hour.partial ? " (only the latest 200 kept)" : ""}; slow: ${slowLine(hour.slow)}`);+ lines.push(`Last hour: ${plural(hour.turns, "turn")}, ${hour.failed} failed${hour.partial ? ` (only the latest ${RING_CAP} kept)` : ""}; slow: ${slowLine(hour.slow)}`);if (hour.turns) lines.push(` ${phaseLine(hour.phases)}`);lines.push(`Last 24 h: ${plural(day.turns, "turn")}, ${day.failed} failed; slow: ${slowLine(day.slow)}`);if (day.turns) lines.push(` ${phaseLine(day.phases)}`);@@ -107,8 +121,9 @@ export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], rlines.push(`Processes, last hour (${proc.scope === "all" ? "every process here" : "this app's own"}, sampled every ${proc.intervalS}s): ${proc.buckets.map((bucket) =>`${bucket.bucket} ${bucket.cpu60mS}s CPU (5 min ${bucket.cpu5mS}s, peak ${bucket.peakPct}% of a core, ${bucket.procs} running, ${bucket.rssMB} MB)`).join("; ")}`);lines.push(` Browsers running: ${proc.browsers}${proc.unseen60mS !== null ? `; CPU no sample accounts for: ${proc.unseen60mS}s` : ""}`);- lines.push(`Event loop: busy ${proc.loop.eluPct ?? "?"}% (max ${proc.loop.eluMaxPct ?? "?"}%), timer late p95 ${duration(proc.loop.driftP95Ms)}, max ${duration(proc.loop.driftMaxMs)}`);+ lines.push(`Event loop: busy ${proc.loop.eluPct ?? "?"}% (max ${proc.loop.eluMaxPct ?? "?"}%), sampler timer late p95 ${duration(proc.loop.driftP95Ms)}, max ${duration(proc.loop.driftMaxMs)} (one reading per sample)`);} else lines.push("Processes: not sampled yet");+ if (sources.stalls) lines.push(...stallLines(sources.stalls));lines.push(recentTitle);lines.push(...(recent.length ? recent.map((turn) => ` ${turnLine(turn)}`) : [" (none)"]));return lines;diff --git a/server/perf/turn-timings.test.ts b/server/perf/turn-timings.test.tsindex e97d6e1bc1..cee9aac90d 100644--- a/server/perf/turn-timings.test.ts+++ b/server/perf/turn-timings.test.ts@@ -159,7 +159,7 @@ describe("the ring and its file", () => {w.emit({ type: "turn.completed", ok: true }, "thread_1", `t${index}`);}w.timings.flush();- expect(statSync(file).size).toBeLessThan(150_000);+ expect(statSync(file).size).toBeLessThan(RING_CAP * 250);const saved = JSON.parse(readFileSync(file, "utf8"));saved.ring.push({ startedAt: 1, endedAt: 2, threadId: "../../etc/passwd", engine: "claude --api-key=sk-x", tools: [{ kind: "rm -rf /", n: 1 }] });writeFileSync(file, JSON.stringify(saved));diff --git a/server/perf/turn-timings.ts b/server/perf/turn-timings.tsindex 8d06a51626..e1d4302dfe 100644--- a/server/perf/turn-timings.ts+++ b/server/perf/turn-timings.ts@@ -13,7 +13,8 @@ import {type FailoverWhy, type LimitScope, type QueueWhy, type ToolKind, type ToolStat, type TurnTiming,} from "./turn-record.ts";-export const RING_CAP = 200;+/** Enough for an hour of 34 bots' turns, so the hour's percentiles are not cut short. */+export const RING_CAP = 1_000;const LIVE_CAP = 200, PENDING_CAP = 500, OPEN_TOOLS_CAP = 64;/** A turn whose end never came is taken as over after this long: dropped, or, while it waits on a person, finished as such. */export const LIVE_TTL_MS = 6 * 3_600_000;@@ -247,14 +248,15 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {},/** Every message the store appends: a person's message starts their wait for a turn; a reply or a failure row while* no turn runs ends that wait unanswered. Other bot rows do not: wait notices are posted while the turn waits. */- noteMessage(threadId: string, message: Pick<Message, "at" | "role" | "kind" | "steered" | "aside" | "from" | "peerAsk" | "automation" | "tool">) {+ noteMessage(threadId: string, message: Pick<Message, "at" | "role" | "kind" | "steered" | "aside" | "from" | "peerAsk" | "automation" | "tool">, arrivedAt?: number) {if (message.role !== "user") {if (!live.has(threadId) && (message.kind === "text" || message.tool?.ok === false)) clearWaiting(threadId);return;}const waiting = pending.get(threadId);if (!PERSON_MESSAGE(message) || (waiting && message.at - waiting.at <= PENDING_TTL_MS)) return;- remember(pending, threadId, { at: message.at, behind: live.has(threadId) }, PENDING_CAP);+ // The wait starts when the request carrying the message arrived: work the server did before storing it is part of it.+ remember(pending, threadId, { at: Math.min(message.at, arrivedAt ?? message.at), behind: live.has(threadId) }, PENDING_CAP);},/*** A turn this thread was dispatching never ran (`turnId`, the id the driver refused it under). Its wait ends; a turndiff --git a/server/restart.test.ts b/server/restart.test.tsindex c65a9ce021..4af9301e07 100644--- a/server/restart.test.ts+++ b/server/restart.test.ts@@ -3,7 +3,7 @@ import type { ChildProcess } from "node:child_process";import { expect, it, vi } from "vitest";import type { CliOptions } from "./cli.ts";import { serveUntilStopped } from "./cli.ts";-import { RESTART_EXIT_CODE, restartPolicy, STABLE_RUN_MS } from "./restart.ts";+import { CRASH_BACKOFF_MS, CRASH_EXIT_CODE, crashed, RESTART_EXIT_CODE, restartPolicy, STABLE_RUN_MS } from "./restart.ts";import { superviseServer } from "./server-launcher.ts";it("one policy counts for every launcher: again only on 75, not while stopping, at most five in a row, and a run that stayed up starts the count again", () => {@@ -90,13 +90,63 @@ it("the container launcher stops on any other exit, and on a 75 that arrives whichild.emit("exit", RESTART_EXIT_CODE, null);expect(await stopping).toBe(RESTART_EXIT_CODE);expect(started).toBe(1);- child = fakeChild(3);- const killed = superviseServer(() => child as unknown as ChildProcess, { signals: signals as unknown as NodeJS.Process });- child.emit("exit", null, "SIGKILL");- expect(await killed).toBe(1);let runs = 0;const looping = superviseServer(() => { runs++; const next = fakeChild(runs); queueMicrotask(() => next.emit("exit", RESTART_EXIT_CODE, null)); return next as unknown as ChildProcess; },{ signals: signals as unknown as NodeJS.Process, now: () => 0 });expect(await looping).toBe(RESTART_EXIT_CODE);expect(runs).toBe(6);});++it("a crash starts the server again after a pause that grows, and a crash loop stops; a run that stayed up forgives it", () => {+ let clock = 0;+ const policy = restartPolicy(() => clock);+ for (const [code, signal] of [[CRASH_EXIT_CODE, null], [null, "SIGKILL"], [null, "SIGABRT"], [137, null]] as const) expect(crashed(code, signal), `${code} ${signal}`).toBe(true);+ for (const [code, signal] of [[0, null], [1, null], [null, "SIGTERM"], [null, "SIGINT"], [RESTART_EXIT_CODE, null]] as const) expect(crashed(code, signal), `${code} ${signal}`).toBe(false);+ const delays: number[] = [];+ while (policy.again(CRASH_EXIT_CODE)) delays.push(policy.delayMs());+ expect(delays).toEqual([...CRASH_BACKOFF_MS]);+ expect(delays.every((delay, i) => i === 0 || delay > delays[i - 1]!)).toBe(true);+ // A crash during a stop is the stop.+ expect(restartPolicy(() => clock).again(CRASH_EXIT_CODE, true)).toBe(false);+ // The pause is not counted as the run's time up.+ clock += CRASH_BACKOFF_MS.at(-1)! + STABLE_RUN_MS;+ expect(policy.again(null, false, "SIGKILL")).toBe(true);+ expect(policy.delayMs()).toBe(CRASH_BACKOFF_MS[0]);+ expect(policy.again(1)).toBe(false);+ expect(policy.delayMs()).toBe(0);+});++it("the container launcher waits before starting a crashed server again, and a stop during the wait ends it", async () => {+ vi.useFakeTimers();+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ const signals = new EventEmitter();+ const children: ReturnType<typeof fakeChild>[] = [];+ const done = superviseServer(() => { const child = fakeChild(children.length + 1); children.push(child); return child as unknown as ChildProcess; },+ { signals: signals as unknown as NodeJS.Process, now: () => 0 });+ children[0]!.emit("exit", CRASH_EXIT_CODE, null);+ expect(children).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(CRASH_BACKOFF_MS[0] - 1);+ expect(children).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(children).toHaveLength(2);+ children[1]!.emit("exit", null, "SIGKILL");+ signals.emit("SIGTERM");+ expect(await done).toBe(0);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(children).toHaveLength(2);+ expect(log.mock.calls.map(([line]) => String(line))).toEqual([expect.stringContaining("stopped unexpectedly (70)"), expect.stringContaining("(killed)")]);+ } finally { log.mockRestore(); vi.useRealTimers(); }+});++it("`serve` waits before each start after a crash, and gives up after a crash loop", async () => {+ vi.useFakeTimers();+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ let runs = 0;+ const done = serveUntilStopped(options, async () => { runs++; return CRASH_EXIT_CODE; }, () => 0);+ await vi.advanceTimersByTimeAsync(CRASH_BACKOFF_MS.reduce((sum, ms) => sum + ms, 0));+ expect(await done).toBe(CRASH_EXIT_CODE);+ expect(runs).toBe(CRASH_BACKOFF_MS.length + 1);+ } finally { log.mockRestore(); vi.useRealTimers(); }+});diff --git a/server/restart.ts b/server/restart.tsindex f2452f3e9f..97b45518a3 100644--- a/server/restart.ts+++ b/server/restart.ts@@ -1,17 +1,50 @@// The exit code a server uses to ask its launcher for a fresh start (after a restore commits).export const RESTART_EXIT_CODE = 75;+/** The exit code a server uses after an error it could not survive (server/crash-guard.ts): it logged why and closed+ * cleanly, and its launcher starts it again after a pause. */+export const CRASH_EXIT_CODE = 70;export const MAX_RESTARTS = 5;export const STABLE_RUN_MS = 60_000;+/** The pause before each start after a crash in a row: a crash loop slows down, then stops at the last. */+export const CRASH_BACKOFF_MS = [1_000, 2_000, 5_000, 15_000, 30_000] as const;+/** Killed by the system rather than asked to stop: out of memory (SIGKILL, SIGABRT), or a fault. Shells and+ * containers report these as 128 + the signal's number. */+const CRASH_SIGNALS = new Set(["SIGKILL", "SIGABRT", "SIGSEGV", "SIGBUS", "SIGILL", "SIGFPE"]);+const CRASH_CODES = new Set([CRASH_EXIT_CODE, 134, 135, 136, 137, 139]);++export const crashed = (code: number | null, signal?: NodeJS.Signals | null): boolean =>+ code === null ? Boolean(signal && CRASH_SIGNALS.has(signal)) : CRASH_CODES.has(code);++/**+ * One rule for every launcher. A server that asks for a restart (75) starts again at once, at most MAX_RESTARTS in a+ * row. A server that crashed starts again after CRASH_BACKOFF_MS[n], at most that many times in a row; any other exit+ * (0, a refused start, a person stopping it) ends the launcher. A run that stayed up STABLE_RUN_MS starts both counts+ * again.+ */export function restartPolicy(now: () => number = Date.now) {- let restarts = 0, startedAt = now();+ let restarts = 0, crashes = 0, startedAt = now(), delay = 0;return {- again(code: number | null, stopping = false): boolean {- if (now() - startedAt >= STABLE_RUN_MS) restarts = 0;- if (stopping || code !== RESTART_EXIT_CODE || restarts >= MAX_RESTARTS) return false;- restarts++;- startedAt = now();+ again(code: number | null, stopping = false, signal?: NodeJS.Signals | null): boolean {+ if (now() - startedAt >= STABLE_RUN_MS) { restarts = 0; crashes = 0; }+ delay = 0;+ if (stopping) return false;+ if (code === RESTART_EXIT_CODE) {+ if (restarts >= MAX_RESTARTS) return false;+ restarts++;+ } else if (crashed(code, signal)) {+ if (crashes >= CRASH_BACKOFF_MS.length) return false;+ delay = CRASH_BACKOFF_MS[crashes++]!;+ } else return false;+ startedAt = now() + delay;return true;},+ /** How long to wait before the start the last again() allowed. */+ delayMs: (): number => delay,};}++/** What a launcher says before starting the server again. */+export const restartLine = (code: number | null, delayMs: number): string => code === RESTART_EXIT_CODE+ ? "OpenMausBot is starting again to finish installing a copy from the desktop app…"+ : `OpenMausBot stopped unexpectedly (${code ?? "killed"}); starting it again in ${Math.round(delayMs / 1000)} s…`;diff --git a/server/routes/bots-create.ts b/server/routes/bots-create.tsindex c46712f9dd..8a2bde2f93 100644--- a/server/routes/bots-create.ts+++ b/server/routes/bots-create.ts@@ -19,6 +19,7 @@ import type { TeamPeople } from "../team-people.ts";import { writeMemoryFile, writeMemoryTopic } from "../workspace.ts";import { refusalBody, userError } from "../user-errors.ts";import type { ServerErrorBody } from "../../shared/server-text.ts";+import { botLimitRefusal } from "../bot-limit.ts";import { PASS, type RouteHandler } from "./table.ts";export type ModelSelectionCheck = { ok: true; selection: ModelSelection } | ({ ok: false; status: number } & ServerErrorBody);@@ -188,7 +189,7 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {if (hostedModels && !hostedModels.allows(selection)) return json(res, 400, { error: hostedModels.error() });// The capacity check sits beside the synchronous write, after every await.if (store.bots.length >= MAX_WORKSPACE_BOTS) {- return json(res, 409, { error: `this workspace is limited to ${MAX_WORKSPACE_BOTS} bots` });+ return json(res, 409, { error: botLimitRefusal(MAX_WORKSPACE_BOTS) });}// Apply the audience before creation can announce the bot to members.const created = body.visibility === undefined ? null : parseVisibility(body.visibility);diff --git a/server/runtime/runtime.test.ts b/server/runtime/runtime.test.tsindex 51fb530de5..07bc158a6c 100644--- a/server/runtime/runtime.test.ts+++ b/server/runtime/runtime.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { addHeldSecretScrubber, HELD_SECRET_MASK } from "../../shared/redact.ts";import { checkInvariants } from "./invariants.ts";-import { PROGRESS_WRITE_MS, Runtime, type BeginRequest } from "./runtime.ts";+import { PROGRESS_WRITE_MS, RERUN_BURST, RERUN_GAP_MS, RERUN_HELD, RERUN_SUPERSEDED, Runtime, type BeginRequest } from "./runtime.ts";import { openRuntimeStore, type RuntimeStore } from "./store.ts";import { CUT_TWICE, INTERRUPTED_OUTWARD, loopStop, nextGuard, outwardDetail } from "./tree.ts";import type { Assignment, Clock, EnqueueRequest, Limits, RunInput, RunResult, TurnRunner } from "./types.ts";@@ -1595,3 +1595,55 @@ describe("Runtime: at Full access a question is its requester's to answer, and oinvariants(w);});});++describe("Runtime: turns a restart cut start again a few at a time", () => {+ it("starts the first few at once and the rest one per gap, and a second restart cuts only the ones that had started", async () => {+ const store = openRuntimeStore(":memory:");+ const first = world(() => "hold", {}, store);+ const roots = Array.from({ length: RERUN_BURST + 3 }, (_, i) => first.runtime.begin(beginReq({+ requester: { kind: "person", threadId: `chat-${i}`, chief: true }, assignee: { botId: `bot-${i}`, destination: { kind: "standing_thread", threadId: `chat-${i}` } } })));+ first.runtime.close();++ const second = world(() => "hold", {}, store);+ second.runtime.tick(); await flush();+ expect(second.runner.runs.map(r => r.input.turn)).toEqual(Array(RERUN_BURST).fill("rerun"));+ const waiting = roots.filter(root => store.get(root.id)?.status === "queued");+ expect(waiting).toHaveLength(3);+ for (const root of waiting) expect(store.events(root.id).at(-1)).toMatchObject({ kind: "held", detail: RERUN_HELD });+ second.clock.advance(RERUN_GAP_MS - 1);+ second.runtime.tick(); await flush();+ expect(second.runner.runs).toHaveLength(RERUN_BURST);+ second.clock.advance(1);+ second.runtime.tick(); await flush();+ expect(second.runner.runs).toHaveLength(RERUN_BURST + 1);+ second.runtime.close();++ // Down again during the reruns: those that had started fail as cut twice; the two still waiting are not cut again.+ const third = world(() => "hold", {}, store);+ const cutTwice = roots.filter(root => store.get(root.id)?.status === "failed");+ expect(cutTwice).toHaveLength(RERUN_BURST + 1);+ for (const root of cutTwice) expect(store.get(root.id)).toMatchObject({ outcome: "interrupted", result: CUT_TWICE });+ third.runtime.tick(); await flush();+ expect(third.runner.runs.map(r => r.input.turn)).toEqual(["rerun", "rerun"]);+ });++ it("does not run a cut turn again after newer work in its conversation started first: it fails with a line saying so", async () => {+ const store = openRuntimeStore(":memory:");+ const first = world(() => "hold", {}, store);+ const chat = (i: number) => ({ requester: { kind: "person" as const, threadId: `chat-${i}`, chief: true }, assignee: { botId: `bot-${i}`, destination: { kind: "standing_thread" as const, threadId: `chat-${i}` } } });+ const roots = Array.from({ length: RERUN_BURST + 1 }, (_, i) => first.runtime.begin(beginReq(chat(i))));+ first.runtime.close();++ const second = world(() => "hold", {}, store);+ second.runtime.tick(); await flush();+ const late = roots[RERUN_BURST]!;+ expect(store.get(late.id)?.status).toBe("queued");+ // The person writes in that chat while its cut turn waits its turn: the new request runs, and the old one does not.+ const newer = second.runtime.begin(beginReq(chat(RERUN_BURST)));+ second.clock.advance(RERUN_GAP_MS);+ second.runtime.tick(); await flush();+ expect(store.get(late.id)).toMatchObject({ status: "failed", outcome: "interrupted", result: RERUN_SUPERSEDED });+ expect(second.runner.runs.filter(r => r.a.id === late.id)).toHaveLength(0);+ expect(store.get(newer.id)?.status).toBe("running");+ });+});diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.tsindex 2d0069afa1..4c4c366473 100644--- a/server/runtime/runtime.ts+++ b/server/runtime/runtime.ts@@ -17,8 +17,20 @@ export interface RuntimeOptions {limits?: Partial<Limits>;level?: typeof assignmentLevel;log?: (line: string) => void;+ /** Turns a restart cut start again at most one per this many ms (default RERUN_GAP_MS). */+ rerunGapMs?: number;}+/** After a restart, the first RERUN_BURST turns it cut start again at once and the rest one at a time this far apart: a+ * server that fell under the load of many turns does not meet it again in its first second, and a fall during the+ * reruns cuts only those already started (a turn cut twice fails; one still waiting here was not cut again). Of 34 cut+ * turns, the last starts 15 s after the first. */+export const RERUN_GAP_MS = 500;+export const RERUN_BURST = 4;+export const RERUN_HELD = "waiting its turn to start again after the restart";+/** A cut turn is not run again once newer work in its conversation started first: it would answer out of order. */+export const RERUN_SUPERSEDED = "cut by a restart; newer work in this conversation started before it could run again, so it was not run again";+export interface BeginRequest {/** The host's own id for the requesting turn (its generation); default a fresh uuid. */id?: string;@@ -67,6 +79,10 @@ export class Runtime {private readonly reportDue = new Set<string>();private batch: Map<string, Assignment> | null = null;private lastThrew = false;+ private readonly rerunGapMs: number;+ /** Monotonic: no turn a restart cut starts before this. */+ private nextRerunAt = Number.NEGATIVE_INFINITY;+ private rerunsStarted = 0;constructor(store: RuntimeStore, runner: TurnRunner, options: RuntimeOptions = {}) {this.store = store;@@ -76,6 +92,7 @@ export class Runtime {this.level = options.level ?? assignmentLevel;this.log = options.log ?? (line => console.error("runtime:", line));this.bootAt = this.clock.now();+ this.rerunGapMs = options.rerunGapMs ?? RERUN_GAP_MS;}/** Restart reconciliation and re-park of needs_input, from stored data only. Idempotent; runs before the first tick. */@@ -355,11 +372,14 @@ export class Runtime {continue;}const thread = n.assignee.destination.threadId;+ if (n.restart === "rerun" && this.newerWorkIn(thread, n)) { this.cancelTree(n, RERUN_SUPERSEDED, "failed", "interrupted"); continue; }// Same-conversation turns never overlap; same-room speakers take turns.if (busyThreads.has(thread)) { this.heldBehindTurn(n, "an earlier turn in its conversation is running"); continue; }const parent = n.parentId ? this.store.get(n.parentId) : undefined;const group = n.assignee.destination.groupId;if (parent?.status === "running" && group !== undefined && parent.assignee.destination.groupId === group) { this.heldBehindTurn(n, "its requester's turn in the room is running"); continue; }+ const rerun = n.restart === "rerun";+ if (rerun && this.clock.monotonic() < this.nextRerunAt) { this.held(n.id, RERUN_HELD); busyThreads.add(thread); continue; }const resumed = n.status === "resume";if (!resumed) {const root = n.parentId ? this.store.get(n.rootId) : n;@@ -376,10 +396,17 @@ export class Runtime {if (typeof can === "string") this.held(n.id, can);continue;}- if (this.dispatch(n, parent, resumed)) busyThreads.add(thread);+ if (!this.dispatch(n, parent, resumed)) continue;+ busyThreads.add(thread);+ if (rerun && ++this.rerunsStarted >= RERUN_BURST) this.nextRerunAt = this.clock.monotonic() + this.rerunGapMs;}}+ /** Work in this conversation from another request, begun since this start. */+ private newerWorkIn(threadId: string, n: Assignment): boolean {+ return this.store.all({ assigneeThreadId: threadId }).some(other => other.rootId !== n.rootId && other.createdAt >= this.bootAt);+ }+private dispatch(n: Assignment, parent: Assignment | undefined, resumed: boolean): boolean {const now = this.clock.now();const root = n.parentId ? this.store.get(n.rootId) : n;diff --git a/server/runtime/store.ts b/server/runtime/store.tsindex d34193b114..b96aba1233 100644--- a/server/runtime/store.ts+++ b/server/runtime/store.ts@@ -5,6 +5,7 @@ import { DatabaseSync, type SQLInputValue } from "node:sqlite";import { z } from "zod";import { APPROVAL_MODES } from "../../shared/approval-mode.ts";+import { timeBlocking } from "../perf/loop-stalls.ts";import { TERMINAL, type Assignment, type AssignmentEvent, type EventKind, type InboxItem, type Owner } from "./types.ts";const evidenceSchema = z.object({@@ -323,7 +324,7 @@ export function openRuntimeStore(path: string): RuntimeStore {if (filter.roots) where.push("parent_id IS NULL");if (filter.openSince !== undefined) { where.push("(finished_at IS NULL OR finished_at >= ?)"); params.push(filter.openSince); }const sql = `SELECT id, json FROM assignments${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at, rowid`;- return (db.prepare(sql).all(...params) as Row[]).map(readAssignment);+ return timeBlocking("runtimeReads", () => (db.prepare(sql).all(...params) as Row[]).map(readAssignment));},insert(a, event) {transaction(() => {diff --git a/server/server-launcher.ts b/server/server-launcher.tsindex 2e8eeeb75e..9386683c03 100644--- a/server/server-launcher.ts+++ b/server/server-launcher.ts@@ -7,7 +7,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";import { boxMemory, heapSizeArgs, type BoxMemory } from "./box-memory.ts";import { containerInit, execUnderInit, UNDER_IMAGE_INIT } from "./container-init.ts";import { clearRecordsFromEarlierRunOfThisContainer } from "./data-dir-lease.ts";-import { restartPolicy } from "./restart.ts";+import { restartLine, restartPolicy } from "./restart.ts";/** The server's heap sized to the container's memory limit, run through the bootstrap that keeps Node's compile cache on* the data volume, so a restarted container reuses the compiled bundle. */@@ -24,18 +24,21 @@ export function serverCommand(here: string, env: NodeJS.ProcessEnv, options: { eexport function superviseServer(start: () => ChildProcess, options: { signals?: Pick<NodeJS.Process, "on" | "off">; now?: () => number } = {}): Promise<number> {const signals = options.signals ?? process, now = options.now ?? Date.now;return new Promise((done) => {- let child: ChildProcess, stopping = false;+ let child: ChildProcess, stopping = false, waiting: ReturnType<typeof setTimeout> | undefined;const policy = restartPolicy(now);- const pass = (signal: NodeJS.Signals) => () => { stopping = true; child.kill(signal); };- const onTerm = pass("SIGTERM"), onInt = pass("SIGINT");const finish = (code: number) => { signals.off("SIGTERM", onTerm); signals.off("SIGINT", onInt); done(code); };+ // Stopped while waiting to start again after a crash: there is no server to pass the signal to.+ const pass = (signal: NodeJS.Signals) => () => { stopping = true; if (waiting) { clearTimeout(waiting); waiting = undefined; finish(0); } else child.kill(signal); };+ const onTerm = pass("SIGTERM"), onInt = pass("SIGINT");const run = () => {+ waiting = undefined;child = start();child.once("error", () => finish(1));child.once("exit", (code, signal) => {- if (policy.again(code, stopping)) {- console.log("OpenMausBot is starting again to finish installing a copy from the desktop app…");- run();+ if (policy.again(code, stopping, signal)) {+ console.log(restartLine(code, policy.delayMs()));+ if (policy.delayMs() > 0) waiting = setTimeout(run, policy.delayMs());+ else run();return;}finish(code ?? (stopping && (signal === "SIGTERM" || signal === "SIGINT") ? 0 : 1));diff --git a/server/store.ts b/server/store.tsindex 4bd4e474e6..905bbf2155 100644--- a/server/store.ts+++ b/server/store.ts@@ -1161,10 +1161,10 @@ export class Store {const persist = () => { mdb.appendMessage(threadId, full); return full; };const committed = command ? runCommand(command, persist) : persist();if (committed.id !== full.id) return committed;- t.messages.push(full);+ t.messages.push(full); this.threads.grew(threadId, full);t.activeLeafId = full.id;if (full.kind === "screen") {- for (const pruned of this.pruneScreenFrames(t)) {+ for (const pruned of this.pruneScreenFrames(t, threadId)) {mdb.updateMessage(threadId, pruned);this.emit({ type: "message.patch", threadId, message: pruned });}@@ -1181,10 +1181,10 @@ export class Store {if (!anchorExists || t.activeLeafId === anchorId) return this.appendMessage(threadId, message);const full: Message = { id: newId(), at: Date.now(), ...redactBotAuthored(message), parentId: anchorId };const children = t.messages.filter((m) => m.parentId === anchorId);- t.messages.push(full);+ t.messages.push(full); this.threads.grew(threadId, full);mdb.insertMessage(threadId, full);if (full.kind === "screen") {- for (const pruned of this.pruneScreenFrames(t)) {+ for (const pruned of this.pruneScreenFrames(t, threadId)) {mdb.updateMessage(threadId, pruned);this.emit({ type: "message.patch", threadId, message: pruned });}@@ -1205,7 +1205,7 @@ export class Store {return this.patchMessage(threadId, card.id, { card: { ...card.card, dismissed: true } });}- private pruneScreenFrames(t: { messages: Message[] }, keep = 4): Message[] {+ private pruneScreenFrames(t: { messages: Message[] }, threadId: string, keep = 4): Message[] {const pruned: Message[] = [];let seen = 0;for (let i = t.messages.length - 1; i >= 0 && seen < t.messages.length; i--) {@@ -1213,7 +1213,7 @@ export class Store {if (m.kind !== "screen" || !m.png) continue;seen += 1;if (seen > keep) {- m.png = undefined;+ this.threads.grew(threadId, { ...m, png: undefined }, m); m.png = undefined;pruned.push(m);}}@@ -1237,7 +1237,7 @@ export class Store {...(sender ? { sender } : {}),...(dataContext ? { dataContext } : {}),};- t.messages.push(full);+ t.messages.push(full); this.threads.grew(threadId, full);t.activeLeafId = full.id;mdb.appendMessage(threadId, full);this.noteThreadActivity(threadId, full.at, true);@@ -1273,7 +1273,7 @@ export class Store {const committed = command ? runCommand(command, persist) : persist();if (!applied) return committed;if (!movesThreadToTop(t.messages[idx]) && movesThreadToTop(next)) this.noteThreadActivity(threadId, next.at, true, next.turnCompletedAt ?? next.at);- t.messages[idx] = next;+ this.threads.grew(threadId, next, t.messages[idx]); t.messages[idx] = next;this.emit({ type: "message.patch", threadId, message: next });return next;}diff --git a/server/thread-cache.test.ts b/server/thread-cache.test.tsindex a9d632ec1a..57224ff4f0 100644--- a/server/thread-cache.test.ts+++ b/server/thread-cache.test.ts@@ -5,7 +5,8 @@ import { DATA_DIR } from "./config.ts";import type { ModelSelection } from "./contracts.ts";import { closeMessageDb } from "./message-db.ts";import { Store } from "./store.ts";-import { THREAD_IDLE_MS } from "./thread-cache.ts";+import { approxBytes, ThreadCache, THREAD_IDLE_MS } from "./thread-cache.ts";+import type { Message } from "./store.ts";const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });@@ -100,3 +101,59 @@ describe("Store message cache", () => {expect(store.activeLeaf(bot.threadId)).toBe(added.id);});});++describe("ThreadCache byte cap", () => {+ const text = (id: string, size: number): Message => ({ id, at: 1, role: "bot", kind: "text", text: "x".repeat(size) }) as Message;+ const rows = (id: string, size: number) => ({ messages: [text(`${id}-1`, size)], activeLeafId: null });+ beforeEach(() => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(1_000_000); });+ afterEach(() => { vi.useRealTimers(); });++ it("gives back the least recently used transcripts past the cap, never a busy one, the one just read, or one read moments ago", () => {+ const busy = new Set<string>();+ const cache = new ThreadCache(() => busy, 30_000);+ for (const id of ["a", "b", "c"]) cache.load(id, rows(id, 9_000));+ vi.setSystemTime(1_000_000 + 10_000);+ busy.add("a");+ cache.get("b");+ cache.load("d", rows("d", 9_000));+ // a is busy, b was just read again, so c (least recently used of the rest) goes.+ expect(["a", "b", "c", "d"].filter((id) => cache.get(id))).toEqual(["a", "b", "d"]);+ expect(cache.approxBytes).toBeLessThanOrEqual(30_000);++ vi.setSystemTime(1_000_000 + 20_000);+ cache.load("huge", rows("huge", 100_000));+ expect(cache.get("huge")).toBeDefined();+ expect(cache.get("a")).toBeDefined();+ expect(cache.size).toBe(2);+ });++ it("counts what a transcript gains and loses, and what a delete gives back", () => {+ const cache = new ThreadCache(() => new Set(), 1_000_000);+ cache.load("a", rows("a", 1_000));+ const before = cache.approxBytes;+ const added = text("a-2", 5_000);+ cache.grew("a", added);+ expect(cache.approxBytes).toBe(before + approxBytes(added));+ cache.grew("a", text("a-2", 2_000), added);+ expect(cache.approxBytes).toBe(before + approxBytes(text("a-2", 2_000)));+ cache.grew("nobody", added);+ cache.delete("a");+ expect(cache.approxBytes).toBe(0);+ });+});++describe("the transcript cache's count of a thread with live screens", () => {+ beforeEach(() => { rmSync(DATA_DIR, { recursive: true, force: true }); });+ afterEach(() => { closeMessageDb(); });++ it("gives back what pruned screen frames held, so many frames do not fill the cap", () => {+ const store = new Store(selection);+ const bot = store.createBot({}, { seedMessages: false });+ const cache = (store as unknown as { threads: ThreadCache }).threads;+ const frame = "x".repeat(200_000);+ for (let i = 0; i < 50; i++) store.appendMessage(bot.threadId, { role: "bot", kind: "screen", png: frame } as never);+ const kept = store.messagesFor(bot.threadId).filter((message) => message.kind === "screen" && message.png).length;+ expect(kept).toBe(4);+ expect(cache.approxBytes).toBeLessThan(5 * 200_000 + 100_000);+ });+});diff --git a/server/thread-cache.ts b/server/thread-cache.tsindex 110748cfee..9d9e5a6e06 100644--- a/server/thread-cache.ts+++ b/server/thread-cache.ts@@ -9,38 +9,79 @@ export interface ThreadState {/** A conversation nobody read or wrote for this long gives its parsed transcript back; the next read reloads it from messages.db. */export const THREAD_IDLE_MS = 10 * 60_000;const SWEEP_EVERY_MS = 60_000;+/** Parsed transcripts kept in memory at most, as approxBytes counts them; OMB_THREAD_CACHE_MB overrides. Past it the+ * least recently used go first, but never a busy conversation's, the one just read, or one read in the last few seconds. */+export const THREAD_CACHE_MAX_BYTES = (Number(process.env.OMB_THREAD_CACHE_MB) > 0 ? Number(process.env.OMB_THREAD_CACHE_MB) : 256) * 1024 * 1024;+const MIN_RESIDENCY_MS = 5_000;++/** About what a value holds: its strings' lengths and a few bytes per field. Walks fields, never copies text. */+export function approxBytes(value: unknown, depth = 0): number {+ if (typeof value === "string") return value.length;+ if (value === null || typeof value !== "object" || depth > 8) return 8;+ let bytes = 16;+ if (Array.isArray(value)) for (const item of value) bytes += approxBytes(item, depth + 1);+ else for (const key in value) bytes += key.length + approxBytes((value as Record<string, unknown>)[key], depth + 1);+ return bytes;+}++interface Entry { state: ThreadState; usedAt: number; bytes: number }export class ThreadCache {- private entries = new Map<string, { state: ThreadState; usedAt: number }>();+ private entries = new Map<string, Entry>();private sweptAt = Date.now();+ private bytes = 0;private readonly busyThreadIds: () => ReadonlySet<string>;+ private readonly maxBytes: number;- constructor(busyThreadIds: () => ReadonlySet<string>) {+ constructor(busyThreadIds: () => ReadonlySet<string>, maxBytes = THREAD_CACHE_MAX_BYTES) {this.busyThreadIds = busyThreadIds;+ this.maxBytes = maxBytes;}get(threadId: string): ThreadState | undefined {const now = Date.now();this.sweep(now);const entry = this.entries.get(threadId);- if (entry) entry.usedAt = now;- return entry?.state;+ if (!entry) return undefined;+ // Last in the map is the most recently used.+ entry.usedAt = now;+ this.entries.delete(threadId);+ this.entries.set(threadId, entry);+ return entry.state;}/** Rows stored without a parentId chain onto the row before them. */load(threadId: string, rows: ThreadRows): ThreadState {const { messages } = rows;let prev: string | null = null;+ let bytes = 0;for (const m of messages) {if (m.parentId === undefined) m.parentId = prev;prev = m.id;+ bytes += approxBytes(m);}const state = { messages, activeLeafId: rows.activeLeafId || (messages.at(-1)?.id ?? null) };- this.entries.set(threadId, { state, usedAt: Date.now() });+ this.delete(threadId);+ this.entries.set(threadId, { state, usedAt: Date.now(), bytes });+ this.bytes += bytes;+ this.shrink(threadId);return state;}+ /** A cached transcript gained `added` (and lost `removed`, a message it replaced). */+ grew(threadId: string, added: Message, removed?: Message): void {+ const entry = this.entries.get(threadId);+ if (!entry) return;+ const change = approxBytes(added) - (removed ? approxBytes(removed) : 0);+ entry.bytes += change;+ this.bytes += change;+ if (change > 0) this.shrink(threadId);+ }+delete(threadId: string): void {+ const entry = this.entries.get(threadId);+ if (!entry) return;+ this.bytes -= entry.bytes;this.entries.delete(threadId);}@@ -48,6 +89,21 @@ export class ThreadCache {return this.entries.size;}+ get approxBytes(): number {+ return this.bytes;+ }++ private shrink(keep: string): void {+ if (this.bytes <= this.maxBytes) return;+ const now = Date.now();+ const busy = this.busyThreadIds();+ for (const [threadId, entry] of this.entries) {+ if (this.bytes <= this.maxBytes) break;+ if (threadId === keep || busy.has(threadId) || now - entry.usedAt < MIN_RESIDENCY_MS) continue;+ this.delete(threadId);+ }+ }+private sweep(now: number): void {if (now - this.sweptAt < SWEEP_EVERY_MS) return;this.sweptAt = now;@@ -55,7 +111,7 @@ export class ThreadCache {for (const [threadId, entry] of this.entries) {if (now - entry.usedAt < THREAD_IDLE_MS) continue;busy ??= this.busyThreadIds();- if (!busy.has(threadId)) this.entries.delete(threadId);+ if (!busy.has(threadId)) this.delete(threadId);}}}diff --git a/server/thread-log-rotation.ts b/server/thread-log-rotation.tsindex 67e413e8bc..d1c1f5d994 100644--- a/server/thread-log-rotation.ts+++ b/server/thread-log-rotation.ts@@ -1,6 +1,13 @@// Opt-in size cap for per-thread NDJSON logs: keep the newest half, cut on a line boundary, same filename.import { closeSync, fstatSync, openSync, readSync, renameSync, rmSync, statSync, writeSync } from "node:fs";+/** Where no limit is set, each conversation's event log is still trimmed (to its newest half) past this: one runaway+ * conversation, or hundreds of long ones across many bots, cannot fill the disk. Transcripts are never trimmed. */+export const DEFAULT_THREAD_EVENT_LOG_MAX_BYTES = 256 * 1024 * 1024;++/** The cap the logs are trimmed to: the person's limit (config's threadEventLogMaxBytes), or the default ceiling. */+export const threadLogCapOrDefault = (cap: number | null): number => cap ?? DEFAULT_THREAD_EVENT_LOG_MAX_BYTES;+let capProvider: () => number | null = () => null;export function bindThreadLogCapProvider(provider: () => number | null): void {diff --git a/server/turn-watchdog.test.ts b/server/turn-watchdog.test.tsindex 15fc1519e8..8e73443efb 100644--- a/server/turn-watchdog.test.ts+++ b/server/turn-watchdog.test.ts@@ -726,3 +726,18 @@ describe("a Stop that wins against a provider dispatch", () => {expect(r.dog.watching("t1")).toBe(false);});});++describe("a turn the crash guard stops", () => {+ it("is stopped at once as a stall with the server-error reason, once, and only while it is watched", () => {+ const stalls: Array<[string, StallReason]> = [];+ const dog = new TurnWatchdog({ stallMs: 60_000, toolStallMs: 60_000, parkedStallMs: 60_000, engineExitStallMs: 60_000, checkMs: 60_000,+ onStall: (turn, _silentMs, reason) => stalls.push([turn.threadId, reason]), now: () => 0 });+ dog.watch("t1", "b1");+ dog.watch("t2", "b1");+ expect(dog.fail("t1")).toBe(true);+ expect(dog.fail("t1")).toBe(false);+ expect(dog.fail("never")).toBe(false);+ expect(stalls).toEqual([["t1", "server-error"]]);+ expect(dog.watching("t2")).toBe(true);+ });+});diff --git a/server/turn-watchdog.ts b/server/turn-watchdog.tsindex 519267803a..247b192d18 100644--- a/server/turn-watchdog.ts+++ b/server/turn-watchdog.ts@@ -42,7 +42,7 @@ export function stuckCommand(turn: Partial<Pick<WatchedTurn, "runningTools">>, s/** Why the watchdog stopped a turn: it went silent, or the process running its engine exited and the turn can never* answer. */-export type StallReason = "silent" | "engine-exited";+export type StallReason = "silent" | "engine-exited" | "server-error";/** The silence that stops a turn whose engine process has exited: its engine can never answer it, so it waits only long* enough for the driver to report the turn's own end, and not for the tool limit. */@@ -195,6 +195,15 @@ export class TurnWatchdog {if (turn) this.watch(threadId, turn.botId);}+ /** Stops a watched turn now, as a stall would (server/crash-guard.ts: an error in the turn's own work). */+ fail(threadId: string, reason: StallReason = "server-error"): boolean {+ const turn = this.turns.get(threadId);+ if (!turn) return false;+ this.turns.delete(threadId);+ this.opts.onStall(turn, this.now() - turn.lastEventAt, reason);+ return true;+ }+watching(threadId: string): boolean {return this.turns.has(threadId);}