Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Storage report: bound what is read back from its saved files (#7149)
Milind Soniee0ab8910996
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex b9132374d7..16917ea999 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1912,7 +1912,9 @@ starts a walk.ends. The last pass is kept in the data folder's`cache/storage-report.json`, and the pass under way in`cache/storage-progress.json`, saved at most once a minute between two- folders of the top four levels. Backups leave both out. A home that sleeps+ folders of the top four levels. Backups leave both out. Neither is read+ back when it is over 1 MB, and every count read back is checked to be+ 10 PB at most. A home that sleepsby stopping keeps its report and picks the pass up where it left off.Node has no per-call I/O priority, and lowering the server's own prioritywould slow everything else, so the budget is the only throttle.diff --git a/server/perf/disk-usage.test.ts b/server/perf/disk-usage.test.tsindex c6a57a7d6b..25349c73ae 100644--- a/server/perf/disk-usage.test.ts+++ b/server/perf/disk-usage.test.ts@@ -7,9 +7,9 @@ import { requiredScope, serviceAllowed } from "../request-auth.ts";import { createPerfDiagnosticsRoutes, STORAGE_PATH } from "../routes/perf-diagnostics.ts";import type { RouteContext } from "../routes/table.ts";import { STORAGE_CATEGORIES } from "./disk-categories.ts";-import { MAX_BOTS, nodeWalkFs, type WalkFs } from "./disk-walk.ts";+import { MAX_BOTS, nodeWalkFs, SAVED_FILE_MAX_BYTES, type WalkFs } from "./disk-walk.ts";import { cloudStorage, createPerfHost } from "./perf-host.ts";-import { createDiskUsage, readSavedPass, readSavedProgress, STORAGE_HEALTH_MAX_BYTES, storageHealth, type DiskUsageOptions, type StorageReport } from "./disk-usage.ts";+import { createDiskUsage, readSavedPass, readSavedProgress, savedFileText, STORAGE_HEALTH_MAX_BYTES, storageHealth, type DiskUsageOptions, type StorageReport } from "./disk-usage.ts";const START = 1_800_000_000_000;const dirs: string[] = [];@@ -185,6 +185,36 @@ describe("storage sampler", () => {await again.stop();});+ it("reports a negative unwalkedBytes when the walk counted more than the volume says is used", async () => {+ const w = usage({ statfs: async () => ({ blocks: 1_000_000, bsize: 4096, bavail: 999_999, bfree: 999_999 }) });+ w.advance(60_000);+ await untilDone(w);+ const report = w.disk.report();+ expect(report.walkedBytes).toBeGreaterThan(4096);+ expect(report.unwalkedBytes).toBe(4096 - report.walkedBytes!);+ expect(report.unwalkedBytes).toBeLessThan(0);+ });++ it("never reads a saved file larger than 1 MB, and reads back at most 100 bots from a saved pass", () => {+ const folder = mkdtempSync(join(tmpdir(), "disk-usage-forged-"));+ dirs.push(folder);+ const file = join(folder, "storage-report.json"), progressFile = join(folder, "storage-progress.json");+ const bots = (length: number) => Array.from({ length }, (_, index) => [`bot${index}`, { bytes: 1, files: 1 }]);+ const forged = JSON.stringify({ v: 1, at: START, tookMs: 1, volume: null, totals: { walkedBytes: 9e300, bots: bots(40_000) } });+ expect(forged.length).toBeGreaterThan(SAVED_FILE_MAX_BYTES);+ writeFileSync(file, forged);+ writeFileSync(progressFile, JSON.stringify({ v: 1, startedAt: START, waitedMs: 0, savedAt: START, checkpoint: { totals: { bots: bots(40_000) }, doneRoots: [], frames: [] } }));+ expect(savedFileText(file)).toBeNull();+ expect(savedFileText(progressFile)).toBeNull();+ const disk = createDiskUsage({ roots: [{ path: folder, scope: "home" }], volume: folder, timer: false, file, progressFile, now: () => START, firstPassAfterMs: 0 });+ expect(disk.report()).toMatchObject({ at: null, running: false });+ const small = readSavedPass(JSON.stringify({ v: 1, at: START, tookMs: 1, volume: null, totals: { walkedBytes: 9e300, bots: bots(3_000) } }))!;+ expect(small.totals.bots.size).toBe(100);+ expect(small.totals.botsOverflow).toEqual({ bytes: 2_900, files: 2_900 });+ expect(small.totals.walkedBytes).toBe(0);+ expect(readSavedPass(JSON.stringify({ v: 1, at: 9e300, totals: {} }))).toBeNull();+ });+it("reads back a saved pass field by field: a name that is not a category, a known-shaped id or an allowed name is dropped", () => {const saved = readSavedPass(JSON.stringify({ v: 1, at: START, tookMs: 5, volume: { totalBytes: 10, freeBytes: "x", usedBytes: -1 }, totals: {categories: { conversations: { bytes: 5, files: 1 }, "acme-merger": { bytes: 9, files: 9 } }, bots: [["bot-known", { bytes: 3, files: 1 }], ["Ada's plans", { bytes: 1, files: 1 }]],@@ -203,6 +233,9 @@ describe("storage sampler", () => {const stopping: WalkFs = { opendir: nodeWalkFs.opendir, lstat: async (path) => { if (path.endsWith("messages.db")) void w!.disk.stop(); return nodeWalkFs.lstat(path); } };w = usage({ fs: stopping });w.advance(60_000);+ w.advance(2_000);+ await w.disk.tick();+ expect(w.disk.report()).toMatchObject({ at: null, running: false, failed: false });for (let index = 0; index < 50; index++) { w.advance(2_000); await w.disk.tick(); }expect(w.disk.report()).toMatchObject({ at: null, running: false, failed: false });});diff --git a/server/perf/disk-usage.ts b/server/perf/disk-usage.tsindex a2a3135e90..a90598184f 100644--- a/server/perf/disk-usage.ts+++ b/server/perf/disk-usage.ts@@ -4,7 +4,7 @@// is saved as it goes, so a home that sleeps by stopping goes on after each start rather than starting again. Node gives no// per-call I/O priority and re-nicing would slow the whole server, so the budget is the only throttle. Privacy invariant:// sizes, counts, fixed category names, ids of bots the store knows and names from OTHER_NAMES; never a file's contents.-import { mkdirSync, readFileSync, rmSync } from "node:fs";+import { mkdirSync, readFileSync, rmSync, statSync } from "node:fs";import { statfs } from "node:fs/promises";import { dirname, resolve } from "node:path";import { performance } from "node:perf_hooks";@@ -12,7 +12,7 @@ import { performance } from "node:perf_hooks";import { writeFileAtomic } from "../atomic.ts";import { OTHER_NAMES, STORAGE_CATEGORIES, type StorageCategory, type StorageClass } from "./disk-categories.ts";import {- checkpointFrom, createDiskWalk, totalsFrom, totalsJson, type DiskWalk, type Tally, type WalkCheckpoint, type WalkFs, type WalkRoot, type WalkSkipped, type WalkTotals,+ checkpointFrom, count, createDiskWalk, SAVED_FILE_MAX_BYTES, totalsFrom, totalsJson, type DiskWalk, type Tally, type WalkCheckpoint, type WalkFs, type WalkRoot, type WalkSkipped, type WalkTotals,} from "./disk-walk.ts";export const STORAGE_REPORT_VERSION = 1;@@ -96,7 +96,13 @@ export const PROGRESS_EVERY_MS = 60_000;/** A saved pass under way older than this starts again from nothing. */const PROGRESS_MAX_AGE_MS = 7 * 24 * 3_600_000;-const count = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);+/** A saved file's text, or null when it is missing, not a file or larger than SAVED_FILE_MAX_BYTES (never read whole). */+export function savedFileText(file: string): string | null {+ try {+ const stat = statSync(file);+ return stat.isFile() && stat.size <= SAVED_FILE_MAX_BYTES ? readFileSync(file, "utf8") : null;+ } catch { return null; }+}function savedText(completed: CompletedPass): string {const bots = [...completed.totals.bots].sort(([, a], [, b]) => b.bytes - a.bytes);@@ -114,7 +120,7 @@ export function readSavedPass(text: string): CompletedPass | null {return {at: count(saved.at), tookMs: count(saved.tookMs),volume: volume && typeof volume === "object" ? { totalBytes: count(volume.totalBytes), freeBytes: count(volume.freeBytes), usedBytes: count(volume.usedBytes) } : null,- totals: totalsFrom(saved.totals),+ totals: totalsFrom(saved.totals, SAVED_BOTS),};}@@ -143,13 +149,13 @@ export function createDiskUsage(options: DiskUsageOptions) {} catch { return null; }};let last: CompletedPass | null = null;- if (options.file) { try { last = readSavedPass(readFileSync(options.file, "utf8")); } catch {} }+ if (options.file) { const text = savedFileText(options.file); last = text === null ? null : readSavedPass(text); }const firstAt = now() + (options.firstPassAfterMs ?? FIRST_PASS_AFTER_MS);let dueAt = last && last.at <= now() ? Math.max(firstAt, last.at + everyMs) : firstAt;let walk: DiskWalk | null = null, pass: { startedAt: number; waitedMs: number; lastTickAt: number } | null = null;let failed = false, ticking = false, stopped = false, progressSavedAt = -Infinity;let resumeFrom: SavedProgress | null = null;- if (options.progressFile) { try { resumeFrom = readSavedProgress(readFileSync(options.progressFile, "utf8"), roots, now()); } catch {} }+ if (options.progressFile) { const text = savedFileText(options.progressFile); resumeFrom = text === null ? null : readSavedProgress(text, roots, now()); }if (resumeFrom) dueAt = firstAt;const write = (file: string | undefined, text: string) => {if (!file) return;@@ -160,8 +166,10 @@ export function createDiskUsage(options: DiskUsageOptions) {const checkpoint = take();if (!checkpoint) return;progressSavedAt = now();- write(options.progressFile, JSON.stringify({ v: STORAGE_REPORT_VERSION, startedAt: pass.startedAt, waitedMs: pass.waitedMs, savedAt: progressSavedAt,- checkpoint: { ...checkpoint, totals: totalsJson(checkpoint.totals) } }));+ const text = JSON.stringify({ v: STORAGE_REPORT_VERSION, startedAt: pass.startedAt, waitedMs: pass.waitedMs, savedAt: progressSavedAt,+ checkpoint: { ...checkpoint, totals: totalsJson(checkpoint.totals) } });+ // One too large to be read back is not saved, and the one before it goes: a restart then starts the pass again.+ if (Buffer.byteLength(text) <= SAVED_FILE_MAX_BYTES) write(options.progressFile, text); else forgetProgress();};const forgetProgress = () => { if (options.progressFile) { try { rmSync(options.progressFile, { force: true }); } catch {} } };let timer: ReturnType<typeof setTimeout> | null = null;@@ -213,7 +221,14 @@ export function createDiskUsage(options: DiskUsageOptions) {return {start() { if (options.timer !== false && !timer && !stopped) schedule(); },- async stop() { stopped = true; if (timer) clearTimeout(timer); timer = null; await walk?.close(); walk = null; pass = null; },+ async stop() {+ stopped = true;+ if (timer) clearTimeout(timer);+ timer = null;+ const closing = walk;+ walk = null; pass = null;+ await closing?.close();+ },tick,/** Starts a pass at the next tick, whatever the schedule says. */passNow() { if (!walk) dueAt = now(); },diff --git a/server/perf/disk-walk.test.ts b/server/perf/disk-walk.test.tsindex 4a215aaf9c..81614d96b0 100644--- a/server/perf/disk-walk.test.ts+++ b/server/perf/disk-walk.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { allocatedBytes, checkpointFrom, createDiskWalk, nodeWalkFs, totalsJson, type WalkCheckpoint, type WalkFs, type WalkRoot, type WalkStat, type WalkTotals } from "./disk-walk.ts";+import { allocatedBytes, checkpointFrom, createDiskWalk, MAX_NAME_BYTES, nodeWalkFs, totalsFrom, totalsJson, type WalkCheckpoint, type WalkFs, type WalkRoot, type WalkStat, type WalkTotals } from "./disk-walk.ts";const dirs: string[] = [];afterEach(() => {@@ -214,6 +214,27 @@ describe("disk walk", () => {}});+ it("reads back no count larger than any disk, and no more bots than its cap (the rest summed in the overflow)", () => {+ const bots = Array.from({ length: 30 }, (_, index) => [`bot${index}`, { bytes: 10, files: 1 }]);+ const totals = totalsFrom({ walkedBytes: 9e300, entries: 1e17, categories: { packages: { bytes: 9e300, files: 2 }, temp: { bytes: 1e16, files: 1 } }, bots, botsOverflow: { bytes: 5, files: 1 } }, 20);+ expect([totals.walkedBytes, totals.entries, totals.categories.packages.bytes, totals.categories.temp.bytes]).toEqual([0, 0, 0, 1e16]);+ expect(totals.bots.size).toBe(20);+ expect(totals.botsOverflow).toEqual({ bytes: 105, files: 11 });+ });++ it("keeps a checkpoint's names within MAX_NAME_BYTES a folder: one with longer names is not resumable from inside it", async () => {+ const { data, roots } = tree();+ mkdirSync(join(data, "wide"));+ for (let index = 0; index < 400; index++) mkdirSync(join(data, "wide", `${"w".repeat(200)}${index}`));+ const taken: Array<WalkCheckpoint | null> = [];+ const walk = createDiskWalk(roots, { onBoundary: (take) => { taken.push(take()); } });+ while (!(await walk.step({ entries: 1, stop: () => false })));+ for (const one of taken.filter(Boolean)) {+ for (const frame of one!.frames) expect(frame.names.reduce((sum, name) => sum + Buffer.byteLength(name) + 3, 0)).toBeLessThanOrEqual(MAX_NAME_BYTES);+ }+ expect(taken.some((one) => one === null)).toBe(true);+ });+it("refuses a saved checkpoint naming a folder outside the roots or a name with a separator", () => {const { home, roots } = tree();const totals = totalsJson(createDiskWalk(roots).totals);@@ -221,6 +242,10 @@ describe("disk walk", () => {expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: "/etc", names: ["a"] }] }, roots)).toBeNull();expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: home, names: ["../x"] }] }, roots)).toBeNull();expect(checkpointFrom({ totals, doneRoots: ["/etc"], frames: [] }, roots)).toBeNull();+ // Resolved before the check: a path through `..` is outside, or not one this server wrote.+ expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: join(home, "..", "..", "..", "etc"), names: [] }] }, roots)).toBeNull();+ expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: `${home}/data/../data`, names: [] }] }, roots)).toBeNull();+ expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: home, names: Array.from({ length: 1_000 }, (_, index) => `${"n".repeat(100)}${index}`) }] }, roots)).toBeNull();expect(checkpointFrom({ totals: { categories: { "acme-merger": { bytes: 1, files: 1 } }, bots: [["Ada's plans", { bytes: 1, files: 1 }]] }, doneRoots: [], frames: [] }, roots)?.totals.bots.size).toBe(0);});});diff --git a/server/perf/disk-walk.ts b/server/perf/disk-walk.tsindex 83f9d482b1..a9f4206776 100644--- a/server/perf/disk-walk.ts+++ b/server/perf/disk-walk.ts@@ -2,9 +2,9 @@// steps, one file-system call in flight at a time, lstat only (never a link followed, never a file opened), and never// past the root's filesystem. Memory: the open levels (at most MAX_DEPTH), the per-bot tallies (at most MAX_BOTS), the// hard links seen (at most MAX_LINKS inode numbers) and, for going on after a restart, the names already counted in-// the open folders of the top RESUME_DEPTH levels (at most MAX_NAMES each).+// the open folders of the top RESUME_DEPTH levels (at most MAX_NAMES names and MAX_NAME_BYTES each).import { lstat, opendir } from "node:fs/promises";-import { join, sep } from "node:path";+import { join, resolve, sep } from "node:path";import { OTHER_NAMES, placeChild, STORAGE_CATEGORIES, type Placement, type StorageCategory, type StorageScope } from "./disk-categories.ts";@@ -65,11 +65,18 @@ export const MAX_BOTS = 5_000;export const MAX_LINKS = 500_000;export const RESUME_DEPTH = 4;export const MAX_NAMES = 5_000;+/** The names one open folder keeps for a checkpoint, in all: a saved pass stays under SAVED_FILE_MAX_BYTES. */+export const MAX_NAME_BYTES = 64 * 1024;+/** A saved pass or report larger than this is never read: it is not one this server wrote. */+export const SAVED_FILE_MAX_BYTES = 1024 * 1024;+/** No byte or file count read back is larger than this (10 PB, the Admin's own bound); a larger one reads as 0. */+export const MAX_COUNT = 1e16;interface Frame {path: string; segments: string[]; placement: Placement; scope: StorageScope; dev: number; dir: WalkDir | null;- /** Names counted directly in it so far, for a checkpoint; null past MAX_NAMES or below the top levels. */+ /** Names counted directly in it so far, for a checkpoint; null past MAX_NAMES or MAX_NAME_BYTES, or below the top levels. */names: string[] | null;+ nameBytes: number;/** Names a resumed pass counted before the restart. */skip: ReadonlySet<string> | null;}@@ -93,7 +100,8 @@ export function allocatedBytes(stat: Pick<WalkStat, "size" | "blocks">, windows}const BOT_ID = /^[A-Za-z0-9_-]{1,64}$/;-const count = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);+/** A count read back from a saved file: a finite number from 0 to MAX_COUNT, else 0. */+export const count = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_COUNT ? value : 0);const tallyOf = (value: unknown): Tally => ({ bytes: count((value as Tally | null)?.bytes), files: count((value as Tally | null)?.files) });/** Totals as JSON values (maps as pairs). */@@ -103,18 +111,28 @@ export function totalsJson(totals: WalkTotals): Record<string, unknown> {otherUnlisted: { ...totals.otherUnlisted }, skipped: { ...totals.skipped } };}-/** Totals read back field by field: a name that is not a category, a bot-id-shaped id or an allowed other name is dropped. */-export function totalsFrom(value: unknown): WalkTotals {+/** Totals read back field by field: a name that is not a category, a bot-id-shaped id or an allowed other name is dropped,+ * and bots past `maxBots` are added to the overflow. */+export function totalsFrom(value: unknown, maxBots = MAX_BOTS): WalkTotals {const totals = (value ?? {}) as Record<string, unknown>;const categories = (totals.categories ?? {}) as Record<string, unknown>;- const pairs = (list: unknown, keep: (name: string) => boolean) =>- new Map((Array.isArray(list) ? list : []).flatMap((pair) => (Array.isArray(pair) && typeof pair[0] === "string" && keep(pair[0]) ? [[pair[0], tallyOf(pair[1])] as const] : [])));+ const overflow = tallyOf(totals.botsOverflow);+ const pairs = (list: unknown, keep: (name: string) => boolean, cap: number) => {+ const kept = new Map<string, Tally>();+ for (const pair of Array.isArray(list) ? list : []) {+ if (!Array.isArray(pair) || typeof pair[0] !== "string" || !keep(pair[0]) || kept.has(pair[0])) continue;+ const tally = tallyOf(pair[1]);+ if (kept.size < cap) kept.set(pair[0], tally);+ else { overflow.bytes += tally.bytes; overflow.files += tally.files; }+ }+ return kept;+ };const skipped = (totals.skipped ?? {}) as Record<string, unknown>;const unlisted = (totals.otherUnlisted ?? {}) as Record<string, unknown>;return {categories: Object.fromEntries((Object.keys(STORAGE_CATEGORIES) as StorageCategory[]).map((name) => [name, tallyOf(categories[name])])) as WalkTotals["categories"],- bots: pairs(totals.bots, (id) => BOT_ID.test(id)), botsOverflow: tallyOf(totals.botsOverflow),- otherNamed: pairs(totals.otherNamed, (name) => OTHER_NAMES.has(name)), otherUnlisted: { ...tallyOf(unlisted), entries: count(unlisted.entries) },+ bots: pairs(totals.bots, (id) => BOT_ID.test(id), maxBots), botsOverflow: overflow,+ otherNamed: pairs(totals.otherNamed, (name) => OTHER_NAMES.has(name), OTHER_NAMES.size), otherUnlisted: { ...tallyOf(unlisted), entries: count(unlisted.entries) },skipped: { unreadable: count(skipped.unreadable), otherDevice: count(skipped.otherDevice), tooDeep: count(skipped.tooDeep), vanished: count(skipped.vanished), links: count(skipped.links) },walkedBytes: count(totals.walkedBytes), entries: count(totals.entries), linksCapped: totals.linksCapped === true,linksUncheckedBytes: count(totals.linksUncheckedBytes), resumes: count(totals.resumes),@@ -127,11 +145,14 @@ const NAME = (name: unknown): name is string => typeof name === "string" && nameexport function checkpointFrom(value: unknown, roots: readonly WalkRoot[]): WalkCheckpoint | null {const saved = value as { totals?: unknown; doneRoots?: unknown; frames?: unknown } | null;if (!saved || typeof saved !== "object" || !Array.isArray(saved.frames) || !Array.isArray(saved.doneRoots)) return null;- const inRoots = (path: unknown): path is string => typeof path === "string" && roots.some((root) => path === root.path || path.startsWith(root.path + sep));+ // Resolved before the check: `<root>/../etc` is not under the root, and a path that resolves elsewhere is not one this server wrote.+ const inRoots = (path: unknown): path is string => typeof path === "string" && resolve(path) === path+ && roots.some((root) => path === root.path || path.startsWith(root.path + sep));if (saved.frames.length > RESUME_DEPTH + 1 || !saved.doneRoots.every((path) => roots.some((root) => root.path === path))) return null;const frames: WalkCheckpoint["frames"] = [];for (const frame of saved.frames as Array<{ path?: unknown; names?: unknown }>) {- if (!inRoots(frame?.path) || !Array.isArray(frame.names) || frame.names.length > MAX_NAMES || !frame.names.every(NAME)) return null;+ if (!inRoots(frame?.path) || !Array.isArray(frame.names) || frame.names.length > MAX_NAMES || !frame.names.every(NAME)+ || frame.names.reduce((sum, name) => sum + Buffer.byteLength(name) + 3, 0) > MAX_NAME_BYTES) return null;frames.push({ path: frame.path, names: [...frame.names] });}return { totals: totalsFrom(saved.totals), doneRoots: [...saved.doneRoots as string[]], frames };@@ -184,11 +205,13 @@ export function createDiskWalk(roots: readonly WalkRoot[], options: DiskWalkOpticonst counted = (frame: Frame, name: string) => {if (!frame.names) return;frame.names.push(name);- if (frame.names.length > MAX_NAMES) frame.names = null;+ frame.nameBytes += Buffer.byteLength(name) + 3;+ if (frame.names.length > MAX_NAMES || frame.nameBytes > MAX_NAME_BYTES) frame.names = null;};const newFrame = (path: string, segments: string[], placement: Placement, scope: StorageScope, dev: number): Frame => {const skip = resumed.get(path) ?? null;- return { path, segments, placement, scope, dev, dir: null, names: segments.length < RESUME_DEPTH ? [...skip ?? []] : null, skip };+ const names = segments.length < RESUME_DEPTH ? [...skip ?? []] : null;+ return { path, segments, placement, scope, dev, dir: null, names, nameBytes: (names ?? []).reduce((sum, name) => sum + Buffer.byteLength(name) + 3, 0), skip };};const checkpoint = (): WalkCheckpoint | null => {if (!stack.every((frame) => frame.names !== null)) return null;