Compare commits

..
Author SHA1 Message Date
shinyobjectz cdcb8dacbd The farm's GPU wait gives up on a run that ran out of its own time, as .remote() did
Modal's FunctionTimeoutError is a subclass of its TimeoutError, so waited() caught a run's own timeout as "no answer
yet" and asked again forever, logging "waiting" instead of failing the job. It now goes up as before. Test: a run that
timed out fails the job with no wait lines.
2026-11-30 07:41:25 -08:00
shinyobjectz 349a934eb9 The farm encodes a video's runs with libx264 at the quality's CRF, not openh264 at a bitrate
openh264's near-blacks stepped into blocks even at --quality master's 37.7 Mbps: raea check's blotching failed every
Dutch cut rendered on the farm, and its agent re-encoded each one with x264 CRF 14 afterwards (a second generation and
minutes a cut). RAEA_MEDIA=ffmpeg makes raea's encode the ffmpeg CLI's libx264 (master CRF 11); the runs still join
by stream copy, and the first run's x264 header tells raea check the darks were kept.
2026-11-30 00:41:16 -08:00
shinyobjectz 3a22cede8e The farm gives a job 4 GPUs unless it asks for more, and says when a GPU run hasn't answered
A 1,150-frame cut took all 10 of the workspace's GPUs, each drawing 10-20 s, so every other render queued behind it,
and a queued run printed nothing: StreetTalk's agents read the silence as "stalled before frame 0" (11-30).
RAEA_FARM_JOB_GPUS (4) is a job's default; farm_plan.waited logs every 30 s while a probe, first run or whole job waits.
2026-11-29 23:37:19 -08:00
4 changed files with 77 additions and 39 deletions

No files matched your search

