Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(render-farm): bound stitching ahead of assembly with a shared limiter that puts assembly first
Richie McIlroy673feef73688
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.tsindex 548127712..4bf390084 100644--- a/apps/render-farm/src/coordinator.test.ts+++ b/apps/render-farm/src/coordinator.test.ts@@ -26,6 +26,9 @@ function harness(env: Record<string, string> = {}) {const modifiedAt = new Map<string, number>();let listFailures = 0;const copies: string[] = [];+ const copying = new Map<string, number>();+ const copyPeaks = { total: 0, byJob: new Map<string, number>() };+ let copyGate: (source: string) => Promise<void> | undefined = () => undefined;const completedParts: number[][] = [];const timers: (() => void)[] = [];const watchdogs: (() => void)[] = [];@@ -88,8 +91,21 @@ function harness(env: Record<string, string> = {}) {) {const value = objects.get(source.key);if (!value) throw new Error(`missing ${source.key}`);+ const job = source.key.split("/")[1] ?? "";+ copying.set(job, (copying.get(job) ?? 0) + 1);+ const total = [...copying.values()].reduce((sum, n) => sum + n, 0);+ copyPeaks.total = Math.max(copyPeaks.total, total);+ copyPeaks.byJob.set(+ job,+ Math.max(copyPeaks.byJob.get(job) ?? 0, copying.get(job) ?? 0),+ );+ try {+ await copyGate(source.key);+ } finally {+ copying.set(job, (copying.get(job) ?? 1) - 1);+ }copies.push(source.key);- uploadedParts.set(`${key}#${n}`, value.slice());+ uploadedParts.set(`${key}#${n}`, value);return `etag-${n}`;},async completeMultipart(@@ -222,6 +238,11 @@ function harness(env: Record<string, string> = {}) {ranges,uploadedParts,copies,+ copying,+ copyPeaks,+ gateCopies: (gate: (source: string) => Promise<void> | undefined) => {+ copyGate = gate;+ },completedParts,modifiedAt,failListing: (count = 1) => {@@ -478,6 +499,78 @@ describe("assembly", () => {expect(file[file.byteLength - 1]).toBe(2);});+ function longJob(id: string, count: number): Job {+ const base = job();+ const first = base.chunks[0] as NonNullable<Job["chunks"][number]>;+ return {+ ...base,+ id,+ key: `out/${id}.mp4`,+ totalFrames: count * 30,+ chunks: Array.from({ length: count }, (_, index) => ({+ ...first,+ index,+ frames: [index * 30, (index + 1) * 30] as [number, number],+ firstPart: 3 + index * 60,+ })),+ };+ }++ test("stitching ahead stays within its share across jobs and assembly reuses it", async () => {+ const h = harness();+ const jobs = [longJob("a", 12), longJob("b", 12), longJob("c", 12)];+ let open = () => {};+ const gate = new Promise<void>((resolve) => {+ open = resolve;+ });+ h.gateCopies(() => gate);+ for (const j of jobs) {+ for (const [index] of j.chunks.entries())+ j.videoResults.set(+ index,+ stored(h, j, index, 2 * protocol.MIN_PART, 1),+ );+ h.stitchAhead(j);+ }+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(h.copyPeaks.total).toBe(8);+ for (const j of jobs)+ expect(h.copyPeaks.byJob.get(j.id) ?? 0).toBeLessThanOrEqual(4);+ open();+ for (const j of jobs) {+ await Promise.all(j.stitchParts?.values() ?? []);+ await h.assemble(j);+ const file = h.objects.get(j.key) as Uint8Array;+ expect(file.byteLength).toBeGreaterThan(12 * 2 * protocol.MIN_PART);+ }+ expect(h.copyPeaks.total).toBe(8);+ expect(h.copies.length).toBe(3 * 11);+ expect(new Set(h.copies).size).toBe(3 * 11);+ });++ test("assembly does not wait behind another job's queued ahead work", async () => {+ const h = harness();+ const busy = longJob("busy", 12);+ const ready = longJob("ready", 3);+ h.gateCopies((source) =>+ source.startsWith("stash/busy/") ? new Promise(() => {}) : undefined,+ );+ for (const [index] of busy.chunks.entries())+ busy.videoResults.set(+ index,+ stored(h, busy, index, 2 * protocol.MIN_PART, 1),+ );+ h.stitchAhead(busy);+ for (const [index] of ready.chunks.entries())+ ready.videoResults.set(+ index,+ stored(h, ready, index, 2 * protocol.MIN_PART, 2),+ );+ await h.assemble(ready);+ expect(h.objects.has(ready.key)).toBe(true);+ expect(h.copying.get("busy")).toBe(4);+ });+test("the sweep deletes finished and abandoned jobs' stashes only", async () => {const h = harness();const live = job();diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.tsindex c6c68b7dd..b0500143a 100644--- a/apps/render-farm/src/coordinator.ts+++ b/apps/render-farm/src/coordinator.ts@@ -41,7 +41,12 @@ import {import { acceptOnce, completeUpload, reservePartRange } from "./recovery";import { mediaS3ConfigFromEnv, S3, s3ConfigFromEnv } from "./s3";import { pickQueued as pickQueuedTask } from "./scheduler";-import { planStitch, type StitchPart, uploadProblem } from "./stitch";+import {+ planStitch,+ StitchLimiter,+ type StitchPart,+ uploadProblem,+} from "./stitch";import {AUDIO_FILE,checkManifestBounds,@@ -91,7 +96,11 @@ 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);-const STITCH_CONCURRENCY = 16;+const stitchLimiter = new StitchLimiter({+ total: 16,+ ahead: 8,+ aheadPerJob: 4,+});/*** 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@@ -2144,6 +2153,7 @@ function finish(job: Job) {finishedJobs.push(job.id);if (finishedJobs.length > 50) finishedJobs.shift();rmSync(join(WORK_DIR, job.id), { recursive: true, force: true });+ stitchLimiter.cancel(job.id);job.headerStashes = undefined;job.stitchParts = undefined;dropStashes(job.id).catch((error) =>@@ -2503,7 +2513,9 @@ function stitchAhead(job: Job) {let carried = 0;for (const chunk of accepted) {if (!job.headerStashes.has(chunk.stash.key)) {- const read = journalS3.get(chunk.stash.key);+ const read = stitchLimiter.run(job.id, true, () =>+ journalS3.get(chunk.stash.key),+ );read.catch(() => job.headerStashes?.delete(chunk.stash.key));job.headerStashes.set(chunk.stash.key, read);}@@ -2517,7 +2529,10 @@ function stitchAhead(job: Job) {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);+ const uploadId = job.uploadId;+ const written = stitchLimiter.run(job.id, true, () =>+ writeStitchPart(job.key, uploadId, null, part),+ );written.catch(() => job.stitchParts?.delete(key));job.stitchParts.set(key, written);}@@ -2530,30 +2545,28 @@ async function writeStitchParts(plan: StitchPart[],) {const ahead = job.stitchParts ?? new Map();+ stitchLimiter.promote(job.id);// 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 }[] = [];+ // before the plan rewrites its number. Header reads are awaited here too,+ // not inside a stitch slot, so assembly never holds slots while waiting.+ await Promise.allSettled([+ ...ahead.values(),+ ...(job.headerStashes?.values() ?? []),+ ]);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;+ return Promise.all(+ plan.map((part) => {+ const write = () =>+ stitchLimiter.run(job.id, false, () =>+ writeStitchPart(job.key, uploadId, header, part, readStash),+ );+ const early = ahead.get(stitchPartKey(part));+ return early ? early.catch(write) : write();+ }),+ );}async function dropStashes(id: string) {diff --git a/apps/render-farm/src/stitch.test.ts b/apps/render-farm/src/stitch.test.tsindex 6616133d0..6510d2f96 100644--- a/apps/render-farm/src/stitch.test.ts+++ b/apps/render-farm/src/stitch.test.ts@@ -4,6 +4,7 @@ import {HEADER_PART,planStitch,type StashedChunk,+ StitchLimiter,stashBytes,uploadProblem,} from "./stitch";@@ -156,3 +157,103 @@ describe("planStitch ahead of assembly", () => {}});});++describe("stitch limiter", () => {+ function held() {+ let release = () => {};+ const done = new Promise<void>((resolve) => {+ release = resolve;+ });+ return { done, release };+ }+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));++ test("never runs more than its limits, in total, ahead and per job", async () => {+ const limiter = new StitchLimiter({ total: 6, ahead: 4, aheadPerJob: 2 });+ let running = 0;+ let ahead = 0;+ const perJob = new Map<string, number>();+ const peaks = { running: 0, ahead: 0, perJob: 0 };+ const work = (job: string, isAhead: boolean) =>+ limiter.run(job, isAhead, async () => {+ running++;+ if (isAhead) {+ ahead++;+ perJob.set(job, (perJob.get(job) ?? 0) + 1);+ }+ peaks.running = Math.max(peaks.running, running);+ peaks.ahead = Math.max(peaks.ahead, ahead);+ peaks.perJob = Math.max(peaks.perJob, perJob.get(job) ?? 0);+ await new Promise((resolve) => setTimeout(resolve, Math.random() * 3));+ running--;+ if (isAhead) {+ ahead--;+ perJob.set(job, (perJob.get(job) ?? 1) - 1);+ }+ });+ await Promise.all(+ Array.from({ length: 200 }, (_, index) =>+ work(`j${index % 5}`, index % 3 !== 0),+ ),+ );+ expect(peaks).toEqual({ running: 6, ahead: 4, perJob: 2 });+ });++ test("assembly is admitted before queued ahead work", async () => {+ const limiter = new StitchLimiter({ total: 2, ahead: 2, aheadPerJob: 2 });+ const order: string[] = [];+ const first = held();+ const second = held();+ const running = [+ limiter.run("a", true, () => first.done),+ limiter.run("a", true, () => second.done),+ ];+ const queued = [+ limiter.run("b", true, async () => {+ order.push("b ahead");+ }),+ limiter.run("c", false, async () => {+ order.push("c assembly");+ }),+ ];+ await tick();+ expect(order).toEqual([]);+ first.release();+ await Promise.all(queued);+ expect(order).toEqual(["c assembly", "b ahead"]);+ second.release();+ await Promise.all(running);+ });++ test("promoting a job lifts its queued work past the ahead limits", async () => {+ const limiter = new StitchLimiter({ total: 3, ahead: 1, aheadPerJob: 1 });+ const busy = held();+ const blocking = limiter.run("a", true, () => busy.done);+ let started = 0;+ const queued = [1, 2].map(() =>+ limiter.run("a", true, async () => {+ started++;+ }),+ );+ await tick();+ expect(started).toBe(0);+ limiter.promote("a");+ await Promise.all(queued);+ expect(started).toBe(2);+ busy.release();+ await blocking;+ });++ test("cancelling a job drops its queued ahead work only", async () => {+ const limiter = new StitchLimiter({ total: 1, ahead: 1, aheadPerJob: 1 });+ const busy = held();+ const blocking = limiter.run("a", true, () => busy.done);+ const aheadWork = limiter.run("a", true, async () => "ran");+ const assembly = limiter.run("a", false, async () => "assembled");+ limiter.cancel("a");+ await expect(aheadWork).rejects.toThrow("ended before its stitch ran");+ busy.release();+ await blocking;+ expect(await assembly).toBe("assembled");+ });+});diff --git a/apps/render-farm/src/stitch.ts b/apps/render-farm/src/stitch.tsindex ec5f1fe60..6ae2ba100 100644--- a/apps/render-farm/src/stitch.ts+++ b/apps/render-farm/src/stitch.ts@@ -126,3 +126,103 @@ export function uploadProblem(}return null;}++type StitchWaiter = {+ job: string;+ ahead: boolean;+ start: () => void;+ cancel: (error: Error) => void;+};++/**+ * Bounds the coordinator's stitch requests across jobs. Assembly is on the+ * user's path, so it is admitted first and may use every slot; work done ahead+ * of assembly gets a share of them, and less per job, so one long export+ * can't hold the rest.+ */+export class StitchLimiter {+ private running = 0;+ private aheadRunning = 0;+ private aheadByJob = new Map<string, number>();+ private waiting: StitchWaiter[] = [];++ constructor(+ private limits: { total: number; ahead: number; aheadPerJob: number },+ ) {}++ async run<T>(job: string, ahead: boolean, work: () => Promise<T>) {+ let admittedAhead = false;+ await new Promise<void>((resolve, reject) => {+ const waiter: StitchWaiter = {+ job,+ ahead,+ start: () => {+ admittedAhead = waiter.ahead;+ resolve();+ },+ cancel: reject,+ };+ this.waiting.push(waiter);+ this.pump();+ });+ try {+ return await work();+ } finally {+ this.running--;+ if (admittedAhead) {+ this.aheadRunning--;+ const left = (this.aheadByJob.get(job) ?? 1) - 1;+ if (left > 0) this.aheadByJob.set(job, left);+ else this.aheadByJob.delete(job);+ }+ this.pump();+ }+ }++ /** A job's queued ahead work, which its assembly now waits on. */+ promote(job: string) {+ for (const waiter of this.waiting) {+ if (waiter.job === job) waiter.ahead = false;+ }+ this.pump();+ }++ cancel(job: string) {+ const cancelled = this.waiting.filter(+ (waiter) => waiter.job === job && waiter.ahead,+ );+ this.waiting = this.waiting.filter((waiter) => !cancelled.includes(waiter));+ for (const waiter of cancelled) {+ waiter.cancel(new Error(`job ${job} ended before its stitch ran`));+ }+ }++ private pump() {+ while (this.running < this.limits.total) {+ const index = this.next();+ if (index < 0) return;+ const [waiter] = this.waiting.splice(index, 1);+ if (!waiter) return;+ this.running++;+ if (waiter.ahead) {+ this.aheadRunning++;+ this.aheadByJob.set(+ waiter.job,+ (this.aheadByJob.get(waiter.job) ?? 0) + 1,+ );+ }+ waiter.start();+ }+ }++ private next() {+ const assembly = this.waiting.findIndex((waiter) => !waiter.ahead);+ if (assembly >= 0 || this.aheadRunning >= this.limits.ahead) {+ return assembly;+ }+ return this.waiting.findIndex(+ (waiter) =>+ (this.aheadByJob.get(waiter.job) ?? 0) < this.limits.aheadPerJob,+ );+ }+}