Skip to content

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

See a change made in the same clock tick as the last look; steady the slow-download test (#5208)

Milind Soni0ae26bc6d9f2
diff --git a/server/engine-standalone.test.ts b/server/engine-standalone.test.ts
index 0e3e9d7718..cf6f170ea2 100644
--- a/server/engine-standalone.test.ts
+++ b/server/engine-standalone.test.ts
@@ -357,8 +357,12 @@ describe.skipIf(process.platform === "win32")("installing a standalone engine",
it("lets a slow download finish while bytes keep arriving", async () => {
const release = await served("raw");
- server.routes.set("assets.example.test/blob/fake", { body: Buffer.from(script()), trickle: { bytes: 16, everyMs: 120 } });
- await expect(install(release, { stallMs: 400 })).resolves.toMatchObject({ version: VERSION });
+ // Pieces 60 ms apart against a 1 s stall limit: a busy runner once held one 120 ms piece past a 400 ms limit.
+ server.routes.set("assets.example.test/blob/fake", { body: Buffer.from(script()), trickle: { bytes: 8, everyMs: 60 } });
+ const started = performance.now();
+ await expect(install(release, { stallMs: 1_000 })).resolves.toMatchObject({ version: VERSION });
+ // The whole download outlasted the limit, so it is the arriving bytes that kept it alive.
+ expect(performance.now() - started).toBeGreaterThan(1_000);
});
it("refuses a redirect to a host it does not trust, without contacting that host", async () => {
diff --git a/server/lending-memory.test.ts b/server/lending-memory.test.ts
index 356b9195fe..51cfe3677c 100644
--- a/server/lending-memory.test.ts
+++ b/server/lending-memory.test.ts
@@ -5,12 +5,19 @@ import { dirname, join, relative, sep } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
// Counts disk touches for the cost test: the count is what the design promises, whatever the machine's speed.
-const fsCalls = vi.hoisted(() => ({ lstat: 0, opendir: 0, read: 0, failOpening: "" }));
+// `sameTick`: a path whose mtime and ctime stand still from its first look on, as within one tick of a filesystem's clock.
+const fsCalls = vi.hoisted(() => ({ lstat: 0, opendir: 0, read: 0, failOpening: "", sameTick: "", tick: undefined as { mtimeNs: bigint; ctimeNs: bigint } | undefined }));
vi.mock("node:fs", async (importOriginal) => {
const fs = await importOriginal<typeof import("node:fs")>();
return {
...fs,
- lstatSync: ((...args: Parameters<typeof fs.lstatSync>) => { fsCalls.lstat++; return fs.lstatSync(...args); }) as typeof fs.lstatSync,
+ lstatSync: ((...args: Parameters<typeof fs.lstatSync>) => {
+ fsCalls.lstat++;
+ const stat = fs.lstatSync(...args) as unknown as { mtimeNs?: bigint; ctimeNs?: bigint } | undefined;
+ if (!fsCalls.sameTick || String(args[0]) !== fsCalls.sameTick || typeof stat?.mtimeNs !== "bigint" || typeof stat.ctimeNs !== "bigint") return stat;
+ fsCalls.tick ??= { mtimeNs: stat.mtimeNs, ctimeNs: stat.ctimeNs };
+ return Object.create(stat, { mtimeNs: { value: fsCalls.tick.mtimeNs }, ctimeNs: { value: fsCalls.tick.ctimeNs } });
+ }) as typeof fs.lstatSync,
opendirSync: ((...args: Parameters<typeof fs.opendirSync>) => {
fsCalls.opendir++;
if (fsCalls.failOpening && String(args[0]) === fsCalls.failOpening) throw Object.assign(new Error("EMFILE: too many open files"), { code: "EMFILE" });
@@ -25,7 +32,7 @@ import { botMemoryFiles, changedFiles, createLendingMemory, FOLDER_ENTRY_CAP, fi
const memoryFingerprint = (workspace: string, workingFolders: readonly string[] = []) => fingerprintOf(memoryFiles(workspace, workingFolders));
let dir = "";
-afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; });
+afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; Object.assign(fsCalls, { sameTick: "", tick: undefined }); vi.restoreAllMocks(); });
const workspace = () => {
dir = mkdtempSync(join(tmpdir(), "omb-lending-memory-"));
const ws = join(dir, "workspaces", "bot1");
@@ -336,6 +343,9 @@ describe("a bot's memory and a lent Mac (server/lending-memory.ts)", () => {
for (let i = 0; i < 3_000; i += 1) mkdirSync(join(tasks, "bot1", `t${i}`), { recursive: true });
for (let i = 0; i < 3_000; i += 300) writeFileSync(join(tasks, "bot1", `t${i}`, "AGENTS.md"), `folder ${i}`);
const snapshot = () => botMemoryFiles(bot, { workspace: () => ws, taskWorkspaces: tasks });
+ // Folders made a moment ago are read again at every look (the next test); this is the cost once they have settled.
+ const later = Date.now() + 60_000;
+ vi.spyOn(Date, "now").mockReturnValue(later);
const cold = snapshot();
expect(Object.keys(cold).filter((name) => name.endsWith("AGENTS.md"))).toHaveLength(10);
Object.assign(fsCalls, { lstat: 0, opendir: 0, read: 0 });
@@ -355,6 +365,24 @@ describe("a bot's memory and a lent Mac (server/lending-memory.ts)", () => {
memory.reconcile("bot1", false);
expect(statSync(join(dir, "record.json")).size).toBeLessThan(10_000);
});
+ it("sees a second change made within the same tick of the filesystem's clock as the first, in a folder and in a file", () => {
+ // NTFS moves its clock about every 16 ms: a Windows runner removed a link and planted another inside one tick, and
+ // the folder's remembered names hid the new one. Here the clock of one path stands still instead.
+ const ws = workspace();
+ const project = join(dir, "projects", "site");
+ const skills = join(project, ".claude", "skills");
+ mkdirSync(skills, { recursive: true });
+ fsCalls.sameTick = skills;
+ const empty = memoryFingerprint(ws, [project]);
+ symlinkSync(join(dir, "elsewhere"), join(skills, "evil"));
+ expect(memoryFingerprint(ws, [project])).not.toBe(empty);
+ // A file rewritten in place to the same length, with the same stamp.
+ Object.assign(fsCalls, { sameTick: join(ws, "MEMORY.md"), tick: undefined });
+ const before = memoryFingerprint(ws);
+ writeFileSync(join(ws, "MEMORY.md"), "# Mine!!\n");
+ expect(statSync(join(ws, "MEMORY.md")).size).toBe("# Memory\n".length);
+ expect(memoryFingerprint(ws)).not.toBe(before);
+ });
});
describe("what the harness puts in a bot's folders, and what a bot writes there (server/lending-memory.ts)", () => {
diff --git a/server/lending-memory.ts b/server/lending-memory.ts
index 49f885cbff..aa90dd5a8a 100644
--- a/server/lending-memory.ts
+++ b/server/lending-memory.ts
@@ -18,6 +18,14 @@ export const ANCESTOR_FILES = ["CLAUDE.md", "CLAUDE.local.md", "AGENTS.md", "AGE
export const FOLDER_ENTRY_CAP = 200;
const ROOT_ENTRY_CAP = 5_000;
+/** A filesystem's clock moves in ticks (about 16 ms on NTFS, a kernel tick on ext4, 2 s on FAT), so two changes inside
+ * one tick leave the same mtime and ctime, and what was read at a stamp this recent may be the first of them. Such a
+ * read is used but never remembered: the next look reads again, until the clock has moved well past the stamp. A stamp
+ * ahead of this clock is never remembered either. */
+const RACY_STAMP_MS = 2_000;
+const settled = (stat: { mtimeNs: bigint; ctimeNs: bigint }, now: number) =>
+ (stat.mtimeNs > stat.ctimeNs ? stat.mtimeNs : stat.ctimeNs) / 1_000_000n < BigInt(Math.floor(now) - RACY_STAMP_MS);
+
/** Cached by identity, size and ctime, which no process can set back. */
const contentCache = new Map<string, { key: string; hash: string }>();
function describe(file: string): string | undefined {
@@ -31,8 +39,10 @@ function describe(file: string): string | undefined {
const key = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
const cached = contentCache.get(file);
if (cached?.key === key) return cached.hash;
+ const keep = settled(stat, Date.now());
let hash: string;
try { hash = `file:${createHash("sha256").update(readFileSync(file)).digest("hex")}`; } catch { hash = "file:unreadable"; }
+ if (!keep) { contentCache.delete(file); return hash; }
if (contentCache.size > 50_000) contentCache.clear();
contentCache.set(file, { key, hash });
return hash;
@@ -55,6 +65,7 @@ function listing(dir: string, cap: number, through = false): Listing | undefined
const cacheKey = `${cap}\u0000${dir}`;
const cached = listingCache.get(cacheKey);
if (cached?.key === key) return cached;
+ const keep = settled(stat, Date.now());
const names = new Set<string>();
let overflow = false;
try {
@@ -71,6 +82,7 @@ function listing(dir: string, cap: number, through = false): Listing | undefined
return { key: `${key}:unreadable`, names: new Set(), overflow: true };
}
const listed = { key, names, overflow };
+ if (!keep) { listingCache.delete(cacheKey); return listed; }
if (listingCache.size > 50_000) listingCache.clear();
listingCache.set(cacheKey, listed);
return listed;
diff --git a/shared/app-frame/helper.test.ts b/shared/app-frame/helper.test.ts
index 3cd96fb352..462554621c 100644
--- a/shared/app-frame/helper.test.ts
+++ b/shared/app-frame/helper.test.ts
@@ -32,10 +32,17 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:
const loads = new Set<() => void>();
const observers = new Set<() => void>();
let bridge: AppBridge;
+ // Every hop between the page and its host is a task of this fake frame's, counted until it has run, so a test can wait
+ // for the frame to go quiet instead of for a time: a timer's wait is about 16 ms on Windows, and a report takes three.
+ let pending = 0;
+ const task = (run: () => void) => {
+ pending += 1;
+ setTimeout(() => { try { run(); } finally { pending -= 1; } }, 0);
+ };
const parent = {
postMessage(data: unknown) {
const copy = structuredClone(data);
- setTimeout(() => bridge.handleMessage({ source: frame, data: copy }), 0);
+ task(() => bridge.handleMessage({ source: frame, data: copy }));
},
};
const positions = new Map<unknown, string>();
@@ -49,7 +56,7 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:
},
postMessage(data: unknown) {
const copy = structuredClone(data);
- setTimeout(() => { for (const listener of listeners) listener({ source: parent, data: copy }); }, 0);
+ task(() => { for (const listener of listeners) listener({ source: parent, data: copy }); });
},
getComputedStyle: (element: unknown) => ({ position: positions.get(element) ?? "static" }),
};
@@ -90,7 +97,7 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:
resize: (height) => {
seen.heights.push(height);
frame.innerHeight = height;
- for (const observed of observers) setTimeout(observed, 0);
+ for (const observed of observers) task(observed);
},
engaged: () => engaged,
teardownRequested: () => {},
@@ -103,11 +110,18 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:
}
// The helper's free names, bound to this fake frame: it runs exactly as written.
const run = new Function("window", "document", "ResizeObserver", "requestAnimationFrame", room ? APP_ROOM_HELPER_SOURCE : APP_HELPER_SOURCE);
- run(frame, document, scene ? FakeResizeObserver : undefined, (callback: () => void) => setTimeout(callback, 0));
+ run(frame, document, scene ? FakeResizeObserver : undefined, (callback: () => void) => task(callback));
return {
bridge, seen, frame, root,
load: () => { options.loaded = true; for (const listener of loads) listener(); },
- reflow: () => { for (const observed of observers) setTimeout(observed, 0); },
+ reflow: () => { for (const observed of observers) task(observed); },
+ /** Resolves once no task of the frame's is waiting to run: what a reflow started has reached the host, or come to nothing. */
+ quiet: async () => {
+ for (const deadline = Date.now() + 5_000; pending > 0;) {
+ if (Date.now() > deadline) throw new Error(`the frame still had ${pending} task(s) waiting after 5 s`);
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+ },
mausbot: () => frame.mausbot as {
send(text: string): Promise<void>; open(url: string): Promise<void>; setContext(text: string): Promise<void>; theme: string; room: boolean;
},
@@ -121,7 +135,7 @@ async function settled(page: ReturnType<typeof boot>) {
for (let round = 0; round < 20 && count !== page.seen.heights.length; round++) {
count = page.seen.heights.length;
page.reflow();
- await new Promise((resolve) => setTimeout(resolve, 30));
+ await page.quiet();
}
return page.seen.heights;
}