Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea cloud boxes stop a runaway before it takes the box down: StreetTalk's agent rendered two cuts of 4K interviews on raea-2's CPU and the 8 GB box stopped answering, every agent's socket with it (11-25). A box's processes share one cgroup that can't be split, so there's no kernel cap; server/memguard.ts, like earlyoom, looks at free memory each second and below 700 MB (or 8%) kills the largest process the server's agents started over 1 GB (never an agent or the server), and says so in the box's log and each agent's trace. RAEA_CLOUD_MEMGUARD=0 turns it off. Tested offline and on raea-2 (a real 1.5 GB runaway stopped).

shinyobjectzc8af179033a2
diff --git a/sdk/cloud/server/main.ts b/sdk/cloud/server/main.ts
index b1df13f6..bd964598 100644
--- a/sdk/cloud/server/main.ts
+++ b/sdk/cloud/server/main.ts
@@ -41,6 +41,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
import path from "node:path"
import { WebSocketServer } from "ws"
import { installed, spawnFor } from "./agents.ts"
+import { guard } from "./memguard.ts"
import { device } from "./gpu.ts"
import * as jobs from "./jobs.ts"
import { checkClaude, finishClaudeSignIn, startClaudeSignIn } from "./claude-token.ts"
@@ -315,6 +316,7 @@ const server = createServer(async (req, res) => {
// the WebSocket upgrade checks the token before a socket opens
const wss = new WebSocketServer({ noServer: true })
+const agentSockets = new Set<import("ws").WebSocket>()
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url ?? "/", "http://raea-cloud")
// a Google sign-in's own browser (google-screen.ts): its VNC stream, both ways, as binary frames
@@ -349,6 +351,8 @@ server.on("upgrade", (req, socket, head) => {
wss.handleUpgrade(req, socket, head, (ws) => {
const child = spawn(agent.command, agent.args, { cwd: WORK, env, stdio: ["pipe", "pipe", "pipe"] })
running.add(child)
+ agentSockets.add(ws)
+ ws.on("close", () => agentSockets.delete(ws))
child.on("exit", () => running.delete(child))
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
@@ -370,6 +374,13 @@ server.on("upgrade", (req, socket, head) => {
})
mkdirSync(WORK, { recursive: true })
+// the box kept from running out of memory (memguard.ts): what it stops is said in the box's log and in every agent's
+// trace (_raea/stderr), where a cut-off run's reason is read
+if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
+ guard((line) => {
+ process.stderr.write(line + "\n")
+ for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
+ })
server.listen(PORT, () => {
const d = device(childEnv())
const gpu = process.env.RAEA_CLOUD_GPU_URL
diff --git a/sdk/cloud/server/memguard.ts b/sdk/cloud/server/memguard.ts
new file mode 100644
index 00000000..b85e9baf
--- /dev/null
+++ b/sdk/cloud/server/memguard.ts
@@ -0,0 +1,89 @@
+// The box's memory, kept from running out (11-25): StreetTalk's agent, its renders failing on the farm, found raea's
+// own binary and rendered a cut of 4K interviews on the box's CPU; the 8 GB box ran out and stopped answering, every
+// agent's socket with it. A box is a VM whose processes share one cgroup that can't be split, so there's no kernel
+// cap to set: like earlyoom, this looks at the box's free memory every second and, when it runs low, kills the
+// largest thing the box's agents started (a render, an ffmpeg), never the server and never an agent itself (they're
+// a few hundred MB; only a process over MIN_RSS is a candidate). The command it was part of fails, said in its
+// output by the shell ("Killed"), and the agent carries on.
+import { readdirSync, readFileSync } from "node:fs"
+
+/** below this much available memory (the larger of the two) the guard acts */
+export const FLOOR_MB = 700
+export const FLOOR_SHARE = 0.08
+/** a process smaller than this is never killed: the agents, the server, a shell */
+export const MIN_RSS_MB = 1024
+
+export interface Proc {
+ pid: number
+ ppid: number
+ rssMb: number
+ name: string
+}
+
+/** every process on the box (Linux /proc) */
+export function procs(root = "/proc"): Proc[] {
+ const out: Proc[] = []
+ for (const d of readdirSync(root)) {
+ if (!/^\d+$/.test(d)) continue
+ try {
+ const stat = readFileSync(`${root}/${d}/stat`, "utf8")
+ // the name is in parentheses and may hold spaces: the fields after its last ")" are fixed
+ const close = stat.lastIndexOf(")")
+ const name = stat.slice(stat.indexOf("(") + 1, close)
+ const f = stat.slice(close + 2).split(" ")
+ const status = readFileSync(`${root}/${d}/status`, "utf8")
+ const rss = /VmRSS:\s+(\d+) kB/.exec(status)
+ out.push({ pid: Number(d), ppid: Number(f[1]), rssMb: rss ? Number(rss[1]) / 1024 : 0, name })
+ } catch {} // gone since the listing
+ }
+ return out
+}
+
+/** the box's memory: total and available, in MB */
+export function memory(file = "/proc/meminfo"): { totalMb: number; availableMb: number } {
+ const m = readFileSync(file, "utf8")
+ const kb = (k: string) => Number(new RegExp(`${k}:\\s+(\\d+) kB`).exec(m)?.[1] ?? 0)
+ return { totalMb: kb("MemTotal") / 1024, availableMb: kb("MemAvailable") / 1024 }
+}
+
+/** the process to kill when memory is low: the largest of `root`'s descendants over MIN_RSS_MB, or none */
+export function victim(all: Proc[], root: number, keep: Set<number> = new Set()): Proc | null {
+ const kids = new Map<number, Proc[]>()
+ for (const p of all) kids.set(p.ppid, [...(kids.get(p.ppid) ?? []), p])
+ const under: Proc[] = []
+ const walk = (pid: number) => {
+ for (const k of kids.get(pid) ?? []) {
+ under.push(k)
+ walk(k.pid)
+ }
+ }
+ walk(root)
+ const big = under.filter((p) => p.rssMb >= MIN_RSS_MB && !keep.has(p.pid)).sort((a, b) => b.rssMb - a.rssMb)
+ return big[0] ?? null
+}
+
+export interface Guard {
+ stop(): void
+}
+
+/** watch the box's memory and kill the largest runaway under `root` (this server) when it runs low; `said` hears why */
+export function guard(said: (line: string) => void, o: { root?: number; everyMs?: number; keep?: () => Set<number>; mem?: typeof memory; list?: typeof procs; kill?: (pid: number) => void } = {}): Guard {
+ const root = o.root ?? process.pid
+ const mem = o.mem ?? memory
+ const list = o.list ?? procs
+ const kill = o.kill ?? ((pid: number) => process.kill(pid, "SIGKILL"))
+ const t = setInterval(() => {
+ try {
+ const m = mem()
+ if (m.availableMb >= Math.max(FLOOR_MB, m.totalMb * FLOOR_SHARE)) return
+ const v = victim(list(), root, o.keep?.())
+ if (!v) return
+ kill(v.pid)
+ said(`raea cloud: the box was running out of memory (${Math.round(m.availableMb)} MB of ${Math.round(m.totalMb)} MB left), so ${v.name} (pid ${v.pid}, ${(v.rssMb / 1024).toFixed(1)} GB) was stopped. Render on the GPU with raea render, not on this box`)
+ } catch (e) {
+ said(`raea cloud: the memory guard: ${(e as Error).message}`)
+ }
+ }, o.everyMs ?? 1000)
+ t.unref()
+ return { stop: () => clearInterval(t) }
+}
diff --git a/sdk/cloud/test/memguard.ts b/sdk/cloud/test/memguard.ts
new file mode 100644
index 00000000..83a6c061
--- /dev/null
+++ b/sdk/cloud/test/memguard.ts
@@ -0,0 +1,55 @@
+// The box's memory guard (server/memguard.ts): node test/memguard.ts from sdk/cloud. Offline, on a made-up process
+// table; and on Linux, against a real process that grows past the floor (set high for the test), which it kills.
+import { spawn } from "node:child_process"
+import { existsSync } from "node:fs"
+import { guard, MIN_RSS_MB, type Proc, victim } from "../server/memguard.ts"
+
+const ok = (m: string) => console.log(`ok ${m}`)
+const assert = (c: unknown, m: string) => {
+ if (!c) throw new Error(`not ok: ${m}`)
+}
+
+// the server (1), an agent (2) and its helper (3), a shell (4) running a render (5) and an ffmpeg (6); another box
+// process (9) outside the server
+const table: Proc[] = [
+ { pid: 1, ppid: 0, rssMb: 120, name: "node" },
+ { pid: 2, ppid: 1, rssMb: 300, name: "agy_acp_server" },
+ { pid: 3, ppid: 2, rssMb: 180, name: "localharness" },
+ { pid: 4, ppid: 3, rssMb: 4, name: "bash" },
+ { pid: 5, ppid: 4, rssMb: 5200, name: "raea" },
+ { pid: 6, ppid: 4, rssMb: 1500, name: "ffmpeg" },
+ { pid: 9, ppid: 0, rssMb: 9000, name: "other" },
+]
+assert(victim(table, 1)?.pid === 5, "the largest runaway under the server")
+assert(victim(table, 1, new Set([5]))?.pid === 6, "a kept one is passed over")
+assert(victim(table.filter((p) => p.pid !== 5 && p.pid !== 6), 1) === null, `nothing under ${MIN_RSS_MB} MB is killed: not an agent, not the server`)
+ok("it picks the largest process an agent started, never the agent, the server or anything outside it")
+
+// the loop: memory fine, nothing happens; memory low, the victim is killed and said
+let avail = 4000
+const killed: number[] = []
+const said: string[] = []
+const g = guard((l) => said.push(l), { root: 1, everyMs: 10, mem: () => ({ totalMb: 8192, availableMb: avail }), list: () => table, kill: (p) => killed.push(p) })
+await new Promise((r) => setTimeout(r, 60))
+assert(killed.length === 0, "memory fine: nothing killed")
+avail = 500
+await new Promise((r) => setTimeout(r, 30))
+g.stop()
+assert(killed[0] === 5 && /raea \(pid 5, 5\.1 GB\)/.test(said[0]), `low: the render is stopped and said: ${said[0]}`)
+ok("memory low: the render is stopped, and the guard says why")
+
+if (existsSync("/proc/meminfo")) {
+ // a real child that grows to 1.5 GB, under a floor set just below what's free now, so its growth trips it
+ const { memory } = await import("../server/memguard.ts")
+ const start = memory().availableMb
+ const hog = spawn(process.execPath, ["-e", "const a=[]; for (let i=0;i<150;i++) a.push(Buffer.alloc(10<<20, 1)); setInterval(()=>{}, 1000)"], { stdio: "ignore" })
+ const lines: string[] = []
+ const real = guard((l) => lines.push(l), { everyMs: 200, mem: () => { const m = memory(); return { totalMb: m.totalMb, availableMb: m.availableMb + 700 - (start - 1200) } } })
+ const code = await new Promise<number | null>((r) => {
+ hog.on("exit", (c, sig) => r(sig === "SIGKILL" ? -9 : c))
+ setTimeout(() => (hog.kill("SIGKILL"), r(null)), 30_000)
+ })
+ real.stop()
+ assert(code === -9 && lines.length === 1, `the hog was killed by the guard: ${code} ${lines}`)
+ ok(`on this box: a 1.5 GB runaway was stopped (${lines[0].slice(0, 90)}…)`)
+}