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 renders send a project's footage once: a project not in raea's LFS (every raea cloud project: its repo is on Cloudflare's Git) put all its media in every render's tar, so one frame of StreetTalk's Dutch edit packed and sent 1.9 GB of interviews, read whole into the box's memory (2-4 GB a render); with three agents rendering at once the 15 GB box ran out and every agent's socket dropped. The farm now keeps media by hash (POST /v1/blobs/have, PUT /v1/blobs/OID, streamed and checked against its hash, farm.py); offload.ts sends each footage or large file once (media.ts farmInputs: hashes kept by path, size and time) and names it in the job's .raea-cloud-media.json with no href, and farm_media links it into the job from the cache instead of copying it. Trial on raea-2: the first frame 144 s (hashing and sending 2 GB once), the next 17 s with nothing sent; it had timed out at 60 s. RAEA_CLOUD_GPU_BLOBS=0 puts the media back in the tar; a farm without the cache does too. Tests: test/farm-blobs.ts, test/farm_media.py. Farm deployed (raea-farm). (farm.py and offload.ts also carry the games lane's kits/ fixes that were already on the box.) 11-25, Shane: "if there's an issue with big files ... some kind of r2 streaming thing, I'm happy to have you own the changes"

shinyobjectz00deff035c3a
diff --git a/sdk/cloud/deploy/modal/farm.py b/sdk/cloud/deploy/modal/farm.py
index e18f84c5..3f031e65 100644
--- a/sdk/cloud/deploy/modal/farm.py
+++ b/sdk/cloud/deploy/modal/farm.py
@@ -10,6 +10,9 @@
# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],
# left out of /out
# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)
+# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid]}
+# PUT /v1/blobs/OID?size=N one media file into the farm's cache, kept when it
+# hashes to OID (a box's project not in raea's LFS)
# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from
# R2 through a cache on the volume keyed by hash instead of coming in the tar (docs/cloud-render.feature CR23).
#
@@ -111,7 +114,10 @@ def snapshot(d):
for base, _, files in os.walk(d):
for f in files:
p = os.path.join(base, f)
- s = os.stat(p)
+ try:
+ s = os.stat(p)
+ except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
+ continue
out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
return out
@@ -255,6 +261,19 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: {e!r}", err=True)
code = 1
vol.commit()
+ # what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
+ # reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
+ # Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
+ # and if it still won't, go on with what this container sees rather than lose a finished render
+ for pause in (0.5, 1, 2, 4, 0):
+ try:
+ vol.reload()
+ break
+ except Exception as e: # modal.exception.ConflictError
+ if not pause:
+ log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
+ else:
+ time.sleep(pause)
after = snapshot(work)
changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"):
@@ -323,6 +342,55 @@ def api():
await coordinate.spawn.aio(id, args, opts)
return {"id": id}
+ # a project's footage by hash, sent once (11-25: StreetTalk's 1.9 GB of interviews went in every render's tar, even
+ # one frame's, and three at once ran the box out of memory): the box asks which the farm has, PUTs the rest, and a
+ # job's .raea-cloud-media.json names them with no href (farm_media.fetch uses them from the cache)
+ @web.post("/v1/blobs/have")
+ async def blobs_have(req: Request):
+ check(req)
+ objects = (await req.json()).get("objects") or []
+ try:
+ await vol.reload.aio()
+ except Exception: # another request's open file: what this container sees will do
+ pass
+ have = []
+ for o in objects[:5000]:
+ oid, size = str(o.get("oid", "")), int(o.get("size", -1))
+ blob = f"{ROOT}/blobs/{oid}"
+ if len(oid) == 64 and all(c in "0123456789abcdef" for c in oid) and os.path.exists(blob) and os.path.getsize(blob) == size:
+ have.append(oid)
+ return {"have": have}
+
+ @web.put("/v1/blobs/{oid}")
+ async def blob_put(oid: str, req: Request):
+ import hashlib
+
+ check(req)
+ if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid):
+ raise HTTPException(400, "not an object id: 64 hex characters")
+ size = int(req.query_params.get("size", "-1"))
+ os.makedirs(f"{ROOT}/blobs", exist_ok=True)
+ blob = f"{ROOT}/blobs/{oid}"
+ if os.path.exists(blob) and os.path.getsize(blob) == size:
+ return {"oid": oid, "bytes": size, "had": True}
+ tmp = f"{blob}.up-{uuid.uuid4().hex[:8]}"
+ h = hashlib.sha256()
+ n = 0
+ try:
+ with open(tmp, "wb") as f:
+ async for chunk in req.stream():
+ h.update(chunk)
+ f.write(chunk)
+ n += len(chunk)
+ if h.hexdigest() != oid or n != size:
+ raise HTTPException(400, f"the file came as {h.hexdigest()[:12]}… ({n} bytes), not {oid[:12]}… ({size} bytes)")
+ os.replace(tmp, blob)
+ finally:
+ if os.path.exists(tmp):
+ os.remove(tmp)
+ await vol.commit.aio()
+ return {"oid": oid, "bytes": n}
+
@web.get("/v1/jobs/{id}")
async def follow(id: str, req: Request):
check(req)
diff --git a/sdk/cloud/deploy/modal/farm_media.py b/sdk/cloud/deploy/modal/farm_media.py
index 7fe79936..8e6b580d 100644
--- a/sdk/cloud/deploy/modal/farm_media.py
+++ b/sdk/cloud/deploy/modal/farm_media.py
@@ -5,6 +5,8 @@
# a raea credential, only signed URLs that each reach one object.
#
# .raea-cloud-media.json in the job's folder, from the box: {"objects": [{"path", "oid", "size", "href", "header"}]}
+# An object with no href is one the box sent the farm itself (PUT /v1/blobs/OID, farm.py:
+# a project not in raea's LFS, 11-25): it is used from the cache, and only from there
# fetch(work, cache, ...) each object into the cache (once), then into its path in the job's folder
# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]
# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]
@@ -78,7 +80,12 @@ def fetch(work, cache, log=print, download=get, check=probe):
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):
raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")
blob = os.path.join(cache, oid)
- if os.path.exists(blob) and os.path.getsize(blob) == size:
+ if not o.get("href"):
+ # sent by the box over the farm's own token (PUT /v1/blobs), checked against its hash as it came
+ if not (os.path.exists(blob) and os.path.getsize(blob) == size):
+ raise ValueError(f"media: {path} ({oid[:12]}…) was never sent to the farm")
+ cached += size
+ elif os.path.exists(blob) and os.path.getsize(blob) == size:
# a hash alone doesn't open the cache: the job's URL, signed for its account, has to answer
check(o["href"], o.get("header"))
cached += size
@@ -95,7 +102,12 @@ def fetch(work, cache, log=print, download=get, check=probe):
os.makedirs(os.path.dirname(dest), exist_ok=True)
if os.path.lexists(dest):
os.remove(dest)
- shutil.copyfile(blob, dest)
+ # a link into the cache, not a copy: a project's footage is gigabytes, the same across every job (11-25); every
+ # container of the job mounts the volume at the same place, so the link resolves on the GPUs too
+ try:
+ os.symlink(blob, dest)
+ except OSError:
+ shutil.copyfile(blob, dest)
log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")
return {"objects": len(objects), "fetched": fetched, "cached": cached}
diff --git a/sdk/cloud/server/media.ts b/sdk/cloud/server/media.ts
index 9ed0b6f8..3fbc0827 100644
--- a/sdk/cloud/server/media.ts
+++ b/sdk/cloud/server/media.ts
@@ -10,8 +10,10 @@
import { createHash } from "node:crypto"
import { spawnSync } from "node:child_process"
-import { createReadStream, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
+import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
+import os from "node:os"
import path from "node:path"
+import { Readable } from "node:stream"
import type { Media } from "../src/index.ts"
const LFS = "application/vnd.git-lfs+json"
@@ -132,5 +134,101 @@ export async function outputs(root: string, lfs: Lfs, made: Media[]): Promise<{
return { send, done }
}
+// what goes by hash when the project isn't in raea's LFS (farmInputs): media by type, and anything large, as the farm's
+// farm_media.py MEDIA and LARGE judge it; a file under SMALL stays in the tar, where it costs less than a lookup
+const MEDIA = new Set(
+ "mp4 mov m4v webm mkv avi mxf mp3 wav aiff aif flac m4a ogg opus caf png jpg jpeg heic heif webp gif tif tiff exr hdr psd blend glb gltf fbx obj usd usdz abc ply splat spz ktx2 ttf otf woff woff2 zip tar gz zst safetensors onnx bin npz npy pdf".split(" "),
+)
+const LARGE = 4 << 20
+const SMALL = 256 << 10
+
+/** the farm's cache of media (farm.py POST /v1/blobs/have, PUT /v1/blobs/OID), over its own token */
+export interface FarmBlobs {
+ /** which of these it holds; null when this farm has no cache (an older one): the media goes in the tar */
+ have(objects: { oid: string; size: number }[]): Promise<Set<string> | null>
+ put(file: string, oid: string, size: number): Promise<void>
+}
+
+export function farmBlobs(url: string, token: string): FarmBlobs {
+ const auth = { authorization: `Bearer ${token}` }
+ return {
+ async have(objects) {
+ const r = await fetch(`${url}/v1/blobs/have`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ objects }) })
+ if (r.status === 404) return null
+ if (!r.ok) throw new Error(`the farm's media cache answered ${r.status}: ${(await r.text()).slice(0, 200)}`)
+ return new Set(((await r.json()) as { have: string[] }).have)
+ },
+ async put(file, oid, size) {
+ // streamed from the disk: a file is never held in memory (a project's interviews are gigabytes)
+ const body = Readable.toWeb(createReadStream(file)) as unknown as ReadableStream
+ const r = await fetch(`${url}/v1/blobs/${oid}?size=${size}`, { method: "PUT", headers: { ...auth, "content-type": "application/octet-stream", "content-length": String(size) }, body, duplex: "half" } as RequestInit)
+ if (!r.ok) throw new Error(`the farm didn't keep ${path.basename(file)}: ${r.status} ${(await r.text()).slice(0, 200)}`)
+ },
+ }
+}
+
+/** each file's hash, kept by its path, size and time so a project's footage is hashed once, not on every render */
+function hashes(file: string) {
+ let known: Record<string, { size: number; mtime: number; oid: string }> = {}
+ try {
+ known = JSON.parse(readFileSync(file, "utf8"))
+ } catch {}
+ let changed = false
+ return {
+ async of(p: string, size: number, mtime: number): Promise<string> {
+ const k = known[p]
+ if (k && k.size === size && k.mtime === mtime) return k.oid
+ const oid = await sha256(p)
+ known[p] = { size, mtime, oid }
+ changed = true
+ return oid
+ },
+ save() {
+ if (!changed) return
+ mkdirSync(path.dirname(file), { recursive: true })
+ const tmp = `${file}.${process.pid}`
+ writeFileSync(tmp, JSON.stringify(known))
+ renameSync(tmp, file)
+ },
+ }
+}
+
+/** A project's media when it isn't in raea's LFS (11-25): each media or large file by its hash, sent once into the
+ * farm's cache and named in the job's manifest with no href, so a render's tar holds the code and not the footage
+ * (StreetTalk's 1.9 GB of interviews went in every render's tar, even one frame's). null when the farm has no cache.
+ * `skip`: the tar's excludes. Links are left to the tar, as before. */
+export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json")): Promise<{ media: Media[]; sent: number } | null> {
+ const found: { path: string; abs: string; size: number; mtime: number }[] = []
+ const walk = (dir: string) => {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const abs = path.join(dir, e.name)
+ const rel = path.relative(root, abs).split(path.sep).join("/")
+ if (skip(rel)) continue
+ if (e.isDirectory()) walk(abs)
+ else if (e.isFile()) {
+ const st = statSync(abs)
+ const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
+ if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs, size: st.size, mtime: st.mtimeMs })
+ }
+ }
+ }
+ walk(root)
+ if (!found.length) return { media: [], sent: 0 }
+ const h = hashes(store)
+ const media: (Media & { abs: string })[] = []
+ for (const f of found) media.push({ path: f.path, oid: await h.of(f.abs, f.size, f.mtime), size: f.size, abs: f.abs })
+ h.save()
+ const have = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
+ if (!have) return null
+ let sent = 0
+ const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
+ if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
+ for (const m of todo) {
+ await farm.put(m.abs, m.oid, m.size)
+ sent += m.size
+ }
+ return { media: media.map(({ abs: _, ...m }) => m), sent }
+}
+
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"
diff --git a/sdk/cloud/server/offload.ts b/sdk/cloud/server/offload.ts
index 83800060..aec6e88a 100644
--- a/sdk/cloud/server/offload.ts
+++ b/sdk/cloud/server/offload.ts
@@ -21,7 +21,7 @@ import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { RaeaCloud } from "../src/index.ts"
-import { excluded, excludes as mediaExcludes, inputs, lfsOf, outputs } from "./media.ts"
+import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, outputs } from "./media.ts"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
// flags whose value is a path raea writes; the rest of a render's path arguments are read
@@ -93,13 +93,23 @@ async function main() {
const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-offload-"))
try {
- const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out").split(/\s+/).filter(Boolean)
+ // kits/ (raea-game-kit) is a link into the box's shared cache, hundreds of MB, that the farm can't follow: a
+ // composition uses copies of the kit files it needs in its own folder (11-21: the dangling link hung farm jobs)
+ const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./kits").split(/\s+/).filter(Boolean)
// zstd with GNU tar (the image's); gzip with another tar (a Mac's), whose zstd needs a program of its own
const gnu = spawnSync("tar", ["--version"], { encoding: "utf8" }).stdout?.includes("GNU")
const sent = path.join(tmp, "in.tar")
// the media that goes by hash: out of the tar, named in its manifest
const lfs = lfsOf(p.root)
- const byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
+ let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
+ // not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
+ // (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
+ // leaves it in the tar, and the health check below says why the farm can't be reached
+ let viaFarm: { media: typeof byHash; sent: number } | null = null
+ if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
+ viaFarm = await farmInputs(p.root, farmBlobs(url, token), excluded(excludes), say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
+ if (viaFarm) byHash = viaFarm.media
+ }
const extra: string[] = []
if (byHash.length) {
writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))
@@ -120,7 +130,8 @@ async function main() {
throw new Error(`the GPU worker at ${url} didn't answer: ${(e as Error).message} (RAEA_CLOUD_GPU_FALLBACK=cpu renders here instead)`)
}
say(`rendering on ${new URL(url).host}, ${h.device.renders === "gpu" ? `GPU ${h.device.name}` : `its CPU (${h.device.name})`}: ${p.root} (${(folder.length / 1e6).toFixed(1)} MB) sent`)
- if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
+ if (viaFarm && byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
+ else if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USD
const n = (v?: string) => (v ? Number(v) : undefined)
diff --git a/sdk/cloud/test/farm-blobs.ts b/sdk/cloud/test/farm-blobs.ts
new file mode 100644
index 00000000..03da86e8
--- /dev/null
+++ b/sdk/cloud/test/farm-blobs.ts
@@ -0,0 +1,88 @@
+// A box's media by hash into the farm's own cache (server/media.ts farmInputs, 11-25), against a local stand-in for
+// the farm's POST /v1/blobs/have and PUT /v1/blobs/OID: node test/farm-blobs.ts from sdk/cloud.
+// Checked: a project's footage and large files go by hash and its code and small files stay in the tar; the first
+// render sends each once (streamed, checked against its hash), the next sends nothing and hashes nothing again; a
+// file changed since is sent again; out/ and links are left alone; a farm without the cache answers null.
+
+import { createHash } from "node:crypto"
+import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"
+import { createServer } from "node:http"
+import type { AddressInfo } from "node:net"
+import { tmpdir } from "node:os"
+import path from "node:path"
+import { excluded, farmBlobs, farmInputs } from "../server/media.ts"
+
+const ok = (m: string) => console.log(`ok ${m}`)
+const assert = (c: unknown, m: string) => {
+ if (!c) throw new Error(`not ok: ${m}`)
+}
+
+const held = new Map<string, number>()
+let puts = 0
+let cache = true
+const farm = createServer((req, res) => {
+ const u = new URL(req.url!, "http://x")
+ if (req.headers.authorization !== "Bearer farm-token") return void res.writeHead(401).end()
+ if (!cache) return void res.writeHead(404).end()
+ if (req.method === "POST" && u.pathname === "/v1/blobs/have") {
+ let b = ""
+ req.on("data", (c) => (b += c)).on("end", () => {
+ const objects = (JSON.parse(b).objects ?? []) as { oid: string; size: number }[]
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ have: objects.filter((o) => held.get(o.oid) === o.size).map((o) => o.oid) }))
+ })
+ return
+ }
+ const m = /^\/v1\/blobs\/([0-9a-f]{64})$/.exec(u.pathname)
+ if (req.method === "PUT" && m) {
+ const h = createHash("sha256")
+ let n = 0
+ req.on("data", (c: Buffer) => (h.update(c), (n += c.length))).on("end", () => {
+ if (h.digest("hex") !== m[1] || n !== Number(u.searchParams.get("size"))) return void res.writeHead(400).end("wrong hash")
+ held.set(m[1], n)
+ puts++
+ res.writeHead(200).end("{}")
+ })
+ return
+ }
+ res.writeHead(404).end()
+})
+await new Promise<void>((r) => farm.listen(0, "127.0.0.1", r))
+const url = `http://127.0.0.1:${(farm.address() as AddressInfo).port}`
+
+const root = mkdtempSync(path.join(tmpdir(), "farm-blobs-"))
+const store = path.join(root, "..", `${path.basename(root)}-hashes.json`)
+mkdirSync(path.join(root, "media"), { recursive: true })
+mkdirSync(path.join(root, "out"), { recursive: true })
+mkdirSync(path.join(root, "brand"), { recursive: true })
+writeFileSync(path.join(root, "media", "interview.MOV"), Buffer.alloc(5 << 20, 7))
+writeFileSync(path.join(root, "media", "copy.MOV"), Buffer.alloc(5 << 20, 7)) // the same bytes: one upload
+writeFileSync(path.join(root, "brand", "logo.png"), Buffer.alloc(300 << 10, 3))
+writeFileSync(path.join(root, "brand", "icon.png"), Buffer.alloc(2 << 10, 3)) // small: stays in the tar
+writeFileSync(path.join(root, "data.bin"), Buffer.alloc(6 << 20, 1)) // large, of no media type
+writeFileSync(path.join(root, "edit.tsx"), "export default () => null\n")
+writeFileSync(path.join(root, "out", "old.mp4"), Buffer.alloc(5 << 20, 9)) // an old render: the tar's excludes leave it
+symlinkSync(path.join(root, "media", "interview.MOV"), path.join(root, "media", "link.MOV"))
+
+const skip = excluded(["./.git", "./out/*", "./.raea-cloud-out", "./kits"])
+const blobs = farmBlobs(url, "farm-token")
+const first = await farmInputs(root, blobs, skip, () => {}, store)
+assert(first, "a farm with the cache answers")
+const paths = first!.media.map((m) => m.path).sort()
+assert(JSON.stringify(paths) === JSON.stringify(["brand/logo.png", "data.bin", "media/copy.MOV", "media/interview.MOV"]), `what goes by hash: ${paths}`)
+assert(first!.media.every((m) => !m.href), "no href: the farm's own cache")
+assert(puts === 3 && first!.sent === (5 << 20) + (300 << 10) + (6 << 20), `sent once each, the same bytes once: ${puts} puts, ${first!.sent}`)
+ok("footage, large files and media over 256 KB go by hash, each sent once; code, small files, out/ and links stay in the tar")
+
+const second = await farmInputs(root, blobs, skip, () => {}, store)
+assert(second!.sent === 0 && puts === 3, "the next render sends nothing")
+ok("the next render sends nothing: the farm has it all")
+
+writeFileSync(path.join(root, "brand", "logo.png"), Buffer.alloc(300 << 10, 4))
+const third = await farmInputs(root, blobs, skip, () => {}, store)
+assert(third!.sent === 300 << 10 && puts === 4, `a changed file is sent again: ${third!.sent}`)
+ok("a file changed since is hashed and sent again")
+
+cache = false
+assert((await farmInputs(root, blobs, skip, () => {}, store)) === null, "an older farm")
+ok("a farm without the cache answers null: the media goes in the tar")
+farm.close()
diff --git a/sdk/cloud/test/farm_media.py b/sdk/cloud/test/farm_media.py
index 972ba970..04db0373 100644
--- a/sdk/cloud/test/farm_media.py
+++ b/sdk/cloud/test/farm_media.py
@@ -70,6 +70,23 @@ def job(objects):
obj = {"path": "footage/take.mov", "oid": oid, "size": len(take), "href": f"{base}/{oid}", "header": {}}
+
+# footage the box sent the farm itself (PUT /v1/blobs, no href): used from the cache as a link, never fetched
+sent = b"interview " * 5000
+soid = hashlib.sha256(sent).hexdigest()
+open(os.path.join(cache, soid), "wb").write(sent)
+ws = job([{"path": "media/int1.MOV", "oid": soid, "size": len(sent)}])
+gets = hits["GET"]
+ss = fm.fetch(ws, cache, log=lambda _: None)
+assert open(os.path.join(ws, "media/int1.MOV"), "rb").read() == sent and os.path.islink(os.path.join(ws, "media/int1.MOV"))
+assert ss == {"objects": 1, "fetched": 0, "cached": len(sent)} and hits["GET"] == gets, ss
+try:
+ fm.fetch(job([{"path": "media/gone.MOV", "oid": "ab" * 32, "size": 10}]), cache, log=lambda _: None)
+ raise AssertionError("footage never sent was used")
+except ValueError as e:
+ assert "never sent" in str(e)
+ok("footage the box sent the farm itself comes from the cache as a link, and footage it never sent is refused")
+
w1 = job([obj])
s1 = fm.fetch(w1, cache, log=lambda _: None)
assert open(os.path.join(w1, "footage/take.mov"), "rb").read() == take