Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Browser memory: the bots' Chrome on a Cloud home under a kernel memory limit (#7229)
Milind Soni297f00c40700
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ea2ebf738e..5dbe889a94 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -176,6 +176,16 @@ jobs:- run: pnpm check:electron- name: production UI buildrun: pnpm exec vite build+ - name: The bots' browsers' kernel memory limit, on a real kernel, as root+ # A Cloud home's root supervisor puts the bots' Chrome under a cgroup v2 memory limit (server/browser/memory-cgroup.ts):+ # here a memory-hungry child started through the real launcher must be killed by the kernel while the unprivileged+ # "server" beside it keeps answering. Root without CAP_SYS_ADMIN, as the supervisor runs after its setpriv drop;+ # OMB_CGROUP_TEST=require fails rather than skips.+ run: |+ scratch="$(mktemp -d)"+ sudo setpriv --inh-caps=-sys_admin,-setpcap --bounding-set=-sys_admin,-setpcap -- \+ env "PATH=$PATH" HOME="$scratch" OMB_DATA_DIR="$scratch/data" TMPDIR="$scratch" OMB_CGROUP_TEST=require \+ "$(command -v pnpm)" exec vitest run server/browser/memory-cgroup.linux.test.ts --reporter=verbose --silent=falsevitest:# Admit the expensive runner fan-out only after the quick checks pass.diff --git a/scripts/ci-workflow.test.ts b/scripts/ci-workflow.test.tsindex a064085d57..b4108e2655 100644--- a/scripts/ci-workflow.test.ts+++ b/scripts/ci-workflow.test.ts@@ -264,8 +264,11 @@ describe("CI concurrency", () => {});// The build job runs where the scope selects it, and static holds only what is quick and always runs.expect(workflow.jobs.build.if).toBe(`contains(needs.static.outputs.jobs, '"build"')`);- expect((workflow.jobs.build.steps as { run?: string }[]).map((step) => step.run).filter(Boolean))- .toEqual(["pnpm install --frozen-lockfile", "pnpm typecheck", "pnpm check:electron", "pnpm exec vite build"]);+ const buildRuns = (workflow.jobs.build.steps as { run?: string }[]).map((step) => step.run).filter(Boolean);+ expect(buildRuns.slice(0, 4)).toEqual(["pnpm install --frozen-lockfile", "pnpm typecheck", "pnpm check:electron", "pnpm exec vite build"]);+ // Then the one test that needs root on a real kernel (the browsers' memory limit), which fails rather than skips there.+ expect(buildRuns).toHaveLength(5);+ expect(buildRuns[4]).toMatch(/sudo setpriv .*--bounding-set=-sys_admin.*OMB_CGROUP_TEST=require .*vitest run server\/browser\/memory-cgroup\.linux\.test\.ts/s);for (const run of ["pnpm typecheck", "pnpm check:electron", "pnpm exec vite build"]) {expect((workflow.jobs.static.steps as { run?: string }[]).some((step) => step.run === run), run).toBe(false);}diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 42245618a5..d20d35ed72 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -12,8 +12,8 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY", "OMB_ANTIGRAVITY_NATIVE_CLI","OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT","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_CONNECTION", "OMB_BROWSER_HOLD_IDLE_MS", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL",- "OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING",+ "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_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",diff --git a/server/browser/chrome/launcher.ts b/server/browser/chrome/launcher.tsindex 140d564394..27920239c2 100644--- a/server/browser/chrome/launcher.ts+++ b/server/browser/chrome/launcher.ts@@ -15,6 +15,7 @@ import { installChromeForTesting, type ChromeForTestingPin, type DownloadProgresimport { chromeHost, installedGoogleChrome, resolveChromePlan, type ChromeEngine, type ChromeHost, type ChromePlan, type FoundChrome } from "./resolve.ts";import { IdentitySidecars } from "./sidecar.ts";import { browserLanguage, browserTimeZone, languageList, launcherPath, primaryScreen, writeLauncher, type LauncherBox, type LauncherSettings, type Screen } from "./wrapper.ts";+import { BROWSER_CGROUP_ENV, browserCgroupDir } from "../memory-cgroup.ts";type Ready = { kind: "ready"; chrome: FoundChrome; identity: ChromeIdentity; product: string; fingerprint: string; launcher?: LauncherSettings };type State =@@ -276,6 +277,7 @@ export class ChromeLauncher implements BrowserLaunch {language: this.resolvedLanguage(), timeZone: browserTimeZone(env, platform),...(platform === "darwin" ? { home: userInfo().homedir } : {}),...this.boxed(),+ ...(platform === "linux" && browserCgroupDir(env[BROWSER_CGROUP_ENV]) ? { memoryGroup: browserCgroupDir(env[BROWSER_CGROUP_ENV])! } : {}),};writeLauncher(this.path, launcher, platform);if (platform !== "win32") await (this.options.checkLauncher ?? runsLauncher)(this.path, this.chromeEnv());diff --git a/server/browser/chrome/wrapper.ts b/server/browser/chrome/wrapper.tsindex 08b015edba..96e696f435 100644--- a/server/browser/chrome/wrapper.ts+++ b/server/browser/chrome/wrapper.ts@@ -21,6 +21,9 @@ export interface LauncherSettings {home?: string;/** Every Chrome this launcher starts runs in this box (a Team Cloud's), with only the profile it was started on. */box?: LauncherBox;+ /** A Cloud home's browsers' cgroup (browser/memory-cgroup.ts): Chrome joins it before it starts, so all of its processes+ * are born under the kernel's memory limit. A failed join leaves Chrome where it was. */+ memoryGroup?: string;}/** bubblewrap's options for a browser's box, before `--` and without the profile, which the launcher binds per start. */@@ -75,6 +78,7 @@ export function launcherScript(settings: LauncherSettings, platform: NodeJS.Platconst chrome = `${shellQuote(settings.chrome)} "$@" ${flags.map(shellQuote).join(" ")} $headless`;return ["#!/bin/sh",+ ...(settings.memoryGroup ? [`{ echo $$ > ${shellQuote(`${settings.memoryGroup}/cgroup.procs`)}; } 2>/dev/null`] : []),...(settings.home ? [`HOME=${shellQuote(settings.home)}`, "export HOME"] : []),...(settings.timeZone ? [`TZ=${shellQuote(settings.timeZone)}`, "export TZ"] : []),"headless=",diff --git a/server/browser/memory-ceiling.test.ts b/server/browser/memory-ceiling.test.tsindex 630b11c400..14e85723e4 100644--- a/server/browser/memory-ceiling.test.ts+++ b/server/browser/memory-ceiling.test.ts@@ -199,4 +199,88 @@ describe("a bot browser's memory ceiling", () => {expect(killed).toEqual(["11 SIGKILL"]);expect(count).toBe(1);});++ it("after the kernel kills at the browsers' limit, closes the browser that lost processes, with the turn that held it", async () => {+ let kills = 0;+ const contained: string[] = [];+ const sizes: Record<number, number> = { 10: 30 * MB, 11: 200 * MB, 12: 400 * MB };+ const forced: string[] = [];+ const ceiling = createBrowserCeiling({+ lines: { softBytes: 700 * MB, hardBytes: 1000 * MB },+ browsers: async () => [{ session: "bot-a", pids: Object.keys(sizes).map(Number), daemon: 10 }, { session: "bot-b", pids: [20, 21], daemon: 20 }],+ pss: (pid) => sizes[pid] ?? (pid >= 20 ? 100 * MB : null),+ quiet: () => false, tabs: async () => [], closeTab: async () => false, close: async () => false,+ forceClose: async (browser, used) => { forced.push(`${browser.session} [${browser.pids.join(",")}] ${Math.round(used / MB)} MB`); return true; },+ kernelKills: () => kills,+ contain: (browser) => contained.push(browser.session),+ log: () => {},+ });+ await ceiling.tick();+ expect(forced).toEqual([]);+ expect(contained).toEqual(["bot-a", "bot-b"]);+ // The kernel killed bot-a's largest renderer at the group's limit.+ delete sizes[12];+ kills = 1;+ await ceiling.tick();+ expect(forced).toEqual(["bot-a [10,11] 630 MB"]);+ // No new kill: nothing more is closed.+ await ceiling.tick();+ expect(forced).toHaveLength(1);+ });++ function twoBrowsers() {+ let kills = 0;+ const a: Record<number, number> = { 10: 30 * MB, 11: 200 * MB, 12: 400 * MB };+ const b: Record<number, number> = { 20: 30 * MB, 21: 800 * MB, 22: 20 * MB };+ const forced: string[] = [];+ const ceiling = createBrowserCeiling({+ lines: { softBytes: 700 * MB, hardBytes: 1000 * MB },+ browsers: async () => [{ session: "bot-a", pids: Object.keys(a).map(Number), daemon: 10 }, { session: "bot-b", pids: Object.keys(b).map(Number), daemon: 20 }],+ pss: (pid) => a[pid] ?? b[pid] ?? null,+ quiet: () => false, tabs: async () => [], closeTab: async () => false, close: async () => false,+ forceClose: async (browser) => { forced.push(browser.session); return true; },+ kernelKills: () => kills,+ log: () => {},+ });+ return { ceiling, a, b, forced, kill: () => { kills += 1; } };+ }++ it("after a kernel kill, closes the browser whose lost process was the victim, not one that swapped a small renderer", async () => {+ const run = twoBrowsers();+ await run.ceiling.tick();+ // The kernel kills bot-a's 400 MB renderer while bot-b swaps a 20 MB renderer on a normal navigation.+ delete run.a[12];+ delete run.b[22]; run.b[23] = 20 * MB;+ run.kill();+ await run.ceiling.tick();+ expect(run.forced).toEqual(["bot-a"]);+ });++ it("closes nothing when no process lost since could have been the victim, and looks once more against the earlier look", async () => {+ const run = twoBrowsers();+ await run.ceiling.tick();+ // The kill is counted before its victim is reaped: only a small renderer is gone at this look.+ delete run.b[22];+ run.kill();+ await run.ceiling.tick();+ expect(run.forced).toEqual([]);+ // Reaped by the next look: found against the sizes from before the kill.+ delete run.a[12];+ await run.ceiling.tick();+ expect(run.forced).toEqual(["bot-a"]);+ });++ it("lets a kill nothing explains go after one more look, so a later large loss is not taken for it", async () => {+ const run = twoBrowsers();+ await run.ceiling.tick();+ delete run.b[22];+ run.kill();+ await run.ceiling.tick();+ await run.ceiling.tick();+ expect(run.forced).toEqual([]);+ // bot-b closes its 800 MB tab itself afterwards, with no new kill: nothing is closed for it.+ delete run.b[21];+ await run.ceiling.tick();+ expect(run.forced).toEqual([]);+ });});diff --git a/server/browser/memory-ceiling.ts b/server/browser/memory-ceiling.tsindex e59f50b5d3..59c0f4027a 100644--- a/server/browser/memory-ceiling.ts+++ b/server/browser/memory-ceiling.ts@@ -18,6 +18,9 @@ export const CEILING_FAST_TICK_MS = 3_000;const PAGE_BYTES = 4096;/** A browser's tabs are closed at most this often, and a refused close is logged at most this often. */const ACT_EVERY_MS = 60_000;+/** A process lost since the last look smaller than this was not the kernel's victim at the browsers' limit: Chrome swaps+ * small renderers on every navigation. */+const VICTIM_MIN_BYTES = 50 * MB;export interface CeilingLines { softBytes: number; hardBytes: number }@@ -104,6 +107,10 @@ export interface BrowserCeilingDeps {/** Closes the browser now whatever holds it: the turn holding it ends with the line that the browser was closed for* memory, and its Chrome's processes are stopped at once. False when it could not. */forceClose?(browser: CeilingBrowser, usedBytes: number): Promise<boolean>;+ /** The kernel's count of processes it killed at the browsers' memory limit (memory-cgroup.ts); null where there is none. */+ kernelKills?(): number | null;+ /** Puts this browser's Chrome under the browsers' memory limit where it is not yet (one started outside the launcher). */+ contain?(browser: CeilingBrowser): void;log?(line: string): void;now?(): number;}@@ -119,21 +126,32 @@ export function tabsClosedNote(usedBytes: number, closed: readonly CeilingTab[])return `This browser was using ${mb(usedBytes)} MB of this computer's memory, so its other tabs were closed to keep everything else running: ${closed.map(page).join("; ")}. Open one again if you still need it. Earlier @eN refs are gone: take a new snapshot before acting.`;}+type Seen = { browser: CeilingBrowser; used: number; each: Map<number, number> };+export function createBrowserCeiling(deps: BrowserCeilingDeps) {const now = deps.now ?? Date.now;const log = deps.log ?? ((line: string) => console.warn(line));const notes = new Map<string, string>();const acted = new Map<string, number>();let running = false;+ /** Each browser as the last look found it, with each process's size, and the kernel's kill count then. */+ let seen = new Map<string, Seen>();+ let kills: number | null = null, unexplained = false;- function size(browser: CeilingBrowser): number | null {- let total = 0, read = 0;+ /** A browser's size, and each of its processes' where a kernel kill may need to be explained (kernelKills). With memory+ * short, from statm (quickSize), which takes no lock. */+ function measure(browser: CeilingBrowser, short: boolean): { used: number | null; each: Map<number, number> } {+ const each = new Map<number, number>();+ const quick = short && deps.quickSize ? deps.quickSize : null;+ if (quick) {+ if (deps.kernelKills) for (const pid of browser.pids) { const bytes = quick([pid]); if (bytes !== null) each.set(pid, bytes); }+ return { used: quick(browser.pids), each };+ }for (const pid of browser.pids) {const bytes = deps.pss(pid);- if (bytes === null) continue;- total += bytes; read += 1;+ if (bytes !== null) each.set(pid, bytes);}- return read ? total : null;+ return { used: each.size ? [...each.values()].reduce((sum, bytes) => sum + bytes, 0) : null, each };}async function closeBackgroundTabs(session: string, used: number): Promise<boolean> {@@ -152,9 +170,10 @@ export function createBrowserCeiling(deps: BrowserCeilingDeps) {}/** Whether the browser is over its soft line. `short`: memory available is under relief's floor. */- async function check(browser: CeilingBrowser, short: boolean): Promise<boolean> {- const used = short && deps.quickSize ? deps.quickSize(browser.pids) : size(browser);+ async function check(browser: CeilingBrowser, short: boolean, looked: Map<string, Seen>): Promise<boolean> {+ const { used, each } = measure(browser, short);const { session } = browser;+ if (used !== null) looked.set(session, { browser, used, each });if (used === null || used < deps.lines.softBytes) return false;const at = now();// Ahead of the minute between actions: a refused close must not keep a growing browser from this for a minute.@@ -167,6 +186,30 @@ export function createBrowserCeiling(deps: BrowserCeilingDeps) {return true;}+ /** The kernel killed at the browsers' limit since the last look. Its victim is about the largest process in the group, and+ * Chrome loses small renderers all the time (a navigation, a closed tab): the browser whose largest lost process was the+ * largest is closed, and the turn that held it ends with the line that the browser was closed for memory. Nothing is+ * closed when no process lost since was large enough to be the victim; the next look tries again. */+ async function afterKernelKill(browsers: readonly CeilingBrowser[]): Promise<boolean> {+ const found = new Map(browsers.map((browser) => [browser.session, browser]));+ let hit: Seen | null = null, victim = 0;+ for (const before of seen.values()) {+ const pids = new Set(found.get(before.browser.session)?.pids ?? []);+ for (const [pid, bytes] of before.each) {+ if (pid === before.browser.daemon || pids.has(pid) || bytes <= victim) continue;+ hit = before; victim = bytes;+ }+ }+ if (!hit || victim < VICTIM_MIN_BYTES || !deps.forceClose) return false;+ const { session } = hit.browser;+ const current = found.get(session) ?? { session, pids: [], ...(hit.browser.daemon === undefined ? {} : { daemon: hit.browser.daemon }) };+ if (await deps.forceClose(current, hit.used).catch(() => false)) {+ acted.set(session, now());+ log(`browser ${session}: the kernel stopped a ${mb(victim)} MB process of it at the browsers' memory limit (${mb(hit.used)} MB at the last look); closed it, with the turn that held it, if any`);+ }+ return true;+ }+async function act(browser: CeilingBrowser, used: number, at: number): Promise<void> {const { session } = browser;if (at - (acted.get(session) ?? -Infinity) < ACT_EVERY_MS) return;@@ -191,8 +234,18 @@ export function createBrowserCeiling(deps: BrowserCeilingDeps) {const browsers = await deps.browsers();const live = new Set(browsers.map((browser) => browser.session));for (const session of acted.keys()) if (!live.has(session)) acted.delete(session);+ const killed = deps.kernelKills?.() ?? null;+ // A kill no lost process explains yet (its victim not reaped at this look) is looked for once more, then let go.+ if (killed !== null && kills !== null && killed > kills && !await afterKernelKill(browsers).catch(() => false) && !unexplained) unexplained = true;+ else { kills = killed ?? kills; unexplained = false; }const short = deps.memoryShort?.() ?? false;- for (const browser of browsers) if (await check(browser, short).catch(() => false)) large = true;+ const looked = new Map<string, Seen>();+ for (const browser of browsers) {+ try { deps.contain?.(browser); } catch {}+ if (await check(browser, short, looked).catch(() => false)) large = true;+ }+ // The look before the kill is kept while one is unexplained: its sizes are what the victim is found by.+ if (!unexplained) seen = looked;} finally { running = false; }return large && (deps.memoryShort?.(2) ?? false);},diff --git a/server/browser/memory-cgroup.linux.test.ts b/server/browser/memory-cgroup.linux.test.tsnew file mode 100644index 0000000000..f152142884--- /dev/null+++ b/server/browser/memory-cgroup.linux.test.ts@@ -0,0 +1,128 @@+// The browsers' kernel memory limit on a real kernel, as the Cloud home's root supervisor sets it up: a "server" child,+// running as an unprivileged user in its own leaf, starts a memory-hungry "Chrome" through the generated launcher; the+// launcher moves it into the browsers' group; the kernel kills it at the group's limit; the server keeps answering.+// It needs root and a cgroup v2 tree with the memory controller: CI runs it as root in the build job+// (OMB_CGROUP_TEST=require, where it fails rather than skips); elsewhere it is skipped.+import { spawn, type ChildProcess } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";+import { request } from "node:http";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { launcherScript } from "./chrome/wrapper.ts";+import { groupOomKills, ownCgroupDir, setUpBrowserCgroup, spawnInCgroup } from "./memory-cgroup.ts";++const MB = 1_048_576;+const required = process.env.OMB_CGROUP_TEST === "require";+const root = process.platform === "linux" && process.getuid?.() === 0;+const v2 = process.platform === "linux" && existsSync("/sys/fs/cgroup/cgroup.controllers")+ && /(^|\s)memory(\s|$)/.test(readFileSync("/sys/fs/cgroup/cgroup.controllers", "utf8"));+/** nobody, as maus is on a Cloud home: the supervisor gives it the right to move its own processes, and nothing else. */+const NOBODY = { uid: 65_534, gid: 65_534 };++function answer(port: number): Promise<string> {+ return new Promise((resolve, reject) => {+ const req = request({ host: "127.0.0.1", port, path: "/", timeout: 5_000 }, (res) => {+ let body = "";+ res.on("data", (chunk) => { body += String(chunk); });+ res.on("end", () => resolve(body));+ });+ req.on("timeout", () => req.destroy(new Error("no answer in 5 s")));+ req.on("error", reject);+ req.end();+ });+}++function lines(child: ChildProcess): { next(pattern: RegExp, ms: number): Promise<string>; all: string[] } {+ const all: string[] = [];+ const waiting: Array<{ pattern: RegExp; resolve: (line: string) => void }> = [];+ let rest = "";+ child.stdout!.on("data", (chunk) => {+ rest += String(chunk);+ let at: number;+ while ((at = rest.indexOf("\n")) >= 0) {+ const line = rest.slice(0, at); rest = rest.slice(at + 1);+ all.push(line);+ for (const wait of waiting.filter((one) => one.pattern.test(line))) { waiting.splice(waiting.indexOf(wait), 1); wait.resolve(line); }+ }+ });+ return {+ all,+ next: (pattern, ms) => new Promise((resolve, reject) => {+ const found = all.find((line) => pattern.test(line));+ if (found) { resolve(found); return; }+ const timer = setTimeout(() => reject(new Error(`no line like ${pattern} in ${ms} ms; saw: ${all.join(" | ")}`)), ms);+ waiting.push({ pattern, resolve: (line) => { clearTimeout(timer); resolve(line); } });+ }),+ };+}++describe.skipIf(!required && !(root && v2))("the browsers' kernel memory limit on a real kernel", () => {+ it("kills a browser over the limit while the server beside it keeps answering", async () => {+ expect(root, "run as root (the Cloud home's supervisor is)").toBe(true);+ expect(v2, "a cgroup v2 tree with the memory controller at /sys/fs/cgroup").toBe(true);+ // A fresh, empty cgroup of the test's own under the root one stands for the supervisor's; the test goes back to its own+ // cgroup after each spawn, as the supervisor does.+ const own = ownCgroupDir(readFileSync("/proc/self/cgroup", "utf8"))!;+ const base = join("/sys/fs/cgroup", `omb-test-${process.pid}-${Date.now()}`);+ // Under /tmp itself: the unprivileged "server" must reach it, and a runner's TMPDIR is its own, mode 0700.+ const work = mkdtempSync("/tmp/omb-cgroup-");+ chmodSync(work, 0o755);+ let server: ChildProcess | undefined;+ try {+ mkdirSync(base);+ const started = performance.now();+ const setup = setUpBrowserCgroup({ base, limitBytes: 160 * MB, ids: NOBODY });+ const took = performance.now() - started;+ console.log(`browser memory limit set up in ${took.toFixed(2)} ms`);+ expect(setup).toMatchObject({ ok: true });+ if (!setup.ok) return;+ expect(readFileSync(`${setup.group.browsers}/memory.max`, "utf8").trim()).toBe(String(160 * MB));+ // A runner has swap: the browsers may not use it, or a hog would swap rather than end.+ if (existsSync(`${setup.group.browsers}/memory.swap.max`)) expect(readFileSync(`${setup.group.browsers}/memory.swap.max`, "utf8").trim()).toBe("0");++ // "Chrome": fills memory 16 MB at a time, up to 2 GB, then waits.+ const hog = join(work, "hog.mjs");+ writeFileSync(hog, `#!${process.execPath}\nconst kept = [];\nfor (let i = 0; i < 128; i++) { kept.push(Buffer.alloc(16 * 1024 * 1024, 1)); }\nconsole.log("hog survived");\nsetInterval(() => {}, 1000);\n`);+ chmodSync(hog, 0o755);+ const launcher = join(work, "chrome-launcher.sh");+ writeFileSync(launcher, launcherScript({ chrome: hog, userAgent: "UA", screen: { width: 1280, height: 720 }, memoryGroup: setup.group.browsers }, "linux"));+ chmodSync(launcher, 0o755);++ // The "server": answers on a port, starts the launcher, and says how it ended.+ const serverScript = join(work, "server.cjs");+ writeFileSync(serverScript, [+ "const http = require('node:http'); const { spawn } = require('node:child_process'); const fs = require('node:fs');",+ "const s = http.createServer((q, r) => r.end('ok')).listen(0, '127.0.0.1', () => {",+ " console.log('port ' + s.address().port + ' cgroup ' + fs.readFileSync('/proc/self/cgroup', 'utf8').trim());",+ ` const c = spawn(${JSON.stringify(launcher)}, ['--headless'], { stdio: ['ignore', 'inherit', 'inherit'] });`,+ " console.log('chrome ' + c.pid);",+ " c.on('exit', (code, signal) => console.log('chrome ended ' + code + ' ' + signal));",+ "});",+ ].join("\n"));+ chmodSync(serverScript, 0o644);+ // The supervisor's cost on the start path: joining the leaf for the spawn and going back, beyond the spawn itself.+ const joinStarted = performance.now();+ spawnInCgroup(setup.group.server, own, () => undefined);+ console.log(`joining the server's leaf and going back took ${(performance.now() - joinStarted).toFixed(2)} ms`);+ server = spawnInCgroup(setup.group.server, own, () =>+ spawn(process.execPath, [serverScript], { uid: NOBODY.uid, gid: NOBODY.gid, cwd: work, stdio: ["ignore", "pipe", "inherit"] }));+ const out = lines(server);+ const first = await out.next(/^port \d+ cgroup /, 20_000);+ const port = Number(/^port (\d+)/.exec(first)![1]);+ expect(first).toMatch(new RegExp(`cgroup 0::${setup.group.server.slice("/sys/fs/cgroup".length)}$`));+ const ended = await out.next(/^chrome ended /, 60_000);+ expect(ended).toBe("chrome ended null SIGKILL");+ expect(out.all).not.toContain("hog survived");+ expect(groupOomKills(setup.group.browsers)).toBeGreaterThanOrEqual(1);+ // The server is still there, in its own leaf, and answers.+ expect(server.exitCode).toBeNull();+ expect(await answer(port)).toBe("ok");+ } finally {+ server?.kill("SIGKILL");+ await new Promise((resolve) => setTimeout(resolve, 300));+ for (const dir of [`${base}/omb/browsers`, `${base}/omb/server`, `${base}/omb`, base]) try { rmdirSync(dir); } catch {}+ rmSync(work, { recursive: true, force: true });+ }+ }, 120_000);+});diff --git a/server/browser/memory-cgroup.test.ts b/server/browser/memory-cgroup.test.tsnew file mode 100644index 0000000000..d24232a4fc--- /dev/null+++ b/server/browser/memory-cgroup.test.ts@@ -0,0 +1,133 @@+import { describe, expect, it } from "vitest";++import { launcherScript } from "./chrome/wrapper.ts";+import {+ browserCgroupDir, browserCgroupProblem, browserMemoryMax, containInGroup, defaultBrowserMemoryMax, groupOomKills, ownCgroupDir, prepareBrowserCgroup, setUpBrowserCgroup,+ spawnInCgroup, type CgroupFs,+} from "./memory-cgroup.ts";++const MB = 1_048_576;++/** A cgroup tree in memory: files by path, with the writes in order. */+function tree(files: Record<string, string>, fail: Record<string, string> = {}, readOnly = false) {+ const writes: string[] = [], made: string[] = [], owned: string[] = [];+ const fs: CgroupFs = {+ exists: (path) => path in files,+ writable: () => !readOnly,+ read: (path) => { if (!(path in files)) throw Object.assign(new Error("missing"), { code: "ENOENT" }); return files[path]!; },+ write: (path, data) => { if (fail[path]) throw Object.assign(new Error(fail[path]), { code: fail[path] }); writes.push(`${path} ${data}`); },+ mkdir: (path) => { made.push(path); },+ chown: (path, uid, gid) => { owned.push(`${path} ${uid}:${gid}`); },+ };+ return { fs, writes, made, owned };+}++describe("the bots' browsers' kernel memory limit", () => {+ it("is off unless turned on; on, it leaves the server, edge and engines 30% of the machine, at least 900 MB", () => {+ expect(browserMemoryMax({}, 2048 * MB)).toEqual({ on: false });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "off" }, 2048 * MB)).toEqual({ on: false });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "0" }, 2048 * MB)).toEqual({ on: false });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "auto" }, 2048 * MB)).toEqual({ on: true, bytes: 1148 * MB });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: " AUTO " }, 4096 * MB)).toEqual({ on: true, bytes: Math.round(4096 * MB * 0.7) });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "auto" }, 8192 * MB)).toEqual({ on: true, bytes: Math.round(8192 * MB * 0.7) });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "1500" }, 2048 * MB)).toEqual({ on: true, bytes: 1500 * MB });+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "12" }, 2048 * MB)).toEqual({ on: true, bytes: 256 * MB });+ const warned: string[] = [];+ expect(browserMemoryMax({ OMB_BROWSER_MEMORY_MAX: "lots" }, 2048 * MB, (line) => warned.push(line))).toEqual({ on: false });+ expect(warned).toHaveLength(1);+ expect([defaultBrowserMemoryMax(2048 * MB), defaultBrowserMemoryMax(1024 * MB)]).toEqual([1148 * MB, null]);+ // What a 2 GB Cloud reports: about 1970 MB.+ expect(defaultBrowserMemoryMax(1970 * MB)).toBe(1070 * MB);+ });++ it("finds this process's cgroup, and takes only a plain folder under /sys/fs/cgroup as the browsers' one", () => {+ expect(ownCgroupDir("0::/\n")).toBe("/sys/fs/cgroup");+ expect(ownCgroupDir("0::/system.slice/omb.service\n")).toBe("/sys/fs/cgroup/system.slice/omb.service");+ expect(ownCgroupDir("12:memory:/docker/abc\n1:name=systemd:/docker/abc\n")).toBeNull();+ expect(browserCgroupDir("/sys/fs/cgroup/omb/browsers")).toBe("/sys/fs/cgroup/omb/browsers");+ for (const bad of [undefined, "", "/tmp/omb", "/sys/fs/cgroup/../etc", "/sys/fs/cgroup/omb browsers", "/sys/fs/cgroup/omb/$(id)", "/sys/fs/cgroup/omb'x"]) expect(browserCgroupDir(bad)).toBeNull();+ });++ it("is set up under the supervisor's cgroup: server and browsers leaves, the limit, and maus may move its own processes between them", () => {+ // The machine's root cgroup (no cgroup.type), with processes in it: the memory controller may be turned on for children.+ const t = tree({ "/sys/fs/cgroup/cgroup.controllers": "cpuset cpu io memory pids", "/sys/fs/cgroup/cgroup.subtree_control": "", "/sys/fs/cgroup/cgroup.procs": "1\n412\n" });+ const setup = setUpBrowserCgroup({ base: "/sys/fs/cgroup", limitBytes: 1126 * MB, ids: { uid: 1000, gid: 1000 }, fs: t.fs });+ expect(setup).toEqual({ ok: true, group: { base: "/sys/fs/cgroup", server: "/sys/fs/cgroup/omb/server", browsers: "/sys/fs/cgroup/omb/browsers", limitBytes: 1126 * MB } });+ expect(t.made).toEqual(["/sys/fs/cgroup/omb", "/sys/fs/cgroup/omb/server", "/sys/fs/cgroup/omb/browsers"]);+ expect(t.writes).toEqual([+ "/sys/fs/cgroup/cgroup.subtree_control +memory",+ "/sys/fs/cgroup/omb/cgroup.subtree_control +memory",+ `/sys/fs/cgroup/omb/browsers/memory.max ${1126 * MB}`,+ "/sys/fs/cgroup/omb/browsers/memory.swap.max 0",+ ]);+ // Only the move files: memory.max stays root's.+ expect(t.owned).toEqual(["/sys/fs/cgroup/omb/cgroup.procs 1000:1000", "/sys/fs/cgroup/omb/server/cgroup.procs 1000:1000", "/sys/fs/cgroup/omb/browsers/cgroup.procs 1000:1000"]);+ });++ it("changes nothing where it can't be set up, and says why, mostly from reading alone", () => {+ // A container's own cgroup (it has a cgroup.type) holding its processes: nothing is written at all.+ const container = tree({ "/sys/fs/cgroup/cgroup.controllers": "cpu memory pids", "/sys/fs/cgroup/cgroup.subtree_control": "", "/sys/fs/cgroup/cgroup.type": "domain\n", "/sys/fs/cgroup/cgroup.procs": "1\n7\n" });+ expect(setUpBrowserCgroup({ base: "/sys/fs/cgroup", limitBytes: MB, ids: null, fs: container.fs })).toEqual({ ok: false, why: "processes share /sys/fs/cgroup (a container's own cgroup), and none are moved out of it" });+ expect([container.writes, container.made]).toEqual([[], []]);+ // The same refused by the kernel where the look could not tell.+ const busy = tree({ "/sys/fs/cgroup/cgroup.controllers": "cpu memory pids", "/sys/fs/cgroup/cgroup.subtree_control": "" }, { "/sys/fs/cgroup/cgroup.subtree_control": "EBUSY" });+ expect(setUpBrowserCgroup({ base: "/sys/fs/cgroup", limitBytes: MB, ids: null, fs: busy.fs })).toEqual({ ok: false, why: "processes share /sys/fs/cgroup (a container's own cgroup), and none are moved out of it" });+ expect(busy.made).toEqual([]);+ const v1 = tree({});+ expect(setUpBrowserCgroup({ base: "/sys/fs/cgroup", limitBytes: MB, ids: null, fs: v1.fs })).toMatchObject({ ok: false, why: expect.stringMatching(/^no cgroup v2 tree at \/sys\/fs\/cgroup/) });+ const noMemory = tree({ "/sys/fs/cgroup/cgroup.controllers": "cpu pids" });+ expect(browserCgroupProblem("/sys/fs/cgroup", noMemory.fs)).toBe("the memory controller is not offered at /sys/fs/cgroup");+ const readOnly = tree({ "/sys/fs/cgroup/cgroup.controllers": "memory", "/sys/fs/cgroup/cgroup.subtree_control": "" }, {}, true);+ expect(browserCgroupProblem("/sys/fs/cgroup", readOnly.fs)).toBe("/sys/fs/cgroup is read-only here");+ const failing = tree({ "/sys/fs/cgroup/cgroup.controllers": "memory", "/sys/fs/cgroup/cgroup.subtree_control": "memory" }, { "/sys/fs/cgroup/omb/cgroup.subtree_control": "EROFS" });+ expect(setUpBrowserCgroup({ base: "/sys/fs/cgroup", limitBytes: MB, ids: null, fs: failing.fs })).toEqual({ ok: false, why: "/sys/fs/cgroup/omb could not be set up (EROFS)" });+ // An empty cgroup of its own (a systemd service's leaf moved aside, or a test's): fine.+ expect(browserCgroupProblem("/sys/fs/cgroup/omb-test", tree({ "/sys/fs/cgroup/omb-test/cgroup.controllers": "memory", "/sys/fs/cgroup/omb-test/cgroup.type": "domain", "/sys/fs/cgroup/omb-test/cgroup.procs": "" }).fs)).toBeNull();+ // Already on (a machine's root cgroup under systemd): not written again.+ const on = tree({ "/sys/fs/cgroup/cgroup.controllers": "memory", "/sys/fs/cgroup/cgroup.subtree_control": "cpu memory" });+ expect(setUpBrowserCgroup({ base: "/sys/fs/cgroup", limitBytes: MB, ids: null, fs: on.fs }).ok).toBe(true);+ expect(on.writes[0]).toBe("/sys/fs/cgroup/omb/cgroup.subtree_control +memory");+ });++ it("logs one line at start: off with what a look found, writing nothing, or on with the limit and how long it took", () => {+ const clock = { t: 0 };+ const now = () => (clock.t += 0.4);+ const root = () => tree({ "/sys/fs/cgroup/cgroup.controllers": "memory", "/sys/fs/cgroup/cgroup.subtree_control": "", "/sys/fs/cgroup/cgroup.procs": "1\n" });+ const fly = root();+ expect(prepareBrowserCgroup({}, 2048 * MB, { uid: 1000, gid: 1000 }, { fs: fly.fs, procSelfCgroup: () => "0::/\n", now })).toEqual({ group: null,+ line: "browser memory limit: off (OMB_BROWSER_MEMORY_MAX=auto turns it on); it could be set here, in /sys/fs/cgroup/omb/browsers, 1148 MB (looked in 0.4 ms)" });+ expect([fly.writes, fly.made, fly.owned]).toEqual([[], [], []]);+ const docker = tree({ "/sys/fs/cgroup/cgroup.controllers": "memory", "/sys/fs/cgroup/cgroup.subtree_control": "", "/sys/fs/cgroup/cgroup.type": "domain", "/sys/fs/cgroup/cgroup.procs": "1\n" });+ expect(prepareBrowserCgroup({}, 4096 * MB, null, { fs: docker.fs, procSelfCgroup: () => "0::/\n", now }).line)+ .toBe("browser memory limit: off (OMB_BROWSER_MEMORY_MAX=auto turns it on); it could not be set here: processes share /sys/fs/cgroup (a container's own cgroup), and none are moved out of it (looked in 0.4 ms)");+ expect(prepareBrowserCgroup({}, 2048 * MB, null, { fs: fly.fs, procSelfCgroup: () => "1:name=systemd:/\n", now }).line).toMatch(/it could not be set here: this process is in no cgroup v2/);+ const on = root();+ const set = prepareBrowserCgroup({ OMB_BROWSER_MEMORY_MAX: "auto" }, 2048 * MB, { uid: 1000, gid: 1000 }, { fs: on.fs, procSelfCgroup: () => "0::/\n", now });+ expect(set.group?.browsers).toBe("/sys/fs/cgroup/omb/browsers");+ expect(set.line).toBe("browser memory limit: 1148 MB for the bots' Chrome together, in /sys/fs/cgroup/omb/browsers (set up in 0.4 ms)");+ });++ it("starts a child in a leaf by joining it for the spawn, then goes back", () => {+ const t = tree({});+ expect(spawnInCgroup("/sys/fs/cgroup/omb/server", "/sys/fs/cgroup", () => { t.writes.push("spawned"); return 7; }, t.fs)).toBe(7);+ expect(t.writes).toEqual([`/sys/fs/cgroup/omb/server/cgroup.procs ${process.pid}`, "spawned", `/sys/fs/cgroup/cgroup.procs ${process.pid}`]);+ const refused = tree({}, { "/sys/fs/cgroup/omb/server/cgroup.procs": "EACCES" });+ expect(spawnInCgroup("/sys/fs/cgroup/omb/server", "/sys/fs/cgroup", () => 8, refused.fs)).toBe(8);+ expect(refused.writes).toEqual([]);+ });++ it("moves into the group only a browser process that is not in it yet, and reads the kernel's kill count", () => {+ const t = tree({ "/proc/11/cgroup": "0::/omb/browsers\n", "/proc/12/cgroup": "0::/omb/server\n", "/sys/fs/cgroup/omb/browsers/memory.events": "low 0\nhigh 0\nmax 9\noom 2\noom_kill 2\n" });+ expect(containInGroup("/sys/fs/cgroup/omb/browsers", [11, 12, 13], t.fs)).toBe(1);+ expect(t.writes).toEqual(["/sys/fs/cgroup/omb/browsers/cgroup.procs 12"]);+ expect(groupOomKills("/sys/fs/cgroup/omb/browsers", t.fs.read)).toBe(2);+ expect(groupOomKills("/sys/fs/cgroup/none", t.fs.read)).toBeNull();+ });++ it("has Chrome join the group before anything else in its launcher, and only where one is given", () => {+ const settings = { chrome: "/opt/openmausbot-browser/chrome", userAgent: "UA", screen: { width: 1920, height: 1080 } };+ const lines = launcherScript({ ...settings, memoryGroup: "/sys/fs/cgroup/omb/browsers" }, "linux").split("\n");+ expect(lines.slice(0, 2)).toEqual(["#!/bin/sh", "{ echo $$ > '/sys/fs/cgroup/omb/browsers/cgroup.procs'; } 2>/dev/null"]);+ expect(launcherScript(settings, "linux")).not.toContain("cgroup");+ });+});diff --git a/server/browser/memory-cgroup.ts b/server/browser/memory-cgroup.tsnew file mode 100644index 0000000000..575f7d22a8--- /dev/null+++ b/server/browser/memory-cgroup.ts@@ -0,0 +1,184 @@+// The bots' Chrome on a Cloud home runs under a memory limit the kernel enforces, so a browser can never take the memory+// the server needs to keep answering. The server's own guards (memory-ceiling.ts, engine-memory.ts) run on its event+// loop; on a 2 GB home without swap a growing browser left the machine thrashing on its page cache, the server's own code+// was evicted, and nothing that could act ran any more (Nov 2026). Under a cgroup v2 `memory.max` the kernel reclaims and,+// at the limit, kills inside the browsers' group alone: the server, the edge and the engines keep their pages.+//+// Off unless OMB_BROWSER_MEMORY_MAX turns it on ("auto" or a number of MB): until then the supervisor only looks, without+// writing anything, and logs whether it could be set here. On, the root supervisor (cloud-home-start.ts) makes+// `<its cgroup>/omb/{server,browsers}`, puts the server in `server` and gives `maus` the right to move its own processes+// between the two (cgroup.procs of `omb` and of both leaves). Each Chrome+// moves itself into `browsers` before it starts: the generated launcher's first line (chrome/wrapper.ts). Anything missing+// (cgroup v1, a read-only cgroup tree, a container whose own cgroup holds its processes, as Docker's does) leaves things+// as they were, with one line in the log saying why. Nothing is moved out of a container's cgroup to make room: that would+// break `docker exec` into it.+import { accessSync, chownSync, constants, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { posix } from "node:path";++/** Read by the root supervisor only: unset or "off" (or 0) for no limit, "auto" for the default size, or a number of MB. */+export const BROWSER_MEMORY_MAX_ENV = "OMB_BROWSER_MEMORY_MAX";+/** Handed by the supervisor to the server: the browsers' cgroup folder, which every bot Chrome joins as it starts. */+export const BROWSER_CGROUP_ENV = "OMB_BROWSER_CGROUP";++const MB = 1_048_576;+/** What the browsers together leave the server, the edge and the engines: 30% of the machine, at least 900 MB. */+const RESERVE_SHARE = 0.3, RESERVE_FLOOR_BYTES = 900 * MB, SMALLEST_BYTES = 256 * MB;++/** The default limit: the machine's memory as the kernel reports it, less the reserve. A 2 GB Cloud reports about 1970 MB,+ * so about 1070 MB there, above one browser's hard line (985 MB), so the server's own close usually comes first; about+ * 2.8 GB on 4 GB and 5.6 GB on 8 GB. Null on a machine too small to leave a browser room. One group holds every bot's+ * browser, so this caps them together. */+export function defaultBrowserMemoryMax(memoryBytes: number): number | null {+ const limit = Math.round(memoryBytes - Math.max(RESERVE_FLOOR_BYTES, memoryBytes * RESERVE_SHARE));+ return limit >= 2 * SMALLEST_BYTES ? limit : null;+}++export type BrowserMemorySetting = { on: false } | { on: true; bytes: number | null };++/** OMB_BROWSER_MEMORY_MAX: off unless "auto" (the default size) or a number of MB. */+export function browserMemoryMax(env: NodeJS.ProcessEnv, memoryBytes: number, warn: (line: string) => void = () => undefined): BrowserMemorySetting {+ const raw = env[BROWSER_MEMORY_MAX_ENV]?.trim().toLowerCase() ?? "";+ if (/^\d+$/.test(raw) && !/^0+$/.test(raw)) return { on: true, bytes: Math.max(SMALLEST_BYTES, Number(raw) * MB) };+ if (raw === "auto") return { on: true, bytes: memoryBytes > 0 ? defaultBrowserMemoryMax(memoryBytes) : null };+ if (raw && raw !== "off" && !/^0+$/.test(raw)) warn(`${BROWSER_MEMORY_MAX_ENV}=${JSON.stringify(env[BROWSER_MEMORY_MAX_ENV])} is not "auto", a number of MB or "off", so it stays off`);+ return { on: false };+}++/** This process's cgroup folder in the v2 tree, from /proc/self/cgroup's "0::" line; null without one. */+export function ownCgroupDir(procSelfCgroup: string, mount = "/sys/fs/cgroup"): string | null {+ const own = /^0::(\/\S*)$/m.exec(procSelfCgroup)?.[1];+ return own === undefined ? null : own === "/" ? mount : posix.join(mount, own);+}++/** A browsers' cgroup folder the launcher may write to: an absolute path under /sys/fs/cgroup, nothing a shell would read. */+export function browserCgroupDir(value: string | undefined): string | null {+ const dir = value?.trim() ?? "";+ return /^\/sys\/fs\/cgroup(?:\/[A-Za-z0-9_.-]+)+$/.test(dir) && !dir.split("/").includes("..") ? dir : null;+}++export interface CgroupFs {+ read(path: string): string;+ write(path: string, data: string): void;+ mkdir(path: string): void;+ chown(path: string, uid: number, gid: number): void;+ exists(path: string): boolean;+ /** Whether this process may write the file (a read-only mount says no). */+ writable(path: string): boolean;+}++const realFs: CgroupFs = {+ exists: existsSync,+ writable: (path) => { try { accessSync(path, constants.W_OK); return true; } catch { return false; } },+ read: (path) => readFileSync(path, "utf8"),+ write: (path, data) => writeFileSync(path, data),+ mkdir: (path) => { try { mkdirSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } },+ chown: chownSync,+};++export interface BrowserCgroup { base: string; server: string; browsers: string; limitBytes: number }+export type BrowserCgroupSetup = { ok: true; group: BrowserCgroup } | { ok: false; why: string };++const code = (error: unknown) => (error as NodeJS.ErrnoException)?.code ?? (error instanceof Error ? error.message : String(error));+const hasMemory = (list: string) => /(^|\s)memory(\s|$)/.test(list);++/** What stands in the way of the group under `base` (the supervisor's own cgroup), found by reading only; null when+ * nothing does. A cgroup other than the machine's root one (it has a cgroup.type) that holds processes, as a container's+ * own does, can't have the memory controller turned on for children without moving them out first, which is not done. */+export function browserCgroupProblem(base: string, fs: Pick<CgroupFs, "read" | "exists" | "writable"> = realFs): string | null {+ let controllers: string;+ try { controllers = fs.read(`${base}/cgroup.controllers`); } catch (error) { return `no cgroup v2 tree at ${base} (${code(error)})`; }+ if (!hasMemory(controllers)) return `the memory controller is not offered at ${base}`;+ if (!fs.writable(`${base}/cgroup.subtree_control`)) return `${base} is read-only here`;+ let enabled = "";+ try { enabled = fs.read(`${base}/cgroup.subtree_control`); } catch {}+ let procs = "";+ try { procs = fs.read(`${base}/cgroup.procs`).trim(); } catch {}+ if (!hasMemory(enabled) && fs.exists(`${base}/cgroup.type`) && procs) return `processes share ${base} (a container's own cgroup), and none are moved out of it`;+ return null;+}++/** Root, once at start, before the server runs: the browsers' group under `base` (the supervisor's own cgroup). */+export function setUpBrowserCgroup(options: { base: string; limitBytes: number; ids: { uid: number; gid: number } | null; fs?: CgroupFs }): BrowserCgroupSetup {+ const fs = options.fs ?? realFs, { base } = options;+ const problem = browserCgroupProblem(base, fs);+ if (problem) return { ok: false, why: problem };+ let enabled = "";+ try { enabled = fs.read(`${base}/cgroup.subtree_control`); } catch {}+ if (!hasMemory(enabled)) {+ try { fs.write(`${base}/cgroup.subtree_control`, "+memory"); } catch (error) {+ return { ok: false, why: code(error) === "EBUSY"+ ? `processes share ${base} (a container's own cgroup), and none are moved out of it`+ : `the memory controller could not be turned on at ${base} (${code(error)})` };+ }+ }+ const root = `${base}/omb`, server = `${root}/server`, browsers = `${root}/browsers`;+ try {+ for (const dir of [root, server, browsers]) fs.mkdir(dir);+ fs.write(`${root}/cgroup.subtree_control`, "+memory");+ fs.write(`${browsers}/memory.max`, String(options.limitBytes));+ // Nor swap beyond it (where swap is counted): at the limit a browser ends rather than pushes the machine into swap.+ try { fs.write(`${browsers}/memory.swap.max`, "0"); } catch {}+ if (options.ids) for (const dir of [root, server, browsers]) fs.chown(`${dir}/cgroup.procs`, options.ids.uid, options.ids.gid);+ } catch (error) {+ return { ok: false, why: `${root} could not be set up (${code(error)})` };+ }+ return { ok: true, group: { base, server, browsers, limitBytes: options.limitBytes } };+}++/** Starts a child in `dir`: this process joins it for the spawn (a child is born in its parent's cgroup), then goes back to+ * `back`. Where it can't join, the child starts where this process is. */+export function spawnInCgroup<T>(dir: string, back: string, spawn: () => T, fs: Pick<CgroupFs, "write"> = realFs): T {+ try { fs.write(`${dir}/cgroup.procs`, String(process.pid)); } catch { return spawn(); }+ try { return spawn(); } finally { try { fs.write(`${back}/cgroup.procs`, String(process.pid)); } catch {} }+}++/** The kernel's count of processes it killed at the group's limit (memory.events), or null where it can't be read. */+export function groupOomKills(dir: string, read: (path: string) => string = (path) => readFileSync(path, "utf8")): number | null {+ try {+ const found = /^oom_kill (\d+)$/m.exec(read(`${dir}/memory.events`));+ return found ? Number(found[1]) : null;+ } catch {+ return null;+ }+}++/** The supervisor's part, and its one line for the log. Off (the default): it only looks, writing nothing, and says whether+ * the limit could be set here and how large it would be. On: the group set up, with how long that took. */+export function prepareBrowserCgroup(env: NodeJS.ProcessEnv, memoryBytes: number, ids: { uid: number; gid: number } | null,+ deps: { fs?: CgroupFs; procSelfCgroup?: () => string; now?: () => number } = {}): { group: BrowserCgroup | null; line: string } {+ const now = deps.now ?? (() => performance.now()), started = now();+ const warnings: string[] = [];+ const setting = browserMemoryMax(env, memoryBytes, (line) => warnings.push(line));+ const lead = `browser memory limit${warnings.length ? ` (${warnings.join("; ")})` : ""}`;+ let own: string | null = null;+ try { own = ownCgroupDir((deps.procSelfCgroup ?? (() => readFileSync("/proc/self/cgroup", "utf8")))()); } catch {}+ const would = setting.on ? setting.bytes : defaultBrowserMemoryMax(memoryBytes);+ if (!setting.on) {+ const problem = own === null ? "this process is in no cgroup v2" : browserCgroupProblem(own, deps.fs ?? realFs);+ const size = would === null ? "" : `, ${Math.round(would / MB)} MB`;+ return { group: null, line: `${lead}: off (${BROWSER_MEMORY_MAX_ENV}=auto turns it on); ${problem ? `it could not be set here: ${problem}` : `it could be set here, in ${own}/omb/browsers${size}`} (looked in ${(now() - started).toFixed(1)} ms)` };+ }+ if (setting.bytes === null) return { group: null, line: `${lead}: not set (this machine's memory is too small for one)` };+ if (own === null) return { group: null, line: `${lead}: not set (this process is in no cgroup v2)` };+ const setup = setUpBrowserCgroup({ base: own, limitBytes: setting.bytes, ids, ...(deps.fs ? { fs: deps.fs } : {}) });+ const took = `${(now() - started).toFixed(1)} ms`;+ return setup.ok+ ? { group: setup.group, line: `${lead}: ${Math.round(setting.bytes / MB)} MB for the bots' Chrome together, in ${setup.group.browsers} (set up in ${took})` }+ : { group: null, line: `${lead}: not set, ${setup.why} (${took})` };+}++/** Moves into the group each of these processes that is not in it yet (a Chrome started outside the launcher, or before+ * the limit), reading /proc/<pid>/cgroup first: a move takes a lock every fork on the machine waits on, so a process+ * already there is never moved again. How many moved. */+export function containInGroup(dir: string, pids: readonly number[], fs: Pick<CgroupFs, "read" | "write"> = realFs, mount = "/sys/fs/cgroup"): number {+ const inside = dir.startsWith(`${mount}/`) ? dir.slice(mount.length) : null;+ if (inside === null) return 0;+ let moved = 0;+ for (const pid of pids) {+ let own: string;+ try { own = /^0::(\/\S*)$/m.exec(fs.read(`/proc/${pid}/cgroup`))?.[1] ?? ""; } catch { continue; }+ if (!own || own === inside || own.startsWith(`${inside}/`)) continue;+ try { fs.write(`${dir}/cgroup.procs`, String(pid)); moved += 1; } catch {}+ }+ return moved;+}diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex 7ac534448f..5eed14830c 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -13,6 +13,7 @@ import {} from "./cloud-home.ts";import { procHidepid } from "./bot-box/hidepid.ts";import { boxMemory, heapSizeArgs } from "./box-memory.ts";+import { BROWSER_CGROUP_ENV, prepareBrowserCgroup, spawnInCgroup } from "./browser/memory-cgroup.ts";import { clearRecordsFromOtherMachines } from "./data-dir-lease.ts";import { OOM_SCORE, protectInit, protectSupervisor, spawnWithOomScore } from "./oom-score.ts";import { restartLine, restartPolicy } from "./restart.ts";@@ -451,6 +452,13 @@ export function startCloudHome(processEnv: NodeJS.ProcessEnv = process.env) {}// Names only, never values: what the server does not get from here.if (dropped.length) console.log(`cloud home: not passed to the server: ${dropped.join(", ")}`);+ // The bots' Chrome under a memory limit the kernel enforces (browser/memory-cgroup.ts); the server is started in its own+ // leaf beside it. Root only: nothing changes where it can't be set up.+ const browserLimit = ids && process.platform === "linux" ? prepareBrowserCgroup(env, boxMemory().bytes, ids) : null;+ if (browserLimit) console.log(`cloud home: ${browserLimit.line}`);+ const browserGroup = browserLimit?.group ?? null;+ if (browserGroup) server[BROWSER_CGROUP_ENV] = browserGroup.browsers;+ const inServerGroup = <T>(start: () => T): T => browserGroup ? spawnInCgroup(browserGroup.server, browserGroup.base, start) : start();const children: ChildProcess[] = [];let stopping = false, restartTimer: ReturnType<typeof setTimeout> | undefined;const stop = (failed: boolean) => {@@ -473,7 +481,7 @@ export function startCloudHome(processEnv: NodeJS.ProcessEnv = process.env) {const policy = restartPolicy();const runServer = () => {if (stopping) return;- watch(spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids)), (code, signal) => {+ watch(inServerGroup(() => spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids))), (code, signal) => {if (!policy.again(code, stopping, signal)) return false;console.warn(`cloud home: ${restartLine(code, policy.delayMs())}`);if (policy.delayMs() > 0) restartTimer = setTimeout(runServer, policy.delayMs());diff --git a/server/host/browser.ts b/server/host/browser.tsindex 3a1e92d237..361bfd9381 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -43,6 +43,7 @@ import { browserEngineKind, browserPaneWanted, cloudDisplayWanted, type BrowserEimport { parseSocks5Proxy } from "../browser/egress/policy.ts";import { ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter } from "../browser/engines.ts";import { ceilingLines, createBrowserCeiling, killChrome, startCeilingLoop, statmBytes } from "../browser/memory-ceiling.ts";+import { BROWSER_CGROUP_ENV, browserCgroupDir, containInGroup, groupOomKills } from "../browser/memory-cgroup.ts";import { browserProcessTree } from "../browser-processes.ts";import { pssBytes } from "../bot-memory-cap.ts";import { boxMemory } from "../box-memory.ts";@@ -313,8 +314,14 @@ export function createBrowserHost(deps: BrowserHostDeps) {return agentBrowserSweep.closeAll();},};- // Linux servers only: there a browser's proportional size can be read, and its memory is the home's.+ // Linux servers only: there a browser's proportional size can be read, and its memory is the home's. A Cloud home's root+ // supervisor may also have put the bots' Chrome under a kernel memory limit (browser/memory-cgroup.ts).+ const browserGroup = process.platform === "linux" ? browserCgroupDir(process.env[BROWSER_CGROUP_ENV]) : null;const browserCeiling = process.platform === "linux" && !DESKTOP_MANAGED ? createBrowserCeiling({+ ...(browserGroup ? {+ kernelKills: () => groupOomKills(browserGroup),+ contain: ({ pids, daemon }: { pids: readonly number[]; daemon?: number }) => { containInGroup(browserGroup, pids.filter((pid) => pid !== daemon)); },+ } : {}),lines: ceilingLines(boxMemory().bytes),browsers: async () => (await Promise.all(browserOwners().map(async ({ pid, session }) => {const spec = usedBrowserSessions.get(session);