Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(render-farm): sweep stashes a finished export's cleanup missed

Richie McIlroy223b5653c2bb
diff --git a/apps/render-farm/README.md b/apps/render-farm/README.md
index 498dd5fe4..54ea72803 100644
--- a/apps/render-farm/README.md
+++ b/apps/render-farm/README.md
@@ -66,7 +66,9 @@ Jobs created with version 2 can resume across subsequent coordinator restarts.
Run workers with the NVIDIA container toolkit (`--gpus all`) and `--init`.
Give the coordinator a bucket-scoped IAM role (or keys), a shared `RF_TOKEN`,
and a lifecycle rule on the bucket that aborts incomplete multipart uploads and
-expires `hls/` and `jobs/` objects.
+expires `hls/`, `jobs/` and `stash/` objects. The coordinator deletes each
+export's `stash/` objects when it ends and sweeps any it missed, so a day's
+expiry there is only a backstop.
| Variable | Default | Role |
| --- | --- | --- |
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.ts
index 7a29c2fc8..e33a7c46d 100644
--- a/apps/render-farm/src/coordinator.test.ts
+++ b/apps/render-farm/src/coordinator.test.ts
@@ -183,12 +183,13 @@ function harness(env: Record<string, string> = {}) {
const compiled = new Bun.Transpiler({ loader: "ts" }).transformSync(source);
const coordinator = new Function(
...Object.keys(deps),
- `${compiled}\nreturn {jobs, queue, straggler, dispatchedTask, onVideoDone, onAudioDone, publishPlaylist, journalJob, resumeJobs, newHlsState, finish, requeue, sourceIndex, assemble, stitchAhead, setPlanner: (fn) => { planJob = fn; }};`,
+ `${compiled}\nreturn {jobs, queue, straggler, dispatchedTask, onVideoDone, onAudioDone, publishPlaylist, journalJob, resumeJobs, newHlsState, finish, requeue, sourceIndex, assemble, stitchAhead, sweepStashes, setPlanner: (fn) => { planJob = fn; }};`,
)(...Object.values(deps)) as {
setPlanner: (fn: (job: Job) => Promise<void>) => void;
sourceIndex: (prefix: string, sourceRoot?: string) => Promise<unknown>;
assemble: (job: Job) => Promise<void>;
stitchAhead: (job: Job) => void;
+ sweepStashes: () => Promise<void>;
requeue: (state: TaskState, reason: string) => void;
jobs: Map<string, Job>;
queue: TaskState[];
@@ -291,7 +292,7 @@ function videoState(job: Job, duplicate = false): TaskState {
firstPart: 3,
partLimit: 10,
partTarget: 16 << 20,
- stashKey: `jobs/${job.id}/stash/c0-p3`,
+ stashKey: `stash/${job.id}/c0-p3`,
},
audio: null,
hls: null,
@@ -331,7 +332,7 @@ function result(state: TaskState): protocol.VideoResult {
audioRuns: [],
firstPart: state.firstPart ?? 3,
stash: {
- key: `jobs/job/stash/c0-p${state.firstPart ?? 3}`,
+ key: `stash/job/c0-p${state.firstPart ?? 3}`,
bytes: 100,
},
parts: [],
@@ -371,7 +372,7 @@ describe("assembly", () => {
): protocol.VideoResult {
const chunk = j.chunks[index] as NonNullable<Job["chunks"][number]>;
const data = new Uint8Array(bytes).fill(fill);
- const stashKey = `jobs/${j.id}/stash/c${index}-p${chunk.firstPart}`;
+ const stashKey = `stash/${j.id}/c${index}-p${chunk.firstPart}`;
const stash = stitch.stashBytes(bytes);
h.objects.set(stashKey, data.subarray(0, stash));
const parts: protocol.VideoResult["parts"] = [];
@@ -453,7 +454,7 @@ describe("assembly", () => {
for (const [index, bytes] of [11 * MB, 13 * MB].entries())
j.videoResults.set(index, stored(h, j, index, bytes, index + 1));
await h.assemble(j);
- expect(h.copies).toEqual(["jobs/job/stash/c1-p63"]);
+ expect(h.copies).toEqual(["stash/job/c1-p63"]);
});
test("parts written while chunks render are reused, not written again", async () => {
@@ -463,13 +464,36 @@ describe("assembly", () => {
j.videoResults.set(index, stored(h, j, index, bytes, index + 1));
h.stitchAhead(j);
await Promise.all(j.stitchParts?.values() ?? []);
- expect(h.copies).toEqual(["jobs/job/stash/c1-p63"]);
+ expect(h.copies).toEqual(["stash/job/c1-p63"]);
await h.assemble(j);
- expect(h.copies).toEqual(["jobs/job/stash/c1-p63"]);
+ expect(h.copies).toEqual(["stash/job/c1-p63"]);
const file = h.objects.get(j.key) as Uint8Array;
expect(file[file.byteLength - 1]).toBe(2);
});
+ test("stashes outlive neither their job nor a restart", async () => {
+ const h = harness();
+ const live = job();
+ const done = { ...job(), id: "done", status: "ready" as const };
+ h.jobs.set(live.id, live);
+ h.jobs.set(done.id, done);
+ for (const key of [
+ "stash/job/c0-p3",
+ "stash/done/c0-p3",
+ "stash/gone/c1-p63",
+ ])
+ h.objects.set(key, new Uint8Array(1));
+ // A sweep before the journal is resumed would take jobs about to be
+ // resumed for finished ones.
+ await h.sweepStashes();
+ expect(h.objects.has("stash/gone/c1-p63")).toBe(true);
+ await h.resumeJobs();
+ await h.sweepStashes();
+ expect(
+ [...h.objects.keys()].filter((key) => key.startsWith("stash/")),
+ ).toEqual(["stash/job/c0-p3"]);
+ });
+
test("a result whose parts leave a gap in the chunk is refused", async () => {
const h = harness();
const j = job();
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
index 666c7fc10..086c56acf 100644
--- a/apps/render-farm/src/coordinator.ts
+++ b/apps/render-farm/src/coordinator.ts
@@ -1098,9 +1098,12 @@ const JOURNAL = process.env.RF_JOURNAL !== "0";
// Workers heartbeat every 3 s; this is enough for all of them to report in.
const RESUME_HOLD_MS = 10_000;
const journalKey = (id: string, name: string) => `jobs/${id}/${name}`;
-/** Where a dispatch stores its chunk's opening bytes (see stitch.ts). */
+/**
+ * Where a dispatch stores its chunk's opening bytes (see stitch.ts). Outside
+ * `jobs/` so a sweep can list every stash without reading journals.
+ */
const stashKey = (id: string, chunk: number, firstPart: number) =>
- journalKey(id, `stash/c${chunk}-p${firstPart}`);
+ `stash/${id}/c${chunk}-p${firstPart}`;
async function journalPut(key: string, body: Uint8Array | string) {
if (!JOURNAL) return;
@@ -1204,6 +1207,17 @@ function segmentsFromResult(
}
async function resumeJobs() {
+ try {
+ await resumeJournal();
+ } finally {
+ journalResumed = true;
+ sweepStashes().catch((error) =>
+ console.error(`stash sweep failed: ${error}`),
+ );
+ }
+}
+
+async function resumeJournal() {
if (!JOURNAL) return;
const keys = await journalS3.list("jobs/");
const byJob = new Map<string, Set<string>>();
@@ -2534,10 +2548,34 @@ async function writeStitchParts(
}
async function dropStashes(id: string) {
- const keys = await journalS3.list(journalKey(id, "stash/"));
+ const keys = await journalS3.list(`stash/${id}/`);
await Promise.all(keys.map(({ key }) => journalS3.delete(key)));
}
+const STASH_SWEEP_MS = 10 * 60_000;
+let journalResumed = false;
+
+/**
+ * Deletes the stashes of every job not rendering or assembling. A job's own
+ * cleanup misses those a losing copy writes after it, and any left when the
+ * coordinator stops mid-cleanup; restart never reopens a finished job.
+ */
+async function sweepStashes() {
+ // Before resume, jobs about to be resumed are not in memory yet.
+ if (!journalResumed) return;
+ const stale = (await journalS3.list("stash/")).filter(({ key }) => {
+ const job = jobs.get(key.split("/")[1] ?? "");
+ return job?.status !== "rendering" && job?.status !== "assembling";
+ });
+ await Promise.all(stale.map(({ key }) => journalS3.delete(key)));
+}
+
+setInterval(() => {
+ sweepStashes().catch((error) =>
+ console.error(`stash sweep failed: ${error}`),
+ );
+}, STASH_SWEEP_MS);
+
async function verifyPlayable(job: Job) {
if (!job.url) return;
const probe = Bun.spawn(