Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Restart after a memory freeze: a turn that browsed is not started again (#7228)

Milind Soni01bcd69ed323
diff --git a/server/coordinator.ts b/server/coordinator.ts
index b9d6bc593d..c72161159f 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -261,6 +261,8 @@ export interface CoordinatorOptions {
legacyThreads?: LegacyThreadResolver;
/** After every write to the assignment store, so a host that ticks only when work is due can tick again. */
wrote?: () => void;
+ /** What a turn a restart cut ends with in place of starting again, or null (runtime/runtime.ts RuntimeOptions). */
+ restartCut?: (threadId: string, startedAt: number | undefined) => string | null;
}
export function createCoordinator(options: CoordinatorOptions): Coordinator {
diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.ts
index ff87be5961..df2fa63dc4 100644
--- a/server/host/chief-notices-retry.test.ts
+++ b/server/host/chief-notices-retry.test.ts
@@ -5,6 +5,7 @@ import "../server-line-packs.ts";
import { engineFailureMessage } from "../drivers/engine-errors.ts";
import { memoryStopText } from "../engine-memory.ts";
import { AUTO_RETRY_LEAD, RETRY_BLOCKED } from "../incidents.ts";
+import { FROZE_BROWSING } from "../memory-freeze-restart.ts";
import type { RoutineFailureFacts } from "../routine-recovery.ts";
import { createChiefNotices, MEMORY_RETRY_MS, MEMORY_RETRY_TEXT, ROOM_RETRY_TEXT, SERVER_MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";
@@ -224,6 +225,15 @@ describe("a run stopped to free memory", () => {
expect(busy.continued).toEqual([]);
});
+ it("never starts again a routine run that the restart after a memory freeze ended", () => {
+ const f = roomFixture();
+ f.store.appendMessage("chief-main", { role: "user", kind: "text", text: "Check the prices page." });
+ f.notices.reportIncident({ kind: "routine-failed", bot: f.chief as never, threadId: "chief-main", detail: `Prices: ${FROZE_BROWSING}`, failure: FROZE_BROWSING });
+ f.settle();
+ expect(f.waiting).toEqual([]);
+ expect(f.continued).toEqual([]);
+ });
+
it("on a self-hosted server, starts a teammate's run again by itself too, saying it was this server, and asks no Chief", () => {
const f = roomFixture({ selfHosted: () => true });
f.store.appendMessage("ada-job", { role: "user", kind: "text", text: "Reconcile the September invoices." });
diff --git a/server/index.ts b/server/index.ts
index e8a0b63a98..10b3657c26 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -436,7 +436,7 @@ import { claudeUserSkillsEnabled } from "./turn-settings.ts";
import { addHeldSecretScrubber, redactSecretsInText, scrubHeldSecrets } from "./redact.ts";
import * as vps from "./vps-computer.ts";
import { vpsConfigForBot, vpsSshAliasForBot } from "./vps-hosts.ts"; import { vpsContainerExec } from "./vps-exec.ts";
-import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineHistoryFor, routineRunsFor } from "./routine-run-window.ts"; import { runTurnLive } from "./routine-turn-live.ts"; import { batchSaves, flushLaterSaves } from "./save-batch.ts";
+import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineHistoryFor, routineRunsFor } from "./routine-run-window.ts"; import { runTurnLive } from "./routine-turn-live.ts"; import { batchSaves, flushLaterSaves } from "./save-batch.ts"; import { restartCutStop } from "./memory-freeze-restart.ts";
import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";
import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";
import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";
@@ -3842,7 +3842,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:
const remoteTeammates = new RemoteTeammates(); const remoteHandoff = createRemoteHandoff({ teammates: remoteTeammates, coordinator: () => coordinator, localBots: () => store.bots, botName: (id) => store.bot(id)?.name, outside: (threadId) => (outsideLineage.outsideDrivenThread(threadId) || outsideLineage.cloudGuestDriven(threadId) ? OUTSIDE_STAYS_HERE : undefined), file: join(DATA_DIR, "remote-teammate-work.json"), log: (line) => console.error(line) }); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),
worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });
const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: beginGroupTurnOperation, finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, refusal: botMoveRefusal, language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
- dataDir: DATA_DIR,
+ dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),
now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },
log: line => console.error("coordinator:", line),
legacyThreads: {
@@ -8669,7 +8669,7 @@ const automationDestinations = createAutomationDestinations({ store, mainThread:
cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: (id, routine) => (routine && teamRoutines.opener(routine)) || routineOpener(id), reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });
const routineModelChecks: RoutineModelChecks = { check: (raw) => checkedModelSelection(raw), bot: (botId) => store.bot(botId), engineSwitchNeedsAsk };
routines = new RoutineManager({
- emit: (payload) => { broadcast(payload); starterRoutineWake?.emitted(payload); }, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,
+ restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }), emit: (payload) => { broadcast(payload); starterRoutineWake?.emitted(payload); }, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,
limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },
launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")
? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,
diff --git a/server/memory-freeze-restart.test.ts b/server/memory-freeze-restart.test.ts
new file mode 100644
index 0000000000..06ddf93168
--- /dev/null
+++ b/server/memory-freeze-restart.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+
+import { memoryStopText } from "./engine-memory.ts";
+import { browsedSince, frozeForMemory, FROZE_BROWSING, restartCutStop } from "./memory-freeze-restart.ts";
+import type { StallRecord } from "./perf/stall-sample.ts";
+
+const START = 1_800_000_000_000, MINUTE = 60_000;
+
+function stall(at: number, machine: Partial<StallRecord["machine"]>, why?: StallRecord["why"]): StallRecord {
+ return { at, blockedSinceMs: 71_000, kind: "not-profiled", ...(why ? { why } : {}), top: [], stack: [], thread: { state: "D", wchan: "folio_wait_bit_common" },
+ machine: { availableMB: null, memoryFull10: null, cpuSome10: null, stealPct: null, ...machine }, memory: [{ bucket: "browser", rssMB: 1406, procs: 22 }] };
+}
+
+describe("the restart after a memory freeze", () => {
+ const turnStart = START - 30 * MINUTE;
+
+ it("knows a freeze for want of memory that a turn ran through from the stall watch's records", () => {
+ const frozen = stall(START - 26 * MINUTE, { availableMB: 17, memoryFull10: 51 }, "memory");
+ expect(frozeForMemory([frozen], turnStart, START)).toBe(true);
+ // Memory available alone, or the stall alone, is enough.
+ expect(frozeForMemory([stall(START - MINUTE, { availableMB: 120, memoryFull10: 2 })], turnStart, START)).toBe(true);
+ expect(frozeForMemory([stall(START - MINUTE, { availableMB: 900, memoryFull10: 45 })], turnStart, START)).toBe(true);
+ // A record that read neither counts by the reason it took no profile.
+ expect(frozeForMemory([stall(START - MINUTE, {}, "memory")], turnStart, START)).toBe(true);
+ expect(frozeForMemory([stall(START - MINUTE, {}, "hourly-cap")], turnStart, START)).toBe(false);
+ });
+
+ it("does not take a busy main thread with memory to spare, a stall before the turn started, or one after this start", () => {
+ expect(frozeForMemory([stall(START - MINUTE, { availableMB: 900, memoryFull10: 6 }, "memory")], turnStart, START)).toBe(false);
+ expect(frozeForMemory([stall(turnStart - 1, { availableMB: 17, memoryFull10: 51 })], turnStart, START)).toBe(false);
+ expect(frozeForMemory([stall(START + 1, { availableMB: 17, memoryFull10: 51 })], turnStart, START)).toBe(false);
+ expect(frozeForMemory([], turnStart, START)).toBe(false);
+ });
+
+ it("knows a turn browsed from its browser calls since it started, in any of the names they arrive in", () => {
+ const at = START - 2 * MINUTE;
+ expect(browsedSince([{ at, tool: { name: "agent_browser_open" } }], at)).toBe(true);
+ expect(browsedSince([{ at, tool: { name: "mcp__browser__browser_navigate" } }], at)).toBe(true);
+ expect(browsedSince([{ at, tool: { name: "mcp__computer__click" } }, { at, tool: { name: "Bash" } }, { at }], at)).toBe(false);
+ // A call of an earlier turn in the same conversation is not this one's.
+ expect(browsedSince([{ at: at - 1, tool: { name: "agent_browser_open" } }], at)).toBe(false);
+ });
+
+ it("ends a browsing turn that ran through the freeze with the line of a browser closed for memory", () => {
+ expect(FROZE_BROWSING).toBe(memoryStopText(true));
+ expect(FROZE_BROWSING).toBe("Ran out of room, so I closed the browser to keep everything else running.");
+ let reads = 0;
+ const lines: Record<string, Array<{ at: number; tool?: { name: string } }>> = {
+ browsed: [{ at: turnStart + MINUTE, tool: { name: "agent_browser_open" } }],
+ wrote: [{ at: turnStart + MINUTE, tool: { name: "Write" } }],
+ };
+ const cut = restartCutStop({ dataDir: "/data", startedAt: START, lines: (threadId) => lines[threadId] ?? [],
+ read: (file) => { reads += 1; expect(file.replaceAll("\\", "/")).toBe("/data/perf-stalls.json"); return [stall(START - 26 * MINUTE, { availableMB: 17, memoryFull10: 51 }, "memory")]; } });
+ expect(cut("browsed", turnStart)).toBe(FROZE_BROWSING);
+ expect(cut("wrote", turnStart)).toBeNull();
+ // A turn whose start is unknown is started again: any browser call ever made in its conversation would count otherwise.
+ expect(cut("browsed", undefined)).toBeNull();
+ expect(reads).toBe(1);
+ const healthy = restartCutStop({ dataDir: "/data", startedAt: START, lines: (threadId) => lines[threadId] ?? [], read: () => [] });
+ expect(healthy("browsed", turnStart)).toBeNull();
+ });
+
+ it("starts again a browsing turn that began after a freeze the server came back from, when an update restart cuts it", () => {
+ // A freeze 50 minutes ago, then a turn that started 5 minutes ago and browsed, cut by an ordinary update restart.
+ const started = START - 5 * MINUTE;
+ const cut = restartCutStop({ dataDir: "/data", startedAt: START, lines: () => [{ at: started + 30_000, tool: { name: "agent_browser_open" } }],
+ read: () => [stall(START - 50 * MINUTE, { availableMB: 17, memoryFull10: 51 }, "memory")] });
+ expect(cut("browsed", started)).toBeNull();
+ });
+});
diff --git a/server/memory-freeze-restart.ts b/server/memory-freeze-restart.ts
new file mode 100644
index 0000000000..92dd85caf6
--- /dev/null
+++ b/server/memory-freeze-restart.ts
@@ -0,0 +1,55 @@
+// A turn that browsed when the server froze for want of memory is not started again by the restart that ends the freeze.
+// A 2 GB Cloud froze on a bot's first browsing turn (Nov 2026); the Admin's restart reran the turn a restart cut off, the
+// turn opened the same page, and the Cloud froze again within two minutes. The evidence is on the volume: the stall
+// watch's records (perf/stall-watch.ts) say the main thread was stuck with memory too short even to profile it. Such a
+// turn ends with the line a turn stopped for memory ends with, and the person sends again when they choose. A memory
+// stop's automatic retry never follows: it hears only a turn that failed while it ran.
+import { join } from "node:path";
+
+import { chatNotice } from "./chat-notices.ts";
+import { readStallRecords, STALL_FILE } from "./perf/stall-watch.ts";
+import type { StallRecord } from "./perf/stall-sample.ts";
+import { toolSurfaceKind } from "../shared/tool-surface.ts";
+
+/** Memory available below this, or the memory stall (full avg10, percent) at least this, in a stall record is a freeze for
+ * want of memory (relief's critical line on a 2 GB home, and its thrash line). A record that could read neither counts
+ * when it gave memory as the reason it took no profile. */
+const FREEZE_AVAILABLE_MB = 160, FREEZE_STALL_PERCENT = 40;
+
+function outOfMemory(record: StallRecord): boolean {
+ const { availableMB, memoryFull10 } = record.machine;
+ if (availableMB === null && memoryFull10 === null) return record.why === "memory";
+ return (availableMB ?? Infinity) < FREEZE_AVAILABLE_MB || (memoryFull10 ?? 0) >= FREEZE_STALL_PERCENT;
+}
+
+/** Whether the watch recorded a stall with memory run out between `from` (a cut turn's start) and `to` (this start): a
+ * freeze that turn ran through, not one before it that the server came back from. */
+export function frozeForMemory(records: readonly StallRecord[], from: number, to: number): boolean {
+ return records.some((record) => from <= record.at && record.at <= to && outOfMemory(record));
+}
+
+type Line = { at?: number; tool?: { name?: string } | null };
+
+/** Whether the conversation shows a browser call from `since` on. */
+export function browsedSince(lines: readonly Line[], since: number): boolean {
+ return lines.some((line) => (line.at ?? 0) >= since && typeof line.tool?.name === "string" && toolSurfaceKind(line.tool.name) === "browser");
+}
+
+/** The line a cut turn ends with in place of running again: that of a turn whose browser was closed for memory. */
+export const FROZE_BROWSING = chatNotice("chat.notice.memoryReclaimedBrowser");
+
+/**
+ * What a turn a restart cut off ends with instead of starting again, or null to start it again: null unless the turn ran
+ * through a freeze for want of memory (one recorded after it started) and browsed, or when its start is unknown. Each
+ * caller (the coordinator, the routines) reads the records once, at its first ask.
+ */
+export function restartCutStop(deps: { dataDir: string; lines(threadId: string): readonly Line[]; startedAt?: number; read?: (file: string) => StallRecord[] }) {
+ // This process's own start: a stall this run records later is not one the turn ran through.
+ const startedAt = deps.startedAt ?? Date.now() - process.uptime() * 1000;
+ let records: StallRecord[] | undefined;
+ return (threadId: string, since: number | undefined): string | null => {
+ if (since === undefined) return null;
+ records ??= (deps.read ?? readStallRecords)(join(deps.dataDir, STALL_FILE));
+ return frozeForMemory(records, since, startedAt) && browsedSince(deps.lines(threadId), since) ? FROZE_BROWSING : null;
+ };
+}
diff --git a/server/routines.test.ts b/server/routines.test.ts
index 39bfe6adce..bf953002d1 100644
--- a/server/routines.test.ts
+++ b/server/routines.test.ts
@@ -1635,6 +1635,38 @@ describe("RoutineManager", () => {
expect(new RoutineManager(h.options).listRuns()).toHaveLength(1);
});
+ it("fails a run the restart after a memory freeze cut, with the given line, instead of starting it again", async () => {
+ const h = harness();
+ const routine = h.manager.create({ name: "Prices", prompt: "Check the prices page", botId: "maus-1", schedule: { type: "once", at: new Date(2026, 7, 17, 8, 5).getTime() } });
+ h.setNow(routine.nextRunAt!);
+ await h.manager.tick();
+ const line = "Ran out of room, so I closed the browser to keep everything else running.";
+ const asked: Array<[string, string]> = [];
+ h.options.restartCut = (threadId, startedAt) => { asked.push([threadId, typeof startedAt]); return line; };
+ h.options.onRunFailed = (run) => h.failed.push(run);
+ const reloaded = new RoutineManager(h.options);
+ expect(asked).toEqual([["thread-1", "number"]]);
+ expect(reloaded.listRuns()).toMatchObject([{ routineId: routine.id, status: "failed", threadId: "thread-1", error: line }]);
+ expect(reloaded.listRuns()[0]!.retried).toBeUndefined();
+ expect(h.failed).toMatchObject([{ status: "failed", error: line }]);
+ h.setNow(routine.nextRunAt! + 60_000);
+ await reloaded.tick();
+ expect(h.started.map((turn) => turn.threadId)).toEqual(["thread-1"]);
+ });
+
+ it("keeps a run that waits on teammates' hand-offs waiting through the restart after a memory freeze", async () => {
+ const h = harness();
+ const routine = h.manager.create({ name: "Prices", prompt: "Check the prices page", botId: "maus-1", schedule: { type: "once", at: new Date(2026, 7, 17, 8, 5).getTime() } });
+ h.setNow(routine.nextRunAt!);
+ await h.manager.tick();
+ const asked: string[] = [];
+ h.options.restartCut = (threadId) => { asked.push(threadId); return "Ran out of room, so I closed the browser to keep everything else running."; };
+ h.options.hasPendingDelegations = () => true;
+ const reloaded = new RoutineManager(h.options);
+ expect(asked).toEqual([]);
+ expect(reloaded.listRuns()).toMatchObject([{ routineId: routine.id, status: "waiting", threadId: "thread-1" }]);
+ });
+
it("migrates optional attachment and timeout metadata without losing legacy records", () => {
const h = harness();
h.setBot("busy");
diff --git a/server/routines.ts b/server/routines.ts
index 365ff056a1..406f060a66 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -278,7 +278,7 @@ export interface RoutineManagerOptions {
onRunDeferred?: (run: RoutineRun, alert?: RoutineAlert) => void;
/** A run a restart cut off, before it starts again or fails: its old turn's work must not resume as well. */
onRunCut?: (run: RoutineRun) => void;
- hasPendingDelegations?: (threadId: string) => boolean; /** Why a run that ended well in this thread must fail instead (a hand-off refused, the lent computer refused), once; null when nothing was. */ refusedHandoff?: (threadId: string) => string | RefusedRunLine | null;
+ hasPendingDelegations?: (threadId: string) => boolean; /** What a run a restart cut ends with in place of starting again, or null (memory-freeze-restart.ts). */ restartCut?: (threadId: string, startedAt: number | undefined) => string | null; /** Why a run that ended well in this thread must fail instead (a hand-off refused, the lent computer refused), once; null when nothing was. */ refusedHandoff?: (threadId: string) => string | RefusedRunLine | null;
/** The turn in this thread is a routine's own, not one a person started there while its run waits on teammates. */
routineTurn?: (threadId: string) => boolean; /** The thread's latest turn is one a person started there by typing (false when not known, e.g. after a restart). */ personTurn?: (threadId: string) => boolean;
/** When an engine's usage limit resets (epoch ms), or null while that is not known. */
@@ -374,13 +374,13 @@ export class RoutineManager {
const cut = settleRestored(this.routines, this.runs, this.ledger.restoredThrough, this.now(), (routine, past) => this.advancePastOccurrence(routine, past, past)).map(cloneRun); this.ledger.restoredThrough = null;
let restarts = 0;
for (const run of this.runs.filter((candidate) => candidate.status === "running" || candidate.status === "waiting")) {
- settleAsk(run, undefined, this.now());
+ const turnRan = run.status === "running"; settleAsk(run, undefined, this.now());
if (run.threadId && run.target === "bot" && this.options.hasPendingDelegations?.(run.threadId) === true) {
this.wait(run, ROUTINE_HANDOFF_WAIT);
continue;
- }
- if (!requeueOnce(run, "restarted", ROUTINE_RESTARTED, this.now(), restartRetryAt(this.now(), restarts++, this.ledger.retryAfterBoot(run)))) {
- Object.assign(run, { status: "failed", error: ROUTINE_RESTARTED, attention: undefined, finishedAt: this.now() } satisfies Partial<RoutineRun>);
+ } const froze = run.threadId && turnRan ? this.options.restartCut?.(run.threadId, run.startedAt) ?? null : null; // A run waiting on hand-offs keeps waiting; one whose turn ran through a memory freeze ends.
+ if (froze !== null || !requeueOnce(run, "restarted", ROUTINE_RESTARTED, this.now(), restartRetryAt(this.now(), restarts++, this.ledger.retryAfterBoot(run)))) {
+ Object.assign(run, { status: "failed", error: froze ?? ROUTINE_RESTARTED, attention: undefined, finishedAt: this.now() } satisfies Partial<RoutineRun>);
if (run.target === "room-goal") run.goalStatus = "failed";
}
cut.push(cloneRun(run));
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index e9ad64cee8..9e2001dfa1 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -177,6 +177,7 @@ export class RuntimeCoordinator implements Coordinator {
clock: { now: () => this.now(), monotonic: () => performance.now() },
limits: { depth: 4, requests: REQUESTS_PER_ROOT, executions: EXECUTIONS_PER_ROOT, turnStallMs: TURN_STALL_MS, inputWaitMs: PARKED_LIMIT_MS, inputRemindMs: PARKED_REMIND_MS, ...handoffLimits(), ...options.runtimeLimits },
...(options.log ? { log: options.log } : {}),
+ ...(options.restartCut ? { restartCut: options.restartCut } : {}),
});
}
diff --git a/server/runtime/runtime.test.ts b/server/runtime/runtime.test.ts
index 07bc158a6c..43a59978a3 100644
--- a/server/runtime/runtime.test.ts
+++ b/server/runtime/runtime.test.ts
@@ -1647,3 +1647,31 @@ describe("Runtime: turns a restart cut start again a few at a time", () => {
expect(store.get(newer.id)?.status).toBe("running");
});
});
+
+describe("Runtime: a turn cut by the restart after a memory freeze", () => {
+ it("ends with the given line instead of starting again, and other cut turns start again as before", () => {
+ const store = openRuntimeStore(":memory:");
+ const first = world(undefined, {}, store);
+ first.runtime.begin(beginReq({ id: "root-browsed", assignee: { botId: "chief", destination: { kind: "standing_thread", threadId: "browsed-chat" } } }));
+ first.runtime.begin(beginReq({ id: "root-other", assignee: { botId: "chief", destination: { kind: "standing_thread", threadId: "other-chat" } } }));
+ first.runtime.close();
+
+ const asked: string[] = [];
+ const line = "Ran out of room, so I closed the browser to keep everything else running.";
+ const runner = fakeRunner(() => "hold");
+ const runtime = new Runtime(store, runner, { clock: fakeClock(), restartCut: (threadId, startedAt) => {
+ asked.push(`${threadId} ${typeof startedAt}`);
+ return threadId === "browsed-chat" ? line : null;
+ } });
+ runtime.open();
+ expect(asked.sort()).toEqual(["browsed-chat number", "other-chat number"]);
+ expect(store.get("root-browsed")).toMatchObject({ status: "failed", outcome: "interrupted", result: line });
+ expect(store.get("root-other")).toMatchObject({ status: "queued", restart: "rerun", restarts: 1 });
+ expect(runner.reports.map(r => r.a.id)).toEqual(["root-browsed"]);
+ runtime.tick();
+ expect(runner.runs.map(r => r.a.id)).toEqual(["root-other"]);
+ expect(checkInvariants(store, runner.live())).toEqual([]);
+ runtime.close();
+ store.close();
+ });
+});
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index 30c5ae992d..17a5f3827a 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -20,6 +20,9 @@ export interface RuntimeOptions {
log?: (line: string) => void;
/** Turns a restart cut start again at most one per this many ms (default RERUN_GAP_MS). */
rerunGapMs?: number;
+ /** What a turn a restart cut, which would start again, ends with instead; null to start it again (memory-freeze-restart.ts:
+ * a turn that browsed when the server froze for want of memory). */
+ restartCut?: (threadId: string, startedAt: number | undefined) => string | null;
}
/** 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
@@ -88,6 +91,7 @@ export class Runtime {
/** Monotonic: no turn a restart cut starts before this. */
private nextRerunAt = Number.NEGATIVE_INFINITY;
private rerunsStarted = 0;
+ private readonly restartCut: RuntimeOptions["restartCut"];
constructor(store: RuntimeStore, runner: TurnRunner, options: RuntimeOptions = {}) {
this.store = store;
@@ -98,6 +102,7 @@ export class Runtime {
this.log = options.log ?? (line => console.error("runtime:", line));
this.bootAt = this.clock.now();
this.rerunGapMs = options.rerunGapMs ?? RERUN_GAP_MS;
+ this.restartCut = options.restartCut;
}
/** Restart reconciliation and re-park of needs_input, from stored data only. Idempotent; runs before the first tick. */
@@ -119,6 +124,7 @@ export class Runtime {
}
if (n.status !== "running") continue;
const carried = n.carrying ?? [];
+ let stop: string | null;
const handedOut = childrenSince(this.store, n).length > 0;
const outward = handedOut ? [] : this.outwardOf(n);
if (handedOut) {
@@ -131,6 +137,9 @@ export class Runtime {
} else if (n.restart === "rerun") {
this.store.update(n, { kind: "restart_reconciled", at: now, detail: "failed: cut twice" });
this.settle(n, "failed", "interrupted", CUT_TWICE);
+ } else if ((stop = this.safe("restartCut", () => this.restartCut?.(n.assignee.destination.threadId, n.startedAt)) ?? null) !== null) {
+ this.store.update(n, { kind: "restart_reconciled", at: now, detail: "failed: froze for want of memory" });
+ this.settle(n, "failed", "interrupted", stop);
} else {
n.restart = "rerun"; n.restarts += 1; n.lastActivityAt = now;
n.status = this.store.children(n.id).length ? "resume" : "queued";