Skip to content

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

Browser memory: close a turn's browser over its hard line when memory is short or it is far over (#7226)

Milind Soni0837d73081b1
diff --git a/server/browser/memory-ceiling.linux.test.ts b/server/browser/memory-ceiling.linux.test.ts
new file mode 100644
index 0000000000..2796cddd4c
--- /dev/null
+++ b/server/browser/memory-ceiling.linux.test.ts
@@ -0,0 +1,58 @@
+// The forced close's process side on a real kernel: a "daemon" that started two "Chrome" processes in a process group of
+// their own, as agent-browser does. killChrome stops the Chrome processes and leaves the daemon; a pid whose start time no
+// longer matches what was listed is left alone; statm sizes real processes. Runs in CI's Linux vitest shards.
+import { spawn, type ChildProcess } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+import { killChrome, statmBytes } from "./memory-ceiling.ts";
+
+const startTime = (pid: number): string => {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]!;
+};
+const state = (pid: number): string | null => {
+ try { const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]!; } catch { return null; }
+};
+const gone = (pid: number) => { const now = state(pid); return now === null || now === "Z" || now === "X"; };
+
+async function until(check: () => boolean, ms: number): Promise<boolean> {
+ const end = Date.now() + ms;
+ while (Date.now() < end) { if (check()) return true; await new Promise((resolve) => setTimeout(resolve, 50)); }
+ return check();
+}
+
+describe.skipIf(process.platform !== "linux")("a forced close on a real kernel", () => {
+ it("SIGKILLs the browser's Chrome processes and leaves its daemon, and never a pid that now runs something else", async () => {
+ const script = [
+ "const { spawn } = require('node:child_process');",
+ "const a = spawn('sleep', ['60'], { detached: true, stdio: 'ignore' });",
+ "const b = spawn('sleep', ['60'], { detached: true, stdio: 'ignore' });",
+ "const ended = [];",
+ "for (const [name, child] of [['a', a], ['b', b]]) child.on('exit', (code, signal) => { ended.push(name + ' ' + signal); if (ended.length === 2) console.log('ended ' + ended.sort().join(', ')); });",
+ "console.log('chrome ' + a.pid + ' ' + b.pid);",
+ "setInterval(() => {}, 1000);",
+ ].join("\n");
+ let daemon: ChildProcess | undefined, other: ChildProcess | undefined;
+ try {
+ daemon = spawn(process.execPath, ["-e", script], { stdio: ["ignore", "pipe", "inherit"] });
+ let out = "";
+ daemon.stdout!.on("data", (chunk) => { out += String(chunk); });
+ expect(await until(() => /chrome \d+ \d+/.test(out), 10_000)).toBe(true);
+ const [a, b] = /chrome (\d+) (\d+)/.exec(out)!.slice(1).map(Number) as [number, number];
+ // A process that has since taken a listed pid: its start time differs from the one listed.
+ other = spawn("sleep", ["60"], { stdio: "ignore" });
+ const started = new Map([[daemon.pid!, startTime(daemon.pid!)], [a, startTime(a)], [b, startTime(b)], [other.pid!, "1"]]);
+ expect(statmBytes([daemon.pid!, a, b])).toBeGreaterThan(0);
+
+ expect(killChrome({ session: "bot-a", pids: [daemon.pid!, a, b, other.pid!], daemon: daemon.pid!, started })).toBe(2);
+ expect(await until(() => /ended a SIGKILL, b SIGKILL/.test(out), 10_000)).toBe(true);
+ expect(gone(a) && gone(b)).toBe(true);
+ expect(gone(daemon.pid!)).toBe(false);
+ expect(gone(other.pid!)).toBe(false);
+ } finally {
+ daemon?.kill("SIGKILL");
+ other?.kill("SIGKILL");
+ }
+ }, 30_000);
+});
diff --git a/server/browser/memory-ceiling.test.ts b/server/browser/memory-ceiling.test.ts
index 78feafe653..630b11c400 100644
--- a/server/browser/memory-ceiling.test.ts
+++ b/server/browser/memory-ceiling.test.ts
@@ -1,29 +1,32 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import { ceilingLines, createBrowserCeiling, type BrowserCeilingDeps, type CeilingTab } from "./memory-ceiling.ts";
+import { ceilingLines, createBrowserCeiling, killChrome, mustForceClose, startCeilingLoop, statmBytes, type BrowserCeilingDeps, type CeilingTab } from "./memory-ceiling.ts";
const MB = 1_048_576;
-function harness(options: { sizes?: Record<number, number | null>; quiet?: boolean; tabs?: CeilingTab[] | null; closes?: boolean } = {}) {
+function harness(options: { sizes?: Record<number, number | null>; quiet?: boolean; tabs?: CeilingTab[] | null; closes?: boolean; short?: boolean; tight?: boolean; forces?: boolean; quick?: number } = {}) {
const sizes: Record<number, number | null> = options.sizes ?? { 10: 300 * MB, 11: 500 * MB };
- const state = { now: 0, quiet: options.quiet ?? true, tabs: options.tabs === undefined ? [
+ const state = { now: 0, short: options.short ?? false, tight: options.tight ?? false, quiet: options.quiet ?? true, tabs: options.tabs === undefined ? [
{ tabId: "t1", title: "Inbox", url: "https://mail.example/", active: false },
{ tabId: "t2", title: "Report", url: "https://example.com/report", active: true },
{ tabId: "t3", title: "", url: "https://news.example/a", active: false },
] : options.tabs };
- const closedTabs: string[] = [], closed: string[] = [], logs: string[] = [];
+ const closedTabs: string[] = [], closed: string[] = [], forced: string[] = [], logs: string[] = [];
const deps: BrowserCeilingDeps = {
lines: { softBytes: 700 * MB, hardBytes: 1000 * MB },
- browsers: async () => [{ session: "bot-a", pids: Object.keys(sizes).map(Number) }],
+ browsers: async () => [{ session: "bot-a", pids: Object.keys(sizes).map(Number), daemon: 10 }],
pss: (pid) => sizes[pid] ?? null,
quiet: () => state.quiet,
tabs: async () => state.tabs,
closeTab: async (_session, tabId) => { closedTabs.push(tabId); return true; },
close: async (session) => { closed.push(session); return options.closes ?? true; },
+ memoryShort: (times = 1) => state.short || (times >= 2 && state.tight),
+ ...(options.quick === undefined ? {} : { quickSize: () => options.quick! * MB }),
+ forceClose: async (browser, used) => { forced.push(`${browser.session} ${Math.round(used / MB)} MB, daemon ${browser.daemon}`); return options.forces ?? true; },
log: (line) => logs.push(line),
now: () => state.now,
};
- return { ceiling: createBrowserCeiling(deps), state, sizes, closedTabs, closed, logs };
+ return { ceiling: createBrowserCeiling(deps), state, sizes, closedTabs, closed, forced, logs };
}
describe("a bot browser's memory ceiling", () => {
@@ -106,4 +109,94 @@ describe("a bot browser's memory ceiling", () => {
expect(silent.closedTabs).toEqual([]);
expect(silent.ceiling.takeNote("bot-a")).toBeNull();
});
+
+ it("closes a browser whatever holds it only over its hard line with memory short, never for its size alone", () => {
+ const lines = { softBytes: 700 * MB, hardBytes: 1000 * MB };
+ const table: Array<[number, boolean, boolean]> = [
+ // used MB, memory short, closed whatever holds it
+ [690, true, false], [999, true, false],
+ [1000, true, true], [1100, true, true],
+ [1000, false, false], [1250, false, false], [9800, false, false],
+ ];
+ for (const [used, short, force] of table) expect([used, short, mustForceClose(used * MB, lines, short)]).toEqual([used, short, force]);
+ });
+
+ it("a turn's browser over its hard line on a healthy machine is kept open, as before", async () => {
+ const run = harness({ sizes: { 10: 600 * MB, 11: 500 * MB }, quiet: false, closes: false });
+ await run.ceiling.tick();
+ expect(run.forced).toEqual([]);
+ expect(run.logs.at(-1)).toMatch(/kept open/u);
+ });
+
+ it("however large a turn's browser grows, with memory plentiful it is kept", async () => {
+ const run = harness({ sizes: { 10: 1800 * MB, 11: 700 * MB }, quiet: false, closes: false });
+ await run.ceiling.tick();
+ expect(run.forced).toEqual([]);
+ expect(run.logs.at(-1)).toMatch(/2500 MB, over its hard line of 1000 MB; kept open/u);
+ });
+
+ it("over its hard line with memory short, a turn's browser is closed at once, with no minute's wait after a refused close", async () => {
+ const run = harness({ sizes: { 10: 600 * MB, 11: 500 * MB }, quiet: false, closes: false });
+ await run.ceiling.tick();
+ expect(run.forced).toEqual([]);
+ run.state.short = true;
+ run.state.now = 3_000;
+ await run.ceiling.tick();
+ expect(run.forced).toEqual(["bot-a 1100 MB, daemon 10"]);
+ expect(run.logs.at(-1)).toMatch(/1100 MB, over its hard line of 1000 MB with memory short; closed it at once/u);
+ });
+
+ it("with memory short, sizes a browser without its memory map's lock", async () => {
+ const run = harness({ sizes: { 10: 100 * MB, 11: 100 * MB }, quiet: false, short: true, quick: 1500 });
+ await run.ceiling.tick();
+ expect(run.forced).toEqual(["bot-a 1500 MB, daemon 10"]);
+ });
+
+ it("falls back to the usual steps when the forced close fails, and tries it again on the next look", async () => {
+ const run = harness({ sizes: { 10: 800 * MB, 11: 500 * MB }, quiet: false, short: true, forces: false, closes: false });
+ await run.ceiling.tick();
+ expect(run.logs.at(-1)).toMatch(/kept open/u);
+ run.state.now = 3_000;
+ await run.ceiling.tick();
+ expect(run.forced).toHaveLength(2);
+ });
+
+ it("asks for a sooner look only while a browser is over its soft line and memory is under twice the floor", async () => {
+ expect(await harness({ sizes: { 10: 300 * MB, 11: 300 * MB }, tight: true }).ceiling.tick()).toBe(false);
+ expect(await harness().ceiling.tick()).toBe(false);
+ expect(await harness({ tight: true }).ceiling.tick()).toBe(true);
+ });
+
+ it("looks every 15 s, and 3 s after a look that asks for a sooner one", async () => {
+ vi.useFakeTimers();
+ try {
+ const answers = [true, false, false];
+ const at: number[] = [];
+ const loop = startCeilingLoop(async () => { at.push(Date.now()); return answers.shift() ?? false; });
+ const start = Date.now();
+ for (let i = 0; i < 4; i++) await vi.advanceTimersToNextTimerAsync();
+ loop.stop();
+ expect(at.map((time) => time - start)).toEqual([15_000, 18_000, 33_000, 48_000]);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(at).toHaveLength(4);
+ } finally { vi.useRealTimers(); }
+ });
+
+ it("sizes a browser from statm: each process's own pages, and the shared ones once", () => {
+ const files: Record<string, string> = { "/proc/10/statm": "1000 300 100 1 0 200 0\n", "/proc/11/statm": "2000 500 150 1 0 400 0\n" };
+ const read = (path: string) => { if (!(path in files)) throw new Error("gone"); return files[path]!; };
+ expect(statmBytes([10, 11, 12], read)).toBe((200 + 350 + 150) * 4096);
+ expect(statmBytes([12], read)).toBeNull();
+ });
+
+ it("kills a browser's Chrome, never its daemon, a zombie, or a pid that now runs another program", () => {
+ const stat = (state: string, started: string) => `1 (chrome --type=renderer (x)) ${state} 1 1 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 ${started} 0 0`;
+ const files: Record<string, string> = { "/proc/10/stat": stat("S", "500"), "/proc/11/stat": stat("S", "600"), "/proc/12/stat": stat("S", "999"), "/proc/13/stat": stat("Z", "700"), "/proc/15/stat": stat("S", "800") };
+ const killed: string[] = [];
+ const count = killChrome({ session: "bot-a", pids: [10, 11, 12, 13, 14, 15], daemon: 10, started: new Map([[10, "500"], [11, "600"], [12, "650"], [13, "700"], [14, "750"]]) },
+ (path) => { if (!(path in files)) throw new Error("gone"); return files[path]!; }, (pid, signal) => killed.push(`${pid} ${signal}`));
+ // 12 was reused, 13 has exited, 14 is gone, 15 has no start time listed.
+ expect(killed).toEqual(["11 SIGKILL"]);
+ expect(count).toBe(1);
+ });
});
diff --git a/server/browser/memory-ceiling.ts b/server/browser/memory-ceiling.ts
index b369c3caa5..e59f50b5d3 100644
--- a/server/browser/memory-ceiling.ts
+++ b/server/browser/memory-ceiling.ts
@@ -1,11 +1,21 @@
// One bot browser never takes a Linux server's memory. Each running browser (agent-browser's daemon and its Chrome) is
// measured by proportional set size, shared pages counted once: a sum of RSS over Chrome's 10 to 30 processes counts
// the browser binary's pages in every one of them. Over its soft line, between calls, its background tabs close and the
-// bot hears which on its next call. Over its hard line it is closed only through memory relief's own close, which keeps
-// a browser a turn holds, one a call runs in, and one attached to the person's own Chrome.
+// bot hears which on its next call. Over its hard line it is closed through memory relief's own close, which keeps a
+// browser a turn holds, one a call runs in, and one attached to the person's own Chrome, except while memory available is
+// under relief's floor: then it is closed whatever holds it, and the turn holding it ends saying so. A large browser on a
+// machine with memory to spare is never closed for its size alone. A 2 GB Cloud with no swap went from a 1.3 GB browser
+// kept open to frozen in under two minutes (Nov 2026): the machine thrashed on its page cache and the server, which holds
+// every guard, could no longer run.
+import { readFileSync } from "node:fs";
const MB = 1_048_576;
export const CEILING_TICK_MS = 15_000;
+/** While a browser is over its soft line and memory available is under twice relief's floor, the next look comes this
+ * soon instead: a Starter with an ordinary 700–900 MB browser and memory to spare is looked at no more often. */
+export const CEILING_FAST_TICK_MS = 3_000;
+/** Linux's page size on the machines a Cloud runs on (x86-64): /proc/<pid>/statm counts pages. */
+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;
@@ -16,7 +26,64 @@ export function ceilingLines(memoryBytes: number): CeilingLines {
return { softBytes: Math.max(600 * MB, Math.round(memoryBytes / 3)), hardBytes: Math.max(900 * MB, Math.round(memoryBytes / 2)) };
}
-export interface CeilingBrowser { session: string; pids: readonly number[] }
+/** `daemon`: agent-browser's own process, the root of `pids`; the rest are its Chrome's. `started`: each pid's start time
+ * when it was listed (browser-processes.ts), so a pid the system has since given to another program is never signalled. */
+export interface CeilingBrowser { session: string; pids: readonly number[]; daemon?: number; started?: ReadonlyMap<number, string> }
+
+/** Whether a browser this size is closed even while a turn holds it or a call runs in it: over its hard line with memory
+ * available (not counting swap) under relief's floor. Never for its size alone, however large next to the machine. */
+export function mustForceClose(usedBytes: number, lines: CeilingLines, memoryShort: boolean): boolean {
+ return memoryShort && usedBytes >= lines.hardBytes;
+}
+
+type Read = (path: string) => string;
+const readText: Read = (path) => readFileSync(path, "utf8");
+
+/** A browser's size from /proc/<pid>/statm, which takes no lock on the process's memory map (smaps_rollup does, and under
+ * memory pressure a read of it can wait as long as the process does): each process's own pages, and the largest share
+ * of file and shared pages once, as they are mostly Chrome's one binary. Null where none could be read. */
+export function statmBytes(pids: readonly number[], read: Read = readText): number | null {
+ let own = 0, shared = 0, counted = 0;
+ for (const pid of pids) {
+ let fields: number[];
+ try { fields = read(`/proc/${pid}/statm`).trim().split(/\s+/).map(Number); } catch { continue; }
+ const [, resident, file] = fields;
+ if (!Number.isFinite(resident) || !Number.isFinite(file)) continue;
+ own += Math.max(0, resident! - file!); shared = Math.max(shared, file!); counted += 1;
+ }
+ return counted ? (own + shared) * PAGE_BYTES : null;
+}
+
+/** SIGKILLs a browser's Chrome processes (never its daemon), each only while its pid still runs the process that was
+ * listed: its start time (field 22 of /proc/<pid>/stat) is read again just before. How many were signalled. */
+export function killChrome(browser: CeilingBrowser, read: Read = readText, kill: (pid: number, signal: NodeJS.Signals) => void = (pid, signal) => { process.kill(pid, signal); }): number {
+ let killed = 0;
+ for (const pid of browser.pids) {
+ if (pid === browser.daemon || pid <= 1 || pid === process.pid) continue;
+ let stat: string;
+ try { stat = read(`/proc/${pid}/stat`); } catch { continue; }
+ // pid (comm) state ppid … starttime: comm may hold spaces and parentheses.
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ if (fields[0] === "Z" || fields[0] === "X") continue;
+ const listed = browser.started?.get(pid);
+ if (listed === undefined || listed === "" || fields[19] !== listed) continue;
+ try { kill(pid, "SIGKILL"); killed += 1; } catch {}
+ }
+ return killed;
+}
+
+/** Looks with `tick` every `slowMs`, and after a look that asks for a sooner one, `fastMs` later. */
+export function startCeilingLoop(tick: () => Promise<boolean>, options: { fastMs?: number; slowMs?: number } = {}): { stop(): void } {
+ const fastMs = options.fastMs ?? CEILING_FAST_TICK_MS, slowMs = options.slowMs ?? CEILING_TICK_MS;
+ let stopped = false, timer: ReturnType<typeof setTimeout> | undefined;
+ const next = (soon: boolean) => {
+ if (stopped) return;
+ timer = setTimeout(() => void tick().then(next, () => next(false)), soon ? fastMs : slowMs);
+ timer.unref?.();
+ };
+ next(false);
+ return { stop() { stopped = true; clearTimeout(timer); } };
+}
export interface CeilingTab { tabId: string; title: string; url: string; active: boolean }
export interface BrowserCeilingDeps {
@@ -30,6 +97,13 @@ export interface BrowserCeilingDeps {
closeTab(session: string, tabId: string): Promise<boolean>;
/** Memory relief's close; false when its rules keep the browser open. */
close(session: string): Promise<boolean>;
+ /** Memory available, not counting swap, is under relief's floor now (`times` the floor, where given). */
+ memoryShort?(times?: number): boolean;
+ /** A browser's size read without taking its memory map's lock (statmBytes): used while memory is short. */
+ quickSize?(pids: readonly number[]): number | null;
+ /** 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>;
log?(line: string): void;
now?(): number;
}
@@ -77,11 +151,24 @@ export function createBrowserCeiling(deps: BrowserCeilingDeps) {
return true;
}
- async function check(browser: CeilingBrowser): Promise<void> {
- const used = size(browser);
+ /** 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);
const { session } = browser;
- if (used === null || used < deps.lines.softBytes) return;
+ 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.
+ if (deps.forceClose && mustForceClose(used, deps.lines, short) && await deps.forceClose(browser, used).catch(() => false)) {
+ acted.set(session, at);
+ log(`browser ${session}: ${mb(used)} MB, over its hard line of ${mb(deps.lines.hardBytes)} MB with memory short; closed it at once, with the turn that held it, if any`);
+ return true;
+ }
+ await act(browser, used, at);
+ 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;
if (used < deps.lines.hardBytes) {
if (deps.quiet(session) && await closeBackgroundTabs(session, used)) acted.set(session, at);
@@ -94,15 +181,20 @@ export function createBrowserCeiling(deps: BrowserCeilingDeps) {
}
return {
- async tick(): Promise<void> {
- if (running) return;
+ /** One look at every browser; true when the next should come sooner (CEILING_FAST_TICK_MS): a browser is over its soft
+ * line and memory available is under twice relief's floor. */
+ async tick(): Promise<boolean> {
+ if (running) return false;
running = true;
+ let large = false;
try {
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);
- for (const browser of browsers) await check(browser).catch(() => undefined);
+ const short = deps.memoryShort?.() ?? false;
+ for (const browser of browsers) if (await check(browser, short).catch(() => false)) large = true;
} finally { running = false; }
+ return large && (deps.memoryShort?.(2) ?? false);
},
/** What the bot is told on its next call in this browser, once. */
takeNote(session: string): string | null {
diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.ts
index 5843214606..c4677d99a0 100644
--- a/server/engine-memory.test.ts
+++ b/server/engine-memory.test.ts
@@ -689,6 +689,45 @@ describe("bots' browsers", () => {
b.exit("SIGKILL");
expect(h.memory.stopText("b")).toBe(memoryStopText(false));
});
+
+ it("stops the only busy engine when the browser its turn holds is closed for memory, and its turn says the browser was closed", async () => {
+ const h = host();
+ // The ceiling kills Chrome right after: the browser no longer counts as running when the stop is noted.
+ const { closed } = browsers(h, []);
+ h.memory.turnStarted("a"); h.spawn("a");
+ expect(h.memory.stopForBrowser("a")).toBe(true);
+ await settle();
+ expect(h.signals).toEqual(["SIGKILL -1000"]);
+ expect(closed).toEqual(["a"]);
+ expect(h.memory.stopText("a")).toBe(memoryStopText(true));
+ // The automatic retry knows this line, and starts it again once per request (host/chief-notices.ts).
+ expect(memoryStopped(`${memoryStopText(true)} (claude exited null before result)`)).toBe(true);
+ // No engine of ours runs this turn: nothing to stop.
+ expect(h.memory.stopForBrowser("elsewhere")).toBe(false);
+ });
+
+ it("on an engine that carries two conversations, says the browser was closed only to the one whose browser it was", async () => {
+ const h = host();
+ browsers(h, []);
+ h.memory.turnStarted("a"); const shared = h.spawn("a");
+ h.memory.turnStarted("b"); h.memory.attach(shared as unknown as ChildProcess, "b");
+ expect(h.memory.stopForBrowser("a")).toBe(true);
+ await settle();
+ expect(h.memory.stopText("a")).toBe(memoryStopText(true));
+ expect(h.memory.stopText("b")).toBe(memoryStopText(false));
+ });
+
+ it("calls memory short only under relief's floor, not counting swap", () => {
+ const h = host();
+ h.state.swapFree = 4 * GB;
+ h.state.available = 420 * MB;
+ expect(h.memory.memoryShort()).toBe(false);
+ h.state.available = 400 * MB;
+ expect(h.memory.memoryShort()).toBe(true);
+ // Twice the floor: when the browser ceiling looks again sooner.
+ h.state.available = 800 * MB;
+ expect([h.memory.memoryShort(), h.memory.memoryShort(2)]).toEqual([false, true]);
+ });
});
function fakeInstance(driverKind = "opencodeGo") {
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index ba9c3bd1d3..7bfdc81e60 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -687,6 +687,29 @@ export class EngineMemory {
return memory !== null && this.free(memory) < this.floor(memory);
}
+ /** Memory available, not counting swap, is under relief's floor (`times` the floor, where given): a browser over its hard
+ * line then closes whatever holds it (browser/memory-ceiling.ts). False where memory can't be read. */
+ memoryShort(times = 1): boolean {
+ const memory = this.read();
+ return memory !== null && memory.availableBytes < this.floor(memory) * times;
+ }
+
+ /** The browser this thread's turn holds was closed for memory, whatever held it (browser/memory-ceiling.ts): the engine
+ * running that turn is stopped as relief stops one, and the turn ends with the line that the browser was closed. False
+ * when no engine here runs that turn. */
+ stopForBrowser(threadId: string): boolean {
+ const engine = [...this.engines.values()].find((candidate) => this.working(candidate).includes(threadId));
+ if (!engine) return false;
+ if (engine.stopping) return true;
+ const stopped = this.working(engine);
+ // A driver that carries other conversations stops them too; only this one's line says its browser was the cause.
+ this.noteStops(stopped, () => this.busy(), false, threadId);
+ this.noteRoomStopped(engine);
+ this.lastRelief = this.now();
+ void this.stop(engine, "relief").then(() => this.closeBrowsers(stopped));
+ return true;
+ }
+
/** Stops the engine idle longest, if any: what a browser that has no room to open asks before it is refused. */
async reclaimIdle(): Promise<boolean> {
const idle = this.enabled ? this.idle() : null;
@@ -802,10 +825,10 @@ export class EngineMemory {
}
/** These threads' turns were stopped for memory, with how many tasks ran then: each says whether its browser was closed. */
- private noteStops(threadIds: string[], count: (threadId: string) => number, only = false): void {
+ private noteStops(threadIds: string[], count: (threadId: string) => number, only = false, browserClosed?: string): void {
for (const threadId of threadIds) {
if (!this.stops.has(threadId)) this.ledger.note(this.now(), "stopped");
- this.stops.set(threadId, { count: count(threadId), browser: this.browsers?.running(threadId) === true, ...(only ? { only: true as const } : {}) });
+ this.stops.set(threadId, { count: count(threadId), browser: threadId === browserClosed || this.browsers?.running(threadId) === true, ...(only ? { only: true as const } : {}) });
}
}
diff --git a/server/host/browser.ts b/server/host/browser.ts
index d83f2407d5..3a1e92d237 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -42,7 +42,7 @@ import type { HostKind } from "../browser/chrome/flags.ts";
import { browserEngineKind, browserPaneWanted, cloudDisplayWanted, type BrowserEngineKind } from "../browser/config.ts";
import { parseSocks5Proxy } from "../browser/egress/policy.ts";
import { ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter } from "../browser/engines.ts";
-import { CEILING_TICK_MS, ceilingLines, createBrowserCeiling } from "../browser/memory-ceiling.ts";
+import { ceilingLines, createBrowserCeiling, killChrome, startCeilingLoop, statmBytes } from "../browser/memory-ceiling.ts";
import { browserProcessTree } from "../browser-processes.ts";
import { pssBytes } from "../bot-memory-cap.ts";
import { boxMemory } from "../box-memory.ts";
@@ -92,7 +92,7 @@ export interface BrowserHostDeps {
lentChrome?: { route(): ChromeRoute | null; lender(): ChromeLender | null };
/** The engine memory guard, told which browsers each thread's turn starts or holds. */
/** `selfHosted`: turns wait for room on this server, under its pids limit, and so do its bots' browsers. */
- engineMemory?: { useBrowsers(browsers: EngineBrowsers): void; selfHosted?(): boolean; roomFactor?(): number; reclaimIdle?(): Promise<boolean> };
+ engineMemory?: { useBrowsers(browsers: EngineBrowsers): void; selfHosted?(): boolean; roomFactor?(): number; reclaimIdle?(): Promise<boolean>; memoryShort?(times?: number): boolean; stopForBrowser?(threadId: string): boolean };
/** Whose browser a conversation's turns use on a Team Cloud: the member's, the group chat's or the team's. Every
* browser is the bot's own without it. */
audienceOf?(threadId: string): Audience;
@@ -293,22 +293,20 @@ export function createBrowserHost(deps: BrowserHostDeps) {
running: (session) => browserRunning(session, usedBrowserSessions.get(session)),
inUse: (session) => !turnResources.free(`browser:${session}`) || agentBrowserRuntime.working(session) });
let gateTimer: ReturnType<typeof setInterval> | undefined;
- let ceilingTimer: ReturnType<typeof setInterval> | undefined;
+ // Every 15 s, and every 3 s while a browser is large with memory getting short: a browser can take a small home's memory in minutes.
+ let ceilingLoop: { stop(): void } | undefined;
const browserSweep = {
start() {
gateTimer = setInterval(() => void releaseGates().catch(() => undefined), 60_000);
gateTimer.unref?.();
- if (browserCeiling) {
- ceilingTimer = setInterval(() => void browserCeiling.tick().catch(() => undefined), CEILING_TICK_MS);
- ceilingTimer.unref?.();
- }
+ if (browserCeiling) ceilingLoop = startCeilingLoop(() => browserCeiling.tick());
agentBrowserSweep.start();
chromeEngine.start({ inUse: browserEngineKind(cfg) === "chrome", prepare: builtInBrowserEnabled(cfg) });
return browserSweep;
},
closeAll: () => {
clearInterval(gateTimer);
- clearInterval(ceilingTimer);
+ ceilingLoop?.stop();
doors?.close();
doorUrls.clear();
leftovers.clear();
@@ -321,7 +319,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
browsers: async () => (await Promise.all(browserOwners().map(async ({ pid, session }) => {
const spec = usedBrowserSessions.get(session);
const tree = spec ? await browserProcessTree(spec.command, pid, session) : null;
- return tree ? [{ session, pids: [...tree.members.keys()] }] : [];
+ return tree ? [{ session, pids: [...tree.members.keys()], daemon: tree.daemon, started: tree.members }] : [];
}))).flat(),
pss: (pid) => pssBytes(pid),
quiet: (session) => !agentBrowserRuntime.working(session),
@@ -341,6 +339,20 @@ export function createBrowserHost(deps: BrowserHostDeps) {
savesSignIns: spare?.savesSignIns ?? spec.env.AGENT_BROWSER_RESTORE_SAVE === "auto" };
return reclaimable(candidate, false) && browserRuntime.closeUnused(session, spec);
},
+ memoryShort: (times) => deps.engineMemory?.memoryShort?.(times) ?? false,
+ quickSize: (pids) => statmBytes(pids),
+ // The holder's turn is stopped first, so its line says the browser was closed; Chrome's memory then comes back at once,
+ // and the daemon closes once no turn holds it (closeForMemory). Where no engine of this server runs the turn, Chrome is
+ // still stopped, and the turn's next browser call fails with no line about memory.
+ forceClose: async (browser) => {
+ const spec = usedBrowserSessions.get(browser.session);
+ if (!spec || chromeTarget(browser.session, spec) || attachesToChrome(spec.env)) return false;
+ const holder = turnResources.holder(`browser:${browser.session}`);
+ const ending = holder !== undefined && deps.engineMemory?.stopForBrowser?.(holder.threadId) === true;
+ killChrome(browser);
+ if (!ending) void closeForMemory(browser.session, spec);
+ return true;
+ },
}) : null;
function inRunningSession(session: string, args: string[]): Promise<Record<string, unknown> | null> {
const spec = usedBrowserSessions.get(session);
diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.ts
index 7aad56c459..ff87be5961 100644
--- a/server/host/chief-notices-retry.test.ts
+++ b/server/host/chief-notices-retry.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { TRIAL_CREDIT_REFUSED } from "../../shared/trial-credit.ts";
import "../server-line-packs.ts";
import { engineFailureMessage } from "../drivers/engine-errors.ts";
+import { memoryStopText } from "../engine-memory.ts";
import { AUTO_RETRY_LEAD, RETRY_BLOCKED } from "../incidents.ts";
import type { RoutineFailureFacts } from "../routine-recovery.ts";
import { createChiefNotices, MEMORY_RETRY_MS, MEMORY_RETRY_TEXT, ROOM_RETRY_TEXT, SERVER_MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";
@@ -193,6 +194,18 @@ describe("a run stopped to free memory", () => {
expect(f.told).toHaveLength(1);
});
+ it("starts a turn whose browser was closed for memory again once, never twice for one request, so a heavy page cannot loop", () => {
+ const f = roomFixture();
+ const closedBrowser = `${memoryStopText(true)} (claude exited null before result)`;
+ f.store.appendMessage("chief-main", { role: "user", kind: "text", text: "Read the long report." });
+ for (let stop = 0; stop < 3; stop++) {
+ f.notices.reportIncident({ kind: "failed", bot: f.chief as never, threadId: "chief-main", detail: closedBrowser });
+ f.settle();
+ }
+ expect(f.continued).toHaveLength(1);
+ expect(f.told).toHaveLength(2);
+ });
+
it("starts nothing when someone wrote in the thread since, or it runs or waits again", () => {
const wrote = roomFixture();
wrote.store.appendMessage("chief-main", { role: "user", kind: "text", text: "Book the train." });