Skip to content

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

fix(memory-upkeep): coalesce state writes into one per tick

ppjswaedfd801c92f
diff --git a/server/memory-upkeep-lifecycle.test.ts b/server/memory-upkeep-lifecycle.test.ts
index 07712b1bc5..cd84466f6c 100644
--- a/server/memory-upkeep-lifecycle.test.ts
+++ b/server/memory-upkeep-lifecycle.test.ts
@@ -144,9 +144,18 @@ describe("scheduled memory upkeep", () => {
expect(generateText).toHaveBeenCalledTimes(1);
expect(generateText.mock.calls[0]![0]).toContain(marker);
const stateFile = join(DATA_DIR, "memory-upkeep.json");
+ // State writes are coalesced per tick, so a tidy that finished before the held dream is saved
+ // when the loop stops; the held step's own report is what must never appear.
+ const savedState = () => {
+ if (!existsSync(stateFile)) return {};
+ const saved = JSON.parse(readFileSync(stateFile, "utf8")) as { bots?: Record<string, Record<string, unknown>> };
+ const bot = { ...saved.bots?.[BOT.id] };
+ if (step === "dream") delete bot.lastTidy;
+ return bot;
+ };
const snapshot = () => ({
notebook: memory(), topic: readMemoryTopic(BOT.id, "project.md"), archive: readMemoryTopic(BOT.id, "archive.md"),
- state: existsSync(stateFile) ? readFileSync(stateFile, "utf8") : null,
+ state: savedState(),
});
const before = snapshot();
if (action === "freeze") freeze.freeze("https://fixture.example");
diff --git a/server/memory-upkeep-writes.test.ts b/server/memory-upkeep-writes.test.ts
new file mode 100644
index 0000000000..6297fcd19d
--- /dev/null
+++ b/server/memory-upkeep-writes.test.ts
@@ -0,0 +1,114 @@
+import { readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "./config.ts";
+import { NO_TEXT_ENGINE, createMemoryUpkeep, type UpkeepBot } from "./memory-upkeep.ts";
+import { ensureWorkspace, writeMemoryFile, writeMemoryTopic, WORKSPACES_DIR } from "./workspace.ts";
+
+// Counts every atomic write the upkeep makes, without changing how any of them lands on disk.
+const written = vi.hoisted(() => ({ paths: [] as string[] }));
+vi.mock("./atomic.ts", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./atomic.ts")>();
+ return {
+ ...actual,
+ writeFileAtomic: (path: string, data: string | Uint8Array, options?: { mode?: number; durable?: boolean }) => {
+ written.paths.push(path);
+ return actual.writeFileAtomic(path, data, options);
+ },
+ };
+});
+
+const BOT_COUNT = 24;
+const NOTEBOOK = "- 2026-09-01 · Trip · until 2026-09-02\n";
+const TODAY_AT = new Date(2026, 8, 25, 10, 0, 0);
+const BOTS: UpkeepBot[] = Array.from({ length: BOT_COUNT }, (_, i) => ({
+ id: `counted-${String(i + 1).padStart(2, "0")}`,
+ name: `Bot ${i + 1}`,
+}));
+const writesTo = (name: string) => written.paths.filter((path) => path.endsWith(`/${name}`) || path === name).length;
+const state = () => JSON.parse(readFileSync(join(DATA_DIR, "memory-upkeep.json"), "utf8")) as {
+ bots: Record<string, { lastTidy?: { at: number; expired: number; topicChecks?: number; contradictionsChecked: boolean }; lastCapture?: { note?: string }; topicCursor?: string }>;
+};
+
+function loopWith(engine: (botId: string) => { generateText?: (prompt: string) => Promise<string> } | null = () => null) {
+ return createMemoryUpkeep({
+ bots: () => BOTS,
+ bot: (id) => BOTS.find((bot) => bot.id === id),
+ engine,
+ busy: () => false,
+ addToAboutMe: () => 0,
+ sourceLabel: () => "chat",
+ quietMs: () => 60_000,
+ tidyHour: () => 0,
+ now: () => TODAY_AT,
+ });
+}
+
+describe("upkeep state writes", () => {
+ beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ written.paths.length = 0;
+ for (const bot of BOTS) {
+ ensureWorkspace(bot.id);
+ writeMemoryFile(bot.id, NOTEBOOK);
+ }
+ writeMemoryTopic(BOTS[0]!.id, "project.md", "- 2026-09-20 · Launch is Friday\n- 2026-09-22 · Launch is Monday\n");
+ written.paths.length = 0;
+ });
+
+ it("writes memory-upkeep.json once for a tick that tidies every bot", async () => {
+ const loop = loopWith((botId) => (botId === BOTS[0]!.id ? { generateText: async () => "{}" } : null));
+ await loop.tick();
+ await loop.idle();
+
+ expect(writesTo("memory-upkeep.json")).toBe(1);
+ // Each notebook really changed (one expired note was archived), so each is written exactly once.
+ expect(writesTo("MEMORY.md")).toBe(BOT_COUNT);
+
+ // Nothing is lost to the batching: every bot's report is in the one file that was written.
+ const saved = state();
+ expect(Object.keys(saved.bots).sort()).toEqual(BOTS.map((bot) => bot.id).sort());
+ for (const bot of BOTS) {
+ expect(saved.bots[bot.id]?.lastTidy).toMatchObject({ at: TODAY_AT.getTime(), expired: 1, contradictionsChecked: bot.id === BOTS[0]!.id });
+ }
+ // The topic cursor set during the tick survives the coalesced write.
+ expect(saved.bots[BOTS[0]!.id]?.topicCursor).toBe("project.md");
+ expect(saved.bots[BOTS[0]!.id]?.lastTidy?.topicChecks).toBe(1);
+ });
+
+ it("writes nothing at all on a later tick with no work to do", async () => {
+ const loop = loopWith();
+ await loop.tick();
+ await loop.idle();
+ written.paths.length = 0;
+ await loop.tick();
+ await loop.idle();
+ expect(written.paths).toEqual([]);
+ expect(writesTo("memory-upkeep.json")).toBe(0);
+ expect(writesTo("MEMORY.md")).toBe(0);
+ });
+
+ it("seeds each bot's notebook once, never once per tick", async () => {
+ // A fresh workspace has no MEMORY.md, so the first tick creates one per bot — and only the first.
+ for (const bot of BOTS) rmSync(join(WORKSPACES_DIR, bot.id), { recursive: true, force: true });
+ const loop = loopWith();
+ written.paths.length = 0;
+ await loop.tick();
+ await loop.idle();
+ expect(writesTo("MEMORY.md")).toBe(BOT_COUNT);
+ written.paths.length = 0;
+ await loop.tick();
+ await loop.idle();
+ expect(writesTo("MEMORY.md")).toBe(0);
+ });
+
+ it("still saves a report made outside a tick right away", async () => {
+ const loop = loopWith();
+ written.paths.length = 0;
+ const report = await loop.capture({ botId: BOTS[1]!.id, threadId: "chat", turns: [{ person: "I like short answers", bot: "Noted" }] });
+ expect(report.note).toBe(NO_TEXT_ENGINE);
+ expect(writesTo("memory-upkeep.json")).toBe(1);
+ expect(state().bots[BOTS[1]!.id]?.lastCapture?.note).toBe(NO_TEXT_ENGINE);
+ });
+});
diff --git a/server/memory-upkeep.ts b/server/memory-upkeep.ts
index d3df8e498c..44d7a8a4f1 100644
--- a/server/memory-upkeep.ts
+++ b/server/memory-upkeep.ts
@@ -126,11 +126,14 @@ function loadState(): UpkeepState {
}
}
-function saveState(state: UpkeepState): void {
+/** Answers whether the file on disk is now current; a failed write stays pending for the next flush. */
+function saveState(state: UpkeepState): boolean {
try {
mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
writeFileAtomic(statePath(), `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
+ return true;
} catch {
+ return false;
}
}
@@ -282,12 +285,45 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const queue: Waiting[] = [];
let worker: Promise<void> | null = null;
- const record = (botId: string, patch: { lastTidy?: TidyReport; lastCapture?: CaptureReport; topicCursor?: string; lastDream?: DreamReport; dreamedTo?: number }) => {
+ // The reports this process knows about: read once, written only when a batch ends. One tick over a
+ // large workspace used to re-read and re-write the whole file once per bot (#4115). Records made
+ // outside a batch are still written at once, so a report is never left only in memory.
+ let known: UpkeepState | null = null;
+ let unsaved = false;
+ let batching = 0;
+
+ const loaded = (): UpkeepState => (known ??= loadState());
+
+ function flush(): void {
+ if (!unsaved || !known) return;
+ if (saveState(known)) unsaved = false;
+ }
+
+ function endBatch(): void {
+ batching -= 1;
+ if (!batching) flush();
+ }
+
+ /** One write for everything recorded inside `work`, however many bots it touches. */
+ function batched<T>(work: () => Promise<T>): Promise<T> {
+ batching += 1;
+ let promise: Promise<T>;
+ try {
+ promise = work();
+ } catch (error) {
+ endBatch();
+ throw error;
+ }
+ return promise.finally(endBatch);
+ }
+
+ const record = (botId: string, patch: { lastTidy?: TidyReport; lastCapture?: CaptureReport; topicCursor?: string; lastDream?: DreamReport; dreamedTo?: number; core?: string[] }) => {
// a capture or tidy that was out when its bot was deleted leaves nothing behind
if (!deps.bot(botId)) return;
- const state = loadState();
+ const state = loaded();
state.bots[botId] = { ...state.bots[botId], ...patch };
- saveState(state);
+ unsaved = true;
+ if (!batching) flush();
};
const track = <T>(promise: Promise<T>): Promise<T> => {
@@ -466,7 +502,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
while (!cancelled(started) && queue.length) {
const call = takeCall();
try {
- const report = await captureCall(call.map((entry) => entry.batch));
+ const report = await batched(() => captureCall(call.map((entry) => entry.batch)));
for (const entry of call) entry.done?.resolve(report);
} catch (error) {
log(`memory upkeep: capture failed for ${call[0]!.batch.botId}: ${(error as Error).message}`);
@@ -511,8 +547,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const engine = deps.engine(botId);
if (!engine?.generateText) return 0;
const today = memoryDate(now());
- const state = loadState();
- const core = new Set(state.bots[botId]?.core ?? []);
+ const core = new Set(loaded().bots[botId]?.core ?? []);
const first = readRaw(botId, "MEMORY.md") ?? "";
const candidates = organizeCandidates(first, today, core);
if (!candidates.length) return 0;
@@ -525,9 +560,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const moved = new Set(proposed.map((move) => move.entry.line));
const moves = proposed.slice(0, MAX_MOVES);
const judgedCore = candidates.filter((entry) => !moved.has(entry.line)).map((entry) => factIdentity(entry.body));
- const saved = loadState();
- saved.bots[botId] = { ...saved.bots[botId], core: [...new Set([...(saved.bots[botId]?.core ?? []), ...judgedCore])].slice(-MAX_CORE) };
- saveState(saved);
+ record(botId, { core: [...new Set([...(loaded().bots[botId]?.core ?? []), ...judgedCore])].slice(-MAX_CORE) });
if (!moves.length) return 0;
return writing(botId, () => {
const { byTopic } = applyMoves(before, moves);
@@ -617,7 +650,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
let topicDeferred = 0;
let topicChecks = 0;
let topicsDeferred = 0;
- let topicCursor = loadState().bots[botId]?.topicCursor;
+ let topicCursor = loaded().bots[botId]?.topicCursor;
const deadline = Date.now() + MODEL_TIMEOUT_MS;
const topics = listMemoryTopics(botId).filter(topic => topic.name !== ARCHIVE_TOPIC).sort((a, b) => a.name.localeCompare(b.name));
const cursorAt = topics.findIndex(topic => topic.name === topicCursor) + 1;
@@ -680,14 +713,14 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
function tidy(botId: string): Promise<TidyReport> {
const running = tidying.get(botId);
if (running) return running;
- const promise = track(runTidy(botId)).finally(() => tidying.delete(botId));
+ const promise = track(batched(() => runTidy(botId))).finally(() => tidying.delete(botId));
tidying.set(botId, promise);
return promise;
}
/** Reads the chats since the last dream that answered; the first one looks back a week. */
function dreamSince(botId: string, at: number): number {
- return loadState().bots[botId]?.dreamedTo ?? at - DREAM_FIRST_LOOKBACK_MS;
+ return loaded().bots[botId]?.dreamedTo ?? at - DREAM_FIRST_LOOKBACK_MS;
}
async function runDream(botId: string): Promise<DreamReport> {
@@ -764,7 +797,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const started = generation;
const running = dreaming.get(botId);
if (running?.generation === started) return running.promise;
- const promise = track(runDream(botId)).finally(() => {
+ const promise = track(batched(() => runDream(botId))).finally(() => {
if (dreaming.get(botId)?.promise === promise) dreaming.delete(botId);
});
dreaming.set(botId, { generation: started, promise });
@@ -773,7 +806,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
function dreamDue(botId: string): boolean {
const current = now();
- const saved = loadState().bots[botId];
+ const saved = loaded().bots[botId];
if (deps.dreamer?.() !== botId || !deps.conversations || current.getHours() < deps.tidyHour()) return false;
if (saved?.lastDream && memoryDate(new Date(saved.lastDream.at)) >= memoryDate(current)) return false;
return deps.conversations(botId, dreamSince(botId, current.getTime())).length >= DREAM_MIN_CONVERSATIONS;
@@ -782,30 +815,36 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
function due(botId: string): boolean {
const current = now();
if (current.getHours() < deps.tidyHour()) return false;
- const last = loadState().bots[botId]?.lastTidy?.at;
+ const last = loaded().bots[botId]?.lastTidy?.at;
return !last || memoryDate(new Date(last)) < memoryDate(current);
}
async function tick(): Promise<void> {
const started = generation;
if (cancelled(started)) return;
- for (const bot of deps.bots()) {
- if (cancelled(started)) return;
- if (!upkeepEnabled(bot) || deps.busy(bot.id)) continue;
- if (due(bot.id)) {
+ // One batch: the state file is written once at the end however many bots this tick touches.
+ batching += 1;
+ try {
+ for (const bot of deps.bots()) {
+ if (cancelled(started)) return;
+ if (!upkeepEnabled(bot) || deps.busy(bot.id)) continue;
+ if (due(bot.id)) {
+ try {
+ await tidy(bot.id);
+ } catch (error) {
+ log(`memory upkeep: tidy failed for ${bot.id}: ${(error as Error).message}`);
+ }
+ }
+ if (cancelled(started)) return;
try {
- await tidy(bot.id);
+ if (deps.busy(bot.id) || !dreamDue(bot.id)) continue;
+ await dream(bot.id);
} catch (error) {
- log(`memory upkeep: tidy failed for ${bot.id}: ${(error as Error).message}`);
+ log(`memory upkeep: dream failed for ${bot.id}: ${(error as Error).message}`);
}
}
- if (cancelled(started)) return;
- try {
- if (deps.busy(bot.id) || !dreamDue(bot.id)) continue;
- await dream(bot.id);
- } catch (error) {
- log(`memory upkeep: dream failed for ${bot.id}: ${(error as Error).message}`);
- }
+ } finally {
+ endBatch();
}
}
@@ -824,20 +863,21 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
buffer.dropBot(botId);
dropQueued(botId);
dropPending(botId);
- const state = loadState();
+ const state = loaded();
if (!state.bots[botId]) return;
delete state.bots[botId];
- saveState(state);
+ unsaved = true;
+ flush();
},
capture: (batch) => new Promise<CaptureReport>((resolve, reject) => enqueue({ batch, done: { resolve, reject } })),
tidy,
dream,
ideas(botId) {
- const last = loadState().bots[botId]?.lastDream;
+ const last = loaded().bots[botId]?.lastDream;
return last && now().getTime() - last.at < IDEAS_FOR_MS ? { ideas: last.ideas, conversations: last.conversations } : { ideas: [], conversations: 0 };
},
status(botId) {
- const { lastTidy, lastCapture, lastDream } = loadState().bots[botId] ?? {};
+ const { lastTidy, lastCapture, lastDream } = loaded().bots[botId] ?? {};
return { ...(lastTidy ? { lastTidy } : {}), ...(lastCapture ? { lastCapture } : {}), ...(lastDream ? { lastDream } : {}), modelSteps: Boolean(deps.engine(botId)?.generateText) };
},
tick,
@@ -873,6 +913,8 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
for (const entry of queued) entry.done?.resolve({ at: now().getTime(), added: 0, topics: 0, aboutMe: 0, note: "kept for the next start" });
const waiting = [...queued.map((entry) => entry.batch), ...buffer.drain()];
if (deps.restoreTurn) savePending(waiting);
+ // Whatever the last tick recorded is on disk before the timer stops carrying it.
+ flush();
},
pause() {
paused = true;