+9 -2
View File
@@ -76,6 +76,9 @@ BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
RAEA_GPUS = os.environ.get("RAEA_FARM_RAEA_GPUS", "T4,A10,L4").split(",")
BLENDER_GPUS = os.environ.get("RAEA_FARM_BLENDER_GPUS", "L40S,RTX-PRO-6000,L4").split(",")
GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit; Team's is 50
# one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in
# the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
ROOT = "/farm"
JOBS = f"{ROOT}/jobs"
@@ -125,7 +128,11 @@ image = (
# the job at once instead of installing it on a GPU's clock
"RAEA_TOKENSYNTH": "/models/tokensynth", "RAEA_TOKENSYNTH_DEVICE": "cuda", "RAEA_AUDIO_AUTOSETUP": "0",
# Stable Audio Open small on ONNX Runtime with CUDA, as deploy/modal/sao.py installs it (CR25)
"RAEA_SAO": "/models/sao"})
"RAEA_SAO": "/models/sao",
# a video's runs encoded by the ffmpeg CLI's libx264 at the quality's CRF (master 11), not openh264 at a
# bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching
# failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30)
"RAEA_MEDIA": "ffmpeg"})
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
)
@@ -573,7 +580,7 @@ def api():
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
q = req.query_params
opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
id = str(uuid.uuid4())
work = f"{JOBS}/{id}/work"
async with gate.use():
+32 -4
View File
@@ -44,6 +44,34 @@ def splittable(args):
return out is not None and (out.endswith(VIDEO) or not os.path.splitext(out)[1]) and any(COMPOSITION.search(a) for a in rest[1:])
# how often a job's log says it's still waiting on a GPU run: from outside, a run queued behind the workspace's GPU
# limit and one still drawing look the same, and a silent wait read as a stall (11-30: StreetTalk's agents said "stalled
# before frame 0" while another app held all 10 of the workspace's GPUs)
WAIT_SAY_S = 30
def waited(fn, log, *a, **kw):
"""fn.remote(*a, **kw), saying in the log every WAIT_SAY_S that it has no answer yet."""
if not hasattr(fn, "spawn"):
return fn.remote(*a, **kw)
try:
import modal.exception as me
timeouts = (TimeoutError, me.TimeoutError)
except Exception:
timeouts = (TimeoutError,)
call = fn.spawn(*a, **kw)
t = time.time()
while True:
try:
return call.get(timeout=WAIT_SAY_S)
except timeouts as e:
# Modal's FunctionTimeoutError is a TimeoutError too: the run itself ran out of time, so it goes up as
# .remote() raised it, not waited on again (it would answer the same at once, forever)
if type(e).__name__ == "FunctionTimeoutError":
raise
log(f"raea farm: waiting {time.time() - t:.0f} s for a GPU run to answer (queued while the workspace's GPUs are busy, or still drawing)")
def gpus_for(frames, frame_s, start_s, most):
"""The GPUs worth starting for `frames` frames of `frame_s` each, when each one first spends `start_s`: the most that
keep each one's start at most SHARE of its time, never more than `most`."""
@@ -190,7 +218,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if out.endswith(VIDEO):
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
t.start()
p = bill.add(render.remote(id, rest, probe=True))
p = bill.add(waited(render, log, id, rest, probe=True))
if p["code"] or not p["length"]:
log(p["out"], err=True)
if not p["code"]:
@@ -200,7 +228,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
video = out.endswith(VIDEO)
n0 = min(length, FIRST)
r0 = bill.add(render.remote(id, rest, list(range(n0)), 0, video=video))
r0 = bill.add(waited(render, log, id, rest, list(range(n0)), 0, video=video))
if r0["code"]:
log(r0["out"], err=True)
return r0["code"]
@@ -321,7 +349,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
if video:
o |= {"video": True, "fps": info["fps"]}
log(f"raea farm: {blend}, frames {first}-{last} ({info['engine']}), at {info['fps']:g} fps")
r0 = bill.add(render.remote(id, blend, first, first, o))
r0 = bill.add(waited(render, log, id, blend, first, first, o))
if r0["code"]:
log(r0["out"], err=True)
return r0["code"]
@@ -366,7 +394,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
if splittable(args):
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill)
else:
r = bill.add(render.remote(opts["id"], args))
r = bill.add(waited(render, log, opts["id"], args))
log(r["out"], err=bool(r["code"]))
code = r["code"]
log(bill.line())
+5 -33
View File
@@ -185,26 +185,12 @@ function files(req: IncomingMessage, res: ServerResponse, url: URL) {
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
}
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
* line with no out, err or exit. */
const KEEPALIVE_MS = 30_000
function streamOpen(res: ServerResponse) {
res.writeHead(200, { "content-type": "application/x-ndjson" })
res.flushHeaders()
const beat = setInterval(() => res.write("{}\n"), KEEPALIVE_MS)
const stop = () => clearInterval(beat)
res.on("finish", stop)
res.on("close", stop)
}
async function run(req: IncomingMessage, res: ServerResponse) {
const { args, cwd } = JSON.parse((await body(req)).toString() || "{}") as { args?: unknown; cwd?: string }
if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) return json(res, { error: "args must be an array of strings: raea's own arguments" }, 400)
const dir = resolve(cwd ?? ".")
mkdirSync(dir, { recursive: true })
streamOpen(res)
res.writeHead(200, { "content-type": "application/x-ndjson" })
const child = spawn(RAEA, args, { cwd: dir, env: childEnv(), stdio: ["ignore", "pipe", "pipe"] })
const line = (v: unknown) => res.write(JSON.stringify(v) + "\n")
child.stdout.setEncoding("utf8").on("data", (out: string) => line({ out }))
@@ -216,8 +202,6 @@ async function run(req: IncomingMessage, res: ServerResponse) {
}
const SHELL_DEFAULT_MS = 600_000
/** an ACP agent silent both ways this long is ended (the /v1/acp socket below) */
const IDLE_AGENT_MS = Number(process.env.RAEA_CLOUD_IDLE_AGENT_MS ?? 45 * 60_000)
const SHELL_MAX_MS = 3_600_000
async function shell(req: IncomingMessage, res: ServerResponse) {
@@ -226,7 +210,7 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
const ms = typeof timeout_ms === "number" && timeout_ms > 0 ? Math.min(timeout_ms, SHELL_MAX_MS) : SHELL_DEFAULT_MS
const dir = resolve(cwd ?? ".")
mkdirSync(dir, { recursive: true })
streamOpen(res)
res.writeHead(200, { "content-type": "application/x-ndjson" })
// the shell on any OS: bash and a process group here, RAEA_CLOUD_BASH and taskkill on Windows (shell-os.ts)
const { bash, groupOpts, shellEnv, stopTree } = await import("./shell-os.ts")
// in a process group of its own, so a timeout or a caller leaving stops what the command started too
@@ -386,19 +370,8 @@ server.on("upgrade", (req, socket, head) => {
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
// never sees it
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
// on raea-3 for 2 h, counted as running, so no box update could go on)
let heard = Date.now()
const idle = setInterval(() => {
if (Date.now() - heard < IDLE_AGENT_MS) return
process.stderr.write(`raea-cloud: ${agent.id} said nothing and was sent nothing for ${Math.round(IDLE_AGENT_MS / 60_000)} min: ended\n`)
ws.terminate()
stopAll()
}, Math.min(60_000, IDLE_AGENT_MS / 2))
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle)))
child.on("exit", () => (running.delete(child), clearInterval(idle)))
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat)))
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)
child.stderr.setEncoding("utf8").on("data", (c: string) => {
@@ -408,11 +381,10 @@ server.on("upgrade", (req, socket, head) => {
let buf = ""
// ACP messages are newline-delimited JSON: split on \n only
child.stdout.setEncoding("utf8").on("data", (c: string) => {
heard = Date.now()
buf += c
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
})
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
ws.on("message", (m) => child.stdin.write(m.toString() + "\n"))
ws.on("close", stopAll)
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
+31
View File
@@ -158,4 +158,35 @@ b.add({"code": 1, "out": "no task id"})
assert "2 GPU containers up 35 s" in b.line(), b.line()
ok("the bill: each container from its boot or the job's start to its last run, plus its boot and idle seconds")
# a GPU run with no answer yet is said in the log, not waited on in silence; its answer still comes back
class SlowCall:
def __init__(self, waits): self.waits = waits
def get(self, timeout=None):
if self.waits:
self.waits -= 1
raise TimeoutError
return {"code": 0, "out": "drawn"}
class SlowGpu:
def spawn(self, *a, **kw): return SlowCall(2)
lines.clear()
fp.WAIT_SAY_S = 0.01
assert fp.waited(SlowGpu(), log, "j4", ["render"]) == {"code": 0, "out": "drawn"}
assert sum("waiting" in l and "GPU run" in l for l in lines) == 2, lines
ok("a GPU run that hasn't answered is said in the log every WAIT_SAY_S until it does")
# a GPU run that ran out of its own time fails the job, as .remote() did, instead of being waited on forever
class FunctionTimeoutError(TimeoutError): pass
class TimedOutCall:
def get(self, timeout=None): raise FunctionTimeoutError("Function timeout")
class TimedOutGpu:
def spawn(self, *a, **kw): return TimedOutCall()
lines.clear()
try:
fp.waited(TimedOutGpu(), log, "j5", ["render"])
raise AssertionError("waited() swallowed a function timeout")
except FunctionTimeoutError:
pass
assert not any("waiting" in l for l in lines), lines
ok("a GPU run that timed out fails the job instead of being waited on forever")
shutil.rmtree(root)