Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit a087e71a0c2502bfdb633371158754717358030e
parent d1d4c16033675f246aa9438f8b6a7039f7bb64ad
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:25:39 -0400

scripts: parakeet-stitch removes its temp dir on a pause, and sweeps stale ones

The pause path left the window loop with process.exit inside the try, so the
finally that removes the parakeet-stitch-* temp dir never ran. It breaks out
now and exits after the finally. Each run first sweeps the tmpdir: a
parakeet-stitch-* dir older than 24 h goes unless it is held — by its owner
file (pid and start time, written at creation; a reused pid is not the owner),
or, for a dir from before the owner file, by any other parakeet-stitch
process or any process with a file or its cwd in it. The script runs main()
only as a program, so the test can import the sweep.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mscripts/parakeet-stitch.mjs | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Ascripts/parakeet-stitch.test.mjs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 291 insertions(+), 8 deletions(-)

diff --git a/scripts/parakeet-stitch.mjs b/scripts/parakeet-stitch.mjs @@ -55,10 +55,11 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, writeFile } from "node:fs/promises"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; const execFileP = promisify(execFile); @@ -266,6 +267,150 @@ function workDirFor(absAudio) { const PARTIAL_PAUSE_CODE = 0; +// ─── The temp dir: removed on every exit; a stale one swept at start-up ─── +// +// Each run slices its windows into a `parakeet-stitch-*` dir under the +// tmpdir (a RAM tmpfs on some hosts). It is removed in a `finally`, and the +// pause path leaves the loop rather than exiting inside it, so the `finally` +// runs there too. What a kill -9 or a crash leaves behind is swept by the next +// run: a dir older than STALE_MS that no running process holds. +// +// "Holds" is decided by an OWNER FILE written into the dir at creation — the +// pid and that process's start time (/proc/<pid>/stat, field 22), so a reused +// pid is not taken for the owner. A scan of /proc for open files or a cwd in +// the dir would not do: a run holds nothing in it between two windows. A dir +// with no owner file (from before this change) is held while any other +// parakeet-stitch process is running (its cmdline), or while any process has a +// file or its cwd in it — the conservative reading. + +export const TMP_PREFIX = "parakeet-stitch-"; +export const OWNER_FILE = "owner.json"; +export const STALE_MS = 24 * 60 * 60 * 1000; + +// A process's start time in clock ticks since boot, or null (no such pid, no /proc). +export function procStartTime(pid) { + try { + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + // rest[0] is field 3 (state); field 22 (starttime) is rest[19]. + return rest[19] ?? null; + } catch { + return null; + } +} + +function pidAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (e) { + return e?.code === "EPERM"; + } +} + +async function procPids() { + try { + return (await readdir("/proc")).filter((n) => /^\d+$/.test(n)).map(Number); + } catch { + return []; + } +} + +// The live system's answers; tests pass their own. +export const liveProc = { + // The owner file's process is the same process, still running. + ownerAlive(owner) { + if (!owner || !Number.isInteger(owner.pid) || !pidAlive(owner.pid)) return false; + const start = procStartTime(owner.pid); + return owner.start == null || start == null || String(start) === String(owner.start); + }, + // Some process has its cwd or an open file inside `dir`. + async holds(dir) { + const inside = (p) => p === dir || p.startsWith(dir + path.sep); + for (const pid of await procPids()) { + try { + if (inside(await readlink(`/proc/${pid}/cwd`))) return true; + } catch { + // gone, or not ours to read + } + let fds = []; + try { + fds = await readdir(`/proc/${pid}/fd`); + } catch { + continue; + } + for (const fd of fds) { + try { + if (inside(await readlink(`/proc/${pid}/fd/${fd}`))) return true; + } catch { + // closed meanwhile + } + } + } + return false; + }, + // Another parakeet-stitch process is running. + async stitchRunning() { + for (const pid of await procPids()) { + if (pid === process.pid) continue; + try { + if (readFileSync(`/proc/${pid}/cmdline`, "utf8").includes("parakeet-stitch")) return true; + } catch { + // gone + } + } + return false; + }, +}; + +export async function writeOwnerFile(dir, pid = process.pid) { + await writeFile(path.join(dir, OWNER_FILE), JSON.stringify({ pid, start: procStartTime(pid) })); +} + +// Remove every stale, unheld `parakeet-stitch-*` dir under `tmpdir`. +// Answers what was removed and what was kept, with why. +export async function sweepStaleTempDirs({ tmpdir = os.tmpdir(), now = Date.now(), staleMs = STALE_MS, proc = liveProc } = {}) { + const removed = []; + const kept = []; + let names = []; + try { + names = (await readdir(tmpdir, { withFileTypes: true })).filter((e) => e.isDirectory() && e.name.startsWith(TMP_PREFIX)).map((e) => e.name); + } catch { + return { removed, kept }; + } + for (const name of names) { + const dir = path.join(tmpdir, name); + let st; + try { + st = await stat(dir); + } catch { + continue; + } + if (now - st.mtimeMs < staleMs) { + kept.push({ dir, why: "young" }); + continue; + } + let owner = null; + try { + owner = JSON.parse(await readFile(path.join(dir, OWNER_FILE), "utf8")); + } catch { + owner = null; + } + const held = owner ? proc.ownerAlive(owner) : (await proc.stitchRunning()) || (await proc.holds(dir)); + if (held) { + kept.push({ dir, why: "held" }); + continue; + } + try { + await rm(dir, { recursive: true, force: true }); + removed.push(dir); + } catch { + kept.push({ dir, why: "not removable" }); + } + } + return { removed, kept }; +} + async function main() { const opts = parseArgs(process.argv.slice(2)); if (!opts.audio) fail("missing <audioFile>\n\n" + HELP); @@ -343,7 +488,12 @@ async function main() { process.on("SIGTERM", onStop); process.on("SIGINT", onStop); - const tmp = await mkdtemp(path.join(os.tmpdir(), "parakeet-stitch-")); + // What a crashed or killed run left in the tmpdir goes first. + const swept = await sweepStaleTempDirs().catch(() => ({ removed: [] })); + if (swept.removed.length) progress(`removed ${swept.removed.length} stale temp dir(s) from earlier runs`); + const tmp = await mkdtemp(path.join(os.tmpdir(), TMP_PREFIX)); + await writeOwnerFile(tmp); + let paused = false; const segTimes = []; // measured wall-time (ms) per freshly-transcribed window, for ETA let done = 0; // windows present (cached or freshly done) try { @@ -356,8 +506,9 @@ async function main() { continue; } if (stopRequested) { - progress(`paused after ${done}/${N} window(s) — re-run to resume`); - process.exit(PARTIAL_PAUSE_CODE); + // Leave the loop, never exit inside it: the `finally` removes the temp dir. + paused = true; + break; } const isLast = i === N - 1; // Last window runs to EOF (no -t) so we never miss a trailing fragment. @@ -380,6 +531,10 @@ async function main() { } finally { if (!opts.keepTemp) await rm(tmp, { recursive: true, force: true }); } + if (paused) { + progress(`paused after ${done}/${N} window(s) — re-run to resume`); + process.exit(PARTIAL_PAUSE_CODE); + } // All windows present — load the raw payloads and stitch the final transcript. const windowWords = []; @@ -435,6 +590,16 @@ async function main() { if (!opts.keepTemp) await rm(workDir, { recursive: true, force: true }); } -main().catch((err) => { - fail(err?.stack || String(err), 1); -}); +// Run as a program (the app's binary, or the CLI), not when a test imports it. +const isMain = (() => { + try { + return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +})(); +if (isMain) { + main().catch((err) => { + fail(err?.stack || String(err), 1); + }); +} diff --git a/scripts/parakeet-stitch.test.mjs b/scripts/parakeet-stitch.test.mjs @@ -0,0 +1,118 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { OWNER_FILE, STALE_MS, TMP_PREFIX, sweepStaleTempDirs, writeOwnerFile } from "./parakeet-stitch.mjs"; + +// Run with: node --test scripts/parakeet-stitch.test.mjs +// +// Release 28 H1: the temp dir a run slices its windows into is removed on the +// pause path too, and a run sweeps the stale ones a crash or a kill left. + +const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "parakeet-stitch.mjs"); + +function sh(file, body) { + writeFileSync(file, `#!/bin/sh\n${body}\n`); + chmodSync(file, 0o755); + return file; +} + +test("the pause path: a SIGTERM mid-run finishes the window, keeps it, exits 0 — and leaves no temp dir", () => { + const root = mkdtempSync(path.join(os.tmpdir(), "stitch-pause-")); + try { + const tmpdir = path.join(root, "tmp"); + const bin = path.join(root, "bin"); + const work = path.join(root, "video"); + mkdirSync(tmpdir); + mkdirSync(bin); + mkdirSync(work); + writeFileSync(path.join(work, "audio.wav"), "not audio"); + writeFileSync(path.join(root, "model.gguf"), "not a model"); + sh(path.join(bin, "ffprobe"), "echo 1000"); + // ffmpeg: write the window wav (its last argument). + sh(path.join(bin, "ffmpeg"), 'for a; do last="$a"; done; echo wav > "$last"'); + // parakeet-cli: the operator pauses during the first window (a SIGTERM to + // the script, its parent), and the window still completes. + sh(path.join(bin, "parakeet-cli"), 'kill -TERM $PPID; echo \'{"words":[{"w":"hello","start":1,"end":1.5}]}\''); + const r = spawnSync( + process.execPath, + [SCRIPT, "--model", path.join(root, "model.gguf"), "--cli", path.join(bin, "parakeet-cli"), "--ffmpeg", path.join(bin, "ffmpeg"), path.join(work, "audio.wav"), path.join(work, "out.json")], + { env: { ...process.env, TMPDIR: tmpdir }, encoding: "utf8", timeout: 30_000 }, + ); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stderr, /paused after 1\/3 window\(s\)/); + assert.deepEqual(readdirSync(tmpdir).filter((n) => n.startsWith(TMP_PREFIX)), [], "no temp dir left"); + // The completed window is kept for the resume; nothing was stitched. + assert.ok(existsSync(path.join(work, ".audio.wav.parakeet", "win-0000.json"))); + assert.ok(!existsSync(path.join(work, "out.json"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("the sweep: an old unheld dir goes; a held one (its owner alive, or a process in it) and a young one stay", async () => { + const tmpdir = mkdtempSync(path.join(os.tmpdir(), "stitch-sweep-")); + try { + const now = Date.now(); + const make = (name, ageMs) => { + const d = path.join(tmpdir, name); + mkdirSync(d); + writeFileSync(path.join(d, "win-0000.wav"), "wav"); + const t = (now - ageMs) / 1000; + utimesSync(d, t, t); + return d; + }; + const old = make(`${TMP_PREFIX}old`, STALE_MS + 60_000); + const owned = path.join(tmpdir, `${TMP_PREFIX}owned`); + mkdirSync(owned); + await writeOwnerFile(owned, 4242); + utimesSync(owned, (now - STALE_MS * 2) / 1000, (now - STALE_MS * 2) / 1000); + const legacyHeld = make(`${TMP_PREFIX}legacy-held`, STALE_MS * 3); + const young = make(`${TMP_PREFIX}young`, 60_000); + const other = make("something-else", STALE_MS * 5); + const proc = { + ownerAlive: (o) => o.pid === 4242, + holds: async (dir) => dir === legacyHeld, + stitchRunning: async () => false, + }; + const out = await sweepStaleTempDirs({ tmpdir, now, proc }); + assert.deepEqual(out.removed, [old]); + assert.deepEqual( + out.kept.map((k) => [path.basename(k.dir), k.why]).sort(), + [ + [`${TMP_PREFIX}legacy-held`, "held"], + [`${TMP_PREFIX}owned`, "held"], + [`${TMP_PREFIX}young`, "young"], + ], + ); + assert.ok(existsSync(owned) && existsSync(legacyHeld) && existsSync(young) && existsSync(other)); + assert.ok(existsSync(path.join(owned, OWNER_FILE))); + // The owner gone: the dir goes. A dir with no owner file waits while + // another parakeet-stitch runs. + const later = await sweepStaleTempDirs({ tmpdir, now, proc: { ...proc, ownerAlive: () => false, stitchRunning: async () => true } }); + assert.deepEqual(later.removed, [owned]); + assert.ok(existsSync(legacyHeld)); + } finally { + rmSync(tmpdir, { recursive: true, force: true }); + } +}); + +test("the live owner check: this process owns a dir it marked; a dead pid does not", async () => { + const { liveProc } = await import("./parakeet-stitch.mjs"); + const dir = mkdtempSync(path.join(os.tmpdir(), "stitch-owner-")); + try { + await writeOwnerFile(dir); + const mine = JSON.parse((await import("node:fs")).readFileSync(path.join(dir, OWNER_FILE), "utf8")); + assert.equal(mine.pid, process.pid); + assert.equal(liveProc.ownerAlive(mine), true); + // The same pid with another start time is a reused pid, not the owner. + assert.equal(liveProc.ownerAlive({ pid: process.pid, start: "1" }), mine.start === null); + const child = spawnSync(process.execPath, ["-e", "console.log(process.pid)"], { encoding: "utf8" }); + assert.equal(liveProc.ownerAlive({ pid: Number(child.stdout.trim()), start: null }), false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});