Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(routines): save a run's progress once per window, not once per step (#4837)
Milind Soni586dc7dd1c8b
diff --git a/server/routine-progress-save.ts b/server/routine-progress-save.tsnew file mode 100644index 0000000000..7cbe37b63e--- /dev/null+++ b/server/routine-progress-save.ts@@ -0,0 +1,62 @@+// How far a routine run has got (its newest reply, a question it opened or had answered, an engine error it may still+// recover from) reaches routines.json at most once per window, not once per step: each save rewrites every routine and+// up to 2,000 runs. A restart acts only on a run's status, and every status change (a start, an end, a retry) is still+// saved before the server yields, taking any waiting progress with it. A crash loses at most the last window of progress+// on a run the restart then retries or fails anyway; a stop (shutdown, backup, a move) writes it first.+import { existsSync } from "node:fs";+import { dirname } from "node:path";++export const RUN_PROGRESS_WINDOW_MS = 5_000;++export class RunProgressSave {+ private timer: ReturnType<typeof setTimeout> | undefined;+ private immediate = false;+ private readonly file: () => string;+ private readonly write: () => void;+ private readonly windowMs: number;++ constructor(file: () => string, write: () => void, windowMs = RUN_PROGRESS_WINDOW_MS) {+ this.file = file;+ this.write = write;+ this.windowMs = windowMs;+ }++ /** Saves within the window; a later change in the same window rides along and never pushes the save back. */+ soon(): void {+ if (this.immediate) return this.writeLogged();+ if (this.timer) return;+ this.timer = setTimeout(() => {+ this.timer = undefined;+ // A folder removed meanwhile (a test's, a wiped data folder) stays removed: progress never recreates it.+ if (existsSync(dirname(this.file()))) this.writeLogged();+ }, this.windowMs);+ this.timer.unref?.();+ }++ /** A whole-file save just ran, so nothing is waiting any more. */+ written(): void {+ clearTimeout(this.timer);+ this.timer = undefined;+ }++ /** Writes what is waiting now, if anything is. */+ flush(): void {+ if (!this.timer) return;+ this.written();+ this.write();+ }++ /** From shutdown on, progress is saved as it happens, as no later window may come. */+ atOnce(): void {+ this.immediate = true;+ }++ private writeLogged(): void {+ try {+ this.write();+ } catch (error) {+ // The progress stays in memory and the next save of the file writes it.+ console.error("routines: could not save run progress; the next save retries it", error);+ }+ }+}diff --git a/server/routines.test.ts b/server/routines.test.tsindex 7ad7a89fa9..b90b345c0c 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { GroupGoalRunStatus } from "../shared/group-goal-run.ts";import { isRoutineProblemRun } from "../shared/routines.ts";import { ROUTINE_SKIPPED_WHILE_WAITING, ROUTINE_SUPERSEDED } from "./routine-execution.ts";+import { RUN_PROGRESS_WINDOW_MS } from "./routine-progress-save.ts";import {nextOccurrence,RoutineManager,@@ -592,7 +593,11 @@ describe("a run waiting on an approval nobody is there to give", () => {const h = harness();const at = await started(h);h.setNow(at + minutes(1));+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });h.manager.handleRuntimeEvent(opened("thread-1", "r1", "mcp__composio__COMPOSIO_SEARCH_TOOLS"));+ // The two minutes waited outlast the progress window: the ask is on disk.+ vi.advanceTimersByTime(RUN_PROGRESS_WINDOW_MS);+ vi.useRealTimers();h.options.hasPendingDelegations = (threadId) => threadId === "thread-1";h.setNow(at + minutes(3));const restarted = new RoutineManager(h.options);diff --git a/server/routines.ts b/server/routines.tsindex a507b1b993..2dc3718f1f 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -4,7 +4,7 @@ import { dirname, join } from "node:path";import { DATA_DIR } from "./config.ts";import type { RuntimeEvent } from "./contracts.ts";-import { OwnedFile } from "./atomic.ts"; import { saveSoon } from "./save-batch.ts";+import { OwnedFile } from "./atomic.ts"; import { saveSoon } from "./save-batch.ts"; import { RunProgressSave } from "./routine-progress-save.ts";import { redactSecretsInText } from "./redact.ts";import { activeRunsOf, nextDueOf, schedulerDueOf, wakeHoldOf } from "./routine-due.ts";import { startDueTimer, type DueTimer } from "./due-timer.ts";@@ -320,7 +320,7 @@ export class RoutineManager {private unreadable = false; private malformedAttachments = false;private frozenPending = false;private readonly bootedAt: number;- private readonly checking = new Set<string>();+ private readonly checking = new Set<string>(); private readonly progress = new RunProgressSave(() => this.file, () => this.save());constructor(options: RoutineManagerOptions) {this.options = options;@@ -947,13 +947,13 @@ export class RoutineManager {}stop() {- this.timer?.stop();- this.timer = null;+ this.timer?.stop(); this.timer = null;+ try { this.progress.flush(); } catch (error) { console.error("routines: could not save run progress", error); }}/** At shutdown: a run whose turn the shutdown cuts stays running on disk, for the next start to pick up once. */close() {- this.closing = true;+ this.closing = true; this.progress.atOnce();this.stop();}@@ -1286,7 +1286,7 @@ export class RoutineManager {} else {return null;}- this.saveLater();+ if (event.type === "turn.completed") this.saveLater(); else this.progress.soon();this.emitRun(run);if (event.type === "turn.completed") queueMicrotask(() => this.tickInBackground());return cloneRun(run);@@ -1540,7 +1540,7 @@ export class RoutineManager {/** Lands at the end of the running save batch (server/save-batch.ts); what a caller rolls back on failure uses save. */private saveLater() { saveSoon(this, () => this.save()); }private save() {- if (this.unreadable) return;+ this.progress.written(); if (this.unreadable) return;// Evict only terminal receipts: an active one owns cancellation, timeout and event routing.let excess = this.runs.length - MAX_RUNS;for (let index = 0; index < this.runs.length && excess > 0;) {diff --git a/server/server-writes.test.ts b/server/server-writes.test.tsindex ad52bee4cb..1040bc3152 100644--- a/server/server-writes.test.ts+++ b/server/server-writes.test.ts@@ -1,5 +1,6 @@// Whole-file saves of bots.json and routines.json: fewer writes, and at every point the server yields to the event loop-// (where a crash or an exit can land) the files hold what one write per change would have left.+// (where a crash or an exit can land) the files hold what one write per change would have left, except a routine run's+// progress, which may lag by one window (server/routine-progress-save.ts).import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { basename, join } from "node:path";@@ -13,6 +14,7 @@ const { DATA_DIR } = await import("./config.ts");const { batchSaves } = await import("./save-batch.ts");const { Store } = await import("./store.ts");const { RoutineManager } = await import("./routines.ts");+const { RUN_PROGRESS_WINDOW_MS } = await import("./routine-progress-save.ts");type RuntimeEvent = import("./contracts.ts").RuntimeEvent;const selection = () => ({ instanceId: "claude", model: "claude-sonnet-5" });@@ -94,7 +96,7 @@ describe("routines.json saves", () => {const event = (threadId: string, rest: Record<string, unknown>) =>({ eventId: `e-${Math.random()}`, provider: "claudeAgent", threadId, turnId: "turn-1", createdAt: new Date().toISOString(), ...rest }) as unknown as RuntimeEvent;- it("write a manual run four times, and a restart after any step reads what that step saved", async () => {+ const setup = () => {const file = join(dir, "routines.json");const options = {file,@@ -106,23 +108,82 @@ describe("routines.json saves", () => {const routine = manager.create({ name: "Morning", prompt: "Summarise.", botId: "bot-1", enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });vi.mocked(fs.renameSync).mockClear();const restart = () => new RoutineManager({ ...options, startTurn: async () => {} }).listRuns()[0];+ const onDisk = () => JSON.parse(readFileSync(file, "utf8")).runs[0];+ const deliver = (rest: Record<string, unknown>) => batchSaves(() => manager.handleRuntimeEvent(event("thread-1", rest)));+ return { file, manager, routine, restart, onDisk, deliver };+ };++ afterEach(() => vi.useRealTimers());++ it("write a manual run three times, and a restart after any step reads the status that step left", async () => {+ const { file, manager, routine, restart, onDisk, deliver } = setup();const run = manager.runNow(routine.id)!;expect(restart()).toMatchObject({ id: run.id, status: "queued" });await manager.tick();- expect(JSON.parse(readFileSync(file, "utf8")).runs[0]).toMatchObject({ status: "running", threadId: "thread-1" });+ expect(onDisk()).toMatchObject({ status: "running", threadId: "thread-1" });- const deliver = (rest: Record<string, unknown>) => batchSaves(() => manager.handleRuntimeEvent(event("thread-1", rest)));deliver({ type: "turn.started" });deliver({ type: "item.completed", itemType: "assistant_text", text: "Calendar clear." });- expect(JSON.parse(readFileSync(file, "utf8")).runs[0]).toMatchObject({ status: "running", output: "Calendar clear." });+ // Progress waits for its window; the status a restart acts on is already there.+ expect(onDisk()).toMatchObject({ status: "running" });+ expect(onDisk().output).toBeUndefined();batchSaves(() => {manager.handleRuntimeEvent(event("thread-1", { type: "turn.completed", ok: true }));manager.noteReport(run.id, { state: "pending" });manager.noteReport(run.id, { state: "quiet" });});- expect(JSON.parse(readFileSync(file, "utf8")).runs[0]).toMatchObject({ status: "completed", output: "Calendar clear.", report: { state: "quiet" } });- expect(writesOf("routines.json")).toBe(4);+ expect(onDisk()).toMatchObject({ status: "completed", output: "Calendar clear.", report: { state: "quiet" } });+ expect(writesOf("routines.json")).toBe(3);expect(readFileSync(file, "utf8")).not.toContain("\n");+ manager.close();+ });++ it("save a long run's progress once per window, so a crash loses at most that window", async () => {+ const { manager, routine, restart, onDisk, deliver } = setup();+ manager.runNow(routine.id);+ await manager.tick();+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const started = writesOf("routines.json");++ // Ten replies a second apart, with a question asked and answered between them.+ for (let step = 1; step <= 10; step++) {+ deliver({ type: "item.completed", itemType: "assistant_text", text: `Step ${step} done.` });+ if (step === 4) deliver({ type: "request.opened", requestId: "r1", requestType: "permission", tool: "shell", summary: "ls" });+ if (step === 4) deliver({ type: "request.resolved", requestId: "r1", behavior: "allow", source: "user" });+ vi.advanceTimersByTime(1_000);+ }+ expect(writesOf("routines.json") - started).toBe(10_000 / RUN_PROGRESS_WINDOW_MS);+ expect(onDisk()).toMatchObject({ status: "running", output: "Step 10 done." });++ // A crash inside the next window: the newest reply is lost, the run restarts as a running one always has.+ deliver({ type: "item.completed", itemType: "assistant_text", text: "Step 11 done." });+ expect(onDisk().output).toBe("Step 10 done.");+ const restarted = restart();+ expect(restarted).toMatchObject({ status: "queued", retried: "restarted", output: "Step 10 done." });++ const before = writesOf("routines.json");+ deliver({ type: "turn.completed", ok: true });+ expect(onDisk()).toMatchObject({ status: "completed", output: "Step 11 done." });+ // The end took the waiting progress with it and cancelled the window: nothing writes again.+ expect(vi.getTimerCount()).toBe(0);+ vi.advanceTimersByTime(RUN_PROGRESS_WINDOW_MS);+ expect(writesOf("routines.json")).toBe(before + 1);+ manager.close();+ });++ it("write waiting progress when the scheduler stops for a backup or a move, and at once from shutdown on", async () => {+ const { manager, routine, onDisk, deliver } = setup();+ manager.runNow(routine.id);+ await manager.tick();+ deliver({ type: "item.completed", itemType: "assistant_text", text: "Half way." });+ expect(onDisk().output).toBeUndefined();+ manager.stop();+ expect(onDisk().output).toBe("Half way.");++ manager.start();+ manager.close();+ deliver({ type: "item.completed", itemType: "assistant_text", text: "Nearly there." });+ expect(onDisk().output).toBe("Nearly there.");});});