Skip to content

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

fix(memory-upkeep): flush a capture's report while a tick is open

ppjswa021f5df566d
diff --git a/server/memory-upkeep-writes.test.ts b/server/memory-upkeep-writes.test.ts
index 6297fcd19d..2c4e9cf20a 100644
--- a/server/memory-upkeep-writes.test.ts
+++ b/server/memory-upkeep-writes.test.ts
@@ -7,13 +7,14 @@ import { NO_TEXT_ENGINE, createMemoryUpkeep, type UpkeepBot } from "./memory-upk
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[] }));
+const written = vi.hoisted(() => ({ paths: [] as string[], states: [] as { bots: Record<string, unknown> }[] }));
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);
+ if (typeof data === "string" && path.endsWith("memory-upkeep.json")) written.states.push(JSON.parse(data) as { bots: Record<string, unknown> });
return actual.writeFileAtomic(path, data, options);
},
};
@@ -49,6 +50,7 @@ describe("upkeep state writes", () => {
beforeEach(() => {
rmSync(DATA_DIR, { recursive: true, force: true });
written.paths.length = 0;
+ written.states.length = 0;
for (const bot of BOTS) {
ensureWorkspace(bot.id);
writeMemoryFile(bot.id, NOTEBOOK);
@@ -111,4 +113,46 @@ describe("upkeep state writes", () => {
expect(writesTo("memory-upkeep.json")).toBe(1);
expect(state().bots[BOTS[1]!.id]?.lastCapture?.note).toBe(NO_TEXT_ENGINE);
});
+
+ it("saves a capture's report while the tick it overlapped is still running", async () => {
+ // Enough live notes for a contradiction check, so the first bot's tidy stops at its model call.
+ writeMemoryFile(BOTS[0]!.id, ["Acme ships Friday", "Beta ships Monday", "Gamma ships Tuesday", "Delta ships Wednesday", "Epsilon ships Thursday", "Zeta ships Friday"]
+ .map((text, i) => `- 2026-09-0${i + 1} · ${text}\n`).join(""));
+ let release!: (answer: string) => void;
+ let entered!: () => void;
+ const held = new Promise<string>((resolve) => { release = resolve; });
+ const atModel = new Promise<void>((resolve) => { entered = resolve; });
+ let calls = 0;
+ const loop = loopWith((botId) => (botId === BOTS[0]!.id ? {
+ generateText: () => {
+ calls += 1;
+ if (calls > 1) return Promise.resolve("{}");
+ entered();
+ return held;
+ },
+ } : null));
+
+ const ticking = loop.tick();
+ await atModel;
+ // The tick holds the only batch open, so nothing of its own is on disk yet.
+ expect(writesTo("memory-upkeep.json")).toBe(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);
+ const midTick = state();
+ expect(midTick.bots[BOTS[1]!.id]?.lastCapture?.note).toBe(NO_TEXT_ENGINE);
+ expect(midTick.bots[BOTS[0]!.id]).toBeUndefined();
+
+ release("{}");
+ await ticking;
+ await loop.idle();
+
+ // One more write for every bot the tick tidied: the tick still writes once, not once per bot.
+ expect(writesTo("memory-upkeep.json")).toBe(2);
+ 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() });
+ expect(saved.bots[BOTS[1]!.id]?.lastCapture?.note).toBe(NO_TEXT_ENGINE);
+ });
});
diff --git a/server/memory-upkeep.ts b/server/memory-upkeep.ts
index 44d7a8a4f1..22c6f1b1a2 100644
--- a/server/memory-upkeep.ts
+++ b/server/memory-upkeep.ts
@@ -285,36 +285,40 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const queue: Waiting[] = [];
let worker: Promise<void> | null = null;
- // 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.
+ // The reports this process knows about: read once, written when the batch that recorded them ends,
+ // so a tick over a large workspace writes once however many bots it touches. A capture's batch also
+ // writes while an outer tick batch is open: its report must outlive a restart mid-tick, and the tick
+ // can be minutes away from its own write.
let known: UpkeepState | null = null;
let unsaved = false;
- let batching = 0;
+ const open: { dirty: boolean; flushWhileOpen: boolean }[] = [];
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();
+ if (!saveState(known)) return;
+ unsaved = false;
+ for (const batch of open) batch.dirty = false;
}
/** One write for everything recorded inside `work`, however many bots it touches. */
- function batched<T>(work: () => Promise<T>): Promise<T> {
- batching += 1;
+ function batched<T>(work: () => Promise<T>, flushWhileOpen = false): Promise<T> {
+ const batch = { dirty: false, flushWhileOpen };
+ open.push(batch);
+ const end = () => {
+ const at = open.lastIndexOf(batch);
+ if (at >= 0) open.splice(at, 1);
+ if (batch.dirty && (batch.flushWhileOpen || !open.length)) flush();
+ };
let promise: Promise<T>;
try {
promise = work();
} catch (error) {
- endBatch();
+ end();
throw error;
}
- return promise.finally(endBatch);
+ return promise.finally(end);
}
const record = (botId: string, patch: { lastTidy?: TidyReport; lastCapture?: CaptureReport; topicCursor?: string; lastDream?: DreamReport; dreamedTo?: number; core?: string[] }) => {
@@ -323,7 +327,11 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const state = loaded();
state.bots[botId] = { ...state.bots[botId], ...patch };
unsaved = true;
- if (!batching) flush();
+ if (!open.length) {
+ flush();
+ return;
+ }
+ for (const batch of open) batch.dirty = true;
};
const track = <T>(promise: Promise<T>): Promise<T> => {
@@ -502,7 +510,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
while (!cancelled(started) && queue.length) {
const call = takeCall();
try {
- const report = await batched(() => captureCall(call.map((entry) => entry.batch)));
+ const report = await batched(() => captureCall(call.map((entry) => entry.batch)), true);
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}`);
@@ -823,8 +831,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const started = generation;
if (cancelled(started)) return;
// One batch: the state file is written once at the end however many bots this tick touches.
- batching += 1;
- try {
+ await batched(async () => {
for (const bot of deps.bots()) {
if (cancelled(started)) return;
if (!upkeepEnabled(bot) || deps.busy(bot.id)) continue;
@@ -843,9 +850,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
log(`memory upkeep: dream failed for ${bot.id}: ${(error as Error).message}`);
}
}
- } finally {
- endBatch();
- }
+ });
}
return {