Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): sweep+clean all video .detached orphans on boot so chained renders are reaped (#1319)
[._.]/ Adam Eivye0f5f67fa152
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.jsindex 7080f0707f..731e289ad1 100644--- a/server/lib/detachedSpawn.js+++ b/server/lib/detachedSpawn.js@@ -46,7 +46,7 @@ import { spawn } from 'child_process';import { EventEmitter } from 'events';import { constants as osConstants } from 'os';import { join } from 'path';-import { open, readFile, rm, stat } from 'fs/promises';+import { open, readFile, rm, stat, readdir } from 'fs/promises';import { ensureDir, sleep } from './fileUtils.js';// Default cadence for tailing the job's log files and polling for completion.@@ -350,3 +350,28 @@ export async function reapDetached(controlDir, { graceMs = REAP_GRACE_MS, pollMs}return { reaped: wasAlive, pid };}++/**+ * Boot-time sweep of a parent dir holding per-job control dirs (e.g.+ * `data/videos/.detached/<jobId>`). Reaps any surviving orphan in each and then+ * removes the dir. Used where job ids aren't enumerable from persisted state —+ * notably chained video renders, whose live child lives under a random INNER+ * chunk id, not the outer queue job id. Safe to call only at boot, before any+ * new job starts (every dir present then is an orphan from the prior process).+ *+ * @param {string} parentDir - the `.detached` parent (e.g. PATHS.videos/.detached)+ * @returns {Promise<{reaped: number, scanned: number}>}+ */+export async function reapAndCleanDetachedDirs(parentDir) {+ const entries = await readdir(parentDir).catch(() => []);+ let reaped = 0;+ for (const name of entries) {+ const dir = join(parentDir, name);+ // eslint-disable-next-line no-await-in-loop+ const res = await reapDetached(dir).catch(() => ({ reaped: false }));+ if (res.reaped) reaped += 1;+ // eslint-disable-next-line no-await-in-loop+ await rm(dir, { recursive: true, force: true }).catch(() => {});+ }+ return { reaped, scanned: entries.length };+}diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.jsindex 8dfc34033e..4a6dd5beef 100644--- a/server/lib/detachedSpawn.test.js+++ b/server/lib/detachedSpawn.test.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import { execFile } from 'child_process';import { promisify } from 'util';-import { spawnDetached, reapDetached } from './detachedSpawn.js';+import { spawnDetached, reapDetached, reapAndCleanDetachedDirs } from './detachedSpawn.js';const execFileAsync = promisify(execFile);const dirs = [];@@ -211,4 +211,29 @@ describe('spawnDetached', () => {expect(res.reaped).toBe(false);});});++ describe('reapAndCleanDetachedDirs', () => {+ it('reaps every surviving orphan under the parent and removes the dirs', async () => {+ const parent = await tmpControlDir();+ const a = join(parent, 'job-a');+ const b = join(parent, 'job-b');+ const hA = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir: a, pollMs: 25 });+ const hB = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir: b, pollMs: 25 });+ const closedA = onClose(hA);+ const closedB = onClose(hB);+ await new Promise((r) => setTimeout(r, 50));+ const res = await reapAndCleanDetachedDirs(parent);+ expect(res.reaped).toBe(2);+ expect(res.scanned).toBe(2);+ expect(await stat(a).then(() => true).catch(() => false)).toBe(false);+ expect(await stat(b).then(() => true).catch(() => false)).toBe(false);+ await Promise.all([closedA, closedB]);+ });++ it('returns zero for a missing or empty parent', async () => {+ const parent = await tmpControlDir();+ const res = await reapAndCleanDetachedDirs(join(parent, 'does-not-exist'));+ expect(res).toEqual({ reaped: 0, scanned: 0 });+ });+ });});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 3d4361d73c..990cf465c1 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -33,7 +33,7 @@ import { randomUUID } from 'crypto';import { unlink } from 'fs/promises';import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';import { PATHS, readJSONFile, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';-import { reapDetached } from '../../lib/detachedSpawn.js';+import { reapAndCleanDetachedDirs } from '../../lib/detachedSpawn.js';import {broadcastSse,attachSseClient as attachSse,@@ -258,18 +258,19 @@ export async function initMediaJobQueue() {const data = await readJSONFile(JOBS_FILE, { jobs: [] });const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];const restartedFailedIds = [];+ // Video renders spawn a detached child that survives a pm2 restart, so an+ // interrupted render may still be alive and holding the GPU. Reap every+ // orphan under data/videos/.detached (and clean the scratch dirs) BEFORE+ // freeing lanes below — a job-id keyed reap would miss chained renders,+ // whose live child lives under a random inner chunk id, not the outer queue+ // job id. (Training children are reaped in initLoraTraining, which knows+ // each run's dir.) This runs before the worker starts, so every dir present+ // is an orphan from the prior process.+ const videoReap = await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));+ if (videoReap.reaped) console.log(`🧹 reaped ${videoReap.reaped} surviving render(s) on boot`);+for (const j of persistedJobs) {if (j.status === 'running') {- // Video renders spawn a detached child that survives a pm2 restart, so- // the persisted 'running' job may still be alive. Reap it (SIGTERM →- // SIGKILL) before freeing the lane, else the orphan keeps consuming the- // GPU while a newly-dequeued job runs concurrently. (Training children- // are reaped in initLoraTraining, which knows their run dir.)- if (j.kind === 'video') {- // eslint-disable-next-line no-await-in-loop- const reaped = await reapDetached(join(PATHS.videos, '.detached', j.id)).catch(() => ({ reaped: false }));- if (reaped.reaped) console.log(`🧹 reaped surviving render pid ${reaped.pid} for job ${j.id.slice(0, 8)}`);- }const failed = {...j,status: 'failed',