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 }); } }); // Release 30 lane Q: --salvage. A window that cannot be sliced or transcribed // is a gap, recorded in the output; without the flag it is the end of the file. function salvageFixture(root, { failSlice = false } = {}) { const bin = path.join(root, "bin"); const work = path.join(root, "video"); 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 writes the window wav (its last argument), named for its window; // with failSlice the second window's slice fails as a damaged file does. sh( path.join(bin, "ffmpeg"), `for a; do last="$a"; done; case "$last" in *win-0001.wav) ${failSlice ? 'echo "Invalid data found when processing input" >&2; exit 1' : "echo wav > \"$last\""};; *) echo wav > "$last";; esac`, ); // parakeet-cli: one word 1 s into each window; the second window fails. sh( path.join(bin, "parakeet-cli"), 'for a; do last="$a"; done; case "$last" in *win-0001.wav) echo "parakeet: decode failed" >&2; exit 1;; esac; echo \'{"words":[{"w":"word","start":1,"end":1.5}]}\'', ); return { bin, work }; } function runStitch(root, bin, work, extra = []) { return spawnSync( process.execPath, [SCRIPT, "--model", path.join(root, "model.gguf"), "--cli", path.join(bin, "parakeet-cli"), "--ffmpeg", path.join(bin, "ffmpeg"), ...extra, path.join(work, "audio.wav"), path.join(work, "out.json")], { env: { ...process.env, TMPDIR: path.join(root, "tmp") }, encoding: "utf8", timeout: 30_000 }, ); } for (const failSlice of [false, true]) { test(`--salvage: a window whose ${failSlice ? "slice" : "transcription"} fails is a gap, the rest is stitched`, async () => { const root = mkdtempSync(path.join(os.tmpdir(), "stitch-salvage-")); try { mkdirSync(path.join(root, "tmp")); const { bin, work } = salvageFixture(root, { failSlice }); // Without the flag: the whole file fails. const plain = runStitch(root, bin, work); assert.equal(plain.status, 1); assert.ok(!existsSync(path.join(work, "out.json"))); // With it: windows 0 and 2 are transcribed, window 1 is a gap. const r = runStitch(root, bin, work, ["--salvage"]); assert.equal(r.status, 0, r.stderr); assert.match(r.stderr, /segment 2\/3 @474s — failed, recorded as a gap \(salvage\)/); const doc = JSON.parse((await import("node:fs")).readFileSync(path.join(work, "out.json"), "utf8")); // 1000 s in 480 s windows with 6 s overlap: starts 0, 474, 948. With the // middle one gone, its neighbours own their whole reach — 0–480 and // 948–1000 — and only what neither reaches is a gap. assert.deepEqual(doc.salvage, { failedWindows: [[480, 948]] }); assert.deepEqual(doc.chunk_data.map((c) => c.start_time), [1, 949]); // A failed window is not cached; the next run asks it again. assert.ok(!existsSync(path.join(work, ".audio.wav.parakeet")), "work dir removed after the stitch"); } finally { rmSync(root, { recursive: true, force: true }); } }); } test("--salvage: every window failing is a failed transcription, not an empty one", () => { const root = mkdtempSync(path.join(os.tmpdir(), "stitch-salvage-all-")); try { mkdirSync(path.join(root, "tmp")); const { bin, work } = salvageFixture(root); sh(path.join(bin, "parakeet-cli"), "exit 1"); const r = runStitch(root, bin, work, ["--salvage"]); assert.equal(r.status, 1); assert.match(r.stderr, /every one of 3 window\(s\) failed \(salvage\)/); assert.ok(!existsSync(path.join(work, "out.json"))); } finally { rmSync(root, { recursive: true, force: true }); } });