Skip to content

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

Cap: a bot whose shares can't be read stops only far over; the browser close no longer holds the next look; a cap stop is a fault a retry cannot fix

milind-soni60fadad18aae
diff --git a/server/bot-memory-cap.ts b/server/bot-memory-cap.ts
index f7ee0888a4..61d50f2f90 100644
--- a/server/bot-memory-cap.ts
+++ b/server/bot-memory-cap.ts
@@ -109,6 +109,7 @@ export class BotMemoryWatchdog {
readonly #stoppedPids = new Map<number, number>();
#stopping = new Set<string>();
#timer: ReturnType<typeof setInterval> | null = null;
+ #closing: Promise<unknown> = Promise.resolve();
#running = false;
#count = 0;
@@ -136,11 +137,18 @@ export class BotMemoryWatchdog {
for (const [id, tally] of bots) {
if (tally.rssBytes <= cap || this.#stopping.has(id)) { this.#strikes.delete(id); continue; }
// Resident pages count what several processes share once each; their proportional share counts it once.
- const used = tally.pids.reduce((sum, pid) => sum + (this.#options.pss?.(pid) ?? rowRss(rows, pid)), 0);
- if (used <= cap) { this.#strikes.delete(id); continue; }
+ // Where a process's share can't be read (another user's, a sandboxed one), its resident pages stand in; they err
+ // high, so a bot counted that way is stopped only when it stays far over.
+ let used = 0, estimated = false;
+ for (const pid of tally.pids) {
+ const share = this.#options.pss?.(pid) ?? null;
+ if (share === null) estimated = true;
+ used += share ?? rowRss(rows, pid);
+ }
+ if (used <= cap || (estimated && used < cap * FAR_OVER)) { this.#strikes.delete(id); continue; }
const strikes = (this.#strikes.get(id) ?? 0) + 1;
this.#strikes.set(id, strikes);
- if (strikes >= STRIKES || used >= cap * FAR_OVER) over.push({ id, tally, used });
+ if (strikes >= STRIKES || (!estimated && used >= cap * FAR_OVER)) over.push({ id, tally, used });
}
return await Promise.all(over.map(({ id, tally, used }) => this.#stopBot(id, tally, used, cap, starts)));
} finally { this.#running = false; }
@@ -164,13 +172,15 @@ export class BotMemoryWatchdog {
const send = (pids: readonly number[], value: NodeJS.Signals) => { for (const pid of pids) if (same(pid)) try { signal(pid, value); } catch {} };
try {
send(engine, "SIGTERM");
- const closing = browser.size ? this.#options.closeBrowsers?.(botId).catch(() => undefined) : undefined;
+ // The browser closes on its own time (it waits for the stopped turn to let it go): the next look at every other bot
+ // does not wait for it.
+ const closing = browser.size && this.#options.closeBrowsers ? this.#options.closeBrowsers(botId).catch(() => undefined) : Promise.resolve();
+ if (browser.size && !this.#options.closeBrowsers) send([...browser], "SIGTERM");
await new Promise((resolve) => { const timer = setTimeout(resolve, this.#options.graceMs ?? STOP_GRACE_MS); timer.unref?.(); });
send(engine, "SIGKILL");
- await closing;
- // A browser that would not close (a turn still held it after its engine was gone) goes as the engine did.
if (browser.size && !this.#options.closeBrowsers) send([...browser], "SIGKILL");
- } finally { this.#stopping.delete(botId); }
+ this.#closing = closing.finally(() => this.#stopping.delete(botId));
+ } catch { this.#stopping.delete(botId); }
return stop;
}
@@ -188,6 +198,9 @@ export class BotMemoryWatchdog {
return when !== undefined && at - when <= EXPLAIN_FOR_MS;
}
+ /** Resolves once the last stop's browser close has finished: for tests. */
+ closed(): Promise<unknown> { return this.#closing; }
+
/** Bots stopped since the server started. */
stops(): number { return this.#count; }
}
diff --git a/server/host-fault.ts b/server/host-fault.ts
index bd6333cd58..6f61e7534e 100644
--- a/server/host-fault.ts
+++ b/server/host-fault.ts
@@ -5,8 +5,9 @@
/** process_start: the server could not start another process (out of processes or file handles);
* out_of_room: no memory to start an engine, or an engine that had started was stopped for memory, killed by the kernel,
* or never sent its first output; disk_full: no room left to write; tool_server: an MCP server did not start, died or
- * needs its own sign-in; signed_out: the engine says the bot's AI needs signing in again. */
-export type HostFault = "process_start" | "out_of_room" | "disk_full" | "tool_server" | "signed_out";
+ * needs its own sign-in; signed_out: the engine says the bot's AI needs signing in again; bot_memory: the bot used more
+ * memory than this server allows one bot, and was stopped (bot-memory-cap.ts). */
+export type HostFault = "process_start" | "out_of_room" | "disk_full" | "tool_server" | "signed_out" | "bot_memory";
const EXHAUSTED = String.raw`(?:EAGAIN|EMFILE|ENFILE)`;
const PROCESS_START = new RegExp(
@@ -18,6 +19,8 @@ const OUT_OF_ROOM = new RegExp(
String.raw`|^Ran out of room, so I (?:closed the browser|stopped this task)\b|\bran out of memory\b|\bout of memory\b|\bOOM[- ]kill` +
String.raw`|\bexited null\b|\bexited 137\b|\(signal SIGKILL\)|\bkilled by (?:the kernel|signal SIGKILL)\b` +
String.raw`|\b(?:never sent|sent nothing|did not send) (?:its|a|any) first (?:frame|event|output|message)\b`, "i");
+/** bot-memory-cap.ts's own line (chat.notice.botMemoryCap), after the bot's name. */
+const BOT_MEMORY = /\bused more memory than this server allows for one bot\b/i;
const DISK_FULL = /\bno space left on device\b|\bENOSPC\b|\bdisk quota exceeded\b|\bEDQUOT\b/i;
const TOOL_SERVER = new RegExp(
String.raw`\bMCP server\b[^\n]*\b(?:could not start|couldn't be set up|failed to start|exited|input closed|stdin (?:is )?closed|is not connected|session expired|needs (?:a sign-in|authentication)|refused the sign-in)\b` +
@@ -35,6 +38,7 @@ const ENGINE_EXIT = /^([\w.-]+ exited (?:-?\d+|null)(?: \(signal \w+\))? before
/** Which such fault a failure's own words name; null for anything else, the AI's own errors and its provider's among
* them. Classify the system's failure text and stop reason only: never a name, a request or a model's reply. */
export function hostFaultOf(failure: string, stopReason?: string | null): HostFault | null {
+ if (BOT_MEMORY.test(failure)) return "bot_memory";
if (PROCESS_START.test(failure)) return "process_start";
if (DISK_FULL.test(failure)) return "disk_full";
if (OUT_OF_ROOM.test(failure)) return "out_of_room";
@@ -55,4 +59,5 @@ export const HOST_FAULT_WHY: Readonly<Record<HostFault, string>> = {
disk_full: "this server's disk is full",
tool_server: "one of its tool servers is not running or not signed in",
signed_out: "its AI is signed out",
+ bot_memory: "it used more memory than this server allows for one bot",
};
diff --git a/server/idle-and-cap.test.ts b/server/idle-and-cap.test.ts
index da7cff5508..b6353923b9 100644
--- a/server/idle-and-cap.test.ts
+++ b/server/idle-and-cap.test.ts
@@ -253,7 +253,9 @@ describe("a memory cap per bot", () => {
{ pid: 200, botIds: ["bot_a"], kind: "engine" }, { pid: 300, botIds: ["bot_b"], kind: "engine" },
{ pid: 500, botIds: ["bot_b"], kind: "browser" }, { pid: 400, botIds: ["bot_a", "bot_b"], kind: "engine" },
];
- function dog(rows: () => ProcessRow[], pss: (pid: number) => number | null = () => null, startOf: (pid: number) => string | null = (pid) => `s${pid}`) {
+ /** By default every process's proportional size reads as its resident size. */
+ function dog(rows: () => ProcessRow[], pss: (pid: number) => number | null = (pid) => rows().find((row) => row.pid === pid)?.rssBytes ?? null,
+ startOf: (pid: number) => string | null = (pid) => `s${pid}`) {
const signals: string[] = [], closed: string[] = [], logs: string[] = [];
let clock = 1_800_000_000_000;
const watchdog = new BotMemoryWatchdog({ cap: () => 1000 * MB, list: rows, owners: () => owners, pss, startOf, graceMs: 0, now: () => clock,
@@ -297,8 +299,19 @@ describe("a memory cap per bot", () => {
expect(shared.signals).toEqual([]);
});
+ it("stops a bot whose shares can't be read only when it stays far over, its resident pages erring high", async () => {
+ let sizes = { a: 1300 };
+ const h = dog(() => processes(sizes), () => null);
+ expect(await h.watchdog.check()).toEqual([]);
+ expect(await h.watchdog.check()).toEqual([]);
+ expect(await h.watchdog.check()).toEqual([]);
+ sizes = { a: 1600 };
+ expect(await h.watchdog.check()).toEqual([]);
+ expect((await h.watchdog.check()).map((stop) => stop.botId)).toEqual(["bot_a"]);
+ });
+
it("leaves alone a pid the system gave to another process since it was read", async () => {
- const h = dog(() => processes({ a: 1600 }), () => null, (pid) => (pid === 201 ? "later" : `s${pid}`));
+ const h = dog(() => processes({ a: 1600 }), undefined, (pid) => (pid === 201 ? "later" : `s${pid}`));
await h.watchdog.check();
expect(h.signals).toEqual(["SIGTERM 200", "SIGKILL 200"]);
});
diff --git a/server/process-shortage.ts b/server/process-shortage.ts
index 020e45b9be..6974f932c9 100644
--- a/server/process-shortage.ts
+++ b/server/process-shortage.ts
@@ -25,10 +25,11 @@ export const outOfProcesses = (cause: string): boolean => NO_ROOM_NOTICE.test(ca
const OWN_CAUSES: ReadonlySet<string> = new Set(["auth", "quota", "unknown_model", "provider_safety"]);
-/** Whether a failure names its own cause (a usage limit, a sign-in, the provider's refusal, a tool server, a full disk): it
+/** Whether a failure names its own cause (a usage limit, a sign-in, the provider's refusal, a tool server, a full disk, a
+ * bot's memory cap): it
* is never relabelled as the server's shortage, though one was seen during the same turn. */
export function namesOwnCause(failure: string): boolean {
if (engineFailureKind(failure) !== null || OWN_CAUSES.has(classifyError({ text: failure }).reason)) return true;
const fault = hostFaultOf(failure);
- return fault === "signed_out" || fault === "tool_server" || fault === "disk_full";
+ return fault === "signed_out" || fault === "tool_server" || fault === "disk_full" || fault === "bot_memory";
}
diff --git a/server/runtime/store.ts b/server/runtime/store.ts
index 3e37a1512f..1e1403c7cf 100644
--- a/server/runtime/store.ts
+++ b/server/runtime/store.ts
@@ -54,7 +54,7 @@ const assignmentSchema = z.object({
outcome: z.enum(["done", "needs_input", "cap_continued", "stalled", "interrupted", "budget", "provider_error", "denied",
"expired", "stopped", "refused", "duplicate"]).optional(),
outcomeDetail: z.string().optional(),
- fault: z.enum(["process_start", "out_of_room", "disk_full", "tool_server", "signed_out"]).optional(),
+ fault: z.enum(["process_start", "out_of_room", "disk_full", "tool_server", "signed_out", "bot_memory"]).optional(),
level: z.enum(APPROVAL_MODES),
levelSource: z.enum(["own", "chief", "engine_cap"]),
executions: z.number().int().nonnegative(),