Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud home: cap the tool cache folders (delete only through open folders, never while a bot works), behind OMB_CACHE_SWEEP (off) (#7139)
Milind Soni868a4746d4a6
diff --git a/docs/bot-box.md b/docs/bot-box.mdindex efb3372c74..b151489b30 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -115,6 +115,60 @@ lands in one folder, `cache` in the box's HOME, instead of all over it:- **Box off, no change.** A Cloud whose box is off (`OMB_BOT_BOX=0`, or no working bubblewrap) runs its bots unboxedwith today's environment.+### Tool caches: the cap++`server/cache-sweep/`, behind `OMB_CACHE_SWEEP`. It is off by default; `1`/`on` turns it on, and only on a Cloud+home. With it off, nothing is read, started or deleted: no state file is read, no timer starts, and the two admin routes+are not there. With it on, making it at start reads nothing either; its first tick is 5 minutes after the server answers.++- **Caps.** The smaller of 10 GB and 15% of the volume (`limits.ts`), once for the tools' cache folders and once for the+ app's own `<data folder>/cache`. On a Team Cloud the tools' cap is split evenly between the cache folders there (the+ server's HOME and each audience's engine home), so one member's caches never push out another's. Overrides:+ `OMB_CACHE_CAP_TOOLS` and `OMB_CACHE_CAP_APP`, in bytes or as `4G`, `512M`.+- **Which folders.** Only a tools root the server made (its `CACHEDIR.TAG`, above), and only while the tools' switch is+ on and the bot box is live. In it, only these whole folders, by fixed name: `npm`, `pip`, `uv`, `huggingface/hub`,+ `huggingface/xet`, `bun`. Nothing else in a root is counted, listed or touched: not a+ person's own folder, not `huggingface/token`, and no browser's folder ever (a Playwright MCP profile holds cookies and+ sign-ins). In the app's own folder: each old `node-compile/<version>`, never the running server's.+- **Least recently written first.** A folder's age is its newest modification or change time. Access times are not+ used: a backup that reads the whole volume would refresh them. A folder written in the last 30 minutes stays. A+ folder that alone is over its root's cap is left and logged once, and not counted, so it does not empty the others on+ every pass; only a clear or the emergency pass removes it, so the cap does not bound such a folder (a Hugging Face+ hub with one large model is the likely one). `npm` goes whole: every npx-installed MCP server goes with it, and npx+ fetches each again the next time it starts it.+- **Never while a bot works.** In a tools root, nothing is deleted while a turn runs, an engine is kept warm, or any+ process the server started (directly or inside a box) uses that root: its working folder, program, open files, mapped+ files or environment name a path in it (`in-use.ts`, from `/proc`). Every bot process is one of the server's+ descendants (`--unshare-pid` and `--die-with-parent` keep even a bot's daemon in its box's tree), and every boxed+ process carries its HOME's cache variables, so any process a bot of that HOME started counts. A descendant that cannot+ be read counts as using every root (logged once); a process the server did not start is not looked at. This is checked+ before each folder goes. A busy home is tried again on the next tick, 5 minutes later; a pass that finishes waits an+ hour. The turn and warm-engine check is for the whole Cloud: on a Team Cloud one member's turn holds every root's+ pass (a process seen in one root holds only that root). Any long-lived bot process holds the cap for its root for as+ long as it runs: a dev server or a watcher a bot left running, an MCP server an engine keeps open. Nothing there is+ removed until it ends. A folder about to go is first renamed inside its own parent (below), so a tool that starts+ meanwhile finds it missing, not half there. What each tool then does with a missing cache folder is its own behaviour:+ npm, pip, uv and bun are expected to fetch again what they need; this was not tested for each.+- **Never outside the root.** Every walk and removal goes through open folders (`tree.ts`): the root is opened with+ `O_NOFOLLOW`, and each step names one child of an open folder through `/proc/self/fd/<fd>/<name>`, so the kernel+ resolves it from that open folder, never again by path. A link is never entered (`O_NOFOLLOW`), a folder on another+ filesystem is never entered, and `unlink`/`rmdir` act on the link itself. A folder above that a bot swaps for a link+ changes nothing. A folder about to go is renamed to `.omb-trash-<random>` in the same open parent (never moved+ elsewhere, never put back), then emptied and removed; whatever a removal that stopped part-way left under that name,+ the next pass in that root finishes the same way (a link there is removed as a link). A walk goes at most 128 folders+ deep, so a bot's endlessly nested folders cannot use up the server's open files or memory; what lies deeper stays.+ This needs Linux; anywhere else nothing is walked or deleted.+- **Emergency.** At 95% of the volume used, the tools' folders go, least recently written first, until it is under 90%,+ under the same rule: if a bot is working, nothing is removed, and one line is logged (the Admin's disk auto-grow and+ its alert cover a full disk). A pass that measured is not repeated within 30 minutes.+- **On demand.** `clearCaches({ dryRun, scope })` returns the bytes and folders that go, or would in a dry run, and how+ many roots were left because a bot was working. Its admin-scope route is `POST /api/caches/clear`, a dry run unless the+ body says `"dryRun": false`; `GET /api/caches` returns the counters. Both only with the switch on.+- **Counters.** `<data folder>/cache-sweep.json` (any shape reads; written whole by rename) keeps the cleared and+ emergency counters and the last pass; the storage report carries them once read.+- **Not touched.** The scattered caches from before the tools' folder (`~/.npm`, `~/.cache/*`, `~/go/pkg/mod`, …) are left+ for a separate cleanup.+## The self-check and the reportAt boot, and by hand with `node dist-server/bot-box/box-check.js`, the server runs `box-probe.ts` inside a real boxdiff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex d9b94e7589..c87b72c5fc 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -14,7 +14,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE","OMB_BROWSER_CGROUP", "OMB_BROWSER_CONNECTION", "OMB_BROWSER_HOLD_IDLE_MS", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL","OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_MEMORY_MAX", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING",- "OMB_BUG_REPORT_URL", "OMB_CACHE_ROOT", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",+ "OMB_BUG_REPORT_URL", "OMB_CACHE_CAP_APP", "OMB_CACHE_CAP_TOOLS", "OMB_CACHE_ROOT", "OMB_CACHE_SWEEP", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT","OMB_CLAUDE_INHERIT_USER_CONFIG", "OMB_CLAUDE_SESSION_IDLE_", "OMB_CLI_OWNER_STDIN", "OMB_CLI_PREFIX", "OMB_CLINE_PROVIDER","OMB_CLOUDFLARED_PATH", "OMB_CLOUD_", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_AI_TOKEN", "OMB_CLOUD_AI_URL","OMB_CLOUD_BOAT_TOKEN", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_CLOUD_CAPS_DROPPED",diff --git a/server/cache-sweep/host.ts b/server/cache-sweep/host.tsnew file mode 100644index 0000000000..f975d37b97--- /dev/null+++ b/server/cache-sweep/host.ts@@ -0,0 +1,32 @@+// The server's one cache sweeper: the only place that reads HOME, the environment, the bot box and the running server's+// compile cache folder for it (sweeper.ts and units.ts take every path as an argument). Making it reads nothing from disk.+import { getCompileCacheDir } from "node:module";+import { homedir } from "node:os";+import { resolve } from "node:path";++import { botBox } from "../bot-box/box.ts";+import { toolCachesOn } from "../bot-box/tool-caches.ts";+import { audienceHomes } from "../engine-homes/layout.ts";+import type { StorageReport } from "../perf/disk-usage.ts";+import { botEngineSessions } from "../procs.ts";+import { createCacheSweeper, volumeOf, type CacheSweeper } from "./sweeper.ts";++/** The storage report with the cache cap's counters, once the sweeper has read them. */+export function withCacheCounters(report: StorageReport | null, sweeper: Pick<CacheSweeper, "counters">): StorageReport | null {+ const caches = sweeper.counters();+ return report && caches ? { ...report, caches } : report;+}++/** An engine process of a bot's lives (a turn, or one kept warm between turns): the sweeper waits. */+export const botEnginesLive = (): boolean => botEngineSessions().live.size > 0;++export function createCacheSweepHost(dataDir: string, env: Record<string, string | undefined> = process.env, home: string = homedir()): CacheSweeper {+ return createCacheSweeper({+ dataDir, home, env,+ // Only while the box is live do bots' tools write there (bot-box/tool-caches.ts); with it off they run unboxed.+ tools: () => toolCachesOn(env) && botBox.enabled(),+ audienceHomes: () => audienceHomes(dataDir),+ keep: () => { const own = getCompileCacheDir?.(); return own ? [resolve(own)] : []; },+ volume: volumeOf,+ });+}diff --git a/server/cache-sweep/in-use.ts b/server/cache-sweep/in-use.tsnew file mode 100644index 0000000000..fe14d2f695--- /dev/null+++ b/server/cache-sweep/in-use.ts@@ -0,0 +1,68 @@+// Which cache folders a live process uses (Linux's /proc). Only the server's own descendants are looked at: every bot+// process is one (a box is the server's child, and `--unshare-pid` with `--die-with-parent` keeps whatever a bot starts,+// even a daemon, inside that box's tree), so a process the server did not start cannot be a bot's. A descendant whose+// working folder, program, root, open files, mapped files or environment (a tool cache variable, PATH, VIRTUAL_ENV, …)+// names a path in a root uses it. A boxed bot's every process carries its HOME's tool cache variables+// (bot-box/tool-caches.ts), so any process a bot of that HOME started counts. The sweeper deletes in a root only when none+// does (sweeper.ts). A descendant it cannot read counts as using every root: then nothing is deleted.+import { readFile, readdir, readlink } from "node:fs/promises";+import { join } from "node:path";++const code = (error: unknown) => (error as NodeJS.ErrnoException)?.code ?? "";+const gone = (error: unknown) => code(error) === "ENOENT" || code(error) === "ESRCH";+const names = (path: string) => (value: string) => value === path || value.startsWith(`${path}/`);++/** The parent of each process, from /proc/<pid>/stat (readable for every process). */+async function parents(proc: string, pids: readonly string[]): Promise<Map<number, number>> {+ const map = new Map<number, number>();+ for (const pid of pids) {+ const stat = await readFile(join(proc, pid, "stat"), "utf8").catch(() => "");+ // "pid (name, which may hold spaces or parentheses) state ppid …"+ const ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(" ")[1]);+ if (Number.isInteger(ppid)) map.set(Number(pid), ppid);+ }+ return map;+}++/** The descendants of `self` among `parent`. */+function descendants(parent: ReadonlyMap<number, number>, self: number): number[] {+ const children = new Map<number, number[]>();+ for (const [pid, ppid] of parent) children.set(ppid, [...(children.get(ppid) ?? []), pid]);+ const found = new Set<number>(), queue = [...(children.get(self) ?? [])];+ while (queue.length) {+ const pid = queue.pop()!;+ if (found.has(pid) || pid === self) continue;+ found.add(pid);+ queue.push(...(children.get(pid) ?? []));+ }+ return [...found];+}++/** The roots of `roots` that a descendant of `self` uses. `proc` is /proc (a test passes a folder shaped like it). */+export async function rootsInUse(roots: readonly string[], options: { proc?: string; self?: number; unreadable?: (pid: number) => void; using?: (pid: number, root: string) => void } = {}): Promise<Set<string>> {+ const proc = options.proc ?? "/proc", self = options.self ?? process.pid;+ const used = new Set<string>();+ let pids: string[];+ try { pids = (await readdir(proc)).filter((name) => /^\d+$/.test(name)); } catch { return new Set(roots); }+ for (const pid of descendants(await parents(proc, pids), self)) {+ if (used.size === roots.length) break;+ const dir = join(proc, String(pid));+ try {+ const paths: string[] = [];+ for (const link of ["cwd", "exe", "root"]) paths.push(await readlink(join(dir, link)).catch((error: unknown) => { if (gone(error)) return ""; throw error; }));+ const fds = await readdir(join(dir, "fd")).catch((error: unknown) => { if (gone(error)) return [] as string[]; throw error; });+ for (const fd of fds) paths.push(await readlink(join(dir, "fd", fd)).catch(() => ""));+ const maps = await readFile(join(dir, "maps"), "utf8").catch((error: unknown) => { if (gone(error)) return ""; throw error; });+ for (const line of maps.split("\n")) { const at = line.indexOf("/"); if (at >= 0) paths.push(line.slice(at).replace(/ \(deleted\)$/, "")); }+ const environ = await readFile(join(dir, "environ"), "utf8").catch((error: unknown) => { if (gone(error)) return ""; throw error; });+ for (const entry of environ.split("\0")) { const at = entry.indexOf("="); if (at > 0) paths.push(...entry.slice(at + 1).split(":")); }+ for (const root of roots) if (!used.has(root) && paths.some(names(root))) { used.add(root); options.using?.(pid, root); }+ } catch (error) {+ if (gone(error)) continue;+ // The server's own descendant, and it cannot be read: it may be using any of them.+ options.unreadable?.(pid);+ return new Set(roots);+ }+ }+ return used;+}diff --git a/server/cache-sweep/limits.ts b/server/cache-sweep/limits.tsnew file mode 100644index 0000000000..6c674a48c7--- /dev/null+++ b/server/cache-sweep/limits.ts@@ -0,0 +1,55 @@+// The cache cap's numbers and switches, in one place (docs/bot-box.md, "Tool caches"). The cap is the smaller of 10 GB and+// 15% of the volume, per root group (the tools' cache folders, split evenly between a Team Cloud's audiences, and the+// app's own cache folder): 15% leaves a small Cloud (10 GB) 1.5 GB of caches, enough for a few projects' packages, and+// 10 GB keeps a large disk's caches from crowding out the work it was bought for. Everything in these folders is+// downloaded or computed again.+import { cloudRole } from "../bot-box/detect.ts";++export const GIB = 1024 ** 3;+/** The cap: the smaller of this and CAP_SHARE of the volume. */+export const CAP_MAX_BYTES = 10 * GIB;+export const CAP_SHARE = 0.15;+/** At this share of the volume used, the tools' caches are removed, least recently written first, until it is under+ * EMERGENCY_TARGET, but only while no bot process is alive (sweeper.ts). */+export const EMERGENCY_FULL = 0.95;+export const EMERGENCY_TARGET = 0.9;+/** An entry changed this recently may be a download or an install that just finished: no pass removes it. */+export const RECENT_MS = 30 * 60_000;+/** A full sweep (measure, then remove the least recently written over the cap) at most this often. */+export const SWEEP_EVERY_MS = 60 * 60_000;+/** The sweeper's tick: it looks at the disk for the emergency pass, and runs a sweep that is due, or that a busy home put+ * off, so a busy home is tried again within minutes, not an hour. */+export const TICK_EVERY_MS = 5 * 60_000;+/** After an emergency pass removed something, the next waits this long. */+export const EMERGENCY_BACKOFF_MS = 30 * 60_000;+/** Work per tick, then a pause, so the event loop and the disk stay free for turns. */+export const TICK_ENTRIES = 5_000;+export const YIELD_EVERY = 200;+export const TICK_PAUSE_MS = 1_000;++/** The switch: 1, on, true or yes on a Cloud home starts the sweeper and the admin routes; off, nothing is read, started or+ * deleted, and the routes are not there. */+export const CACHE_SWEEP_SWITCH = "OMB_CACHE_SWEEP";+/** Cap overrides, in bytes or with a K, M, G or T suffix (powers of 1024). */+export const TOOL_CAP_ENV = "OMB_CACHE_CAP_TOOLS";+export const APP_CAP_ENV = "OMB_CACHE_CAP_APP";++const ON = new Set(["1", "on", "true", "yes"]);++export function cacheSweepOn(env: Record<string, string | undefined>): boolean {+ return cloudRole(env) && ON.has((env[CACHE_SWEEP_SWITCH] ?? "").trim().toLowerCase());+}++/** `10G`, `512M`, `2000000`: bytes, or null for anything else. */+export function parseSize(raw: string | undefined): number | null {+ const match = /^(\d+(?:\.\d+)?)\s*([KMGT]?)i?B?$/i.exec(raw?.trim() ?? "");+ if (!match) return null;+ const power = ["", "K", "M", "G", "T"].indexOf(match[2]!.toUpperCase());+ const bytes = Math.floor(Number(match[1]) * 1024 ** power);+ return Number.isFinite(bytes) && bytes >= 0 ? bytes : null;+}++/** The cap for a volume of `volumeBytes`: the override when it parses, else the smaller of CAP_MAX_BYTES and CAP_SHARE. */+export function capBytes(volumeBytes: number, override?: string): number {+ return parseSize(override) ?? Math.floor(Math.min(CAP_MAX_BYTES, CAP_SHARE * volumeBytes));+}diff --git a/server/cache-sweep/sweeper.linux.test.ts b/server/cache-sweep/sweeper.linux.test.tsnew file mode 100644index 0000000000..7421a22de8--- /dev/null+++ b/server/cache-sweep/sweeper.linux.test.ts@@ -0,0 +1,417 @@+// The cache cap on real folders, where it can delete: Linux (a Cloud home, CI's Linux runner). Elsewhere it skips, as the+// sweeper itself deletes nothing there. Every path, the "outside" ones too, lives under each test's own temporary folder.+import { spawn, spawnSync } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { CACHE_TAG, CACHE_TAG_FILE, toolCacheRoot } from "../bot-box/tool-caches.ts";+import { rootsInUse } from "./in-use.ts";+import { GIB } from "./limits.ts";+import { createCacheSweeper, type CacheSweeperDeps } from "./sweeper.ts";+import { Pacer, close } from "./tree.ts";+import { measureUnit, openRoot, removeUnit, type Unit } from "./units.ts";++const DAY = 24 * 60 * 60_000;+// Ahead of the files' change times (which a test cannot set), so only the modification times set here decide.+const NOW = Date.now() + 40 * DAY;+const KB = 1024;+const dirs: string[] = [];+const children: Array<ReturnType<typeof spawn>> = [];+afterEach(() => {+ for (const child of children.splice(0)) child.kill("SIGKILL");+ for (const dir of dirs.splice(0)) { spawnSync("chmod", ["-R", "u+w", dir]); rmSync(dir, { recursive: true, force: true }); }+});++function fixture() {+ const root = realpathSync(mkdtempSync(join(tmpdir(), "omb-cache-sweep-")));+ dirs.push(root);+ const home = join(root, "home"), dataDir = join(home, ".openmausbot");+ mkdirSync(dataDir, { recursive: true });+ const tools = tagged(home);+ return { root, home, dataDir, tools, app: join(dataDir, "cache") };+}++/** A HOME's cache folder as the server makes it (bot-box/tool-caches.ts ensureToolCacheRoot). */+function tagged(home: string): string {+ const root = toolCacheRoot(home);+ mkdirSync(root, { recursive: true });+ writeFileSync(join(root, CACHE_TAG_FILE), CACHE_TAG);+ return root;+}++/** A file of `kb` KB whose folders up to `stop` were last written `daysOld` days before NOW. */+function put(path: string, kb: number, daysOld: number, stop: string): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, Buffer.alloc(kb * KB, 1));+ const at = new Date(NOW - daysOld * DAY);+ for (let p = path; p.startsWith(stop) && p !== stop; p = dirname(p)) utimesSync(p, at, at);+}++const ON = { OMB_CLOUD_ROLE: "home", OMB_CACHE_SWEEP: "on" };+const cmdline = (pid: number) => { try { return readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ").slice(0, 200); } catch { return "?"; } };+const ROOMY = async () => ({ total: 100 * GIB, free: 50 * GIB });++function sweeper(f: ReturnType<typeof fixture>, overrides: Partial<CacheSweeperDeps> & { busy?: () => boolean } = {}) {+ const lines: string[] = [];+ const made = createCacheSweeper({+ dataDir: f.dataDir, home: f.home, env: ON, tools: () => true, audienceHomes: () => [], keep: () => [],+ volume: ROOMY, inUse: async () => new Set(), now: () => NOW,+ pace: { entries: 1_000_000, yieldEvery: 50, pauseMs: 0 }, log: (line) => lines.push(line), ...overrides,+ });+ // The server starts it once it answers (start-upkeep.ts); the timer itself is not needed here.+ made.start(overrides.busy ?? (() => false));+ made.stop();+ return { made, lines };+}+const withCap = (cap: string) => ({ env: { ...ON, OMB_CACHE_CAP_TOOLS: cap } });++describe.skipIf(process.platform !== "linux")("the cache cap on real folders", () => {+ it("keeps a root under its cap, removing whole folders, least recently written first", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "http", "a"), 200, 9, f.tools);+ put(join(f.tools, "npm", "_npx", "1a2b", "x"), 100, 7, f.tools);+ put(join(f.tools, "npm", "_cacache", "content", "y"), 200, 5, f.tools);+ put(join(f.tools, "uv", "wheels", "z"), 200, 2, f.tools);+ put(join(f.tools, "bun", "w"), 200, 1, f.tools);+ const { made } = sweeper(f, withCap("600K"));+ const result = await made.sweep();+ expect(result).toMatchObject({ busy: false });+ expect(readdirSync(f.tools).sort()).toEqual([CACHE_TAG_FILE, "bun", "uv"]);+ expect((await made.report()).cacheCleared).toMatchObject({ count: 1, entries: 2 });+ });++ it("under the cap, removes nothing; a folder written in the last 30 minutes stays even over it", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ expect(await sweeper(f).made.sweep()).toMatchObject({ busy: false });+ expect(existsSync(join(f.tools, "pip", "a"))).toBe(true);+ put(join(f.tools, "uv", "old"), 100, 20, f.tools);+ put(join(f.tools, "uv", "new"), 100, 1 / (24 * 60), f.tools);+ await sweeper(f, withCap("250K")).made.sweep();+ expect(existsSync(join(f.tools, "uv", "old"))).toBe(true);+ expect(existsSync(join(f.tools, "pip"))).toBe(false);+ });++ it("a folder alone over the cap is left and not counted, so the others are not emptied every pass", async () => {+ const f = fixture();+ put(join(f.tools, "uv", "big"), 600, 2, f.tools);+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ put(join(f.tools, "bun", "b"), 100, 1, f.tools);+ const { made, lines } = sweeper(f, withCap("300K"));+ await made.sweep();+ await made.sweep();+ for (const name of ["uv/big", "pip/a", "bun/b"]) expect(existsSync(join(f.tools, name)), name).toBe(true);+ expect(lines.filter((line) => line.includes("uv alone is"))).toHaveLength(1);+ });++ it("a person's own folder in the root is neither counted nor touched, by the sweep, the emergency pass or a clear", async () => {+ const f = fixture();+ put(join(f.tools, "my-scraped-data", "big.bin"), 2000, 30, f.tools);+ put(join(f.tools, "huggingface", "token"), 1, 30, f.tools);+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ await sweeper(f, withCap("300K")).made.sweep();+ expect(existsSync(join(f.tools, "pip", "a"))).toBe(true);+ let full = true;+ const { made } = sweeper(f, { volume: async () => ({ total: 100, free: full ? 1 : 50 }) });+ await made.emergency();+ full = false;+ expect(existsSync(join(f.tools, "pip"))).toBe(false);+ put(join(f.tools, "uv", "a"), 100, 9, f.tools);+ await sweeper(f).made.clearCaches({ dryRun: false });+ expect(existsSync(join(f.tools, "uv"))).toBe(false);+ expect(existsSync(join(f.tools, "my-scraped-data", "big.bin"))).toBe(true);+ expect(existsSync(join(f.tools, "huggingface", "token"))).toBe(true);+ });++ it("a browser's folder is never removed: a Playwright MCP profile with its cookies and sign-ins stays", async () => {+ const f = fixture();+ put(join(f.tools, "ms-playwright", "chromium-1140", "chrome"), 300, 20, f.tools);+ put(join(f.tools, "ms-playwright", "mcp-chrome-1a2b3c", "Default", "Cookies"), 10, 20, f.tools);+ put(join(f.tools, "ms-playwright", "mcp-chromium-1a2b3c", "Default", "Login Data"), 10, 20, f.tools);+ put(join(f.tools, "puppeteer", "chrome", "x"), 300, 20, f.tools);+ await sweeper(f, withCap("1K")).made.sweep();+ await sweeper(f, { volume: async () => ({ total: 100, free: 1 }) }).made.emergency();+ await sweeper(f).made.clearCaches({ dryRun: false });+ expect(existsSync(join(f.tools, "ms-playwright", "mcp-chrome-1a2b3c", "Default", "Cookies"))).toBe(true);+ expect(existsSync(join(f.tools, "ms-playwright", "mcp-chromium-1a2b3c", "Default", "Login Data"))).toBe(true);+ expect(existsSync(join(f.tools, "ms-playwright", "chromium-1140", "chrome"))).toBe(true);+ expect(existsSync(join(f.tools, "puppeteer", "chrome", "x"))).toBe(true);+ });++ it("a cache folder the server did not make is never looked into, nor one that is a link", async () => {+ const f = fixture();+ rmSync(join(f.tools, CACHE_TAG_FILE));+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ const { made, lines } = sweeper(f);+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0, refusedRoots: [{ path: f.tools }] });+ writeFileSync(join(f.tools, CACHE_TAG_FILE), "Signature: 8a477f597d28d172789f06886806bc55\n");+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0 });+ expect(existsSync(join(f.tools, "pip", "a"))).toBe(true);+ expect(lines.filter((line) => line.includes("not made by the server"))).toHaveLength(1);+ // The folder a link would name is tagged and full: still never reached through the link.+ const elsewhere = join(f.root, "elsewhere-home");+ const target = tagged(elsewhere);+ put(join(target, "pip", "a"), 100, 9, target);+ rmSync(f.tools, { recursive: true });+ symlinkSync(target, f.tools);+ expect(await sweeper(f).made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0 });+ expect(existsSync(join(target, "pip", "a"))).toBe(true);+ });++ it("with the box off (or the tools' switch off), the tools' folders are not touched", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ expect(await sweeper(f, { tools: () => false }).made.clearCaches({ dryRun: false, scope: "all" })).toMatchObject({ entries: 0 });+ expect(existsSync(join(f.tools, "pip", "a"))).toBe(true);+ });++ it("never deletes while a bot works: a turn or a warm engine, or a process using the root; tried again on the next tick", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ put(join(f.tools, "uv", "a"), 100, 2, f.tools);+ let working = true, using = false, full = true;+ const inUse = async (roots: readonly string[]) => new Set(using ? roots : []);+ const { made, lines } = sweeper(f, { ...withCap("150K"), busy: () => working, inUse, volume: async () => ({ total: 100 * GIB, free: full ? 1 * GIB : 50 * GIB }) });+ expect(await made.sweep()).toEqual({ skipped: "busy" });+ expect(await made.emergency()).toMatchObject({ entries: 0, busy: 1 });+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0, busy: 1 });+ working = false; using = true;+ expect(await made.sweep()).toMatchObject({ busy: true });+ expect(await made.emergency()).toMatchObject({ entries: 0, busy: 1 });+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0, busy: 1 });+ expect(existsSync(join(f.tools, "pip", "a"))).toBe(true);+ expect(lines.filter((line) => line.includes("a bot is working, so no cache was removed"))).toHaveLength(1);+ expect((await made.report()).lastSweep).toBeNull();+ // The next tick (minutes later, not an hour) finds the home idle and does the pass it put off.+ using = false; full = false;+ await made.tick();+ expect(existsSync(join(f.tools, "pip"))).toBe(false);+ expect(existsSync(join(f.tools, "uv", "a"))).toBe(true);+ expect((await made.report()).lastSweep).toMatchObject({ at: NOW });+ });++ it("a real process working in the root (its working folder there) holds every deletion until it ends", async () => {+ const f = fixture();+ put(join(f.tools, "uv", "archive-v0", "env", "lib.py"), 10, 9, f.tools);+ const child = spawn("sleep", ["60"], { cwd: join(f.tools, "uv", "archive-v0", "env"), stdio: "ignore" });+ children.push(child);+ const exited = new Promise((done) => child.once("exit", done));+ await new Promise((done) => child.once("spawn", done));+ const lines: string[] = [];+ const made = createCacheSweeper({ dataDir: f.dataDir, home: f.home, env: ON, tools: () => true, audienceHomes: () => [], keep: () => [], volume: ROOMY, now: () => NOW, log: (line) => lines.push(line) });+ made.start(() => false);+ made.stop();+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0, busy: 1 });+ expect(existsSync(join(f.tools, "uv", "archive-v0", "env", "lib.py"))).toBe(true);+ child.kill("SIGKILL");+ await exited;+ // A process of this user that cannot be read, or another one in the root, would hold it: the message names it.+ const holders: string[] = [];+ await rootsInUse([f.tools], { unreadable: (pid) => holders.push(`unreadable ${pid} ${cmdline(pid)}`), using: (pid) => holders.push(`using ${pid} ${cmdline(pid)}`) });+ expect(await made.clearCaches({ dryRun: false }), [...holders, ...lines].join("\n")).toMatchObject({ entries: 1, busy: 0 });+ expect(existsSync(join(f.tools, "uv"))).toBe(false);+ });++ it("the emergency pass removes the least recently written until the disk is under 90%, then waits", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ put(join(f.tools, "uv", "a"), 100, 3, f.tools);+ const volume = async () => ({ total: 100, free: existsSync(join(f.tools, "pip")) ? 4 : 15 });+ const { made, lines } = sweeper(f, { volume });+ expect(await made.emergency()).toMatchObject({ entries: 1 });+ expect(existsSync(join(f.tools, "pip"))).toBe(false);+ expect(existsSync(join(f.tools, "uv", "a"))).toBe(true);+ expect(lines.some((line) => line.includes("96% full: removed 1"))).toBe(true);+ expect((await made.report()).emergency).toMatchObject({ count: 1, at: NOW });+ expect(await sweeper(f, { volume: async () => ({ total: 100, free: 50 }) }).made.emergency()).toEqual({ skipped: "room" });+ });++ it("a Team Cloud: each audience's root has its share of the cap, and a process in one member's root does not hold another's", async () => {+ const f = fixture();+ const ana = join(f.dataDir, "engine-homes", "member-a"), ben = join(f.dataDir, "engine-homes", "member-b");+ const anaRoot = tagged(ana), benRoot = tagged(ben);+ for (const root of [anaRoot, benRoot]) { put(join(root, "pip", "a"), 150, 9, root); put(join(root, "uv", "a"), 150, 2, root); }+ // Three roots (the server's HOME, ana, ben): 600K split three ways is 200K each, and ana and ben each hold about 310K.+ const { made } = sweeper(f, { ...withCap("600K"), audienceHomes: () => [ana, ben], inUse: async (roots) => new Set(roots.filter((root) => root === benRoot)) });+ expect(await made.sweep()).toMatchObject({ busy: true });+ expect(existsSync(join(anaRoot, "pip"))).toBe(false);+ expect(existsSync(join(anaRoot, "uv", "a"))).toBe(true);+ expect(existsSync(join(benRoot, "pip", "a"))).toBe(true);+ });++ it("the app's own folder: old Node compile caches go, the running server's and anything else stay", async () => {+ const f = fixture();+ put(join(f.app, "node-compile", "v24.1.0-x64-aaaa", "f"), 10, 9, f.app);+ put(join(f.app, "node-compile", "v24.2.0-x64-bbbb", "f"), 10, 9, f.app);+ put(join(f.app, "storage-report.json"), 1, 9, f.app);+ const { made } = sweeper(f, { keep: () => [join(f.app, "node-compile", "v24.2.0-x64-bbbb")] });+ expect(await made.clearCaches({ dryRun: true, scope: "app" })).toMatchObject({ entries: 1 });+ expect(existsSync(join(f.app, "node-compile", "v24.1.0-x64-aaaa"))).toBe(true);+ expect(await made.clearCaches({ dryRun: false, scope: "app" })).toMatchObject({ entries: 1 });+ expect(readdirSync(join(f.app, "node-compile"))).toEqual(["v24.2.0-x64-bbbb"]);+ expect(existsSync(join(f.app, "storage-report.json"))).toBe(true);+ });++ it("a read-only tree is removed, made writable through its own folders", async () => {+ const f = fixture();+ put(join(f.tools, "uv", "archive-v0", "a"), 10, 9, f.tools);+ chmodSync(join(f.tools, "uv", "archive-v0", "a"), 0o444);+ chmodSync(join(f.tools, "uv", "archive-v0"), 0o555);+ chmodSync(join(f.tools, "uv"), 0o555);+ expect(await sweeper(f).made.clearCaches({ dryRun: false })).toMatchObject({ entries: 1, partial: 0 });+ expect(readdirSync(f.tools)).toEqual([CACHE_TAG_FILE]);+ });++ it("a folder goes out of sight first: renamed in its own root, never put back; what a stopped removal left is finished next time", async () => {+ const f = fixture();+ put(join(f.tools, ".omb-trash-0a0b0c", "uv", "x"), 10, 9, f.tools);+ put(join(f.tools, "huggingface", ".omb-trash-0d0e0f", "models--o--m", "x"), 10, 9, f.tools);+ const outside = join(f.root, "outside");+ put(join(outside, "keep"), 1, 9, f.root);+ symlinkSync(outside, join(f.tools, ".omb-trash-1a1b1c"));+ put(join(f.tools, "pip", "a"), 10, 9, f.tools);+ expect(await sweeper(f).made.clearCaches({ dryRun: false })).toMatchObject({ entries: 1, partial: 0 });+ expect(readdirSync(f.tools).sort()).toEqual([CACHE_TAG_FILE, "huggingface"]);+ expect(readdirSync(join(f.tools, "huggingface"))).toEqual([]);+ expect(existsSync(join(outside, "keep"))).toBe(true);+ });++ it("folders nested far deeper than any tool's are not followed to the end: the walk stops at 128 and says so", async () => {+ const f = fixture();+ const chain = (levels: number) => join(f.tools, "uv", ...Array.from({ length: levels }, () => "d"));+ mkdirSync(chain(200), { recursive: true });+ writeFileSync(join(chain(200), "bottom"), "x");+ const { made } = sweeper(f);+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 1, partial: 1 });+ // What lies past the limit stays, under the renamed folder, and only that.+ const left = readdirSync(f.tools).filter((name) => name.startsWith(".omb-trash-"));+ expect(left).toHaveLength(1);+ expect(existsSync(join(f.tools, "uv"))).toBe(false);+ // A shallower tree goes whole.+ mkdirSync(chain(100), { recursive: true });+ writeFileSync(join(chain(100), "bottom"), "x");+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 1, partial: 0 });+ });++ it("a time in the state file later than now (a clock set back) does not hold off a pass", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ put(join(f.tools, "uv", "a"), 100, 2, f.tools);+ writeFileSync(join(f.dataDir, "cache-sweep.json"), JSON.stringify({ lastSweep: { at: NOW + DAY, roots: {} }, emergency: { count: 1, bytes: 1, at: NOW + DAY } }));+ const { made } = sweeper(f, { ...withCap("150K"), volume: async () => ({ total: 100 * GIB, free: 50 * GIB }) });+ await made.tick();+ expect(existsSync(join(f.tools, "pip"))).toBe(false);+ const full = sweeper(f, { volume: async () => ({ total: 100, free: 1 }) }).made;+ expect(await full.emergency()).not.toEqual({ skipped: "backoff" });+ });++ it("a state file of any shape: every pass still runs, and it is replaced whole", async () => {+ const f = fixture();+ put(join(f.tools, "pip", "a"), 100, 9, f.tools);+ writeFileSync(join(f.dataDir, "cache-sweep.json"), '{"measured":null,"cleared":null}');+ const { made } = sweeper(f, withCap("1K"));+ expect(await made.sweep()).toMatchObject({ busy: false });+ expect(readdirSync(f.dataDir).filter((name) => name.startsWith("cache-sweep"))).toEqual(["cache-sweep.json"]);+ });+});++describe.skipIf(process.platform !== "linux")("never outside the root", () => {+ /** The bot's unit, and a folder outside every root that a bot names: another member's engine home. */+ function scene() {+ const f = fixture();+ const victim = join(f.dataDir, "engine-homes", "member-0000000000000000");+ put(join(victim, "abcd", "transcript.jsonl"), 1, 30, f.dataDir);+ put(join(f.tools, "npm", "_npx", "abcd", "x"), 1, 30, f.tools);+ return { ...f, victim };+ }+ const unit: Unit = { group: "tools", root: "", name: "npm" };+ const opened = async (f: ReturnType<typeof fixture>) => {+ const result = await openRoot({ group: "tools", path: f.tools }, [f.home, f.dataDir]);+ if (!result || !("folder" in result)) throw new Error("root not opened");+ return result.folder;+ };++ it("a unit swapped for a link between the check and the removal: nothing is removed, and the folder it names stays", async () => {+ const f = scene();+ const folder = await opened(f);+ try {+ expect(await measureUnit(folder, unit, new Pacer())).toMatchObject({ files: 4 });+ renameSync(join(f.tools, "npm"), join(f.tools, "npm-real"));+ symlinkSync(f.victim, join(f.tools, "npm"));+ expect(await removeUnit(folder, unit, new Pacer())).toBeNull();+ } finally { await close(folder); }+ expect(existsSync(join(f.victim, "abcd", "transcript.jsonl"))).toBe(true);+ expect(existsSync(join(f.tools, "npm-real", "_npx", "abcd", "x"))).toBe(true);+ });++ it("a folder inside the unit that is a link is removed as a link, never followed", async () => {+ const f = scene();+ rmSync(join(f.tools, "npm", "_npx"), { recursive: true });+ symlinkSync(f.victim, join(f.tools, "npm", "_npx"));+ const folder = await opened(f);+ try { expect(await removeUnit(folder, unit, new Pacer())).toMatchObject({ partial: false }); } finally { await close(folder); }+ expect(existsSync(join(f.tools, "npm"))).toBe(false);+ expect(existsSync(join(f.victim, "abcd", "transcript.jsonl"))).toBe(true);+ });++ it("the whole root swapped for a link after it was opened: the removal stays in the folder it opened", async () => {+ const f = scene();+ const folder = await opened(f);+ try {+ renameSync(f.tools, `${f.tools}-moved`);+ symlinkSync(f.victim, f.tools);+ mkdirSync(join(f.victim, "npm"));+ writeFileSync(join(f.victim, "npm", "keep"), "theirs");+ expect(await removeUnit(folder, unit, new Pacer())).toMatchObject({ partial: false });+ } finally { await close(folder); }+ expect(existsSync(join(`${f.tools}-moved`, "npm"))).toBe(false);+ expect(existsSync(join(f.victim, "npm", "keep"))).toBe(true);+ expect(existsSync(join(f.victim, "abcd", "transcript.jsonl"))).toBe(true);+ });++ it("a bot flipping folders for links to a folder outside while the unit is deleted never reaches it (20 runs)", async () => {+ const f = fixture();+ const precious = join(f.root, "precious");+ for (let j = 0; j < 100; j++) put(join(precious, `p${j}`), 1, 30, f.root);+ const racer = join(f.root, "racer.mjs");+ // The racer swaps each d<i> for a link to `precious` and back, as fast as it can, in the unit or the name it was+ // renamed to on its way out, until neither is there.+ writeFileSync(racer, `+ import { readdirSync, renameSync, symlinkSync, unlinkSync, existsSync } from "node:fs";+ import { join } from "node:path";+ const [root, name, precious] = process.argv.slice(2);+ const target = () => {+ if (existsSync(join(root, name))) return join(root, name);+ const trash = readdirSync(root).find((entry) => entry.startsWith(".omb-trash-"));+ return trash ? join(root, trash) : null;+ };+ process.send?.("ready");+ for (let unit = target(); unit; unit = target()) {+ for (let i = 0; i < 200; i++) {+ const d = join(unit, "d" + i);+ try { renameSync(d, d + ".r"); } catch { continue; }+ try { symlinkSync(precious, d); } catch {}+ try { unlinkSync(d); } catch {}+ try { renameSync(d + ".r", d); } catch {}+ }+ }+ `);+ for (let run = 0; run < 20; run++) {+ const unitPath = join(f.tools, "uv");+ for (let i = 0; i < 200; i++) for (let j = 0; j < 5; j++) put(join(unitPath, `d${i}`, `f${j}`), 1, 30, f.tools);+ const child = spawn(process.execPath, [racer, f.tools, "uv", precious], { stdio: ["ignore", "ignore", "ignore", "ipc"] });+ children.push(child);+ // It ends by itself once the unit is gone, maybe before the kill below.+ const exited = new Promise((done) => child.once("exit", done));+ await new Promise((done) => child.once("message", done));+ const folder = await opened(f);+ try { await removeUnit(folder, { group: "tools", root: f.tools, name: "uv" }, new Pacer()); } finally { await close(folder); }+ child.kill("SIGKILL");+ await exited;+ expect(readdirSync(precious), `run ${run}`).toHaveLength(100);+ for (const name of readdirSync(f.tools)) if (name === "uv" || name.startsWith(".omb-trash-")) rmSync(join(f.tools, name), { recursive: true, force: true });+ }+ }, 120_000);+});diff --git a/server/cache-sweep/sweeper.test.ts b/server/cache-sweep/sweeper.test.tsnew file mode 100644index 0000000000..a07b2a78ee--- /dev/null+++ b/server/cache-sweep/sweeper.test.ts@@ -0,0 +1,242 @@+// The cache cap's rules that hold on every system: the switch, the numbers, the state file, which processes count as+// using a root, and that nothing is ever walked or deleted off Linux. What it deletes, and that it never leaves a root,+// is in sweeper.linux.test.ts and tree.linux.test.ts. Every path lives under each test's own temporary folder.+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { CACHE_TAG, CACHE_TAG_FILE, TOOL_CACHES, toolCacheRoot } from "../bot-box/tool-caches.ts";+import type { StorageReport } from "../perf/disk-usage.ts";+import { requiredScope } from "../request-auth.ts";+import { CACHES_CLEAR_PATH, CACHES_PATH, createCachesRoutes } from "../routes/caches.ts";+import { PASS } from "../routes/table.ts";+import { withCacheCounters } from "./host.ts";+import { rootsInUse } from "./in-use.ts";+import { GIB, capBytes, cacheSweepOn, parseSize } from "./limits.ts";+import { CACHE_SWEEP_STATE, CacheSweepOff, createCacheSweeper, parseState, type CacheSweeperDeps } from "./sweeper.ts";+import { anchoredSupported } from "./tree.ts";+import { TOOL_UNITS, expectedRoots } from "./units.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+const scratch = (prefix = "omb-cache-sweep-") => { const dir = mkdtempSync(join(tmpdir(), prefix)); dirs.push(dir); return dir; };++function fixture() {+ const root = scratch();+ const home = join(root, "home"), dataDir = join(home, ".openmausbot");+ mkdirSync(dataDir, { recursive: true });+ const tools = toolCacheRoot(home);+ mkdirSync(join(tools, "pip"), { recursive: true });+ writeFileSync(join(tools, CACHE_TAG_FILE), CACHE_TAG);+ writeFileSync(join(tools, "pip", "wheel"), "x".repeat(10_000));+ return { root, home, dataDir, tools };+}++const ON = { OMB_CLOUD_ROLE: "home", OMB_CACHE_SWEEP: "on" };++function sweeper(f: ReturnType<typeof fixture>, overrides: Partial<CacheSweeperDeps> = {}) {+ const lines: string[] = [];+ const made = createCacheSweeper({+ dataDir: f.dataDir, home: f.home, env: ON, tools: () => true, audienceHomes: () => [], keep: () => [],+ volume: async () => ({ total: 100 * GIB, free: 1 * GIB }), inUse: async () => new Set(),+ pace: { entries: 1_000_000, yieldEvery: 50, pauseMs: 0 }, log: (line) => lines.push(line), ...overrides,+ });+ return { made, lines };+}++describe("limits", () => {+ it("the cap is the smaller of 10 GB and 15% of the volume, unless overridden", () => {+ expect(capBytes(10 * GIB)).toBe(Math.floor(1.5 * GIB));+ expect(capBytes(80 * GIB)).toBe(10 * GIB);+ expect(capBytes(80 * GIB, "4G")).toBe(4 * GIB);+ expect(capBytes(80 * GIB, "nonsense")).toBe(10 * GIB);+ expect(parseSize("512M")).toBe(512 * 1024 ** 2);+ expect(parseSize("2000")).toBe(2000);+ expect(parseSize("1.5GiB")).toBe(Math.floor(1.5 * GIB));+ });++ it("the switch is on only on a Cloud home that sets it", () => {+ expect(cacheSweepOn({})).toBe(false);+ expect(cacheSweepOn({ OMB_CACHE_SWEEP: "on" })).toBe(false);+ expect(cacheSweepOn({ OMB_CLOUD_ROLE: "home" })).toBe(false);+ expect(cacheSweepOn(ON)).toBe(true);+ expect(cacheSweepOn({ OMB_CLOUD_ROLE: "team", OMB_CACHE_SWEEP: "1" })).toBe(true);+ });+});++describe("what may ever be removed", () => {+ it("only whole tool folders the box routes a tool to, by fixed name, and never a browser's", () => {+ const routed = new Set(TOOL_CACHES.map((cache) => cache.folder));+ for (const name of TOOL_UNITS) expect(routed.has(name), name).toBe(true);+ for (const name of TOOL_UNITS) expect(name).not.toMatch(/playwright|puppeteer|chrom|browser|mcp/i);+ for (const name of ["go-mod", "go-build", "corepack"]) expect(TOOL_UNITS).not.toContain(name);+ });++ it("the tools' roots only while their folders are in use (the switch and a live box); the app's own always", () => {+ const input = { home: "/data", dataDir: "/data/.openmausbot", audienceHomes: ["/data/.openmausbot/engine-homes/member-a"] };+ expect(expectedRoots({ ...input, tools: false }).map((root) => root.group)).toEqual(["app"]);+ expect(expectedRoots({ ...input, tools: true }).filter((root) => root.group === "tools")).toHaveLength(2);+ });++ it("off Linux nothing is walked or deleted", () => {+ expect(anchoredSupported("linux")).toBe(true);+ for (const platform of ["darwin", "win32", "freebsd"] as const) expect(anchoredSupported(platform)).toBe(false);+ });++ it("where it cannot delete by open folders, every pass and every clear removes nothing", async () => {+ const f = fixture();+ const { made, lines } = sweeper(f, { supported: () => false });+ made.start(() => false);+ made.stop();+ expect(await made.sweep()).toEqual({ skipped: "unsupported" });+ expect(await made.emergency()).toEqual({ skipped: "unsupported" });+ expect(await made.clearCaches({ dryRun: false })).toMatchObject({ entries: 0, unsupported: true });+ expect(readFileSync(join(f.tools, "pip", "wheel"), "utf8")).toHaveLength(10_000);+ expect(lines.filter((line) => line.includes("needs Linux"))).toHaveLength(1);+ });+});++describe("switch off: nothing at all", () => {+ it("making it reads nothing; off, start reads nothing, starts no timer, and a real clear is refused", async () => {+ const f = fixture();+ writeFileSync(join(f.dataDir, CACHE_SWEEP_STATE), JSON.stringify({ cleared: { count: 7 } }));+ const reads: string[] = [];+ const readText = async (path: string) => { reads.push(path); return readFileSync(path, "utf8"); };+ const off = sweeper(f, { env: { OMB_CLOUD_ROLE: "home" }, readText });+ off.made.start(() => false);+ await new Promise((done) => setImmediate(done));+ expect(reads).toEqual([]);+ expect(off.lines).toEqual([]);+ expect(off.made.counters()).toBeNull();+ expect(await off.made.sweep()).toEqual({ skipped: "off" });+ expect(await off.made.emergency()).toEqual({ skipped: "off" });+ await expect(off.made.clearCaches({ dryRun: false })).rejects.toBeInstanceOf(CacheSweepOff);+ expect(existsSync(join(f.tools, "pip", "wheel"))).toBe(true);+ // On, making it still reads nothing: the counters come once it is started (after the server answers), read once.+ const on = sweeper(f, { readText });+ await new Promise((done) => setImmediate(done));+ expect(reads).toEqual([]);+ expect(on.made.counters()).toBeNull();+ on.made.start(() => true);+ on.made.stop();+ await on.made.report();+ expect(on.made.counters()).toMatchObject({ cacheCleared: { count: 7 } });+ expect(reads).toEqual([join(f.dataDir, CACHE_SWEEP_STATE)]);+ });++ it("the storage report is unchanged until the counters are read", () => {+ const report = { v: 1, at: 1 } as unknown as StorageReport;+ expect(withCacheCounters(report, { counters: () => null })).toBe(report);+ expect(withCacheCounters(null, { counters: () => ({ cacheCleared: { count: 1, bytes: 2, entries: 1, at: 3, reason: "r" }, emergency: { count: 0, bytes: 0, at: null } }) })).toBeNull();+ expect(withCacheCounters(report, { counters: () => ({ cacheCleared: { count: 1, bytes: 2, entries: 1, at: 3, reason: "r" }, emergency: { count: 0, bytes: 0, at: null } }) })).toMatchObject({ caches: { cacheCleared: { count: 1 } } });+ });+});++describe("the state file", () => {+ it("any shape reads as counters, never an error", () => {+ for (const text of ['{"measured":null}', '{"cleared":null}', "[1,2]", "null", '{"emergency":{"at":"x"}}', "not json", "", '{"lastSweep":{"at":"x"}}', '{"cleared":{"count":-1,"bytes":"9"}}']) {+ const state = parseState(text);+ expect(state.cleared).toEqual({ count: 0, bytes: 0, entries: 0, at: null, reason: null });+ expect(state.emergency.at).toBeNull();+ expect(state.lastSweep).toBeNull();+ }+ expect(parseState('{"cleared":{"count":2,"bytes":5,"entries":1,"at":9,"reason":"r"},"lastSweep":{"at":4,"roots":{}}}')).toMatchObject({ cleared: { count: 2, bytes: 5, at: 9, reason: "r" }, lastSweep: { at: 4 } });+ });++ it("a broken state file does not stop a pass or the report", async () => {+ const f = fixture();+ writeFileSync(join(f.dataDir, CACHE_SWEEP_STATE), '{"measured":null,"cleared":null}');+ const { made } = sweeper(f, { supported: () => false });+ expect(await made.report()).toMatchObject({ on: true, cacheCleared: { count: 0 } });+ });+});++describe("which roots a live process uses (/proc)", () => {+ /** A folder shaped like /proc: one process per entry, with its links, maps and environment. */+ function proc(processes: Record<string, { parent?: number; cwd?: string; exe?: string; fds?: string[]; maps?: string; environ?: Record<string, string> }>) {+ const dir = scratch("omb-proc-");+ for (const [pid, info] of Object.entries(processes)) {+ const at = join(dir, pid);+ mkdirSync(join(at, "fd"), { recursive: true });+ // The name may hold spaces and parentheses; the parent is the field after the last one.+ writeFileSync(join(at, "stat"), `${pid} (a (b) c) S ${info.parent ?? 1} ${pid} 0 0 -1`);+ symlinkSync(info.cwd ?? "/", join(at, "cwd"));+ symlinkSync(info.exe ?? "/usr/bin/node", join(at, "exe"));+ symlinkSync("/", join(at, "root"));+ (info.fds ?? []).forEach((target, fd) => symlinkSync(target, join(at, "fd", String(fd))));+ writeFileSync(join(at, "maps"), info.maps ?? "");+ writeFileSync(join(at, "environ"), Object.entries(info.environ ?? {}).map(([name, value]) => `${name}=${value}`).join("\0"));+ }+ return dir;+ }+ const personal = "/data/cache", member = "/data/.openmausbot/engine-homes/member-a/cache";++ it.skipIf(process.platform === "win32")("a process whose working folder, program, open file, mapped file or environment names a path in a root uses it", async () => {+ const cases: Array<[string, Parameters<typeof proc>[0][string]]> = [+ ["cwd", { cwd: `${personal}/uv/archive-v0/abc` }],+ ["exe", { exe: `${personal}/npm/_npx/1a2b/node_modules/.bin/server` }],+ ["fd", { fds: ["/dev/null", `${personal}/pip/http-v2/x`] }],+ ["maps", { maps: `7f00-7f01 r-xp 0 00:1 2 ${personal}/uv/archive-v0/abc/lib.so (deleted)\n` }],+ ["environ", { environ: { npm_config_cache: `${personal}/npm`, HOME: "/data" } }],+ ["PATH", { environ: { PATH: `/usr/bin:${personal}/uv/archive-v0/abc/bin` } }],+ ];+ for (const [name, info] of cases) expect([...await rootsInUse([personal, member], { proc: proc({ 100: info }), self: 1 })], name).toEqual([personal]);+ });++ it.skipIf(process.platform === "win32")("not: a process elsewhere, a folder whose name only starts the same, the server itself, one the server did not start", async () => {+ const dir = proc({+ 100: { cwd: "/data/projects/site", environ: { HOME: "/data", PATH: "/usr/bin" } },+ 101: { cwd: "/data/cache-old/x", environ: { X: "/data/cachefile" } },+ 102: { cwd: `${personal}/npm` },+ 103: { parent: 50, cwd: `${member}/uv` },+ });+ expect([...await rootsInUse([personal, member], { proc: dir, self: 102 })]).toEqual([]);+ expect([...await rootsInUse([personal, member], { proc: dir, self: 1 })]).toEqual([personal]);+ // A grandchild (a box's process, or what a bot started inside it) counts.+ const tree = proc({ 200: { parent: 1 }, 201: { parent: 200 }, 202: { parent: 201, cwd: `${member}/pip` } });+ expect([...await rootsInUse([member], { proc: tree, self: 1 })]).toEqual([member]);+ expect([...await rootsInUse([member], { proc: tree, self: 7 })]).toEqual([]);+ });++ it("no /proc to read: every root counts as used", async () => {+ expect([...await rootsInUse([personal], { proc: join(scratch(), "missing") })]).toEqual([personal]);+ });+});++describe("the admin API", () => {+ const call = async (made: Parameters<typeof createCachesRoutes>[0], method: string, path: string, body?: unknown) => {+ const sent: Array<{ status: number; body: unknown }> = [];+ const answer = await createCachesRoutes(made)({+ req: {} as never, res: { setHeader() {} } as never, url: new URL(`http://127.0.0.1${path}`), path, method, auth: {} as never,+ json: ((_res: unknown, status: number, payload: unknown) => { sent.push({ status, body: payload }); }) as never,+ readBody: (async () => { if (body instanceof Error) throw body; return body; }) as never,+ });+ return answer === PASS ? "pass" : sent[0];+ };++ it("is not there with the switch off, or off a Cloud home: the routes pass, as if absent", async () => {+ const f = fixture();+ for (const env of [{}, { OMB_CLOUD_ROLE: "home" }, { OMB_CACHE_SWEEP: "on" }]) {+ const made = sweeper(f, { env }).made;+ expect(await call(made, "GET", CACHES_PATH)).toBe("pass");+ expect(await call(made, "POST", CACHES_CLEAR_PATH, { dryRun: false })).toBe("pass");+ }+ expect(existsSync(join(f.tools, "pip", "wheel"))).toBe(true);+ });++ it("needs the admin scope for both paths", () => {+ expect(requiredScope("GET", CACHES_PATH)).toBe("admin");+ expect(requiredScope("POST", CACHES_CLEAR_PATH)).toBe("admin");+ });++ it("POST is a dry run unless the body says dryRun false, and a broken body is a dry run", async () => {+ const asked: Array<{ dryRun?: boolean; scope?: string }> = [];+ const fake = { available: () => true, report: async () => ({}) as never, clearCaches: async (options: { dryRun?: boolean; scope?: "tools" | "app" | "all" } = {}) => { asked.push(options); return { dryRun: options.dryRun !== false } as never; } };+ await call(fake, "POST", CACHES_CLEAR_PATH, {});+ await call(fake, "POST", CACHES_CLEAR_PATH, new Error("bad json"));+ await call(fake, "POST", CACHES_CLEAR_PATH, { dryRun: "false", scope: "nope" });+ await call(fake, "POST", CACHES_CLEAR_PATH, { dryRun: false, scope: "tools" });+ expect(asked).toEqual([{ dryRun: true, scope: "all" }, { dryRun: true, scope: "all" }, { dryRun: true, scope: "all" }, { dryRun: false, scope: "tools" }]);+ });+});diff --git a/server/cache-sweep/sweeper.ts b/server/cache-sweep/sweeper.tsnew file mode 100644index 0000000000..4366ca2bae--- /dev/null+++ b/server/cache-sweep/sweeper.ts@@ -0,0 +1,341 @@+// The cache cap (docs/bot-box.md, "Tool caches: the cap"): behind OMB_CACHE_SWEEP (off), a background sweeper keeps each+// tools' cache root, and the app's own cache folder, under its cap, removing whole folders, least recently written first+// (units.ts). What makes it safe:+// - it deletes only through open folders inside a root (tree.ts), from a fixed list of whole tool folders, so it can+// never reach anything outside the root, whatever a bot swaps in (structural, not a timing guard);+// - in a tools root it deletes only while no turn runs, no engine is kept warm, and no live process uses that root+// (in-use.ts), checked again before each folder; a turn that starts while a large folder is being removed may still+// see it half gone (the tool downloads it again), so this protects running work, it does not guarantee it. A busy+// home is tried again on the next tick;+// - the emergency pass at EMERGENCY_FULL and a clear on request obey the same rule: a busy home is left as it is, with+// one log line (the Admin's disk auto-grow and its alert cover a full disk);+// - a folder about to go is renamed first, inside its own open parent, and never put back (tree.ts): a later pass+// finishes what a removal that stopped part-way left.+// With the switch off nothing is read, started or deleted: no state file read, no timer, no routes.+import { readFile, rename, statfs, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { APP_CAP_ENV, EMERGENCY_BACKOFF_MS, EMERGENCY_FULL, EMERGENCY_TARGET, SWEEP_EVERY_MS, TICK_EVERY_MS, TOOL_CAP_ENV, capBytes, cacheSweepOn } from "./limits.ts";+import { rootsInUse } from "./in-use.ts";+import { Pacer, anchoredSupported, close, recent, type Folder, type Pace, type Tally } from "./tree.ts";+import { expectedRoots, finishLeftovers, listUnits, measureUnit, openRoot, removeUnit, type CacheGroup, type Root, type Unit } from "./units.ts";++export const CACHE_SWEEP_STATE = "cache-sweep.json";++export interface CacheSweeperDeps {+ dataDir: string;+ home: string;+ /** The switches and cap overrides (OMB_CACHE_SWEEP, OMB_CACHE_CAP_TOOLS, OMB_CACHE_CAP_APP). */+ env: Record<string, string | undefined>;+ /** The tools' cache folders are in use now: their switch is on and the bot box is live (read at every pass). */+ tools: () => boolean;+ audienceHomes: () => readonly string[];+ /** Compile cache folders never removed: the running server's own. */+ keep: () => readonly string[];+ volume: (path: string) => Promise<{ total: number; free: number }>;+ /** The roots a live process uses (in-use.ts rootsInUse). */+ inUse?: (roots: readonly string[]) => Promise<Set<string>>;+ /** Whether this system can delete by open folders (tree.ts); only Linux. */+ supported?: () => boolean;+ now?: () => number;+ /** Reads the state file (a test counts the reads). */+ readText?: (path: string) => Promise<string>;+ pace?: Pace;+ log?: (line: string) => void;+}++export interface Cleared { count: number; bytes: number; entries: number; at: number | null; reason: string | null }+interface RootSummary { group: CacheGroup; bytes: number; cap: number; removed: number; freed: number; tooBig: string[]; busy: boolean }+interface State {+ cleared: Cleared;+ emergency: { count: number; bytes: number; at: number | null };+ lastSweep: { at: number; roots: Record<string, RootSummary> } | null;+}++export interface ClearResult {+ dryRun: boolean;+ /** Bytes and whole folders removed, or that would be in a dry run. */+ bytes: number;+ entries: number;+ files: number;+ /** Written in the last RECENT_MS: left. */+ recent: number;+ /** A tools root a live process uses: nothing in it was removed. */+ busy: number;+ /** Removed only in part (something stayed where it was). */+ partial: number;+ refusedRoots: Array<{ path: string; reason: string }>;+ /** This system cannot delete safely (not Linux): nothing was walked. */+ unsupported?: true;+}++export class CacheSweepOff extends Error {+ constructor() { super("The cache cap is off on this server (OMB_CACHE_SWEEP), so nothing is deleted."); }+}++const empty = (): State => ({ cleared: { count: 0, bytes: 0, entries: 0, at: null, reason: null }, emergency: { count: 0, bytes: 0, at: null }, lastSweep: null });+const record = (value: unknown): Record<string, unknown> => (value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {});+const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);+const time = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);++/** The state file's counters, whatever shape it has: anything unreadable is a fresh start for that part. */+export function parseState(text: string): State {+ let raw: Record<string, unknown>;+ try { raw = record(JSON.parse(text)); } catch { return empty(); }+ const cleared = record(raw.cleared), emergency = record(raw.emergency), last = record(raw.lastSweep);+ return {+ cleared: { count: count(cleared.count), bytes: count(cleared.bytes), entries: count(cleared.entries), at: time(cleared.at), reason: typeof cleared.reason === "string" ? cleared.reason : null },+ emergency: { count: count(emergency.count), bytes: count(emergency.bytes), at: time(emergency.at) },+ lastSweep: time(last.at) === null ? null : { at: time(last.at)!, roots: record(last.roots) as Record<string, RootSummary> },+ };+}++export async function volumeOf(path: string): Promise<{ total: number; free: number }> {+ const stat = await statfs(path);+ return { total: Number(stat.blocks) * Number(stat.bsize), free: Number(stat.bavail) * Number(stat.bsize) };+}++const usedShare = (volume: { total: number; free: number }) => (volume.total > 0 ? 1 - volume.free / volume.total : 0);++export function createCacheSweeper(deps: CacheSweeperDeps) {+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((line: string) => console.log(line));+ const inUse = deps.inUse ?? ((roots: readonly string[]) => rootsInUse(roots, {+ unreadable: (pid) => once("unreadable", `cache sweep: process ${pid}, which the server started, cannot be read, so no tool cache is removed while such a process runs (said once)`),+ using: (pid, root) => once(`using:${root}`, `cache sweep: process ${pid} uses ${root}, so nothing there is removed while a process does (said once)`),+ }));+ const supported = deps.supported ?? (() => anchoredSupported());+ const stateFile = join(deps.dataDir, CACHE_SWEEP_STATE);+ const on = () => cacheSweepOn(deps.env);+ let state: State | null = null;+ let running: Promise<unknown> | null = null;+ let timer: NodeJS.Timeout | null = null;+ /** A turn runs or an engine is kept warm (start-upkeep.ts). Until the sweeper is started, the home counts as busy. */+ let globalBusy: () => boolean = () => true;+ let busyLoggedAt: number | null = null;+ /** When the emergency pass last measured, so a disk that stays full is not walked again every tick. */+ let emergencyTriedAt: number | null = null;+ let loading: Promise<State> | null = null;+ const said = new Set<string>();+ /** A time from the state file, or null when it is later than now (a clock that went back must not hold a pass off). */+ const past = (at: number | null) => (at !== null && at <= now() ? at : null);+ const once = (key: string, line: string) => { if (!said.has(key)) { said.add(key); log(line); } };++ const load = (): Promise<State> => {+ loading ??= (deps.readText ?? ((path: string) => readFile(path, "utf8")))(stateFile).catch(() => "").then((text) => (state = parseState(text)));+ return loading;+ };+ const save = async () => {+ if (!state) return;+ const temporary = `${stateFile}.${process.pid}.tmp`;+ await writeFile(temporary, JSON.stringify(state)).then(() => rename(temporary, stateFile)).catch((error: unknown) => log(`cache sweep: could not save ${CACHE_SWEEP_STATE}: ${error instanceof Error ? error.message : String(error)}`));+ };+ const counted = async (reason: string, bytes: number, entries: number) => {+ const current = await load();+ current.cleared = { count: current.cleared.count + 1, bytes: current.cleared.bytes + bytes, entries: current.cleared.entries + entries, at: now(), reason };+ await save();+ };++ /** The open roots of `scope`. The caller closes them. */+ const openRoots = async (scope: "tools" | "app" | "all") => {+ const opened: Array<{ root: Root; folder: Folder }> = [];+ const refused: Array<{ path: string; reason: string }> = [];+ for (const root of expectedRoots({ home: deps.home, dataDir: deps.dataDir, audienceHomes: deps.audienceHomes(), tools: deps.tools() })) {+ if (scope !== "all" && root.group !== scope) continue;+ const result = await openRoot(root, [deps.home, deps.dataDir]);+ if (!result) continue;+ if ("refused" in result) { refused.push({ path: root.path, reason: result.refused }); once(`refused:${root.path}`, `cache sweep: left ${root.path} alone: ${result.refused}`); continue; }+ opened.push({ root, folder: result.folder });+ }+ return { opened, refused };+ };+ const closeAll = async (opened: ReadonlyArray<{ folder: Folder }>) => { for (const { folder } of opened) await close(folder); };++ /** A tools root may be deleted in only while nothing is alive that could write it or run from it. */+ const busy = async (root: Root): Promise<boolean> => root.group === "tools" && (globalBusy() || (await inUse([root.path])).has(root.path));++ const measured = async (root: Root, folder: Folder, pacer: Pacer) => {+ const entries: Array<{ unit: Unit; tally: Tally }> = [];+ for (const unit of await listUnits(root, folder, deps.keep())) {+ const tally = await measureUnit(folder, unit, pacer);+ if (tally) entries.push({ unit, tally });+ }+ return entries;+ };+ const oldestFirst = (entries: ReadonlyArray<{ unit: Unit; tally: Tally }>) =>+ entries.filter((entry) => !recent(entry.tally, now())).sort((a, b) => a.tally.newest - b.tally.newest);++ /** One pass over every root: the folders that alone exceed their root's cap are left (and logged) and not counted; the+ * rest are removed, least recently written first, while the root is over its cap. A busy tools root is not touched. */+ const sweep = async (): Promise<{ skipped: string } | NonNullable<State["lastSweep"]> & { busy: boolean }> => {+ if (!on()) return { skipped: "off" };+ if (!supported()) { once("unsupported", "cache sweep: deleting by open folders needs Linux; nothing is removed here"); return { skipped: "unsupported" }; }+ if (globalBusy()) return { skipped: "busy" };+ const current = await load();+ const { opened } = await openRoots("all");+ const pacer = new Pacer(deps.pace);+ const roots: Record<string, RootSummary> = {};+ let anyBusy = false;+ try {+ const volume = await deps.volume(deps.dataDir);+ const toolRoots = opened.filter((entry) => entry.root.group === "tools").length;+ for (const { root, folder } of opened) {+ // The tools' cap is shared evenly by a Team Cloud's audiences, so one member's caches never push out another's.+ const cap = root.group === "tools" ? Math.floor(capBytes(volume.total, deps.env[TOOL_CAP_ENV]) / Math.max(1, toolRoots)) : capBytes(volume.total, deps.env[APP_CAP_ENV]);+ const summary: RootSummary = { group: root.group, bytes: 0, cap, removed: 0, freed: 0, tooBig: [], busy: false };+ roots[root.path] = summary;+ if (await busy(root)) { summary.busy = anyBusy = true; continue; }+ await finishLeftovers(root, folder, pacer);+ const entries = await measured(root, folder, pacer);+ const fits = entries.filter((entry) => {+ if (entry.tally.bytes <= cap) return true;+ summary.tooBig.push(entry.unit.name);+ once(`too-big:${root.path}/${entry.unit.name}`, `cache sweep: ${root.path}/${entry.unit.name} alone is ${entry.tally.bytes} bytes, over the cap of ${cap}: left as it is (a clear removes it)`);+ return false;+ });+ let bytes = fits.reduce((sum, entry) => sum + entry.tally.bytes, 0);+ for (const entry of oldestFirst(fits)) {+ if (bytes <= cap) break;+ if (await busy(root)) { summary.busy = anyBusy = true; break; }+ const removed = await removeUnit(folder, entry.unit, pacer);+ if (!removed) continue;+ bytes -= entry.tally.bytes;+ summary.removed += 1;+ summary.freed += removed.bytes;+ if (removed.partial) log(`cache sweep: ${root.path}/${entry.unit.name} was removed only in part; what stayed is left where it is`);+ }+ summary.bytes = Math.max(0, bytes);+ if (summary.removed) await counted(`over the ${root.group === "tools" ? "tools'" : "app's"} cap`, summary.freed, summary.removed);+ }+ } finally {+ await closeAll(opened);+ }+ const result = { at: now(), roots };+ // A busy root's pass is not done: the next tick tries again.+ if (!anyBusy) { current.lastSweep = result; await save(); }+ return { ...result, busy: anyBusy };+ };++ /** At EMERGENCY_FULL of the volume, removes the tools' folders, least recently written first, until it is under+ * EMERGENCY_TARGET; never in a root that is busy. */+ const emergency = async (): Promise<ClearResult | { skipped: string }> => {+ if (!on()) return { skipped: "off" };+ if (!supported()) return { skipped: "unsupported" };+ const volume = await deps.volume(deps.dataDir);+ const full = usedShare(volume);+ if (full < EMERGENCY_FULL) return { skipped: "room" };+ const current = await load();+ const last = Math.max(past(current.emergency.at) ?? -Infinity, emergencyTriedAt ?? -Infinity);+ if (last > now() - EMERGENCY_BACKOFF_MS) return { skipped: "backoff" };+ const { opened, refused } = await openRoots("tools");+ const result: ClearResult = { dryRun: false, bytes: 0, entries: 0, files: 0, recent: 0, busy: 0, partial: 0, refusedRoots: refused };+ const pacer = new Pacer(deps.pace);+ try {+ const queue: Array<{ root: Root; folder: Folder; unit: Unit; tally: Tally }> = [];+ for (const { root, folder } of opened) {+ if (await busy(root)) { result.busy += 1; continue; }+ await finishLeftovers(root, folder, pacer);+ for (const entry of await measured(root, folder, pacer)) queue.push({ root, folder, ...entry });+ emergencyTriedAt = now();+ }+ result.recent = queue.filter((entry) => recent(entry.tally, now())).length;+ for (const entry of oldestFirst(queue) as typeof queue) {+ if (usedShare(await deps.volume(deps.dataDir)) < EMERGENCY_TARGET) break;+ if (await busy(entry.root)) { result.busy += 1; break; }+ const removed = await removeUnit(entry.folder, entry.unit, pacer);+ if (!removed) continue;+ result.entries += 1; result.bytes += removed.bytes; result.files += removed.files;+ if (removed.partial) result.partial += 1;+ }+ } finally {+ await closeAll(opened);+ }+ if (result.entries > 0) {+ log(`cache sweep: the volume was ${Math.round(full * 100)}% full: removed ${result.entries} tool cache folder(s), ${result.bytes} bytes`);+ current.emergency = { count: current.emergency.count + 1, bytes: current.emergency.bytes + result.bytes, at: now() };+ await counted("emergency: volume full", result.bytes, result.entries);+ } else if (result.busy > 0 && (busyLoggedAt === null || busyLoggedAt <= now() - EMERGENCY_BACKOFF_MS)) {+ busyLoggedAt = now();+ log(`cache sweep: the volume is ${Math.round(full * 100)}% full, but a bot is working, so no cache was removed`);+ }+ return result;+ };++ /** Removes every unit of `scope` (or counts them, dry); a busy tools root is left whole. */+ const clearScope = async (scope: "tools" | "app" | "all", dryRun: boolean): Promise<ClearResult> => {+ const result: ClearResult = { dryRun, bytes: 0, entries: 0, files: 0, recent: 0, busy: 0, partial: 0, refusedRoots: [] };+ if (!supported()) return { ...result, unsupported: true };+ const { opened, refused } = await openRoots(scope);+ result.refusedRoots = refused;+ const pacer = new Pacer(deps.pace);+ try {+ for (const { root, folder } of opened) {+ if (!dryRun && await busy(root)) { result.busy += 1; continue; }+ if (!dryRun) await finishLeftovers(root, folder, pacer);+ for (const { unit, tally } of await measured(root, folder, pacer)) {+ if (recent(tally, now())) { result.recent += 1; continue; }+ if (!dryRun && await busy(root)) { result.busy += 1; break; }+ const removed = dryRun ? tally : await removeUnit(folder, unit, pacer);+ if (!removed) continue;+ result.entries += 1; result.bytes += removed.bytes; result.files += removed.files;+ if (removed.partial) result.partial += 1;+ }+ }+ } finally {+ await closeAll(opened);+ }+ if (!dryRun && result.entries > 0) {+ await counted("cleared on request", result.bytes, result.entries);+ log(`cache sweep: cleared on request: ${result.entries} cache folder(s), ${result.bytes} bytes`);+ }+ if (!dryRun && result.busy > 0) log("cache sweep: a clear left the caches a bot is working with as they are");+ return result;+ };++ /** One at a time: a sweep, the emergency pass and a clear never run together. */+ const serial = <T>(work: () => Promise<T>): Promise<T> => {+ const next = (running ?? Promise.resolve()).catch(() => {}).then(work);+ running = next.finally(() => { if (running === next) running = null; });+ return next;+ };++ /** The tick: the emergency pass, then a sweep that is due (hourly) or that a busy home put off. */+ const tick = async () => {+ await emergency();+ const last = past((await load()).lastSweep?.at ?? null);+ if (last === null || last <= now() - SWEEP_EVERY_MS) await sweep();+ };++ return {+ sweep: () => serial(sweep),+ emergency: () => serial(emergency),+ tick: () => serial(tick),+ /** An operator's, and the future "Clear cache" button's: what goes (or would, `dryRun`), by default a dry run. */+ clearCaches: (options: { dryRun?: boolean; scope?: "tools" | "app" | "all" } = {}): Promise<ClearResult> => {+ const dryRun = options.dryRun !== false;+ if (!on()) return Promise.reject(new CacheSweepOff());+ return serial(() => clearScope(options.scope ?? "all", dryRun));+ },+ /** The counters for the storage report, without waiting: null until the state file is read (after start). */+ counters: (): { cacheCleared: Cleared; emergency: State["emergency"] } | null => (state ? { cacheCleared: state.cleared, emergency: state.emergency } : null),+ /** The routes are there only with the switch on. */+ available: () => on(),+ report: async () => {+ const current = await load();+ return { on: on(), tools: deps.tools(), cacheCleared: current.cleared, emergency: current.emergency, lastSweep: current.lastSweep };+ },+ /** Starts the tick, when the switch is on. `busy`: a turn runs or an engine is kept warm. Called once the server+ * answers (start-upkeep.ts); the first tick is TICK_EVERY_MS later. */+ start(busyNow: () => boolean): void {+ if (!on() || timer) return;+ globalBusy = busyNow;+ void load();+ timer = setInterval(() => { serial(tick).catch((error: unknown) => log(`cache sweep failed: ${error instanceof Error ? error.message : String(error)}`)); }, TICK_EVERY_MS);+ timer.unref();+ log(`cache sweep: on (${deps.tools() ? "the tools' cache folders and " : ""}the app's own cache folder)`);+ },+ stop(): void { if (timer) clearInterval(timer); timer = null; },+ };+}++export type CacheSweeper = ReturnType<typeof createCacheSweeper>;diff --git a/server/cache-sweep/tree.linux.test.ts b/server/cache-sweep/tree.linux.test.tsnew file mode 100644index 0000000000..27b02fa586--- /dev/null+++ b/server/cache-sweep/tree.linux.test.ts@@ -0,0 +1,99 @@+// The open-folder walk (tree.ts) with a swap placed exactly between its look at a name and its act on it, with no timing:+// node:fs/promises' lstat is wrapped so a test can change the disk right after the walk has looked. Linux only, as the+// walk is. Every path lives under each test's own temporary folder.+import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++const after: { lstat: ((path: string) => void) | null } = { lstat: null };+vi.mock("node:fs/promises", async (original) => {+ const actual = await original<typeof import("node:fs/promises")>();+ return {+ ...actual,+ lstat: (async (path: string, ...rest: unknown[]) => {+ const stat = await (actual.lstat as (...args: unknown[]) => Promise<unknown>)(path, ...rest);+ after.lstat?.(String(path));+ return stat;+ }) as typeof actual.lstat,+ };+});++const { Pacer, close, openFolder, removeChild } = await import("./tree.ts");++const dirs: string[] = [];+afterEach(() => { after.lstat = null; for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function scene() {+ const base = realpathSync(mkdtempSync(join(tmpdir(), "omb-cache-tree-")));+ dirs.push(base);+ const root = join(base, "cache"), precious = join(base, "precious");+ mkdirSync(join(root, "uv", "d1"), { recursive: true });+ for (const name of ["f1", "f2"]) writeFileSync(join(root, "uv", "d1", name), "cache");+ writeFileSync(join(root, "uv", "f0"), "cache");+ mkdirSync(precious);+ for (let i = 0; i < 5; i++) writeFileSync(join(precious, `p${i}`), "precious");+ writeFileSync(join(precious, "f1"), "precious");+ return { base, root, precious };+}++async function removeUv(root: string) {+ const folder = await openFolder(root);+ if (!folder) throw new Error("root not opened");+ try { return await removeChild(folder, "uv", new Pacer()); } finally { await close(folder); }+}++describe.skipIf(process.platform !== "linux")("a swap between the walk's look and its act", () => {+ it("the unit swapped for a link just before it is renamed: only the link is renamed and removed", async () => {+ const { root, precious } = scene();+ after.lstat = (path) => {+ if (!path.endsWith("/uv")) return;+ after.lstat = null;+ renameSync(path, `${path}-real`);+ symlinkSync(precious, path);+ };+ expect(await removeUv(root)).toMatchObject({ partial: true });+ expect(readdirSync(root).sort()).toEqual(["uv-real"]);+ expect(readdirSync(precious)).toHaveLength(6);+ });++ it("a folder swapped for a link after it was looked at is not entered: the folder the link names keeps everything", async () => {+ const { root, precious } = scene();+ after.lstat = (path) => {+ if (!path.endsWith("/d1")) return;+ after.lstat = null;+ renameSync(path, `${path}.real`);+ symlinkSync(precious, path);+ };+ expect(await removeUv(root)).toMatchObject({ partial: true });+ expect(readdirSync(precious).sort()).toEqual(["f1", "p0", "p1", "p2", "p3", "p4"]);+ });++ it("a file swapped for a link after it was looked at: the link is removed, never what it names", async () => {+ const { root, precious } = scene();+ after.lstat = (path) => {+ if (!path.endsWith("/f1")) return;+ after.lstat = null;+ unlinkSync(path);+ symlinkSync(join(precious, "f1"), path);+ };+ expect(await removeUv(root)).toMatchObject({ partial: false });+ expect(existsSync(join(root, "uv"))).toBe(false);+ expect(readdirSync(precious)).toHaveLength(6);+ });++ it("the folder being emptied, swapped for a link mid-walk: the walk stays in the folder it opened", async () => {+ const { root, precious } = scene();+ after.lstat = (path) => {+ if (!path.endsWith("/f0")) return;+ after.lstat = null;+ // It was renamed on its way out: the swap names that.+ const trash = readdirSync(root).find((name) => name.startsWith(".omb-trash-"))!;+ renameSync(join(root, trash), join(root, "uv-moved"));+ symlinkSync(precious, join(root, trash));+ };+ expect(await removeUv(root)).toMatchObject({ partial: true });+ expect(readdirSync(join(root, "uv-moved"))).toEqual([]);+ expect(readdirSync(precious)).toHaveLength(6);+ });+});diff --git a/server/cache-sweep/tree.ts b/server/cache-sweep/tree.tsnew file mode 100644index 0000000000..5f8e392680--- /dev/null+++ b/server/cache-sweep/tree.ts@@ -0,0 +1,216 @@+// Walking and deleting inside a cache folder a bot can write in, without ever leaving it (docs/bot-box.md, "Tool caches:+// the cap"). Every step goes through a folder the sweeper holds open, never through a path read again by name:+// - a folder is opened with O_DIRECTORY | O_NOFOLLOW, so a link is never entered;+// - each step below it names one plain child of an open folder through /proc/self/fd/<fd>/<name>, which the kernel+// resolves from that open folder (Linux's openat, from Node), so a folder above that a bot swaps for a link+// changes nothing: the open folder is still the one the walk began in;+// - a folder on another filesystem (a different device) is never entered or removed;+// - lstat, unlink and rmdir act on the last name itself and never follow it: a link swapped in is removed as a link,+// or left; a folder's permissions are changed through its own open handle (fchmod).+// - a folder about to go is first renamed, inside the same open parent, to a TRASH_PREFIX name, so a tool that starts+// meanwhile finds it gone rather than half there; it is never put back, and a later pass finishes any leftover;+// - a walk goes at most MAX_DEPTH folders deep (each level holds one open folder), so a bot's endlessly nested folders+// cannot use up the server's open files or memory: what lies deeper is left, and the walk says it was partial.+// So the sweeper can delete only what is inside the folder it opened, which a bot that writes there could delete itself.+// Needs Linux's /proc/self/fd: anywhere else nothing is walked or deleted (anchoredSupported).+import { randomBytes } from "node:crypto";+import { constants } from "node:fs";+import { lstat, open, readdir, rename, rmdir, unlink, type FileHandle } from "node:fs/promises";++import { RECENT_MS, TICK_ENTRIES, TICK_PAUSE_MS, YIELD_EVERY } from "./limits.ts";++/** Whether this system can walk by open folders (Linux only). */+export function anchoredSupported(platform: NodeJS.Platform = process.platform): boolean {+ return platform === "linux";+}++const FOLDER_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;+/** How deep a walk goes. A tool's cache is a few levels deep (npx's node_modules perhaps 20); deeper is left. */+export const MAX_DEPTH = 128;+/** What a folder being removed is renamed to first, in its own parent. */+export const TRASH_PREFIX = ".omb-trash-";++export interface Folder {+ handle: FileHandle;+ dev: number;+ ino: number;+}++/** The path that names `name` inside the open `folder` (or the folder itself), resolved from the open folder. */+const at = (folder: Folder, name?: string) => `/proc/self/fd/${folder.handle.fd}${name === undefined ? "" : `/${name}`}`;+const plainName = (name: string) => name !== "" && name !== "." && name !== ".." && !name.includes("/") && !name.includes("\0");++async function opened(handle: FileHandle, dev: number | null): Promise<Folder | null> {+ try {+ const stat = await handle.stat();+ if (stat.isDirectory() && (dev === null || Number(stat.dev) === dev)) return { handle, dev: Number(stat.dev), ino: Number(stat.ino) };+ } catch { /* closed below */ }+ await handle.close().catch(() => {});+ return null;+}++/** Opens the folder at `path`; null when it is missing, a link, or not a folder. Only the last name is checked: the server+ * calls it for folders whose parents no bot can change (HOME, an engine home, the data folder). */+export async function openFolder(path: string): Promise<Folder | null> {+ if (!anchoredSupported()) return null;+ const handle = await open(path, FOLDER_FLAGS).catch(() => null);+ return handle ? opened(handle, null) : null;+}++/** Opens `name` inside `parent`: null when it is missing, a link, not a folder, or on another filesystem. */+export async function openChild(parent: Folder, name: string): Promise<Folder | null> {+ if (!plainName(name)) return null;+ const handle = await open(at(parent, name), FOLDER_FLAGS).catch(() => null);+ return handle ? opened(handle, parent.dev) : null;+}++/** Opens `parts` below `root`, one open folder at a time; the folders on the way are closed again. */+export async function openPath(root: Folder, parts: readonly string[]): Promise<Folder | null> {+ let current = root;+ for (const part of parts) {+ const next = await openChild(current, part);+ if (current !== root) await current.handle.close().catch(() => {});+ if (!next) return null;+ current = next;+ }+ return current;+}++export async function close(folder: Folder | null): Promise<void> {+ await folder?.handle.close().catch(() => {});+}++/** A regular file's text inside `folder`, never through a link; null when it is not one. */+export async function readPlainFile(folder: Folder, name: string, max = 4096): Promise<string | null> {+ if (!plainName(name)) return null;+ const handle = await open(at(folder, name), constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => null);+ if (!handle) return null;+ try {+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size > max) return null;+ return await handle.readFile("utf8");+ } catch {+ return null;+ } finally {+ await handle.close().catch(() => {});+ }+}++/** Plain names in an open folder, sorted; none when it cannot be listed. */+export async function names(folder: Folder): Promise<string[]> {+ try { return (await readdir(at(folder))).filter(plainName).sort(); } catch { return []; }+}++export interface Pace { entries: number; yieldEvery: number; pauseMs: number }+export const DEFAULT_PACE: Pace = { entries: TICK_ENTRIES, yieldEvery: YIELD_EVERY, pauseMs: TICK_PAUSE_MS };++/** Counts walked entries: yields to the event loop every `yieldEvery`, and pauses after `entries` (a tick's budget). */+export class Pacer {+ private count = 0;+ private readonly pace: Pace;+ constructor(pace: Pace = DEFAULT_PACE) { this.pace = pace; }+ async step(): Promise<void> {+ this.count += 1;+ if (this.count % this.pace.entries === 0) await new Promise((done) => setTimeout(done, this.pace.pauseMs));+ else if (this.count % this.pace.yieldEvery === 0) await new Promise((done) => setImmediate(done));+ }+}++export interface Tally {+ bytes: number;+ files: number;+ /** The newest modification or change time of anything in it (ms): its last write. */+ newest: number;+ /** Something could not be read or removed (another filesystem, a folder that went away mid-walk, a refusal). */+ partial: boolean;+}++const emptyTally = (): Tally => ({ bytes: 0, files: 0, newest: 0, partial: false });+type Stat = Awaited<ReturnType<typeof lstat>>;+const note = (tally: Tally, stat: Stat) => {+ tally.bytes += typeof stat.blocks === "number" && stat.blocks > 0 ? Number(stat.blocks) * 512 : Number(stat.size);+ tally.files += 1;+ tally.newest = Math.max(tally.newest, Number(stat.mtimeMs), Number(stat.ctimeMs));+};++/** Walks the open `folder` (sizes, files, last write); with `remove`, deletes everything inside it as it goes, leaving+ * the folder itself. A child folder is entered only through its own open handle, on the same filesystem. */+export async function walk(folder: Folder, options: { remove: boolean; pacer: Pacer }, tally: Tally = emptyTally(), depth = 0): Promise<Tally> {+ if (depth >= MAX_DEPTH) { tally.partial = true; return tally; }+ if (options.remove) {+ // A folder without write permission (a read-only tree) cannot be emptied: made writable through its own handle.+ const own = await folder.handle.stat().catch(() => null);+ if (own && (Number(own.mode) & 0o200) === 0) await folder.handle.chmod((Number(own.mode) & 0o7777) | 0o700).catch(() => {});+ }+ for (const name of await names(folder)) {+ await options.pacer.step();+ const stat = await lstat(at(folder, name)).catch(() => null);+ if (!stat) continue;+ if (stat.isDirectory()) {+ if (Number(stat.dev) !== folder.dev) { tally.partial = true; continue; }+ const child = await openChild(folder, name);+ if (!child) { tally.partial = true; continue; }+ note(tally, stat);+ try { await walk(child, options, tally, depth + 1); } finally { await close(child); }+ if (options.remove) await rmdir(at(folder, name)).catch(() => { tally.partial = true; });+ continue;+ }+ note(tally, stat);+ if (options.remove) await unlink(at(folder, name)).catch(() => { tally.partial = true; });+ }+ return tally;+}++/** Walks `name` inside the open `parent` (null: it is not there, or is a link or on another filesystem). */+export async function measureChild(parent: Folder, name: string, pacer: Pacer): Promise<Tally | null> {+ const stat = await lstat(at(parent, name)).catch(() => null);+ const child = stat?.isDirectory() ? await openChild(parent, name) : null;+ if (!stat || !child) return null;+ try {+ const tally = await walk(child, { remove: false, pacer });+ note(tally, stat);+ return tally;+ } finally {+ await close(child);+ }+}++/** Deletes the folder `name` inside the open `parent` and everything in it, never leaving it: renamed first to a+ * TRASH_PREFIX name in the same parent, then emptied and removed. Null when `name` is not a folder there (missing, a+ * link, a file). Returns what it walked; `partial` when anything stayed (a later pass finishes it, removeLeftovers). */+export async function removeChild(parent: Folder, name: string, pacer: Pacer): Promise<Tally | null> {+ if (!plainName(name) || name.startsWith(TRASH_PREFIX)) return null;+ const stat = await lstat(at(parent, name)).catch(() => null);+ if (!stat?.isDirectory() || Number(stat.dev) !== parent.dev) return null;+ const trash = `${TRASH_PREFIX}${randomBytes(6).toString("hex")}`;+ try { await rename(at(parent, name), at(parent, trash)); } catch { return null; }+ return removeTrash(parent, trash, pacer);+}++/** Removes a TRASH_PREFIX entry of the open `parent`: a folder through its own open handle; anything else (a link a bot+ * swapped in before the rename) as itself, never followed. */+async function removeTrash(parent: Folder, trash: string, pacer: Pacer): Promise<Tally> {+ const child = await openChild(parent, trash);+ if (!child) {+ await unlink(at(parent, trash)).catch(() => {});+ return { ...emptyTally(), partial: true };+ }+ let tally: Tally;+ try { tally = await walk(child, { remove: true, pacer }); } finally { await close(child); }+ await rmdir(at(parent, trash)).catch(() => { tally.partial = true; });+ return tally;+}++/** Finishes the TRASH_PREFIX entries an earlier removal left in the open `parent`. */+export async function removeLeftovers(parent: Folder, pacer: Pacer): Promise<number> {+ let done = 0;+ for (const name of await names(parent)) {+ if (!name.startsWith(TRASH_PREFIX)) continue;+ const tally = await removeTrash(parent, name, pacer);+ if (!tally.partial) done += 1;+ }+ return done;+}++/** Changed in the last RECENT_MS: a download or an install may still be finishing it. */+export const recent = (tally: Tally, now: number) => tally.newest > now - RECENT_MS;diff --git a/server/cache-sweep/units.ts b/server/cache-sweep/units.tsnew file mode 100644index 0000000000..209287ec35--- /dev/null+++ b/server/cache-sweep/units.ts@@ -0,0 +1,117 @@+// What the cache sweeper may remove: a fixed list of whole folders in cache roots the server made, and old Node compile+// caches in the app's own cache folder. Invariants, each with a test (sweeper.test.ts, units.linux.test.ts):+// - every path comes from the arguments (no HOME or environment read here);+// - a tools root is used only when it is a real folder (not a link) holding the server's own CACHEDIR.TAG+// (bot-box/tool-caches.ts ensureToolCacheRoot), so a `cache` folder a person made is never looked into;+// - only the names on TOOL_UNITS are ever measured or removed there, each as one whole folder; nothing else in a root is+// counted, listed or touched, and no browser folder is on the list (a Playwright MCP profile holds sign-ins);+// - every walk and removal goes through open folders (tree.ts), so nothing outside the opened root is ever reached.+import { basename, join, resolve } from "node:path";++import { under } from "../bot-box/plan.ts";+import { CACHE_TAG, CACHE_TAG_FILE, toolCacheRoot } from "../bot-box/tool-caches.ts";+import { close, measureChild, names, openFolder, openPath, readPlainFile, removeChild, removeLeftovers, type Folder, type Pacer, type Tally } from "./tree.ts";++export type CacheGroup = "tools" | "app";++/** The app's own cache folder in the data folder, which the bot box hides. */+export const APP_CACHE_DIR = "cache";++/** The tools' units: whole folders, by fixed name. Each is a folder bot-box/tool-caches.ts routes a tool's cache to; a+ * tool keeps its own index and cross-references inside it (npm's content store, uv's archive links), so it goes whole or+ * not at all. Not here, ever: a browser's folder, and any name not on this list. */+export const TOOL_UNITS: readonly string[] = ["npm", "pip", "uv", "huggingface/hub", "huggingface/xet", "bun"];++/** The app's: Node's compile cache, one folder per Node version and build (cloud-home-start.ts NODE_COMPILE_CACHE). The+ * box hides the data folder, so no bot writes here. */+const APP_COMPILE_DIR = "node-compile";++export interface Root {+ group: CacheGroup;+ /** As expected (`<HOME>/cache`, `<data folder>/cache`): a name for logs and counters. */+ path: string;+}++export interface RootInput {+ home: string;+ dataDir: string;+ /** A Team Cloud's audience engine homes (engine-homes/layout.ts audienceHomes). */+ audienceHomes: readonly string[];+ /** The tools' cache folders are in use: the switch (bot-box/tool-caches.ts toolCachesOn) and the bot box is on. */+ tools: boolean;+}++/** The roots to look at: each box HOME's `cache` when the tools' folders are on, and the data folder's own `cache`. */+export function expectedRoots(input: RootInput): Root[] {+ const tools = input.tools ? [...new Set([input.home, ...input.audienceHomes].map((home) => toolCacheRoot(home)))].map((path) => ({ group: "tools" as const, path })) : [];+ return [...tools, { group: "app", path: join(resolve(input.dataDir), APP_CACHE_DIR) }];+}++/** Opens a root, or says why it is left alone. `forbidden`: HOME and the data folder, which a root may never hold. */+export async function openRoot(root: Root, forbidden: readonly string[]): Promise<{ folder: Folder } | { refused: string } | null> {+ if (forbidden.some((place) => under(resolve(place), root.path))) return { refused: "it holds HOME or the data folder" };+ const folder = await openFolder(root.path);+ if (!folder) return null;+ if (root.group === "tools" && await readPlainFile(folder, CACHE_TAG_FILE) !== CACHE_TAG) {+ await close(folder);+ return { refused: "not made by the server (no CACHEDIR.TAG of ours)" };+ }+ return { folder };+}++export interface Unit {+ group: CacheGroup;+ root: string;+ /** Under the root, with `/` between parts. */+ name: string;+}++const split = (name: string) => name.split("/");++/** The units of an open root. `keep`: compile cache folders that are never units (the running server's own). */+export async function listUnits(root: Root, folder: Folder, keep: readonly string[] = []): Promise<Unit[]> {+ if (root.group === "tools") return TOOL_UNITS.map((name) => ({ group: "tools", root: root.path, name }));+ const compile = await openPath(folder, [APP_COMPILE_DIR]);+ if (!compile) return [];+ try {+ // By name: the running server's folder is node-compile/<its version>, whichever way the data folder's path is spelled.+ const kept = new Set(keep.map((path) => basename(resolve(path))));+ return (await names(compile)).filter((name) => !name.startsWith(".") && !kept.has(name))+ .map((name) => ({ group: "app" as const, root: root.path, name: `${APP_COMPILE_DIR}/${name}` }));+ } finally {+ await close(compile);+ }+}++/** The open parent of a unit and its own name, or null when the way there is missing, a link or another filesystem. */+async function parentOf(folder: Folder, unit: Unit): Promise<{ parent: Folder; name: string } | null> {+ const parts = split(unit.name);+ const parent = parts.length === 1 ? folder : await openPath(folder, parts.slice(0, -1));+ return parent ? { parent, name: parts.at(-1)! } : null;+}++/** A unit's size and last write; null when it is not there (or is a link, or on another filesystem). */+export async function measureUnit(folder: Folder, unit: Unit, pacer: Pacer): Promise<Tally | null> {+ const found = await parentOf(folder, unit);+ if (!found) return null;+ try { return await measureChild(found.parent, found.name, pacer); } finally { if (found.parent !== folder) await close(found.parent); }+}++/** Finishes what an earlier removal left (tree.ts TRASH_PREFIX) in the folders that hold a root's units. The caller+ * decides whether it may, as for removeUnit. */+export async function finishLeftovers(root: Root, folder: Folder, pacer: Pacer): Promise<number> {+ let done = 0;+ for (const parts of root.group === "tools" ? [[], ["huggingface"]] : [[APP_COMPILE_DIR]]) {+ const parent = parts.length ? await openPath(folder, parts) : folder;+ if (!parent) continue;+ try { done += await removeLeftovers(parent, pacer); } finally { if (parent !== folder) await close(parent); }+ }+ return done;+}++/** Deletes a unit inside its open root and never outside it (tree.ts). The caller decides whether it may. */+export async function removeUnit(folder: Folder, unit: Unit, pacer: Pacer): Promise<Tally | null> {+ const found = await parentOf(folder, unit);+ if (!found) return null;+ try { return await removeChild(found.parent, found.name, pacer); } finally { if (found.parent !== folder) await close(found.parent); }+}diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex d0f8c2d7d9..aa8fba180f 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -50,6 +50,8 @@ const SERVER_ENV_NAMES = new Set(["OMB_BOT_BOX",// Tool caches into one folder in each bot box's HOME (server/bot-box/tool-caches.ts): off unless the Admin turns it on."OMB_CACHE_ROOT",+ // Their cap (server/cache-sweep/limits.ts): the sweeper's switch, off unless the Admin turns it on, and the caps' overrides.+ "OMB_CACHE_SWEEP", "OMB_CACHE_CAP_TOOLS", "OMB_CACHE_CAP_APP",// The image's own engine CLIs before older copies in the data folder (server/image-engines.ts), for one test Cloud first."OMB_IMAGE_ENGINES",// The conversation logs' cap and age limit (server/host/thread-log-sweep.ts), off unless the Admin sets it.diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex 534fb4f4cc..7104a7a0a7 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -490,8 +490,8 @@ it("holds requests at the edge while the server starts only when the Admin askedit("hands the server the tool cache switch, and moves no cache of the server's own", () => {const config = cloudHomeConfiguration(withGateway())!;- const server = cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_CACHE_ROOT: "on" }, "/data").server;- expect(server).toMatchObject({ OMB_CACHE_ROOT: "on", HOME: "/data", NODE_COMPILE_CACHE: "/data/.openmausbot/cache/node-compile" });+ const server = cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_CACHE_ROOT: "on", OMB_CACHE_SWEEP: "on", OMB_CACHE_CAP_TOOLS: "4G", OMB_CACHE_CAP_APP: "1G" }, "/data").server;+ expect(server).toMatchObject({ OMB_CACHE_ROOT: "on", OMB_CACHE_SWEEP: "on", OMB_CACHE_CAP_TOOLS: "4G", OMB_CACHE_CAP_APP: "1G", HOME: "/data", NODE_COMPILE_CACHE: "/data/.openmausbot/cache/node-compile" });// Only the bot box adds the tools' variables (bot-box/tool-caches.ts), for each box's own HOME.for (const name of ["npm_config_cache", "PIP_CACHE_DIR", "UV_CACHE_DIR", "HF_HUB_CACHE", "XDG_CACHE_HOME"]) expect(server).not.toHaveProperty(name);});diff --git a/server/host/start-upkeep.test.ts b/server/host/start-upkeep.test.tsindex a60d29adaa..dc6b933a73 100644--- a/server/host/start-upkeep.test.ts+++ b/server/host/start-upkeep.test.ts@@ -105,4 +105,20 @@ describe("start-up upkeep", () => {expect(warn).toHaveBeenCalledWith("thread event log retention sweep failed: logs gone");expect(seen).toEqual(["bot/idle 20", "bot/working 1 busy"]);});++ it("starts the cache cap's sweeper, telling it to wait whenever a thread is busy or an engine process lives", () => {+ vi.useFakeTimers();+ let working = "", warm = false;+ let busy: (() => boolean) | null = null;+ startUpkeep({+ bots: () => [{ id: "bot", tasks: [task("a"), task("b")] }], retentionDays: () => null, busy: (_botId, threadId) => threadId === working,+ openDirectHandoff: () => false, cleanupPartials: () => 0, caches: { start: (given) => { busy = given; } }, enginesLive: () => warm,+ });+ expect(busy!()).toBe(false);+ working = "b";+ expect(busy!()).toBe(true);+ working = "";+ warm = true;+ expect(busy!()).toBe(true);+ });});diff --git a/server/host/start-upkeep.ts b/server/host/start-upkeep.tsindex 7d34353c28..4484316338 100644--- a/server/host/start-upkeep.ts+++ b/server/host/start-upkeep.ts@@ -4,6 +4,7 @@// The task workspaces' sweep is held off unless OMB_TASK_WORKSPACE_RETENTION is on: it deletes any node_modules and// any venv outright, without checking that a package manager made them, so a venv holding the person's own script or// a hand-written node_modules would go, and on a desktop a task workspace can be a project the person also works in.+// The cache cap's sweeper (cache-sweep/) starts here too; it deletes nothing while a turn or an engine process is alive.import { cleanupStaleAttachmentPartials } from "../attachments.ts";import type { BotRecord } from "../store.ts";import { sweepTaskWorkspaceBuildFolders } from "../task-workspace-retention.ts";@@ -23,6 +24,8 @@ export interface StartUpkeepDeps {busy: (botId: string, threadId: string) => boolean;openDirectHandoff: (threadId: string) => boolean;cleanupPartials?: () => number;+ caches?: { start(busy: () => boolean): void };+ enginesLive?: () => boolean;sweepLogs?: typeof sweepThreadEventLogs;sweepWorkspaces?: (candidates: Parameters<typeof sweepTaskWorkspaceBuildFolders>[0]) => string[] | Promise<string[]>;/** Whether the task workspaces' sweep runs; taskWorkspaceRetentionOn by default (off). */@@ -90,4 +93,7 @@ export function startUpkeep(deps: StartUpkeepDeps): void {sweepAll();});setInterval(sweepAll, THREAD_LOG_RETENTION_SWEEP_MS).unref();+ // Busy: a turn runs, or an engine process lives on between turns (a kept-warm engine, the MCP servers it started), which+ // may run a program out of a cache entry.+ deps.caches?.start(() => (deps.enginesLive?.() ?? false) || deps.bots().some((bot) => (bot.tasks ?? []).some((task) => deps.busy(bot.id, task.threadId))));}diff --git a/server/index.ts b/server/index.tsindex 93f9ef8bc0..13c646efa4 100644--- a/server/index.ts+++ b/server/index.ts@@ -636,7 +636,7 @@ import { createPersonReplies } from "./person-replies.ts";import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts"; import { ownServerLendingRefusal } from "./own-server-lending-refusal.ts";import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";-import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";+import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { createCachesRoutes } from "./routes/caches.ts"; import { botEnginesLive, createCacheSweepHost, withCacheCounters } from "./cache-sweep/host.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts"; import { createRemoteHandoff, isRemoteBotId } from "./host/remote-teammate-handoff.ts";@@ -653,7 +653,7 @@ const STATIC_DIR = process.env.OMB_STATIC_DIR || null;dataFormatAtStart("check", DATA_DIR, serverVersion()); ensureDirs();// Acquire before any durable identity, sessions, config or Store state is loaded.-const dataDirLease = acquireDataDirLeaseForProcess(DATA_DIR); void startEngineRecords(DATA_DIR); // stops what an earlier server left+const dataDirLease = acquireDataDirLeaseForProcess(DATA_DIR); void startEngineRecords(DATA_DIR); const cacheSweeper = createCacheSweepHost(DATA_DIR); // stops what an earlier server left; the cache cap (cache-sweep/), off unless OMB_CACHE_SWEEPconst releaseDataDirLeaseAtExit = releaseOnceAtExit(dataDirLease);process.once("exit", releaseDataDirLeaseAtExit);// Restore before constructing any long-lived config, Store, session or provider objects.@@ -2780,7 +2780,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, routineThread: (botId, threadId) => { const run = activeRoutineRunForThread(threadId); return run?.botId === botId && run.target === "bot"; }, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let starterRoutineWake: StarterRoutineWake | undefined; /* made beside tieAutomationsToBots, once the routines and triggers are */ const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: perf.storage, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: () => withCacheCounters(perf.storage(), cacheSweeper), dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -9373,7 +9373,7 @@ const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => waudit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits }); starterRoutineWake = createStarterRoutineWake({ awake: starterAwake, store, held: (botId) => botHolds.held(botId), routines: () => routines!.listRoutines(), triggers: () => [...webhooks.list(), ...appTriggers.manager.list()], busy: workInFlight({ conversations: (botId) => store.tasks(botId).map((task) => task.threadId), turnActive: (botId) => botHasActiveTurn(botId) || routines?.activeBotRunForBot(botId) != null, conversationBusy: (botId, threadId) => threadBusy(botId, threadId) || queuedThreadPosition(botId, threadId) !== null, coordinator, checkBacks: (botId, threadId) => checkBacks.list(botId, threadId).length, waits: (botId) => botWaits.list(botId).length }) });ROUTES.push(appTriggers.routes); ROUTES.unshift(createMoveFreezeRoutes({ freeze: moveFreeze, automationsOff: () => switchAutomationsOff({ routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }), restart: () => { restartRequested = true; gracefulShutdown(); }, busy: createMoveWaits({ bots: () => store.bots, rooms: () => store.groups, answering: (id) => watchdog.answering(id), turn: botHasActiveTurn, runs: () => routines?.listRuns() ?? [], roomWorking: (id) => { const group = store.group(id); return Boolean(group && groupIsWorking(group)); }, handoffs: () => coordinator.active(), exists: (node) => !(!node.parentId && node.groupId ? roomRootProblem(node) : roomHandoffProblem(node)), signingIn: () => providerAuthSessions.active }) }));-ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots, storage: perf.storage, serverId: ENVIRONMENT_ID, storageNow: perf.storageNow, storageMeasureInS: perf.storageMeasureInS, measureStorage: perf.measureStorage, launch: perf.noteLaunch })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,+ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots, storage: () => withCacheCounters(perf.storage(), cacheSweeper), serverId: ENVIRONMENT_ID, storageNow: perf.storageNow, storageMeasureInS: perf.storageMeasureInS, measureStorage: perf.measureStorage, launch: perf.noteLaunch })); ROUTES.push(createCachesRoutes(cacheSweeper)); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,threadTitle: (botId, threadId) => store.bot(botId) && !store.bot(botId)!.hidden ? store.taskByThread(botId, threadId)?.title ?? null : null,created: (id, auth) => cloudRoutineAuthors?.wrote(id, auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY) }));@@ -15148,7 +15148,7 @@ server.listen(PORT, listenHost(server), async () => {drainQueuedSends();drainQueuedChannelSends();void cloudComputerPower.armRunning();- startUpkeep({ bots: () => store.bots, retentionDays: () => threadEventLogRetentionDays(cfg), busy: threadBusy, openDirectHandoff: (threadId) => coordinator.activeDirect(threadId) }); startThreadLogSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, threads: () => knownThreads(store.bots, store.groups, (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId)), paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()), logQuiet: (threadId) => bus.logQuiet(threadId) }); if (folderCleanup) startOrphanSweep({ dataDir: DATA_DIR, mode: () => orphanSweepMode(), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), records: () => store, storedThreadIds: () => transcriptThreads(join(DATA_DIR, "messages.db")), cleanup: folderCleanup }); if (folderCleanup) startIdleReclaim({ dataDir: DATA_DIR, mode: () => idleReclaimMode(), records: () => store, busy: threadBusy, botBusy: botHasActiveTurn, handedOff: (threadId) => coordinator.activeDirect(threadId), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), cleanup: folderCleanup });+ startUpkeep({ bots: () => store.bots, retentionDays: () => threadEventLogRetentionDays(cfg), busy: threadBusy, openDirectHandoff: (threadId) => coordinator.activeDirect(threadId), caches: cacheSweeper, enginesLive: botEnginesLive }); startThreadLogSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, threads: () => knownThreads(store.bots, store.groups, (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId)), paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()), logQuiet: (threadId) => bus.logQuiet(threadId) }); if (folderCleanup) startOrphanSweep({ dataDir: DATA_DIR, mode: () => orphanSweepMode(), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), records: () => store, storedThreadIds: () => transcriptThreads(join(DATA_DIR, "messages.db")), cleanup: folderCleanup }); if (folderCleanup) startIdleReclaim({ dataDir: DATA_DIR, mode: () => idleReclaimMode(), records: () => store, busy: threadBusy, botBusy: botHasActiveTurn, handedOff: (threadId) => coordinator.activeDirect(threadId), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), cleanup: folderCleanup });if (enginesRead) {await enginesRead;if (companyShutdown) return;diff --git a/server/perf/disk-usage.ts b/server/perf/disk-usage.tsindex 21b98b523a..37c5fb9116 100644--- a/server/perf/disk-usage.ts+++ b/server/perf/disk-usage.ts@@ -61,6 +61,8 @@ export interface StorageReport {resumes: number;/** The last pass failed; the figures are from the one before, if any. */failed: boolean;+ /** What the cache cap removed (cache-sweep/sweeper.ts): every clear, and the emergency passes; absent before it ran. */+ caches?: { cacheCleared: { count: number; bytes: number; entries: number; at: number | null; reason: string | null }; emergency: { count: number; bytes: number; at: number | null } };}export interface CompletedPass { at: number; tookMs: number; totals: WalkTotals; volume: VolumeBytes | null }diff --git a/server/routes/caches.ts b/server/routes/caches.tsnew file mode 100644index 0000000000..8b6183699d--- /dev/null+++ b/server/routes/caches.ts@@ -0,0 +1,31 @@+// GET /api/caches: the cache cap's counters and its last sweep (cache-sweep/sweeper.ts). POST /api/caches/clear: clearCaches,+// for an operator now and the customer's "Clear cache" button later; a dry run unless the body says `"dryRun": false`. Both+// admin scope (request-auth's default), so a bot's shell never reaches them, and only with the cap's switch on, which is+// only ever on a Cloud home: off, they are not there at all.+import { CacheSweepOff, type CacheSweeper } from "../cache-sweep/sweeper.ts";+import { PASS, type RouteHandler } from "./table.ts";++export const CACHES_PATH = "/api/caches";+export const CACHES_CLEAR_PATH = "/api/caches/clear";+const SCOPES = new Set(["tools", "app", "all"]);++export function createCachesRoutes(sweeper: Pick<CacheSweeper, "available" | "clearCaches" | "report">): RouteHandler {+ return async ({ req, res, path, method, json, readBody }) => {+ if (path !== CACHES_PATH && path !== CACHES_CLEAR_PATH) return PASS;+ if (!sweeper.available()) return PASS;+ if (method === "GET" && path === CACHES_PATH) {+ res.setHeader("cache-control", "no-store");+ return json(res, 200, await sweeper.report());+ }+ if (method !== "POST" || path !== CACHES_CLEAR_PATH) return PASS;+ res.setHeader("cache-control", "no-store");+ const body = await readBody(req, 4096).catch(() => null) as { dryRun?: unknown; scope?: unknown } | null;+ const scope = typeof body?.scope === "string" && SCOPES.has(body.scope) ? body.scope as "tools" | "app" | "all" : "all";+ try {+ return json(res, 200, await sweeper.clearCaches({ dryRun: body?.dryRun !== false, scope }));+ } catch (error) {+ if (error instanceof CacheSweepOff) return json(res, 409, { error: error.message });+ throw error;+ }+ };+}