Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(render-farm): publish exports without zero padding

Richie McIlroye6966632031e
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.ts
index f38af7d93..c865e2978 100644
--- a/apps/render-farm/src/coordinator.test.ts
+++ b/apps/render-farm/src/coordinator.test.ts
@@ -15,12 +15,16 @@ import * as planning from "./planning";
import * as protocol from "./protocol";
import * as recovery from "./recovery";
import { pickQueued } from "./scheduler";
+import * as stitch from "./stitch";
import * as validate from "./validate";
function harness(env: Record<string, string> = {}) {
const objects = new Map<string, Uint8Array>();
const writes: string[] = [];
const ranges: string[] = [];
+ const uploadedParts = new Map<string, Uint8Array>();
+ const copies: string[] = [];
+ const completedParts: number[][] = [];
const timers: (() => void)[] = [];
const watchdogs: (() => void)[] = [];
let putGate: Promise<void> | undefined;
@@ -58,12 +62,59 @@ function harness(env: Record<string, string> = {}) {
.digest("hex")}"`;
return { bytes, etag };
},
- async list() {
- return [...objects.keys()].map((key) => ({ key }));
+ async list(prefix = "") {
+ return [...objects.keys()]
+ .filter((key) => key.startsWith(prefix))
+ .map((key) => ({ key }));
},
async presignFresh(_method: string, key: string) {
return `https://media.test/${key}`;
},
+ config: { bucket: "farm" },
+ sharesStoreWith: () => true,
+ async ready() {},
+ async uploadPart(key: string, _id: string, n: number, body: Uint8Array) {
+ uploadedParts.set(`${key}#${n}`, body.slice());
+ return `etag-${n}`;
+ },
+ async uploadPartCopy(
+ key: string,
+ _id: string,
+ n: number,
+ source: { key: string },
+ ) {
+ const value = objects.get(source.key);
+ if (!value) throw new Error(`missing ${source.key}`);
+ copies.push(source.key);
+ uploadedParts.set(`${key}#${n}`, value.slice());
+ return `etag-${n}`;
+ },
+ async completeMultipart(
+ key: string,
+ _id: string,
+ list: { partNumber: number; etag: string }[],
+ ) {
+ const bodies = list.map((part) => {
+ const body = uploadedParts.get(`${key}#${part.partNumber}`);
+ if (!body)
+ throw new Error(`part ${part.partNumber} was never uploaded`);
+ return body;
+ });
+ completedParts.push(bodies.map((body) => body.byteLength));
+ const out = new Uint8Array(
+ bodies.reduce((sum, b) => sum + b.byteLength, 0),
+ );
+ let offset = 0;
+ for (const body of bodies) {
+ out.set(body, offset);
+ offset += body.byteLength;
+ }
+ objects.set(key, out);
+ return true;
+ },
+ async delete(key: string) {
+ objects.delete(key);
+ },
async abortMultipart() {},
};
const source = readFileSync(
@@ -87,6 +138,7 @@ function harness(env: Record<string, string> = {}) {
...planning,
...protocol,
...recovery,
+ ...stitch,
pickQueuedTask: pickQueued,
S3: class {
constructor() {
@@ -131,10 +183,12 @@ 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, setPlanner: (fn) => { planJob = fn; }};`,
+ `${compiled}\nreturn {jobs, queue, straggler, dispatchedTask, onVideoDone, onAudioDone, publishPlaylist, journalJob, resumeJobs, newHlsState, finish, requeue, sourceIndex, assemble, stitchAhead, 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;
requeue: (state: TaskState, reason: string) => void;
jobs: Map<string, Job>;
queue: TaskState[];
@@ -162,6 +216,9 @@ function harness(env: Record<string, string> = {}) {
objects,
writes,
ranges,
+ uploadedParts,
+ copies,
+ completedParts,
callbacks,
timers,
watchdogs,
@@ -198,7 +255,7 @@ function job(): Job {
frames: [index * 30, (index + 1) * 30],
packets: [0, 0],
files: [],
- firstPart: 2 + index * 60,
+ firstPart: 3 + index * 60,
partLimit: 10,
dispatches: 0,
})),
@@ -231,10 +288,10 @@ function videoState(job: Job, duplicate = false): TaskState {
upload: {
key: job.key,
uploadId: "upload",
- firstPart: 2,
+ firstPart: 3,
partLimit: 10,
partTarget: 16 << 20,
- isLast: false,
+ stashKey: `jobs/${job.id}/stash/c0-p3`,
},
audio: null,
hls: null,
@@ -272,9 +329,13 @@ function result(state: TaskState): protocol.VideoResult {
height: 1080,
videoRuns: [],
audioRuns: [],
+ firstPart: state.firstPart ?? 3,
+ stash: {
+ key: `jobs/job/stash/c0-p${state.firstPart ?? 3}`,
+ bytes: 100,
+ },
parts: [],
bytes: 100,
- paddedBytes: 0,
timings,
};
}
@@ -295,6 +356,132 @@ function heartbeat(worker: string, taskId: string, attempt: number) {
});
}
+describe("assembly", () => {
+ const MB = 1024 * 1024;
+ /**
+ * Chunk `index` of `bytes`, filled with `fill`, stored the way a worker
+ * stores it: its stash in the farm bucket, any rest as uploaded parts.
+ */
+ function stored(
+ h: ReturnType<typeof harness>,
+ j: Job,
+ index: number,
+ bytes: number,
+ fill: number,
+ ): 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 stash = stitch.stashBytes(bytes);
+ h.objects.set(stashKey, data.subarray(0, stash));
+ const parts: protocol.VideoResult["parts"] = [];
+ if (bytes > stash) {
+ h.uploadedParts.set(`${j.key}#${chunk.firstPart}`, data.subarray(stash));
+ parts.push({
+ partNumber: chunk.firstPart,
+ etag: "worker",
+ size: bytes - stash,
+ });
+ }
+ const frames = chunk.frames[1] - chunk.frames[0];
+ const sizes = Array.from({ length: frames }, (_, i) =>
+ i < frames - 1
+ ? Math.floor(bytes / frames)
+ : bytes - Math.floor(bytes / frames) * (frames - 1),
+ );
+ return {
+ taskId: `job:v${index}`,
+ worker: "worker",
+ sizes,
+ keyframes: [0],
+ extradata: Buffer.from(ANNEX_B_PARAMETER_SETS).toString("base64"),
+ width: 1920,
+ height: 1080,
+ videoRuns: [{ first: chunk.frames[0], count: frames, offset: 0 }],
+ audioRuns: [],
+ firstPart: chunk.firstPart,
+ stash: { key: stashKey, bytes: stash },
+ parts,
+ bytes,
+ timings,
+ };
+ }
+
+ for (const [label, sizes] of [
+ ["short chunks", [220_000, 180_000]],
+ ["a small chunk before a large one", [220_000, 12 * MB]],
+ ["large chunks", [11 * MB, 13 * MB]],
+ ] as const) {
+ test(`${label}: the file is the header then every sample, with no padding`, async () => {
+ const h = harness();
+ const j = job();
+ const results = sizes.map((bytes, index) =>
+ stored(h, j, index, bytes, index + 1),
+ );
+ results.forEach((result, index) => j.videoResults.set(index, result));
+ await h.assemble(j);
+ const file = h.objects.get(j.key) as Uint8Array;
+ const moov = mp4.locateMoov(file, file.byteLength) as {
+ start: number;
+ size: number;
+ };
+ const moovEnd = moov.start + moov.size;
+ // The moov is followed directly by the mdat that holds every byte.
+ const view = new DataView(file.buffer, file.byteOffset);
+ expect(
+ String.fromCharCode(...file.subarray(moovEnd + 4, moovEnd + 8)),
+ ).toBe("mdat");
+ const mdatHeader = view.getUint32(moovEnd) === 1 ? 16 : 8;
+ expect(file.byteLength).toBe(moovEnd + mdatHeader + sizes[0] + sizes[1]);
+ const index = mp4.indexVideoTrack(file.subarray(moov.start, moovEnd));
+ for (let sample = 0; sample < index.sizes.length; sample++) {
+ const offset = index.offsets[sample] ?? 0;
+ const chunk = sample < 30 ? 0 : 1;
+ expect(file[offset]).toBe(chunk + 1);
+ expect(file[offset + (index.sizes[sample] ?? 1) - 1]).toBe(chunk + 1);
+ }
+ for (const size of (h.completedParts[0] ?? []).slice(0, -1)) {
+ expect(size).toBeGreaterThanOrEqual(protocol.MIN_PART);
+ }
+ });
+ }
+
+ test("large stashes are copied server side instead of passing through the coordinator", async () => {
+ const h = harness();
+ const j = job();
+ [11 * MB, 13 * MB].forEach((bytes, index) =>
+ j.videoResults.set(index, stored(h, j, index, bytes, index + 1)),
+ );
+ await h.assemble(j);
+ expect(h.copies).toEqual(["jobs/job/stash/c1-p63"]);
+ });
+
+ test("parts written while chunks render are reused, not written again", async () => {
+ const h = harness();
+ const j = job();
+ [11 * MB, 13 * MB].forEach((bytes, index) =>
+ 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"]);
+ await h.assemble(j);
+ expect(h.copies).toEqual(["jobs/job/stash/c1-p63"]);
+ const file = h.objects.get(j.key) as Uint8Array;
+ expect(file[file.byteLength - 1]).toBe(2);
+ });
+
+ test("a result whose parts leave a gap in the chunk is refused", async () => {
+ const h = harness();
+ const j = job();
+ const state = videoState(j);
+ const padded = { ...stored(h, j, 0, 220_000, 1) };
+ padded.parts = [{ partNumber: 3, etag: "pad", size: protocol.MIN_PART }];
+ await expect(h.onVideoDone(j, state, padded)).rejects.toThrow("add up");
+ expect(j.videoResults.size).toBe(0);
+ });
+});
+
describe("coordinator recovery", () => {
test("a later dispatch waits for its reservation, resume preserves original and hedge ranges", async () => {
const h = harness();
@@ -322,7 +509,7 @@ describe("coordinator recovery", () => {
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);
+ expect(next.kind === "video" && next.upload.firstPart).toBe(23);
});
test("a first dispatch writes nothing, stays retired after resume and any worker can re-attach it", async () => {
@@ -520,12 +707,12 @@ test("segment reports only list objects the reporting dispatch wrote", async ()
),
);
expect((await report("media/private.mp4")).status).toBe(400);
- expect((await report("hls/job/c0-p12-0.m4s")).status).toBe(400);
- expect((await report("hls/job/c0-p2-0.m4s", hedge)).status).toBe(400);
+ expect((await report("hls/job/c0-p13-0.m4s")).status).toBe(400);
+ expect((await report("hls/job/c0-p3-0.m4s", hedge)).status).toBe(400);
expect(j.hls.segments.size).toBe(0);
- expect((await report("hls/job/c0-p12-0.m4s", hedge)).status).toBe(200);
- expect((await report("hls/job/c0-p2-0.m4s")).status).toBe(200);
- expect(j.hls.segments.get(0)?.get(0)?.key).toBe("hls/job/c0-p12-0.m4s");
+ expect((await report("hls/job/c0-p13-0.m4s", hedge)).status).toBe(200);
+ expect((await report("hls/job/c0-p3-0.m4s")).status).toBe(200);
+ expect(j.hls.segments.get(0)?.get(0)?.key).toBe("hls/job/c0-p13-0.m4s");
});
test("job acknowledgement waits for a planning receipt and receipt-only jobs resume", async () => {
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
index 0013a31d8..7e570d07c 100644
--- a/apps/render-farm/src/coordinator.ts
+++ b/apps/render-farm/src/coordinator.ts
@@ -42,6 +42,7 @@ import {
} from "./recovery";
import { mediaS3ConfigFromEnv, S3, s3ConfigFromEnv } from "./s3";
import { pickQueued as pickQueuedTask } from "./scheduler";
+import { planStitch, type StitchPart, uploadProblem } from "./stitch";
import {
AUDIO_FILE,
checkManifestBounds,
@@ -89,6 +90,8 @@ const HLS_SEGMENT_SECONDS = Number(process.env.RF_HLS_SEGMENT_SECONDS ?? 2);
/** Unfinished chunks per job (from the front) that outrank other work. */
const HEAD_CHUNKS = Number(process.env.RF_HEAD_CHUNKS ?? 2);
const LEAD_IN_SECONDS = Number(process.env.RF_LEAD_IN_SECONDS ?? 4);
+/** Coordinator-owned parts uploaded or copied at once during assembly. */
+const STITCH_CONCURRENCY = 16;
/**
* Shortest audio section. Each one after the first also renders a 10 s
* preroll, but a short export's audio is what its video chunks wait on, so
@@ -285,6 +288,10 @@ type HlsState = {
type Job = {
verified?: boolean;
acceptances: Map<string, Promise<void>>;
+ /** Coordinator parts written ahead of assembly, by `stitchPartKey`. */
+ stitchParts?: Map<string, Promise<{ partNumber: number; etag: string }>>;
+ /** Stashes the header's part will carry, read ahead of assembly. */
+ headerStashes?: Map<string, Promise<Uint8Array>>;
/** Summary frozen when the job ends; the job's media data is released then. */
final?: ReturnType<typeof summary>;
hls?: HlsState;
@@ -856,7 +863,9 @@ async function planJob(job: Job) {
});
const chunkCount = boundaries.length - 1;
const partsPerChunk = Math.floor(9998 / chunkCount);
- const partLimit = Math.floor(partsPerChunk / PART_RANGES);
+ // Each chunk's block opens with a part number the coordinator fills from
+ // the chunk's stash (see stitch.ts); its dispatch ranges follow.
+ const partLimit = Math.floor((partsPerChunk - 1) / PART_RANGES);
if (partLimit < 3) {
throw new Error("too many chunks for one multipart upload");
}
@@ -907,7 +916,7 @@ async function planJob(job: Job) {
mediaSpec(file.path, perFile.get(file.path) ?? []),
),
],
- firstPart: 2 + index * partsPerChunk,
+ firstPart: 2 + index * partsPerChunk + 1,
partLimit,
dispatches: 0,
});
@@ -1059,7 +1068,7 @@ async function planJob(job: Job) {
firstPart: chunk.firstPart,
partLimit: chunk.partLimit,
partTarget,
- isLast: chunk.index === job.chunks.length - 1,
+ stashKey: stashKey(job.id, chunk.index, chunk.firstPart),
},
audio: hasAudio
? {
@@ -1093,6 +1102,9 @@ 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). */
+const stashKey = (id: string, chunk: number, firstPart: number) =>
+ journalKey(id, `stash/c${chunk}-p${firstPart}`);
async function journalPut(key: string, body: Uint8Array | string) {
if (!JOURNAL) return;
@@ -1117,11 +1129,11 @@ type JournaledJob = Pick<
| "sections"
| "plan"
| "probe"
-> & { version: 2; tasks: Task[]; hls: { prefix: string } | null };
+> & { version: 3; tasks: Task[]; hls: { prefix: string } | null };
function journalJob(job: Job) {
const record: JournaledJob = {
- version: 2,
+ version: 3,
id: job.id,
request: job.request,
key: job.key,
@@ -1179,8 +1191,7 @@ function segmentsFromResult(
result: VideoResult,
): SegmentReport[] {
if (!job.hls) return [];
- // Parts are numbered from the dispatch's first part, which names its segments.
- const firstPart = Math.min(...result.parts.map((part) => part.partNumber));
+ const firstPart = result.firstPart;
const cuts = segmentCuts(
result.keyframes,
result.sizes.length,
@@ -1236,7 +1247,9 @@ async function resumeJobs() {
await journalPut(journalKey(id, "done"), "expired");
continue;
}
- if (record.version !== 2) {
+ // Version 3 numbers parts around the coordinator's stash parts;
+ // earlier journals' uploads cannot be completed with it.
+ if (record.version !== 3) {
if (record.uploadId)
await s3.abortMultipart(record.key, record.uploadId);
await journalPut(
@@ -1457,7 +1470,12 @@ async function dispatchedTask(
const dispatched = {
...task,
attempt: state.attempts,
- upload: { ...task.upload, firstPart, partLimit: chunk.partLimit },
+ upload: {
+ ...task.upload,
+ firstPart,
+ partLimit: chunk.partLimit,
+ stashKey: stashKey(job.id, chunk.index, firstPart),
+ },
};
// The journaled plan already reserves every chunk's first range (a resumed
// coordinator never reuses it), so first dispatches skip this write; it
@@ -2107,6 +2125,11 @@ function finish(job: Job) {
finishedJobs.push(job.id);
if (finishedJobs.length > 50) finishedJobs.shift();
rmSync(join(WORK_DIR, job.id), { recursive: true, force: true });
+ job.headerStashes = undefined;
+ job.stitchParts = undefined;
+ dropStashes(job.id).catch((error) =>
+ console.error(`job ${job.id}: stash cleanup failed: ${error}`),
+ );
}
function recordStat(
@@ -2131,6 +2154,20 @@ 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;
+ const plan = job.chunks[chunk];
+ const firstPart = state.firstPart ?? plan?.firstPart;
+ const problem =
+ plan && firstPart !== undefined && result.firstPart === firstPart
+ ? uploadProblem(
+ {
+ stashKey: stashKey(job.id, chunk, firstPart),
+ firstPart,
+ partLimit: plan.partLimit,
+ },
+ result,
+ )
+ : "result is not from this chunk's dispatch";
+ if (problem) throw new Error(`chunk ${chunk}: ${problem}`);
await journalPut(
journalKey(job.id, `v/${chunk}.json`),
JSON.stringify(result),
@@ -2166,6 +2203,7 @@ async function acceptVideo(job: Job, state: TaskState, result: VideoResult) {
}
job.videoResults.set(chunk, result);
job.t.lastProgress = now();
+ stitchAhead(job);
// Segments reported to a previous coordinator process (before a restart)
// are not reported again; derive any missing ones from the result.
const chunkPlan = job.chunks[chunk];
@@ -2262,6 +2300,7 @@ async function assemble(job: Job) {
const videoRuns: Run[] = [];
const audioRuns: Run[] = [];
const parts: { partNumber: number; etag: string }[] = [];
+ const stashed: Parameters<typeof planStitch>[1] = [];
let base = 0;
job.chunks.forEach((chunk, index) => {
const result = results[index] as VideoResult;
@@ -2272,7 +2311,12 @@ async function assemble(job: Job) {
for (const run of result.audioRuns)
audioRuns.push({ ...run, offset: run.offset + base });
for (const part of result.parts) parts.push(part);
- base += result.bytes + result.paddedBytes;
+ stashed.push({
+ slot: chunk.firstPart - 1,
+ stash: result.stash,
+ parts: result.parts,
+ });
+ base += result.bytes;
});
const payloadSize = base;
@@ -2316,18 +2360,21 @@ async function assemble(job: Job) {
},
audio,
payloadSize,
- minimumSize: MIN_PART + 64 * 1024,
+ minimumSize: 0,
});
job.t.headerBuilt = now();
if (!job.uploadId) throw new Error("no upload");
+ const uploadId = job.uploadId;
+ const stitch = planStitch(header.byteLength, stashed);
job.outputBytes = await completeUpload(
s3,
{
key: job.key,
- uploadId: job.uploadId,
+ uploadId,
header,
payloadSize,
parts,
+ prepare: () => writeStitchParts(job, uploadId, header, stitch),
},
(intent) => journalPut(journalKey(job.id, "assembly.json"), intent),
);
@@ -2359,6 +2406,142 @@ async function assemble(job: Job) {
finish(job);
}
+const stitchPartKey = (part: StitchPart) =>
+ `${part.partNumber}:${part.sources
+ .map((source) => (source.kind === "header" ? "header" : source.key))
+ .join(",")}`;
+
+/**
+ * Uploads a part the coordinator owns: a stash that stands alone is copied
+ * server side; the header and runs of small stashes are joined and uploaded.
+ */
+async function writeStitchPart(
+ key: string,
+ uploadId: string,
+ header: Uint8Array | null,
+ part: StitchPart,
+ readStash: (key: string) => Promise<Uint8Array> = (stash) =>
+ journalS3.get(stash),
+) {
+ const [only] = part.sources;
+ if (
+ part.sources.length === 1 &&
+ only?.kind === "stash" &&
+ s3.sharesStoreWith(journalS3)
+ ) {
+ return {
+ partNumber: part.partNumber,
+ etag: await s3.uploadPartCopy(key, uploadId, part.partNumber, {
+ bucket: journalS3.config.bucket,
+ key: only.key,
+ }),
+ };
+ }
+ const pieces = await Promise.all(
+ part.sources.map(async (source) => {
+ if (source.kind === "stash") return readStash(source.key);
+ if (!header) throw new Error("the header part waits for assembly");
+ return header;
+ }),
+ );
+ const body = new Uint8Array(part.bytes);
+ let offset = 0;
+ for (const [index, piece] of pieces.entries()) {
+ if (piece.byteLength !== part.sources[index]?.bytes) {
+ throw new Error(`stash for part ${part.partNumber} is incomplete`);
+ }
+ body.set(piece, offset);
+ offset += piece.byteLength;
+ }
+ return {
+ partNumber: part.partNumber,
+ etag: await s3.uploadPart(key, uploadId, part.partNumber, body),
+ };
+}
+
+/**
+ * While chunks render, writes every coordinator part whose chunks are all in:
+ * the plan for an accepted run of chunks never changes as later chunks
+ * arrive, except for the part holding the header and the part still open at
+ * the run's end. Assembly then only writes those.
+ */
+function stitchAhead(job: Job) {
+ if (!job.uploadId) return;
+ const accepted: Parameters<typeof planStitch>[1] = [];
+ for (const chunk of job.chunks) {
+ const result = job.videoResults.get(chunk.index);
+ if (!result) break;
+ accepted.push({
+ slot: chunk.firstPart - 1,
+ stash: result.stash,
+ parts: result.parts,
+ });
+ }
+ if (accepted.length === 0) return;
+ // The header's part is the one assembly must write; read its stashes now
+ // so that write is only an upload.
+ job.headerStashes ??= new Map();
+ let carried = 0;
+ for (const chunk of accepted) {
+ if (!job.headerStashes.has(chunk.stash.key)) {
+ const read = journalS3.get(chunk.stash.key);
+ read.catch(() => job.headerStashes?.delete(chunk.stash.key));
+ job.headerStashes.set(chunk.stash.key, read);
+ }
+ carried += chunk.stash.bytes;
+ if (chunk.parts.length > 0 || carried >= MIN_PART) break;
+ }
+ const complete = accepted.length === job.chunks.length;
+ const plan = planStitch(0, accepted, { partial: !complete });
+ job.stitchParts ??= new Map();
+ for (const part of plan) {
+ if (part.sources.some((source) => source.kind === "header")) continue;
+ const key = stitchPartKey(part);
+ if (job.stitchParts.has(key)) continue;
+ const written = writeStitchPart(job.key, job.uploadId, null, part);
+ written.catch(() => job.stitchParts?.delete(key));
+ job.stitchParts.set(key, written);
+ }
+}
+
+async function writeStitchParts(
+ job: Job,
+ uploadId: string,
+ header: Uint8Array,
+ plan: StitchPart[],
+) {
+ const ahead = job.stitchParts ?? new Map();
+ // A part written ahead under a grouping the final plan changed must land
+ // before the plan rewrites its number.
+ await Promise.allSettled(ahead.values());
+ const written: { partNumber: number; etag: string }[] = [];
+ const readStash = (key: string) =>
+ (job.headerStashes?.get(key) ?? Promise.reject()).catch(() =>
+ journalS3.get(key),
+ );
+ const pending = plan.map((part) => () => {
+ const write = () =>
+ writeStitchPart(job.key, uploadId, header, part, readStash);
+ const early = ahead.get(stitchPartKey(part));
+ return early ? early.catch(write) : write();
+ });
+ for (let index = 0; index < pending.length; index += STITCH_CONCURRENCY) {
+ written.push(
+ ...(await Promise.all(
+ pending
+ .slice(index, index + STITCH_CONCURRENCY)
+ .map((write) => write()),
+ )),
+ );
+ }
+ return written;
+}
+
+async function dropStashes(id: string) {
+ const keys = await journalS3.list(journalKey(id, "stash/"));
+ await Promise.all(keys.map(({ key }) => journalS3.delete(key)));
+}
+
async function verifyPlayable(job: Job) {
if (!job.url) return;
const probe = Bun.spawn(
diff --git a/apps/render-farm/src/protocol.ts b/apps/render-farm/src/protocol.ts
index c485fed86..616d46dfa 100644
--- a/apps/render-farm/src/protocol.ts
+++ b/apps/render-farm/src/protocol.ts
@@ -32,8 +32,8 @@ export type VideoTask = {
firstPart: number;
partLimit: number;
partTarget: number;
- /** The final chunk may end in a part smaller than S3's minimum. */
- isLast: boolean;
+ /** Journal-bucket object for the chunk's opening bytes (see stitch.ts). */
+ stashKey: string;
};
audio: { first: number; end: number; coordinator: string } | null;
/** Stream playable fMP4 segments to `${prefix}/c<chunk>-<n>.m4s` while rendering. */
@@ -104,9 +104,13 @@ export type VideoResult = {
/** Runs relative to the chunk's first byte; `first` is a global sample index. */
videoRuns: Run[];
audioRuns: Run[];
+ /** First part number of this dispatch's range (names its HLS segments). */
+ firstPart: number;
+ /** The chunk's opening bytes, stored at `upload.stashKey`. */
+ stash: { key: string; bytes: number };
+ /** The rest of the chunk, each part at least 5 MiB. */
parts: { partNumber: number; etag: string; size: number }[];
bytes: number;
- paddedBytes: number;
timings: TaskTimings;
};
diff --git a/apps/render-farm/src/recovery.test.ts b/apps/render-farm/src/recovery.test.ts
index 3a9afee3a..aa8ecad11 100644
--- a/apps/render-farm/src/recovery.test.ts
+++ b/apps/render-farm/src/recovery.test.ts
@@ -12,6 +12,14 @@ const upload = {
],
};
+/** The upload as the coordinator passes it: its own part is the header. */
+function uploadFor(s3: ReturnType<typeof store>) {
+ return {
+ ...upload,
+ prepare: async () => [{ partNumber: 1, etag: await s3.api.uploadPart() }],
+ };
+}
+
function store() {
let object: { size: number } | null = null;
let header = upload.header;
@@ -84,26 +92,26 @@ describe("multipart recovery", () => {
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(await completeUpload(s3.api, uploadFor(s3), s3.persist)).toBe(10);
+ expect(await completeUpload(s3.api, uploadFor(s3), 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",
- );
+ await expect(
+ completeUpload(s3.api, uploadFor(s3), 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",
- );
+ await expect(
+ completeUpload(s3.api, uploadFor(s3), 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 () => {
+ completeUpload(s3.api, uploadFor(s3), async () => {
throw new Error("journal unavailable");
}),
).rejects.toThrow("journal unavailable");
@@ -113,9 +121,9 @@ describe("multipart recovery", () => {
test("an object created after the initial HEAD is never overwritten", async () => {
const s3 = store();
s3.race();
- await expect(completeUpload(s3.api, upload, s3.persist)).rejects.toThrow(
- "does not match",
- );
+ await expect(
+ completeUpload(s3.api, uploadFor(s3), s3.persist),
+ ).rejects.toThrow("does not match");
expect(await s3.api.head()).toEqual({ size: 20 });
expect(s3.counts()).toEqual({ uploaded: 1, completed: 0 });
});
diff --git a/apps/render-farm/src/recovery.ts b/apps/render-farm/src/recovery.ts
index 9133839e3..80e810acf 100644
--- a/apps/render-farm/src/recovery.ts
+++ b/apps/render-farm/src/recovery.ts
@@ -30,13 +30,15 @@ export function acceptOnce(
}
export async function completeUpload(
- s3: Pick<S3, "head" | "getRange" | "uploadPart" | "completeMultipart">,
+ s3: Pick<S3, "head" | "getRange" | "completeMultipart">,
upload: {
key: string;
uploadId: string;
header: Uint8Array;
payloadSize: number;
parts: { partNumber: number; etag: string }[];
+ /** Writes the coordinator's own parts (header and stashes); idempotent. */
+ prepare: () => Promise<{ partNumber: number; etag: string }[]>;
},
persist: (intent: string) => Promise<void>,
) {
@@ -59,13 +61,11 @@ export async function completeUpload(
if (await completed()) return size;
await persist(JSON.stringify({ uploadId, size, headerHash }));
try {
- const etag = await s3.uploadPart(key, uploadId, 1, header);
+ const own = await upload.prepare();
const accepted = await s3.completeMultipart(
key,
uploadId,
- [...parts, { partNumber: 1, etag }].sort(
- (a, b) => a.partNumber - b.partNumber,
- ),
+ [...parts, ...own].sort((a, b) => a.partNumber - b.partNumber),
{ ifNoneMatch: true },
);
if (!accepted && !(await completed())) {
diff --git a/apps/render-farm/src/worker.test.ts b/apps/render-farm/src/worker.test.ts
index ca6be0e19..e197a29ae 100644
--- a/apps/render-farm/src/worker.test.ts
+++ b/apps/render-farm/src/worker.test.ts
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import type { TranscodeTask, WorkItem } from "./protocol";
+import * as stitch from "./stitch";
import * as transcode from "./transcode";
function harness(
@@ -26,6 +27,8 @@ function harness(
mkdirSync: () => {},
rmSync: (path: string) => removed.push(path),
mediaS3ConfigFromEnv: () => ({}),
+ s3ConfigFromEnv: () => ({}),
+ ...stitch,
S3: class {
async presignFresh() {
await options.presignGate;
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
index cf33ee195..e703cf463 100644
--- a/apps/render-farm/src/worker.ts
+++ b/apps/render-farm/src/worker.ts
@@ -18,7 +18,8 @@ import {
type VideoTask,
type WorkItem,
} from "./protocol";
-import { mediaS3ConfigFromEnv, S3 } from "./s3";
+import { mediaS3ConfigFromEnv, S3, s3ConfigFromEnv } from "./s3";
+import { stashBytes } from "./stitch";
import {
canRemux,
encodedSeconds,
@@ -28,6 +29,8 @@ import {
} from "./transcode";
const s3 = new S3(mediaS3ConfigFromEnv());
+/** The farm's own bucket, for chunk stashes (see stitch.ts). */
+const stashS3 = new S3(s3ConfigFromEnv());
const COORDINATOR = (
process.env.RF_COORDINATOR_URL ?? "http://127.0.0.1:8080"
).replace(/\/$/, "");
@@ -398,16 +401,7 @@ async function uploadLayout(
let pendingBytes = 0;
let nextPart = upload.firstPart;
const inflight = new Set<Promise<void>>();
- const send = async (body: Uint8Array) => {
- if (nextPart >= upload.firstPart + upload.partLimit) {
- throw new Error("chunk needs more parts than reserved");
- }
- const partNumber = nextPart++;
- const promise = s3
- .uploadPart(upload.key, upload.uploadId, partNumber, body)
- .then((etag) => {
- parts.push({ partNumber, etag, size: body.byteLength });
- });
+ const track = async (promise: Promise<void>) => {
inflight.add(promise);
// Handle both outcomes here: a bare .finally() re-rejects unhandled and
// kills the whole worker (e.g. a hedge loser hitting NoSuchUpload after
@@ -416,6 +410,19 @@ async function uploadLayout(
promise.then(forget, forget);
if (inflight.size >= 4) await Promise.race(inflight);
};
+ const send = (body: Uint8Array) => {
+ if (nextPart >= upload.firstPart + upload.partLimit) {
+ throw new Error("chunk needs more parts than reserved");
+ }
+ const partNumber = nextPart++;
+ return track(
+ s3
+ .uploadPart(upload.key, upload.uploadId, partNumber, body)
+ .then((etag) => {
+ parts.push({ partNumber, etag, size: body.byteLength });
+ }),
+ );
+ };
const take = (count: number) => {
const out = new Uint8Array(count);
let filled = 0;
@@ -431,6 +438,10 @@ async function uploadLayout(
pendingBytes -= count;
return out;
};
+ // The opening bytes go to the stash, which the coordinator joins to its
+ // neighbours; everything after them is a part of at least 5 MiB.
+ const stashSize = stashBytes(bytes);
+ let stashed = false;
const files = new Map<string, ReturnType<typeof Bun.file>>();
for (const segment of segments) {
let data: Uint8Array;
@@ -447,24 +458,25 @@ async function uploadLayout(
} else continue;
pending.push(data);
pendingBytes += data.byteLength;
+ if (!stashed && pendingBytes >= stashSize) {
+ stashed = true;
+ await track(stashS3.put(upload.stashKey, take(stashSize)));
+ }
// Always keep >= 5 MiB back so the chunk's last part is never too small.
- while (pendingBytes >= upload.partTarget + MIN_PART)
+ while (stashed && pendingBytes >= upload.partTarget + MIN_PART)
await send(take(upload.partTarget));
}
- let padded = 0;
- if (!upload.isLast && pendingBytes < MIN_PART) {
- // Unreferenced bytes inside mdat are legal; they keep S3's 5 MiB rule.
- padded = MIN_PART - pendingBytes;
- pending.push(new Uint8Array(padded));
- pendingBytes += padded;
- }
+ if (!stashed) throw new Error("chunk ended before its stash filled");
if (pendingBytes > 0) await send(take(pendingBytes));
await Promise.all(inflight);
pending = [];
- if (parts.reduce((sum, part) => sum + part.size, 0) !== bytes + padded) {
+ if (parts.reduce((sum, part) => sum + part.size, 0) + stashSize !== bytes) {
throw new Error("uploaded byte count mismatch");
}
- return { parts: parts.sort((a, b) => a.partNumber - b.partNumber), padded };
+ return {
+ parts: parts.sort((a, b) => a.partNumber - b.partNumber),
+ stash: { key: upload.stashKey, bytes: stashSize },
+ };
}
async function runVideo(
@@ -546,7 +558,7 @@ async function runVideo(
const audioWaitMs = performance.now() - waitStarted;
const uploadStarted = performance.now();
const plan = layout(task, out, result.sizes, audio);
- const [{ parts, padded }, segments] = await Promise.all([
+ const [{ parts, stash }, segments] = await Promise.all([
uploadLayout(task, plan.segments, plan.bytes),
segmentsDone ?? Promise.resolve(0),
]);
@@ -583,9 +595,10 @@ async function runVideo(
height: result.height,
videoRuns: plan.videoRuns,
audioRuns: plan.audioRuns,
+ firstPart: task.upload.firstPart,
+ stash,
parts,
bytes: plan.bytes,
- paddedBytes: padded,
timings,
};
}