Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(render-farm): make dispatch and export recovery durable
Richie McIlroy7fbf6167c06e
diff --git a/apps/render-farm/README.md b/apps/render-farm/README.mdindex db517c47f..f2366083c 100644--- a/apps/render-farm/README.md+++ b/apps/render-farm/README.md@@ -33,8 +33,20 @@ one S3 multipart upload.slot, and a worker-side watchdog kills engines that stop reporting progress.- A worker that restarts or stops heartbeating has its tasks requeued; `SIGTERM`drains a worker (finishes running tasks, takes no new ones) before it exits.-- With the S3 journal a restarted coordinator reloads unfinished jobs and- re-attaches chunks that workers are still rendering.+- Job acceptance waits for a durable request receipt; interrupted planning is+ replayed after restart. The plan and each video dispatch reservation are durable+ before work is sent.+ Each chunk has six disjoint part ranges (five original attempts plus a hedge).+ Retries never wrap around to old ranges; exhausting the range budget fails the+ export. A restart restores reservations, attempt numbers and hedge ownership.+- Accepted video results and audio packets are durable before acknowledgement or+ use by another task. Concurrent copies cannot replace the first accepted result.+- Recovery recognizes a completed MP4 by its expected size and header, including+ when S3 committed completion but its response was lost.+- Failed playlist writes retain the unpublished cursor and retry without waiting+ for another segment report. The final journal marker waits for the HLS end list.+- Probes run serially with a two-minute execution deadline and one fresh-process+ retry after exit or timeout; a failed engine does not poison future exports.- `RF_REQUIRE_GPU=1` refuses a chunk whose engine fell back to software decodingor rendering, so it is retried on a healthy engine instead of slowing the job.- Finished jobs keep a summary for `RF_JOB_RETENTION_MS`; a job with no progress@@ -46,6 +58,11 @@ one S3 multipart upload.docker build -f apps/render-farm/Dockerfile -t cap-render-farm .```+Before upgrading from the initial unversioned journal format, stop accepting new+exports and let the active jobs finish. That format did not durably reserve upload+ranges, so version 2 refuses to resume those unfinished uploads and aborts them.+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 anddiff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.tsnew file mode 100644index 000000000..510a43317--- /dev/null+++ b/apps/render-farm/src/coordinator.test.ts@@ -0,0 +1,443 @@+import { describe, expect, test } from "bun:test";+import { randomUUID, timingSafeEqual } from "node:crypto";+import { readFileSync } from "node:fs";+import type { Job, TaskState } from "./coordinator";+import * as fmp4 from "./fmp4";+import * as hls from "./hls";+import * as mp4 from "./mp4";+import * as planning from "./planning";+import * as protocol from "./protocol";+import * as recovery from "./recovery";+import { pickQueued } from "./scheduler";+import { validateJobRequest } from "./validate";++function harness() {+ const objects = new Map<string, Uint8Array>();+ const writes: string[] = [];+ const timers: (() => void)[] = [];+ const watchdogs: (() => void)[] = [];+ let putGate: Promise<void> | undefined;+ let failures = 0;+ const s3 = {+ async put(key: string, body: Uint8Array | string) {+ writes.push(key);+ await putGate;+ if (failures-- > 0) throw new Error("injected storage failure");+ objects.set(+ key,+ typeof body === "string" ? new TextEncoder().encode(body) : body,+ );+ },+ async get(key: string) {+ const value = objects.get(key);+ if (!value) throw new Error(`missing ${key}`);+ return value;+ },+ async list() {+ return [...objects.keys()].map((key) => ({ key }));+ },+ async presignFresh(_method: string, key: string) {+ return `https://media.test/${key}`;+ },+ async abortMultipart() {},+ };+ const source = readFileSync(+ new URL("./coordinator.ts", import.meta.url),+ "utf8",+ )+ .replace(/^import[\s\S]*?from "[^"]+";\n/gm, "")+ .replace(/^export type .*;\n/gm, "")+ .replace(/^resumeJobs\(\).*;$/m, "");+ let fetchHandler: (request: Request) => Promise<Response> = async () =>+ new Response();+ const deps = {+ timingSafeEqual,+ randomUUID,+ validateJobRequest,+ ...fmp4,+ ...hls,+ ...mp4,+ ...planning,+ ...protocol,+ ...recovery,+ pickQueuedTask: pickQueued,+ S3: class {+ constructor() {+ Object.assign(this, s3);+ }+ },+ s3ConfigFromEnv: () => ({}),+ ProbeEngine: class {},+ Engine: class {},+ process: {+ env: { RF_TOKEN: "test", RF_LOCAL_AUDIO_SLOTS: "0", RF_HLS: "1" },+ },+ Bun: {+ serve: (options: { fetch: typeof fetchHandler }) => {+ fetchHandler = options.fetch;+ },+ },+ setInterval: (callback: () => void) => {+ watchdogs.push(callback);+ },+ setTimeout: (callback: () => void) => {+ timers.push(callback);+ return { unref() {} };+ },+ clearTimeout: () => {},+ console: { log() {}, warn() {}, error() {} },+ mkdirSync: () => {},+ rmSync: () => {},+ join: (...parts: string[]) => parts.join("/"),+ };+ const compiled = new Bun.Transpiler({ loader: "ts" }).transformSync(source);+ const coordinator = new Function(+ ...Object.keys(deps),+ `${compiled}\nreturn {jobs, queue, dispatchedTask, onVideoDone, onAudioDone, publishPlaylist, journalJob, resumeJobs, newHlsState, finish, requeue, setPlanner: (fn) => { planJob = fn; }};`,+ )(...Object.values(deps)) as {+ setPlanner: (fn: (job: Job) => Promise<void>) => void;+ requeue: (state: TaskState, reason: string) => void;+ jobs: Map<string, Job>;+ queue: TaskState[];+ dispatchedTask: (job: Job, state: TaskState) => Promise<protocol.Task>;+ onVideoDone: (+ job: Job,+ state: TaskState,+ result: protocol.VideoResult,+ ) => Promise<void>;+ onAudioDone: (+ job: Job,+ state: TaskState,+ meta: protocol.AudioResultMeta,+ bytes: Uint8Array,+ ) => Promise<void>;+ publishPlaylist: (job: Job) => Promise<void>;+ journalJob: (job: Job) => Promise<void>;+ resumeJobs: () => Promise<void>;+ newHlsState: (prefix: string) => Promise<NonNullable<Job["hls"]>>;+ finish: (job: Job) => void;+ };+ return {+ ...coordinator,+ objects,+ writes,+ timers,+ watchdogs,+ fetch: (request: Request) => fetchHandler(request),+ gate: (gate?: Promise<void>) => {+ putGate = gate;+ },+ fail: (count = 1) => {+ failures = count;+ },+ };+}++function job(): Job {+ return {+ id: "job",+ request: { recording: "recording" },+ status: "rendering",+ key: "out/job.mp4",+ uploadId: "upload",+ t: { requested: Date.now() },+ fps: 30,+ bpp: 0.1,+ resolution: [1920, 1080],+ totalFrames: 60,+ totalSamples: 0,+ width: 1920,+ height: 1080,+ chunks: [0, 1].map((index) => ({+ index,+ frames: [index * 30, (index + 1) * 30],+ packets: [0, 0],+ files: [],+ firstPart: 2 + index * 60,+ partLimit: 10,+ dispatches: 0,+ })),+ sections: [],+ tasks: new Map(),+ videoResults: new Map(),+ audioSections: new Map(),+ acceptances: new Map(),+ audioWaiters: [],+ cpuSeconds: 0,+ fetchedBytes: 0,+ workersUsed: new Set(),+ waiters: [],+ taskStats: [],+ };+}++function videoState(job: Job, duplicate = false): TaskState {+ const task: protocol.VideoTask = {+ kind: "video",+ taskId: `job:v0${duplicate ? ":dup" : ""}`,+ jobId: job.id,+ chunk: 0,+ fps: 30,+ resolution: [1920, 1080],+ bpp: 0.1,+ frames: [0, 30],+ threads: 8,+ files: [],+ upload: {+ key: job.key,+ uploadId: "upload",+ firstPart: 2,+ partLimit: 10,+ partTarget: 16 << 20,+ isLast: false,+ },+ audio: null,+ hls: null,+ };+ const state: TaskState = {+ task,+ state: "running",+ attempts: 1,+ worker: duplicate ? "worker-b" : "worker-a",+ duplicateOf: duplicate ? "job:v0" : undefined,+ };+ job.tasks.set(task.taskId, state);+ return state;+}++const timings: protocol.VideoResult["timings"] = {+ queuedMs: 0,+ fetch: { bytes: 10, ms: 1, requests: 1 },+ engine: {},+ engineMs: 1,+ audioWaitMs: 0,+ uploadMs: 1,+ totalMs: 2,+ cpuSeconds: 1,+};++function result(state: TaskState): protocol.VideoResult {+ return {+ taskId: state.task.taskId,+ worker: state.worker ?? "worker",+ sizes: [100],+ keyframes: [0],+ extradata: "",+ width: 1920,+ height: 1080,+ videoRuns: [],+ audioRuns: [],+ parts: [],+ bytes: 100,+ paddedBytes: 0,+ timings,+ };+}++function heartbeat(worker: string, taskId: string, attempt: number) {+ return new Request("http://test/heartbeat", {+ method: "POST",+ headers: {+ authorization: "Bearer test",+ "content-type": "application/json",+ },+ body: JSON.stringify({+ worker,+ slots: 1,+ cpus: 1,+ running: [{ taskId, attempt, frames: 1, total: 30, elapsedMs: 100 }],+ }),+ });+}++describe("coordinator recovery", () => {+ test("dispatch waits for its reservation, resume preserves original and hedge ranges", async () => {+ const h = harness();+ const j = job();+ const original = videoState(j);+ await h.journalJob(j);+ const gate = Promise.withResolvers<void>();+ h.gate(gate.promise);+ let sent = false;+ const first = h.dispatchedTask(j, original).then((task) => {+ sent = true;+ return task;+ });+ await Promise.resolve();+ expect(sent).toBe(false);+ gate.resolve();+ await first;+ h.gate();+ const hedge = videoState(j, true);+ await h.dispatchedTask(j, hedge);+ await h.resumeJobs();+ const resumed = h.jobs.get(j.id) as Job;+ expect(resumed.chunks[0]?.dispatches).toBe(2);+ expect(resumed.tasks.get(original.task.taskId)?.duplicated).toBe(true);+ await h.fetch(heartbeat("worker-b", hedge.task.taskId, 1));+ expect(resumed.tasks.get(hedge.task.taskId)?.state).toBe("running");+ const next = await h.dispatchedTask(resumed, original);+ expect(next.kind === "video" && next.upload.firstPart).toBe(22);+ });++ test("a stale heartbeat cannot adopt a reserved newer attempt", async () => {+ const h = harness();+ const j = job();+ const original = videoState(j);+ await h.journalJob(j);+ await h.dispatchedTask(j, original);+ original.attempts = 2;+ await h.dispatchedTask(j, original);+ await h.resumeJobs();+ const resumed = h.jobs.get(j.id) as Job;+ await h.fetch(heartbeat("worker-a", original.task.taskId, 1));+ expect(resumed.tasks.get(original.task.taskId)?.state).toBe("queued");+ await h.fetch(heartbeat("worker-a", original.task.taskId, 2));+ expect(resumed.tasks.get(original.task.taskId)?.state).toBe("running");+ });++ test("concurrent winners and duplicate reports persist and count only once", async () => {+ const h = harness();+ const j = job();+ const original = videoState(j);+ const hedge = videoState(j, true);+ const gate = Promise.withResolvers<void>();+ h.gate(gate.promise);+ const first = result(original);+ const second = result(hedge);+ const accepted = h.onVideoDone(j, original, first);+ const duplicate = h.onVideoDone(j, hedge, second);+ expect(j.videoResults.size).toBe(0);+ expect(h.writes).toEqual(["jobs/job/v/0.json"]);+ gate.resolve();+ await Promise.all([accepted, duplicate]);+ await h.onVideoDone(j, original, first);+ expect(j.videoResults.get(0)?.worker).toBe("worker-a");+ expect(j.cpuSeconds).toBe(1);+ expect(original.state).toBe("done");+ expect(hedge.state).toBe("done");+ h.jobs.set(j.id, j);+ h.watchdogs[0]?.();+ h.requeue(hedge, "stale watchdog");+ expect(h.queue.length).toBe(0);+ expect(h.writes.length).toBe(1);+ });++ test("audio stays unavailable until durable, failed persistence can be retried", async () => {+ const h = harness();+ const j = job();+ const state: TaskState = {+ task: {+ kind: "audio",+ taskId: "job:a0",+ jobId: j.id,+ section: 0,+ fps: 30,+ range: [0, 1024],+ preroll: 0,+ files: [],+ },+ state: "running",+ attempts: 1,+ };+ const meta: protocol.AudioResultMeta = {+ taskId: "job:a0",+ worker: "worker",+ firstPacket: 0,+ sizes: [2],+ extradata: "",+ timings,+ };+ const bytes = new Uint8Array([1, 2]);+ h.fail();+ await expect(h.onAudioDone(j, state, meta, bytes)).rejects.toThrow(+ "injected",+ );+ expect(j.audioSections.size).toBe(0);+ expect(state.state).toBe("running");+ const gate = Promise.withResolvers<void>();+ h.gate(gate.promise);+ const pending = h.onAudioDone(j, state, meta, bytes);+ expect(j.audioSections.size).toBe(0);+ gate.resolve();+ await pending;+ expect(j.audioSections.get(0)?.data).toEqual(bytes);+ });++ test("the final playlist retries without another report or live audio data", async () => {+ const h = harness();+ const j = job();+ j.chunks.splice(1);+ j.hls = await h.newHlsState("hls/job");+ j.hls.initUrl = "https://media.test/init.mp4";+ j.hls.segments.set(+ 0,+ new Map([+ [+ 0,+ {+ chunk: 0,+ index: 0,+ frames: [0, 30],+ key: "segment",+ last: true,+ extradata: "",+ },+ ],+ ]),+ );+ h.fail();+ await h.publishPlaylist(j);+ expect(j.hls.cursor.chunk).toBe(0);+ expect(j.hls.listed).toEqual([]);+ expect(j.hls.ended).toBe(false);+ j.status = "ready";+ h.finish(j);+ expect(h.objects.has("jobs/job/done")).toBe(false);+ h.timers[0]?.();+ for (let i = 0; i < 20; i++) await Promise.resolve();+ expect(j.hls.ended).toBe(true);+ expect(+ new TextDecoder().decode(h.objects.get("hls/job/index.m3u8")),+ ).toContain("#EXT-X-ENDLIST");+ expect(h.objects.has("jobs/job/done")).toBe(true);+ });+});++test("job acknowledgement waits for a planning receipt and receipt-only jobs resume", async () => {+ const h = harness();+ const planned: string[] = [];+ h.setPlanner(async (job) => {+ planned.push(job.id);+ });+ const gate = Promise.withResolvers<void>();+ h.gate(gate.promise);+ let acknowledged = false;+ const response = h+ .fetch(+ new Request("http://test/jobs", {+ method: "POST",+ headers: {+ authorization: "Bearer test",+ "content-type": "application/json",+ },+ body: JSON.stringify({ recording: "recording" }),+ }),+ )+ .then((value) => {+ acknowledged = true;+ return value;+ });+ for (let i = 0; i < 20; i++) await Promise.resolve();+ expect(h.writes.length).toBe(1);+ expect(acknowledged).toBe(false);+ expect(planned).toEqual([]);+ gate.resolve();+ const receipt = (await (await response).json()) as { id: string };+ expect(h.objects.has(`jobs/${receipt.id}/request.json`)).toBe(true);+ expect(planned).toEqual([receipt.id]);+ h.jobs.clear();+ await h.resumeJobs();+ expect(planned).toEqual([receipt.id, receipt.id]);+ expect(h.jobs.get(receipt.id)?.status).toBe("planning");+});diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.tsindex c84c93b6c..ac9c0b698 100644--- a/apps/render-farm/src/coordinator.ts+++ b/apps/render-farm/src/coordinator.ts@@ -15,6 +15,7 @@ import {type TrackIndex,} from "./mp4";import { planChunkBoundaries } from "./planning";+import { ProbeEngine } from "./probe-engine";import {type AudioResultMeta,type AudioTask,@@ -26,6 +27,12 @@ import {type VideoResult,type VideoTask,} from "./protocol";+import {+ acceptOnce,+ completeUpload,+ PART_RANGES,+ reservePartRange,+} from "./recovery";import { S3, s3ConfigFromEnv } from "./s3";import { pickQueued as pickQueuedTask } from "./scheduler";import { validateJobRequest } from "./validate";@@ -50,16 +57,13 @@ const JOB_RETENTION_MS = Number(process.env.RF_JOB_RETENTION_MS ?? 60 * 60_000);const SAMPLE_RATE = 48_000;const PACKET = 1024;-const probeEngine = new Engine(ENGINE_BIN, {}, "coordinator-engine");+const probeEngine = new ProbeEngine(+ () => new Engine(ENGINE_BIN, {}, "coordinator-engine"),+);// Audio sections (Studio Sound) are CPU work. These lanes render them on the// coordinator's cores, pulling from the same queue as workers' audio lanes.const LOCAL_AUDIO_SLOTS = Number(process.env.RF_LOCAL_AUDIO_SLOTS ?? 2);-// Every dispatch of a chunk (original, hedge, retry) uploads into its own part-// range, cycling through this many. NVENC output differs between GPUs, so two-// live copies must never write the same part numbers; completion lists exactly-// the accepted copy's parts and S3 discards the rest.-const PART_RANGES = 4;// Progressive playback: chunks stream fMP4 segments while rendering and the// coordinator keeps an HLS EVENT playlist of the contiguous prefix, so an// export is watchable seconds after the request whatever its length. The@@ -164,7 +168,7 @@ async function runAudioLocally(job: Job, state: TaskState) {cpuSeconds: 0,},};- if (job.status === "rendering") onAudioDone(job, state, meta, data);+ if (job.status === "rendering") await onAudioDone(job, state, meta, data);} catch (error) {if (state.attempts >= 3) failJob(job, error);else@@ -215,6 +219,8 @@ type TaskState = {worker?: string;startedAt?: number;attempts: number;+ dispatching?: boolean;+ reattach?: boolean;duplicateOf?: string;duplicated?: boolean;/** Reserved by a busy slot ahead of time; not started until it reports progress. */@@ -241,10 +247,13 @@ type HlsState = {writing: boolean;dirty: boolean;ended: boolean;+ audioExtradata?: string;+ retry?: ReturnType<typeof setTimeout>;};type Job = {verified?: boolean;+ acceptances: Map<string, Promise<void>>;/** Summary frozen when the job ends; the job's media data is released then. */final?: ReturnType<typeof summary>;hls?: HlsState;@@ -312,6 +321,42 @@ function liveSlots() {return { slots, audioSlots, workers: count };}+async function newJob(+ id: string,+ request: JobRequest,+ requestedAt = now(),+): Promise<Job> {+ const compression = request.compression ?? "Maximum";+ const job: Job = {+ id,+ acceptances: new Map(),+ request,+ status: "planning",+ key: `out/${id}.mp4`,+ t: { requested: requestedAt },+ fps: request.fps ?? 30,+ bpp: COMPRESSION_BPP[compression],+ resolution: request.resolution ?? [1920, 1080],+ totalFrames: 0,+ totalSamples: 0,+ width: 0,+ height: 0,+ chunks: [],+ sections: [],+ tasks: new Map(),+ videoResults: new Map(),+ audioSections: new Map(),+ audioWaiters: [],+ cpuSeconds: 0,+ fetchedBytes: 0,+ workersUsed: new Set(),+ waiters: [],+ taskStats: [],+ };+ if (HLS) job.hls = await newHlsState(`hls/${id}`);+ return job;+}+// ---------------------------------------------------------------- planning ---type Manifest = { files: { path: string; size: number; key?: string }[] };@@ -530,13 +575,14 @@ async function planJob(job: Job) {audio_cuts: number[];clips: { index: number; camera: number; mic: number }[];};- const probe = await probeEngine.request<Probe>("probe", {- project: probeDir,- fps: job.fps,- resolution: job.resolution,- span_step: gop,- });- cache.close();+ const probe = await probeEngine+ .request<Probe>({+ project: probeDir,+ fps: job.fps,+ resolution: job.resolution,+ span_step: gop,+ })+ .finally(() => cache.close());job.t.probed = now();if (request.frameLimit && request.frameLimit < probe.total_frames) {probe.total_frames = request.frameLimit;@@ -829,8 +875,8 @@ async function planJob(job: Job) {};enqueue(job, task);}+ await journalJob(job);job.status = "rendering";- journalJob(job);dispatch();}@@ -846,9 +892,9 @@ const JOURNAL = process.env.RF_JOURNAL !== "0";const RESUME_HOLD_MS = 10_000;const journalKey = (id: string, name: string) => `jobs/${id}/${name}`;-function journalPut(key: string, body: Uint8Array | string) {+async function journalPut(key: string, body: Uint8Array | string) {if (!JOURNAL) return;- s3.put(key, body).catch((error) => console.error(`journal ${key}: ${error}`));+ await s3.put(key, body);}type JournaledJob = Pick<@@ -869,10 +915,11 @@ type JournaledJob = Pick<| "sections"| "plan"| "probe"-> & { tasks: Task[]; hls: { prefix: string } | null };+> & { version: 2; tasks: Task[]; hls: { prefix: string } | null };function journalJob(job: Job) {const record: JournaledJob = {+ version: 2,id: job.id,request: job.request,key: job.key,@@ -894,7 +941,7 @@ function journalJob(job: Job) {.map((state) => state.task),hls: job.hls ? { prefix: job.hls.prefix } : null,};- journalPut(journalKey(job.id, "job.json"), JSON.stringify(record));+ return journalPut(journalKey(job.id, "job.json"), JSON.stringify(record));}function audioFrame(meta: AudioResultMeta, data: Uint8Array) {@@ -957,18 +1004,52 @@ async function resumeJobs() {byJob.set(id, names);}for (const [id, names] of byJob) {- if (names.has("done") || !names.has("job.json") || jobs.has(id)) continue;+ if (names.has("done") || jobs.has(id)) continue;try {+ if (!names.has("job.json")) {+ if (!names.has("request.json")) continue;+ const receipt = JSON.parse(+ new TextDecoder().decode(+ await s3.get(journalKey(id, "request.json")),+ ),+ ) as { request: JobRequest; requestedAt: number };+ if (Date.now() - receipt.requestedAt > 5 * 3600_000) {+ await journalPut(journalKey(id, "done"), "expired");+ continue;+ }+ const job = await newJob(id, receipt.request, receipt.requestedAt);+ jobs.set(id, job);+ planJob(job).catch((error) => failJob(job, error));+ continue;+ }const record = JSON.parse(new TextDecoder().decode(await s3.get(journalKey(id, "job.json"))),) as JournaledJob;// Presigned segment/playlist URLs last 6 h; older jobs are abandoned.if (Date.now() - (record.t.requested ?? 0) > 5 * 3600_000) {- journalPut(journalKey(id, "done"), "expired");+ await journalPut(journalKey(id, "done"), "expired");+ continue;+ }+ if (record.version !== 2) {+ if (record.uploadId)+ await s3.abortMultipart(record.key, record.uploadId);+ await journalPut(+ journalKey(id, "done"),+ "incompatible journal version",+ );+ console.error(+ `job ${id}: legacy journal has no durable upload reservations`,+ );continue;}+ const reservations: {+ task: Task;+ worker: string;+ duplicateOf?: string;+ }[] = [];const job: Job = {...record,+ acceptances: new Map(),status: "rendering",tasks: new Map(),videoResults: new Map(),@@ -984,6 +1065,21 @@ async function resumeJobs() {job.t.resumed = now();job.t.lastProgress = now();for (const name of names) {+ const dispatch = name.match(/^dispatches\/(\d+)\/(\d+)\.json$/);+ if (dispatch) {+ const chunk = job.chunks[Number(dispatch[1])];+ if (!chunk) throw new Error("invalid reserved chunk");+ chunk.dispatches = Math.max(+ chunk.dispatches,+ Number(dispatch[2]) + 1,+ );+ reservations.push(+ JSON.parse(+ new TextDecoder().decode(await s3.get(journalKey(id, name))),+ ),+ );+ continue;+ }const video = name.match(/^v\/(\d+)\.json$/);if (video) {const result = JSON.parse(@@ -1026,7 +1122,36 @@ async function resumeJobs() {requeued++;}}+ for (const reservation of reservations) {+ const { task, worker, duplicateOf } = reservation;+ let state = job.tasks.get(task.taskId);+ if (!state) {+ const done =+ task.kind === "video" && job.videoResults.has(task.chunk);+ state = {+ task,+ state: done ? "done" : "queued",+ attempts: 0,+ duplicateOf,+ heldUntil: done ? undefined : Date.now() + RESUME_HOLD_MS,+ };+ job.tasks.set(task.taskId, state);+ if (!done) queue.push(state);+ }+ if ((task.attempt ?? 0) >= state.attempts) {+ state.attempts = task.attempt ?? 0;+ state.worker = worker;+ state.reattach = true;+ }+ if (duplicateOf) {+ const original = job.tasks.get(duplicateOf);+ if (original) original.duplicated = true;+ }+ }if (job.hls) {+ job.hls.audioExtradata = job.audioSections+ .values()+ .next().value?.meta.extradata;for (const chunk of job.chunks) {const result = job.videoResults.get(chunk.index);if (!result) continue;@@ -1067,6 +1192,10 @@ function enqueue(job: Job, task: Task, duplicateOf?: string) {}function pickQueued(accepts: (kind: string) => boolean) {+ for (const state of [...queue]) {+ const job = jobs.get(state.task.jobId);+ if (job && taskAccepted(job, state.task)) retireTask(state);+ }const schedulable = [...jobs.values()].map((job) => {let runningTasks = 0;for (const state of job.tasks.values()) {@@ -1089,30 +1218,56 @@ function pickQueued(accepts: (kind: string) => boolean) {}/** The task as sent for this attempt: its attempt number and part range. */-function dispatchedTask(job: Job | undefined, state: TaskState): Task {+async function dispatchedTask(+ job: Job | undefined,+ state: TaskState,+): Promise<Task> {const task = state.task;if (task.kind !== "video" || !job)return { ...task, attempt: state.attempts };const chunk = job.chunks[task.chunk];- if (!chunk) return { ...task, attempt: state.attempts };- const range = chunk.dispatches++ % PART_RANGES;- return {+ if (!chunk) throw new Error("unknown chunk");+ const { range, firstPart } = reservePartRange(chunk);+ const dispatched = {...task,attempt: state.attempts,- upload: {- ...task.upload,- firstPart: chunk.firstPart + range * chunk.partLimit,- partLimit: chunk.partLimit,- },+ upload: { ...task.upload, firstPart, partLimit: chunk.partLimit },};+ await journalPut(+ journalKey(job.id, `dispatches/${chunk.index}/${range}.json`),+ JSON.stringify({+ task: dispatched,+ worker: state.worker,+ duplicateOf: state.duplicateOf,+ }),+ );+ return dispatched;+}++function taskAccepted(job: Job, task: Task) {+ return task.kind === "video"+ ? job.videoResults.has(task.chunk)+ : job.audioSections.has(task.section);+}++function retireTask(state: TaskState) {+ state.state = "done";+ const index = queue.indexOf(state);+ if (index >= 0) queue.splice(index, 1);}/** Put a task back in the queue, at most once. */function requeue(state: TaskState, reason: string) {+ const job = jobs.get(state.task.jobId);+ if (!job || job.status !== "rendering" || taskAccepted(job, state.task)) {+ retireTask(state);+ return;+ }console.warn(`requeue ${state.task.taskId}: ${reason}`);state.state = "queued";state.worker = undefined;state.progress = undefined;+ state.reattach = false;if (!queue.includes(state)) queue.unshift(state);}@@ -1147,7 +1302,21 @@ function dispatch() {if (state.task.kind === "video") job.t.firstVideoStarted ??= now();job.workersUsed.add(poller.worker);}- poller.resolve(dispatchedTask(job, state));+ state.dispatching = true;+ state.reattach = false;+ const dispatchedState = state;+ dispatchedTask(job, state).then(+ (task) => {+ dispatchedState.dispatching = false;+ dispatchedState.startedAt = now();+ poller.resolve(job?.status === "rendering" ? task : null);+ },+ (error) => {+ dispatchedState.dispatching = false;+ if (job) failJob(job, error);+ poller.resolve(null);+ },+ );}}@@ -1179,6 +1348,7 @@ function straggler(): TaskState | undefined {for (const state of job.tasks.values()) {if (state.task.kind !== "video" ||+ state.dispatching ||state.state !== "running" ||state.duplicated ||state.duplicateOf ||@@ -1257,7 +1427,11 @@ function supersede(id: string) {for (const job of jobs.values()) {if (job.status !== "rendering") continue;for (const state of job.tasks.values()) {- if (state.state === "running" && state.worker === old) {+ if (+ state.state === "running" &&+ !state.dispatching &&+ state.worker === old+ ) {requeue(state, `worker ${old} restarted`);}}@@ -1284,6 +1458,7 @@ setInterval(() => {for (const state of job.tasks.values()) {if (state.state !== "running" ||+ state.dispatching ||!state.worker ||state.worker === "coordinator")@@ -1323,9 +1498,8 @@ async function writeInit(job: Job, hls: HlsState) {if (!hls.extradata) return false;let asc: Uint8Array | null = null;if (job.sections.length > 0) {- const section = job.audioSections.values().next().value;- if (!section) return false;- asc = Buffer.from(section.meta.extradata, "base64");+ if (!hls.audioExtradata) return false;+ asc = Buffer.from(hls.audioExtradata, "base64");}const key = `${hls.prefix}/init.mp4`;await s3.put(@@ -1346,7 +1520,8 @@ async function writeInit(job: Job, hls: HlsState) {/** Rewrites the playlist whenever the contiguous run of segments grows. */async function publishPlaylist(job: Job) {const hls = job.hls;- if (!hls || hls.ended) return;+ if (!hls || hls.ended || job.status === "error") return;+ clearTimeout(hls.retry);if (hls.writing) {hls.dirty = true;return;@@ -1357,46 +1532,60 @@ async function publishPlaylist(job: Job) {hls.dirty = false;if (!hls.initUrl && !(await writeInit(job, hls))) return;let grew = false;+ let cursor = { ...hls.cursor };+ const listed = [...hls.listed];for (;;) {- const segment = hls.segments- .get(hls.cursor.chunk)- ?.get(hls.cursor.index);+ const segment = hls.segments.get(cursor.chunk)?.get(cursor.index);if (!segment) break;- hls.listed.push({+ listed.push({url: await s3.presignFresh("GET", segment.key, 6 * 3600),duration: (segment.frames[1] - segment.frames[0]) / job.fps,});grew = true;- hls.cursor = segment.last- ? { chunk: hls.cursor.chunk + 1, index: 0 }- : { chunk: hls.cursor.chunk, index: hls.cursor.index + 1 };+ cursor = segment.last+ ? { chunk: cursor.chunk + 1, index: 0 }+ : { chunk: cursor.chunk, index: cursor.index + 1 };}- const ended = hls.cursor.chunk >= job.chunks.length;+ const ended = cursor.chunk >= job.chunks.length;if (!grew && !ended) continue;await s3.put(`${hls.prefix}/index.m3u8`,- playlist(hls.listed, {+ playlist(listed, {initUrl: hls.initUrl as string,targetDuration: HLS_SEGMENT_SECONDS + 2,ended,}),"application/vnd.apple.mpegurl",);+ hls.cursor = cursor;+ hls.listed = listed;if (hls.listed.length > 0) job.t.firstSegment ??= now();if (ended) {hls.ended = true;job.t.hlsEnded = now();+ if (job.status === "ready") persistFinished(job);}} while (hls.dirty && !hls.ended);} catch (error) {console.error(`job ${job.id} playlist: ${error}`);+ if (now() - (job.t.requested ?? 0) < 5 * 3600_000) {+ hls.retry = setTimeout(() => publishPlaylist(job), 1000);+ hls.retry.unref();+ }} finally {hls.writing = false;}}+function persistFinished(job: Job) {+ journalPut(journalKey(job.id, "done"), job.status).catch((error) => {+ console.error(`job ${job.id} terminal journal: ${error}`);+ if (jobs.has(job.id)) setTimeout(() => persistFinished(job), 1000).unref();+ });+}+function finish(job: Job) {- journalPut(journalKey(job.id, "done"), job.status);+ if (job.status === "error" || !job.hls || job.hls.ended) persistFinished(job);job.audioCache?.close();// Freeze the summary, then drop the media: rendered audio alone is ~290 MB// for a 2 h export, and finished jobs were never evicted.@@ -1428,12 +1617,26 @@ function recordStat(job.taskStats.push({ kind, index, worker, ...timings });}-function onVideoDone(job: Job, state: TaskState, result: VideoResult) {+async function onVideoDone(job: Job, state: TaskState, result: VideoResult) {+ if (state.task.kind !== "video") return Promise.resolve();+ await acceptOnce(job.acceptances, `v/${state.task.chunk}`, () =>+ acceptVideo(job, state, result),+ );+ retireTask(state);+}++async function acceptVideo(job: Job, state: TaskState, result: VideoResult) {if (state.task.kind !== "video") return;+ const chunk = state.task.chunk;+ if (job.videoResults.has(chunk) || job.status !== "rendering") return;+ await journalPut(+ journalKey(job.id, `v/${chunk}.json`),+ JSON.stringify(result),+ );+ if (job.status !== "rendering") return;state.state = "done";const queued = queue.indexOf(state);if (queued >= 0) queue.splice(queued, 1);- const chunk = state.task.chunk;recordStat(job, "video", chunk, result.worker, {...result.timings,fetchBytes: result.timings.fetch.bytes,@@ -1445,7 +1648,7 @@ function onVideoDone(job: Job, state: TaskState, result: VideoResult) {});job.cpuSeconds += result.timings.cpuSeconds;job.fetchedBytes += result.timings.fetch.bytes;- if (job.videoResults.has(chunk)) return;+for (const other of job.tasks.values()) {// The sibling copy (original or hedge) is now redundant.if (@@ -1474,32 +1677,46 @@ function onVideoDone(job: Job, state: TaskState, result: VideoResult) {job.hls.segments.set(chunk, known);publishPlaylist(job);}- journalPut(journalKey(job.id, `v/${chunk}.json`), JSON.stringify(result));if (job.videoResults.size === job.chunks.length) {job.t.videoDone = now();maybeAssemble(job);}}-function onAudioDone(+async function onAudioDone(job: Job,state: TaskState,meta: AudioResultMeta,data: Uint8Array,) {- if (state.task.kind !== "audio") return;+ if (state.task.kind !== "audio") return Promise.resolve();+ await acceptOnce(job.acceptances, `a/${state.task.section}`, () =>+ acceptAudio(job, state, meta, data),+ );+ retireTask(state);+}++async function acceptAudio(+ job: Job,+ state: TaskState,+ meta: AudioResultMeta,+ data: Uint8Array,+) {+ if (+ state.task.kind !== "audio" ||+ job.status !== "rendering" ||+ job.audioSections.has(state.task.section)+ )+ return;+ await journalPut(+ journalKey(job.id, `a/${state.task.section}.bin`),+ audioFrame(meta, data),+ );+ if (job.status !== "rendering") return;state.state = "done";const queued = queue.indexOf(state);if (queued >= 0) queue.splice(queued, 1);- // Chunks may already have muxed the first copy's packets; a second render- // replacing them would desync the header from those bytes.- if (job.audioSections.has(state.task.section)) return;- if (!job.audioSections.has(state.task.section)) {- journalPut(- journalKey(job.id, `a/${state.task.section}.bin`),- audioFrame(meta, data),- );- }+ if (job.hls) job.hls.audioExtradata ??= meta.extradata;job.audioSections.set(state.task.section, { meta, data });job.t.lastProgress = now();if (job.hls && !job.hls.initUrl) publishPlaylist(job);@@ -1601,18 +1818,18 @@ async function assemble(job: Job) {});job.t.headerBuilt = now();if (!job.uploadId) throw new Error("no upload");- const etag = await s3.uploadPart(job.key, job.uploadId, 1, header);- parts.push({ partNumber: 1, etag });- // Exactly the accepted copies' parts: other copies' parts sit in their own- // ranges and are discarded, and S3 checks every listed ETag, so a part- // overwritten with other bytes fails the completion instead of corrupting it.- await s3.completeMultipart(- job.key,- job.uploadId,- parts.sort((a, b) => a.partNumber - b.partNumber),+ job.outputBytes = await completeUpload(+ s3,+ {+ key: job.key,+ uploadId: job.uploadId,+ header,+ payloadSize,+ parts,+ },+ (intent) => journalPut(journalKey(job.id, "assembly.json"), intent),);job.t.completed = now();- job.outputBytes = payloadSize + header.byteLength;await s3.ready();job.url = await s3.presignFresh("GET", job.key, 24 * 3600);@@ -1842,19 +2059,32 @@ Bun.serve({const job = jobs.get(entry.taskId.split(":")[0] ?? "");const state = job?.tasks.get(entry.taskId);if (!state) continue;- if (state.state === "queued" && state.heldUntil) {+ if (+ state.state === "queued" &&+ state.heldUntil &&+ (state.task.kind === "audio" ||+ (state.reattach &&+ state.worker === body.worker &&+ state.attempts === entry.attempt))+ ) {// Still running from before a coordinator restart: adopt it.state.state = "running";state.worker = body.worker;state.startedAt = now() - entry.elapsedMs;state.heldUntil = undefined;+ state.reattach = false;state.attempts = entry.attempt ?? 1;state.prefetched = entry.phase === "reserved";const index = queue.indexOf(state);if (index >= 0) queue.splice(index, 1);console.log(`re-attached ${entry.taskId} to ${body.worker}`);}- if (state.state !== "running" || state.worker !== body.worker) continue;+ if (+ state.state !== "running" ||+ state.worker !== body.worker ||+ (entry.attempt !== undefined && state.attempts !== entry.attempt)+ )+ continue;state.lastReportedAt = Date.now();if (entry.phase === "reserved") continue;if (state.task.kind === "video") {@@ -1954,7 +2184,7 @@ Bun.serve({}if (taskMatch[2] === "done") {const result = (await request.json()) as VideoResult;- if (job.status === "rendering") onVideoDone(job, state, result);+ if (job.status === "rendering") await onVideoDone(job, state, result);return Response.json({ ok: true });}// audio: [u32 json length][json][packet bytes]@@ -1965,7 +2195,7 @@ Bun.serve({) as AudioResultMeta;const data = bytes.slice(4 + length);if (state.task.kind === "audio" && job.status === "rendering") {- onAudioDone(job, state, meta, data);+ await onAudioDone(job, state, meta, data);}return Response.json({ ok: true });}@@ -2055,34 +2285,22 @@ Bun.serve({});}const id = randomUUID().slice(0, 12);- const compression = body.compression ?? "Maximum";- const job: Job = {- id,- request: body,- status: "planning",- key: `out/${id}.mp4`,- t: { requested: now() },- fps: body.fps ?? 30,- bpp: COMPRESSION_BPP[compression],- resolution: body.resolution ?? [1920, 1080],- totalFrames: 0,- totalSamples: 0,- width: 0,- height: 0,- chunks: [],- sections: [],- tasks: new Map(),- videoResults: new Map(),- audioSections: new Map(),- audioWaiters: [],- cpuSeconds: 0,- fetchedBytes: 0,- workersUsed: new Set(),- waiters: [],- taskStats: [],- };- if (HLS) job.hls = await newHlsState(`hls/${id}`);+ const job = await newJob(id, body);+jobs.set(id, job);+ try {+ await journalPut(+ journalKey(id, "request.json"),+ JSON.stringify({+ id,+ request: body,+ requestedAt: job.t.requested,+ }),+ );+ } catch (error) {+ jobs.delete(id);+ throw error;+ }planJob(job).catch((error) => failJob(job, error));return Response.json({ id, hlsUrl: job.hls?.url });}@@ -2141,3 +2359,5 @@ console.log(`render-farm coordinator on :${PORT} (${PUBLIC_URL})`);// Pick up exports a previous coordinator process left unfinished.resumeJobs().catch((error) => console.error(`resume failed: ${error}`));++export type { Job, TaskState };diff --git a/apps/render-farm/src/engine.ts b/apps/render-farm/src/engine.tsindex 1b62dc329..9284bcaff 100644--- a/apps/render-farm/src/engine.ts+++ b/apps/render-farm/src/engine.ts@@ -128,8 +128,8 @@ export class Engine {});}- kill() {- this.process.kill();+ kill(signal?: NodeJS.Signals) {+ this.process.kill(signal);}}diff --git a/apps/render-farm/src/planning.test.ts b/apps/render-farm/src/planning.test.tsindex 59fc6c336..1ad4d62b7 100644--- a/apps/render-farm/src/planning.test.ts+++ b/apps/render-farm/src/planning.test.ts@@ -64,3 +64,21 @@ describe("planChunkBoundaries", () => {expectValid(boundaries, 7);});});++test("all planner inputs leave six disjoint ranges even with a lead-in", () => {+ for (const options of [+ { slots: 1000 },+ { chunks: 1000 },+ { chunks: 1000, maxChunks: 1000 },+ ]) {+ const boundaries = planChunkBoundaries({+ ...base,+ totalFrames: 2_160_000,+ leadInFrames: 120,+ ...options,+ });+ const count = boundaries.length - 1;+ expect(Math.floor(Math.floor(9998 / count) / 6)).toBeGreaterThanOrEqual(3);+ expectValid(boundaries, 2_160_000);+ }+});diff --git a/apps/render-farm/src/planning.ts b/apps/render-farm/src/planning.tsindex b9b0848cd..c41d30f23 100644--- a/apps/render-farm/src/planning.ts+++ b/apps/render-farm/src/planning.ts@@ -1,3 +1,5 @@+import { PART_RANGES } from "./recovery";+export type ChunkPlanInput = {totalFrames: number;fps: number;@@ -21,8 +23,7 @@ export type ChunkPlanInput = {* Boundaries sit on GOP edges when chunks are long enough, else on whole* seconds; every chunk opens with its own IDR either way.*/-/** Keeps four part ranges of at least three parts per chunk in one upload. */-export const MAX_CHUNKS = 800;+export const MAX_CHUNKS = Math.floor(9998 / (PART_RANGES * 3)) - 1;export function planChunkBoundaries(input: ChunkPlanInput) {const { totalFrames, fps } = input;@@ -46,7 +47,12 @@ export function planChunkBoundaries(input: ChunkPlanInput) {const units = Math.ceil(totalFrames / unit);chunkCount = Math.max(1,- Math.min(chunkCount, units, input.maxChunks ?? Number.POSITIVE_INFINITY),+ Math.min(+ chunkCount,+ MAX_CHUNKS,+ units,+ input.maxChunks ?? Number.POSITIVE_INFINITY,+ ),);const boundaries: number[] = [];for (let index = 0; index <= chunkCount; index++) {diff --git a/apps/render-farm/src/probe-engine.test.ts b/apps/render-farm/src/probe-engine.test.tsnew file mode 100644index 000000000..9a7c9e170--- /dev/null+++ b/apps/render-farm/src/probe-engine.test.ts@@ -0,0 +1,74 @@+import { expect, test } from "bun:test";+import { ProbeEngine } from "./probe-engine";++test("a process exit retries on a fresh engine and later jobs keep working", async () => {+ let processes = 0;+ const pool = new ProbeEngine(() => {+ const index = processes++;+ let alive = true;+ return {+ get alive() {+ return alive;+ },+ async request<T>() {+ if (index === 0) {+ alive = false;+ throw new Error("process exited");+ }+ return { frames: 30 } as T;+ },+ kill() {+ alive = false;+ },+ };+ });+ expect(await pool.request<{ frames: number }>({})).toEqual({ frames: 30 });+ expect(await pool.request<{ frames: number }>({})).toEqual({ frames: 30 });+ expect(processes).toBe(2);+});++test("a hung probe is killed, retry is bounded, and the next job gets a fresh process", async () => {+ let processes = 0;+ let killed = 0;+ const pool = new ProbeEngine(() => {+ const index = processes++;+ let alive = true;+ return {+ get alive() {+ return alive;+ },+ request<T>(): Promise<T> {+ return index < 2 ? new Promise(() => {}) : Promise.resolve("ok" as T);+ },+ kill() {+ alive = false;+ killed++;+ },+ };+ }, 5);+ await expect(pool.request({})).rejects.toThrow("timed out");+ expect(killed).toBe(2);+ expect(await pool.request<string>({})).toBe("ok");+});++test("queued probes get their full timeout after the previous request settles", async () => {+ const first = Promise.withResolvers<string>();+ let calls = 0;+ const pool = new ProbeEngine(() => ({+ alive: true,+ request<T>(): Promise<T> {+ calls++;+ return (+ calls === 1 ? first.promise : Promise.resolve("second")+ ) as Promise<T>;+ },+ kill() {},+ }));+ const one = pool.request({});+ const two = pool.request({});+ await Promise.resolve();+ expect(calls).toBe(1);+ first.resolve("first");+ expect(await one).toBe("first");+ expect(await two).toBe("second");+});diff --git a/apps/render-farm/src/probe-engine.ts b/apps/render-farm/src/probe-engine.tsnew file mode 100644index 000000000..632771499--- /dev/null+++ b/apps/render-farm/src/probe-engine.ts@@ -0,0 +1,43 @@+import type { Engine } from "./engine";++type ProbeProcess = Pick<Engine, "alive" | "request" | "kill">;++export class ProbeEngine {+ private engine?: ProbeProcess;+ private tail: Promise<unknown> = Promise.resolve();++ constructor(+ private readonly create: () => ProbeProcess,+ private readonly timeoutMs = 120_000,+ ) {}++ request<T>(body: Record<string, unknown>): Promise<T> {+ const result = this.tail.then(async () => {+ for (let attempt = 0; ; attempt++) {+ if (!this.engine?.alive) this.engine = this.create();+ const engine = this.engine;+ let timedOut = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ engine.request<T>("probe", body),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ timedOut = true;+ engine.kill("SIGKILL");+ this.engine = undefined;+ reject(new Error("probe engine timed out"));+ }, this.timeoutMs);+ }),+ ]);+ } catch (error) {+ if (attempt > 0 || (!timedOut && engine.alive)) throw error;+ } finally {+ clearTimeout(timer);+ }+ }+ });+ this.tail = result.catch(() => {});+ return result;+ }+}diff --git a/apps/render-farm/src/recovery.test.ts b/apps/render-farm/src/recovery.test.tsnew file mode 100644index 000000000..59125145c--- /dev/null+++ b/apps/render-farm/src/recovery.test.ts@@ -0,0 +1,101 @@+import { describe, expect, test } from "bun:test";+import { completeUpload, PART_RANGES, reservePartRange } from "./recovery";++const upload = {+ key: "out/job.mp4",+ uploadId: "upload",+ header: new Uint8Array([1, 2, 3]),+ payloadSize: 7,+ parts: [+ { partNumber: 20, etag: "winner" },+ { partNumber: 30, etag: "last" },+ ],+};++function store() {+ let object: { size: number } | null = null;+ let header = upload.header;+ let completed = 0;+ let uploaded = 0;+ let lostResponse = false;+ let intent = false;+ const api = {+ async head() {+ return object;+ },+ async getRange() {+ return header;+ },+ async uploadPart() {+ expect(intent).toBe(true);+ uploaded++;+ return "header";+ },+ async completeMultipart(+ _key: string,+ _id: string,+ parts: { partNumber: number; etag: string }[],+ ) {+ expect(parts).toEqual([+ { partNumber: 1, etag: "header" },+ ...upload.parts,+ ]);+ completed++;+ object = { size: 10 };+ if (lostResponse) throw new Error("lost completion response");+ },+ };+ return {+ api,+ persist: async () => {+ intent = true;+ },+ loseResponse: () => {+ lostResponse = true;+ },+ existing: (size: number, bytes = header) => {+ object = { size };+ header = bytes;+ },+ counts: () => ({ uploaded, completed }),+ };+}++describe("multipart recovery", () => {+ test("ranges never wrap after retries, including unacknowledged dispatches", () => {+ const chunk = { firstPart: 2, partLimit: 20, dispatches: 0 };+ const firstParts = new Set<number>();+ for (let i = 0; i < PART_RANGES; i++)+ firstParts.add(reservePartRange(chunk).firstPart);+ expect(firstParts.size).toBe(PART_RANGES);+ expect(() => reservePartRange(chunk)).toThrow("exhausted");+ });+ test("lost completion response is reconciled and a restart does not upload part 1 again", async () => {+ const s3 = store();+ s3.loseResponse();+ expect(await completeUpload(s3.api, upload, s3.persist)).toBe(10);+ expect(await completeUpload(s3.api, upload, s3.persist)).toBe(10);+ expect(s3.counts()).toEqual({ uploaded: 1, completed: 1 });+ });+ test("an existing object must match both accepted byte count and header", async () => {+ const s3 = store();+ s3.existing(11);+ await expect(completeUpload(s3.api, upload, s3.persist)).rejects.toThrow(+ "does not match",+ );+ s3.existing(10, new Uint8Array([3, 2, 1]));+ await expect(completeUpload(s3.api, upload, s3.persist)).rejects.toThrow(+ "does not match",+ );+ expect(s3.counts()).toEqual({ uploaded: 0, completed: 0 });+ });+ test("an undurable assembly intent cannot consume the upload", async () => {+ const s3 = store();+ await expect(+ completeUpload(s3.api, upload, async () => {+ throw new Error("journal unavailable");+ }),+ ).rejects.toThrow("journal unavailable");+ expect(s3.counts()).toEqual({ uploaded: 0, completed: 0 });+ });+});diff --git a/apps/render-farm/src/recovery.ts b/apps/render-farm/src/recovery.tsnew file mode 100644index 000000000..0c7486ba3--- /dev/null+++ b/apps/render-farm/src/recovery.ts@@ -0,0 +1,75 @@+import { createHash } from "node:crypto";+import type { S3 } from "./s3";++export const PART_RANGES = 6;++export function reservePartRange(chunk: {+ dispatches: number;+ firstPart: number;+ partLimit: number;+}) {+ if (chunk.dispatches >= PART_RANGES) {+ throw new Error(+ "chunk exhausted its upload ranges; refusing to reuse live parts",+ );+ }+ const range = chunk.dispatches++;+ return { range, firstPart: chunk.firstPart + range * chunk.partLimit };+}++export function acceptOnce(+ pending: Map<string, Promise<void>>,+ key: string,+ accept: () => Promise<void>,+) {+ const existing = pending.get(key);+ if (existing) return existing;+ const result = accept().finally(() => pending.delete(key));+ pending.set(key, result);+ return result;+}++export async function completeUpload(+ s3: Pick<S3, "head" | "getRange" | "uploadPart" | "completeMultipart">,+ upload: {+ key: string;+ uploadId: string;+ header: Uint8Array;+ payloadSize: number;+ parts: { partNumber: number; etag: string }[];+ },+ persist: (intent: string) => Promise<void>,+) {+ const { key, uploadId, header, parts } = upload;+ const size = upload.payloadSize + header.byteLength;+ const hash = (bytes: Uint8Array) =>+ createHash("sha256").update(bytes).digest("hex");+ const headerHash = hash(header);+ const completed = async () => {+ const object = await s3.head(key);+ if (!object) return false;+ if (+ object.size !== size ||+ hash(await s3.getRange(key, 0, header.byteLength - 1)) !== headerHash+ ) {+ throw new Error("completed object does not match the accepted media");+ }+ return true;+ };+ if (await completed()) return size;+ await persist(JSON.stringify({ uploadId, size, headerHash }));+ try {+ const etag = await s3.uploadPart(key, uploadId, 1, header);+ await s3.completeMultipart(+ key,+ uploadId,+ [...parts, { partNumber: 1, etag }].sort(+ (a, b) => a.partNumber - b.partNumber,+ ),+ );+ } catch (error) {+ // Completion can commit in S3 even when its response never reaches us.+ if (!(await completed())) throw error;+ }+ return size;+}