Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(render-farm): keep the stash sweep off until recovery succeeds and spare young stashes
Richie McIlroy3ac2b1a143d2
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.tsindex e33a7c46d..548127712 100644--- a/apps/render-farm/src/coordinator.test.ts+++ b/apps/render-farm/src/coordinator.test.ts@@ -23,6 +23,8 @@ function harness(env: Record<string, string> = {}) {const writes: string[] = [];const ranges: string[] = [];const uploadedParts = new Map<string, Uint8Array>();+ const modifiedAt = new Map<string, number>();+ let listFailures = 0;const copies: string[] = [];const completedParts: number[][] = [];const timers: (() => void)[] = [];@@ -63,9 +65,10 @@ function harness(env: Record<string, string> = {}) {return { bytes, etag };},async list(prefix = "") {+ if (listFailures-- > 0) throw new Error("injected listing failure");return [...objects.keys()].filter((key) => key.startsWith(prefix))- .map((key) => ({ key }));+ .map((key) => ({ key, modifiedAt: modifiedAt.get(key) ?? Date.now() }));},async presignFresh(_method: string, key: string) {return `https://media.test/${key}`;@@ -220,6 +223,10 @@ function harness(env: Record<string, string> = {}) {uploadedParts,copies,completedParts,+ modifiedAt,+ failListing: (count = 1) => {+ listFailures = count;+ },callbacks,timers,watchdogs,@@ -471,27 +478,43 @@ describe("assembly", () => {expect(file[file.byteLength - 1]).toBe(2);});- test("stashes outlive neither their job nor a restart", async () => {+ test("the sweep deletes finished and abandoned jobs' stashes only", async () => {const h = harness();const live = job();const done = { ...job(), id: "done", status: "ready" as const };h.jobs.set(live.id, live);h.jobs.set(done.id, done);+ const old = Date.now() - 6 * 3600_000;for (const key of ["stash/job/c0-p3","stash/done/c0-p3",- "stash/gone/c1-p63",+ "stash/abandoned/c0-p3",+ "stash/unknown/c0-p3",])h.objects.set(key, new Uint8Array(1));- // A sweep before the journal is resumed would take jobs about to be- // resumed for finished ones.- await h.sweepStashes();- expect(h.objects.has("stash/gone/c1-p63")).toBe(true);+ h.modifiedAt.set("stash/job/c0-p3", old);+ h.modifiedAt.set("stash/abandoned/c0-p3", old);await h.resumeJobs();- await h.sweepStashes();expect([...h.objects.keys()].filter((key) => key.startsWith("stash/")),- ).toEqual(["stash/job/c0-p3"]);+ ).toEqual(["stash/job/c0-p3", "stash/unknown/c0-p3"]);+ });++ test("a failed journal listing retries and keeps the sweep off until it succeeds", async () => {+ const h = harness();+ const old = Date.now() - 6 * 3600_000;+ h.objects.set("stash/gone/c0-p3", new Uint8Array(1));+ h.modifiedAt.set("stash/gone/c0-p3", old);+ h.failListing(1);+ const resumed = h.resumeJobs();+ await Promise.resolve();+ await Promise.resolve();+ expect(h.timers).toHaveLength(1);+ await h.sweepStashes();+ expect(h.objects.has("stash/gone/c0-p3")).toBe(true);+ h.timers.shift()?.();+ await resumed;+ expect(h.objects.has("stash/gone/c0-p3")).toBe(false);});test("a result whose parts leave a gap in the chunk is refused", async () => {diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.tsindex 086c56acf..8cee66f50 100644--- a/apps/render-farm/src/coordinator.ts+++ b/apps/render-farm/src/coordinator.ts@@ -70,6 +70,8 @@ const MAX_ACTIVE_JOBS = Number(process.env.RF_MAX_ACTIVE_JOBS ?? 32);const JOB_STALL_MS = Number(process.env.RF_JOB_STALL_MS ?? 10 * 60_000);// Finished jobs stay queryable this long, as a summary without media data.const JOB_RETENTION_MS = Number(process.env.RF_JOB_RETENTION_MS ?? 60 * 60_000);+/** Presigned segment and playlist URLs last 6 h; older jobs are abandoned. */+const JOB_LIFETIME_MS = 5 * 3600_000;const SAMPLE_RATE = 48_000;const PACKET = 1024;@@ -1207,14 +1209,23 @@ function segmentsFromResult(}async function resumeJobs() {- try {- await resumeJournal();- } finally {- journalResumed = true;- sweepStashes().catch((error) =>- console.error(`stash sweep failed: ${error}`),- );+ // The stash sweep stays off until every journaled job is back in memory:+ // until then it would take a resumable job for a finished one.+ for (let attempt = 0; ; attempt++) {+ try {+ await resumeJournal();+ break;+ } catch (error) {+ console.error(`resume failed: ${error}`);+ await new Promise((resolve) =>+ setTimeout(resolve, Math.min(60_000, 1000 * 2 ** attempt)),+ );+ }}+ journalResumed = true;+ await sweepStashes().catch((error) =>+ console.error(`stash sweep failed: ${error}`),+ );}async function resumeJournal() {@@ -1238,7 +1249,7 @@ async function resumeJournal() {await journalS3.get(journalKey(id, "request.json")),),) as { request: JobRequest; requestedAt: number };- if (Date.now() - receipt.requestedAt > 5 * 3600_000) {+ if (Date.now() - receipt.requestedAt > JOB_LIFETIME_MS) {await journalPut(journalKey(id, "done"), "expired");continue;}@@ -1252,8 +1263,7 @@ async function resumeJournal() {await journalS3.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) {+ if (Date.now() - (record.t.requested ?? 0) > JOB_LIFETIME_MS) {await journalPut(journalKey(id, "done"), "expired");continue;}@@ -2029,7 +2039,7 @@ async function publishPlaylist(job: Job) {} while (hls.dirty && !hls.ended);} catch (error) {console.error(`job ${job.id} playlist: ${error}`);- if (now() - (job.t.requested ?? 0) < 5 * 3600_000) {+ if (now() - (job.t.requested ?? 0) < JOB_LIFETIME_MS) {hls.retry = setTimeout(() => publishPlaylist(job), 1000);hls.retry.unref();}@@ -2556,17 +2566,20 @@ const STASH_SWEEP_MS = 10 * 60_000;let journalResumed = false;/**- * Deletes the stashes of every job not rendering or assembling. A job's own- * cleanup misses those a losing copy writes after it, and any left when the- * coordinator stops mid-cleanup; restart never reopens a finished job.+ * Deletes stashes a job's own cleanup missed: those a losing copy writes after+ * it, and any left when the coordinator stops mid-cleanup (restart never+ * reopens a finished job). A stash of a job this process doesn't know is+ * kept until the job could no longer be resumed.*/async function sweepStashes() {- // Before resume, jobs about to be resumed are not in memory yet.if (!journalResumed) return;- const stale = (await journalS3.list("stash/")).filter(({ key }) => {- const job = jobs.get(key.split("/")[1] ?? "");- return job?.status !== "rendering" && job?.status !== "assembling";- });+ const stale = (await journalS3.list("stash/")).filter(+ ({ key, modifiedAt }) => {+ const job = jobs.get(key.split("/")[1] ?? "");+ if (!job) return Date.now() - modifiedAt > JOB_LIFETIME_MS;+ return job.status === "ready" || job.status === "error";+ },+ );await Promise.all(stale.map(({ key }) => journalS3.delete(key)));}diff --git a/apps/render-farm/src/s3.ts b/apps/render-farm/src/s3.tsindex f63081df1..f9cb1b52c 100644--- a/apps/render-farm/src/s3.ts+++ b/apps/render-farm/src/s3.ts@@ -558,17 +558,22 @@ export class S3 {}async list(prefix: string) {- const keys: { key: string; size: number }[] = [];+ const keys: { key: string; size: number; modifiedAt: number }[] = [];let token: string | undefined;do {const query: Record<string, string> = { "list-type": "2", prefix };if (token) query["continuation-token"] = token;const response = await this.send("GET", "", { query });const text = await response.text();- for (const match of text.matchAll(- /<Key>([^<]+)<\/Key>[\s\S]*?<Size>(\d+)<\/Size>/g,- )) {- keys.push({ key: decodeXml(match[1] ?? ""), size: Number(match[2]) });+ for (const match of text.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {+ const body = match[1] ?? "";+ keys.push({+ key: decodeXml(body.match(/<Key>([^<]+)<\/Key>/)?.[1] ?? ""),+ size: Number(body.match(/<Size>(\d+)<\/Size>/)?.[1]),+ modifiedAt: Date.parse(+ body.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1] ?? "",+ ),+ });}token = text.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/,