Archilyzer · Source

archilyzer

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

commit 78fdd1a71a5a95d1f726298f49420feac2f1047d
parent f857db5d1a659586f20e63c7571920fa2d07bf60
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 06:14:42 -0500

Merge lane/flaky-tests: three races the tests had been catching are fixed where they were -- a take given the machine that is killed while it is still claiming the hold now releases it; a queue step whose runner is alive reads running until its end is recorded, not failed; an empty queue lock is not broken at once; a failed tracker scrape closes its client; and the tests that only ran out of time on a loaded machine wait for what they wait for

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/seeder.test.ts | 208++++++++++++++++++++++++++++++++++++++++++++++---------------------------------
Mcommon/controller/seeder.ts | 45++++++++++++++++++++++++++++++++++++++-------
Acommon/testing/jobs/quiesce.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/seeder/fixture.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/seeder/webrtcScenario.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 13+++++++++++++
Meditor/app/api/media/fetch-window/route.remote.test.ts | 18++++++++++--------
Meditor/app/api/media/fetch-window/route.storedUrl.test.ts | 21+++++++++++----------
Meditor/app/channels/[slug]/videos/fetchWindowsAction.test.ts | 16++++++++++------
Meditor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts | 16++++++++++------
Mscripts/queue-lock.test.mjs | 12+++++++++---
Mumtool/lib/queue/store.mjs | 34++++++++++++++++++++++++++++------
Mumtool/lib/queue/store.test.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/renderMode.mjs | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mumtool/lib/report/renderMode.test.mjs | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
15 files changed, 724 insertions(+), 182 deletions(-)

diff --git a/common/controller/seeder.test.ts b/common/controller/seeder.test.ts @@ -1,65 +1,22 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { spawn } from "node:child_process"; +import { mkdir, readFile, rm } from "node:fs/promises"; +import { createServer } from "node:net"; import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; import WebTorrent from "webtorrent"; import type { Paths } from "../lib/paths"; -import { DEFAULT_SEEDER_SETTINGS, type SeederSettings } from "../lib/seederSettings"; -import { makePlayableTorrent } from "./preparePlayable"; -import { interfacePresent, mergeScrapes, runSeeder, startTracker, type SeedTarget } from "./seeder"; +import { DEFAULT_SEEDER_SETTINGS } from "../lib/seederSettings"; +import { interfacePresent, mergeScrapes, runSeeder, scrapeTracker, startTracker } from "./seeder"; +import { destroyClient as destroy, newClient, SEED_ID as ID, seederFixture as fixture, seederSettings as settings, until } from "../testing/seeder/fixture"; // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/seeder.test.ts // // SHORT LOCALHOST INTEGRATION: a tracker on 127.0.0.1, the seeder, and a -// leecher in this process; a few hundred KB of synthetic bytes. Nothing -// listens on anything but loopback, no STUN server is asked for an address, -// and everything is torn down at the end. - -const ID = "aaaaaaaaaaa"; - -async function until(pred: () => boolean, ms: number, what: string): Promise<void> { - const t0 = Date.now(); - while (!pred()) { - if (Date.now() - t0 > ms) throw new Error(`timed out waiting for ${what}`); - await new Promise((r) => setTimeout(r, 100)); - } -} - -const newClient = () => - new WebTorrent({ - dht: false, - lsd: false, - natUpnp: false, - natPmp: false, - utp: false, - webSeeds: false, - tracker: { rtcConfig: { iceServers: [] } }, - }); - -const destroy = (c: WebTorrent) => - c.destroyed ? Promise.resolve() : new Promise<void>((resolve) => c.destroy(() => resolve())); - -async function fixture(trackerUrl: (port: number) => string) { - const dir = await mkdtemp(path.join(tmpdir(), "ttb-seeder-")); - const seedDir = path.join(dir, "playable", "demo", ID); - await mkdir(seedDir, { recursive: true }); - const bytes = Buffer.from(Array.from({ length: 600_000 }, (_, i) => (i * 13 + 7) & 0xff)); - const file = path.join(seedDir, `${ID}.mp4`); - await writeFile(file, bytes); - let allowed = new Set<string>(); - const tracker = await startTracker({ host: "127.0.0.1", port: 0, allowed: () => allowed }); - const made = await makePlayableTorrent({ file, name: `${ID}.mp4`, bytes: bytes.length, trackers: [trackerUrl(tracker.port)] }); - allowed = new Set([made.infoHash]); - const torrentPath = path.join(seedDir, `${ID}.torrent`); - await writeFile(torrentPath, made.torrent); - const target: SeedTarget = { slug: "demo", id: ID, infoHash: made.infoHash, torrentPath, file, dir: seedDir, bytes: bytes.length }; - return { dir, bytes, tracker, made, target }; -} - -function settings(): SeederSettings { - return { ...DEFAULT_SEEDER_SETTINGS, sites: ["demo-site"], maxConnections: 10 }; -} +// leecher in this process (the WebRTC one in a child: below); a few hundred KB +// of synthetic bytes. Nothing listens on anything but loopback, no STUN server +// is asked for an address, and everything is torn down at the end. function leechTo(peer: WebTorrent, torrent: Buffer, out: string, ms: number, log: string[]) { const t = peer.add(torrent, { path: out }); @@ -105,6 +62,59 @@ test("the tracker tracks only the torrents it is told to", { timeout: 30_000 }, } }); +// bittorrent-tracker's process-wide WebSocket pool (one socket per announce +// URL, shared by every client in the process): not an exported path, so by file. +async function wsSocketPool(): Promise<Record<string, unknown>> { + const dir = path.dirname(fileURLToPath(import.meta.resolve("bittorrent-tracker"))); + const mod = (await import(pathToFileURL(path.join(dir, "lib/client/websocket-tracker.js")).href)) as { default: { _socketPool: Record<string, unknown> } }; + return mod.default._socketPool; +} + +test("a scrape that fails leaves no tracker client behind (its socket, its reconnect loop)", { timeout: 60_000 }, async () => { + // A port nothing listens on: the WebSocket tracker's connect fails, and + // bittorrent-tracker's static scrape calls back with a warning without + // destroying its client — which then held the shared ws socket and retried + // it forever, keeping the process alive. + const port = await new Promise<number>((resolve) => { + const srv = createServer(); + srv.listen(0, "127.0.0.1", () => { + const p = (srv.address() as { port: number }).port; + srv.close(() => resolve(p)); + }); + }); + const url = `ws://127.0.0.1:${port}`; + const { Client } = await import("bittorrent-tracker"); + const destroy = Client.prototype.destroy; + let destroyed = 0; + Client.prototype.destroy = function (this: InstanceType<typeof Client>, ...args: Parameters<typeof destroy>) { + destroyed += 1; + return destroy.apply(this, args); + }; + try { + await assert.rejects(scrapeTracker(url, ["c".repeat(40)]), /Error connecting/); + } finally { + Client.prototype.destroy = destroy; + } + assert.ok(destroyed >= 1, "the failed scrape's client is destroyed (it would reconnect in 10 s to 5 min, and stay)"); + assert.equal((await wsSocketPool())[url], undefined, "the failed scrape's socket is released"); + // And one that never answers is given up on, not waited for forever. + const held = new Set<import("node:net").Socket>(); + const blackhole = createServer((sock) => held.add(sock)); // accepts, never speaks: no WebSocket handshake + await new Promise<void>((r) => blackhole.listen(0, "127.0.0.1", () => r())); + try { + const bh = `ws://127.0.0.1:${(blackhole.address() as { port: number }).port}`; + const pending = scrapeTracker(bh, ["c".repeat(40)], 1500); + pending.catch(() => {}); + // The pool this test reads is the one the client uses: the socket is in it while the scrape waits. + assert.ok((await wsSocketPool())[bh], "the waiting scrape's socket is in the pool"); + await assert.rejects(pending, /no scrape answer/); + assert.equal((await wsSocketPool())[bh], undefined, "the timed-out scrape's socket is released"); + } finally { + for (const sock of held) sock.destroy(); + await new Promise<void>((r) => blackhole.close(() => r())); + } +}); + test("TCP: it seeds, a leecher completes, the seeder stands by while the leecher seeds and resumes when it leaves", { timeout: 60_000 }, async () => { const f = await fixture((port) => `http://127.0.0.1:${port}/announce`); const ac = new AbortController(); @@ -147,46 +157,70 @@ test("TCP: it seeds, a leecher completes, the seeder stands by while the leecher } }); -test("WebRTC: a peer reaching it through the WebSocket tracker completes (node-datachannel)", { timeout: 60_000 }, async (t) => { +// THE WEBRTC SCENARIO RUNS IN A CHILD (testing/seeder/webrtcScenario.ts), WATCHED. +// Twice on a loaded machine this file's process did not finish: once it never +// exited after this test passed, once its event loop stopped mid-test so that +// no timer fired, its own timeout included. Nothing inside a process can bound +// what node-datachannel's native threads do to it; a parent can. The child +// says its result, then what it still has open after its teardown (every +// tracker socket must be gone), and must exit by itself: one that does not is +// killed and the test fails saying what it last reported — never a hang. +const SCENARIO = fileURLToPath(new URL("../testing/seeder/webrtcScenario.ts", import.meta.url)); + +test("WebRTC: a peer reaching it through the WebSocket tracker completes (node-datachannel), and its process exits", { timeout: 300_000 }, async (t) => { if (!WebTorrent.WEBRTC_SUPPORT) { t.skip("no WebRTC in this node"); return; } - const f = await fixture((port) => `ws://127.0.0.1:${port}`); - const ac = new AbortController(); - const log: string[] = []; - const seederClient = newClient(); - const peer = newClient(); - const running = runSeeder({ - paths: {} as Paths, - settings: settings(), - onLog: (l) => log.push(l), - signal: ac.signal, - deps: { - targets: async () => [f.target], - pollMs: 1000, - policy: { standbyAfterSeconds: 3600, resumeAfterSeconds: 3600 }, - client: seederClient, - }, + // The same loader this file runs under (tsx), without the test runner's flags. + const execArgv = process.execArgv.filter((a) => !a.startsWith("--test")); + const child = spawn(process.execPath, [...execArgv, SCENARIO], { stdio: ["ignore", "pipe", "pipe"] }); + const lines: string[] = []; + let buf = ""; + child.stdout.on("data", (d) => { + buf += d; + for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) { + lines.push(buf.slice(0, i)); + buf = buf.slice(i + 1); + } }); + let stderr = ""; + child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-4000))); + const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((r) => + child.on("exit", (code, signal) => r({ code, signal })), + ); + const said = (tag: string) => { + const l = lines.find((x) => x.startsWith(`${tag} `)); + return l ? JSON.parse(l.slice(tag.length + 1)) : null; + }; + const report = () => `it said: ${lines.join(" / ") || "nothing"}${stderr ? `; stderr: ${stderr.trim()}` : ""}`; + // Backstops, not measures: starting node and compiling the seeder's imports + // can take a minute on a loaded machine; the scenario's own waits are 60/90 s. + const waitFor = async (pred: () => boolean, ms: number) => { + const t0 = Date.now(); + while (!pred() && Date.now() - t0 < ms && child.exitCode === null && child.signalCode === null) { + await new Promise((r) => setTimeout(r, 100)); + } + return pred(); + }; try { - // The leecher announces AFTER the seeder's announce is in. Two peers whose - // WebSocket offers cross in flight each answer the other's and each keep - // the connection the other dropped — an artefact of starting both in the - // same instant, which a browser arriving at a running seeder does not do. - await until(() => (f.tracker.swarm(f.made.infoHash)?.complete ?? 0) >= 1, 20_000, "the seeder's announce"); - const out = path.join(f.dir, "leech"); - await mkdir(out); - const { t: tor, done } = leechTo(peer, f.made.torrent, out, 40_000, log); - await done; - assert.deepEqual(await readFile(path.join(out, `${ID}.mp4`)), f.bytes); - assert.ok(tor.wires.some((w) => w.type === "webrtc"), `wires: ${tor.wires.map((w) => w.type).join(",")}`); + assert.ok(await waitFor(() => !!said("OPEN"), 240_000), `the WebRTC scenario did not finish its teardown; ${report()}`); + const result = said("RESULT"); + assert.ok(result, `no result; ${report()}`); + if (result.skipped) { + t.skip(result.skipped); + return; + } + assert.equal(result.ok, true, result.error); + assert.ok(result.wires.includes("webrtc"), `wires: ${result.wires.join(",")}`); + assert.deepEqual(said("OPEN").wsPool, [], "every tracker socket is closed after the teardown"); + // It exits by itself, everything it opened being closed. + const gone = await Promise.race([exited.then(() => true), new Promise<false>((r) => setTimeout(() => r(false), 30_000).unref())]); + assert.ok(gone, `the WebRTC scenario passed but its process did not exit within 30 s of its teardown; ${report()}`); + const { code, signal } = await exited; + assert.equal(code, 0, `exited ${code ?? signal}; ${report()}`); } finally { - ac.abort(); - await running.catch(() => {}); - await destroy(peer); - await destroy(seederClient); - await f.tracker.close(); - await rm(f.dir, { recursive: true, force: true }); + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + await exited; } }); diff --git a/common/controller/seeder.ts b/common/controller/seeder.ts @@ -103,18 +103,49 @@ export function interfacePresent( export type ScrapeFn = ( announce: string, infoHashes: string[], + timeoutMs?: number, ) => Promise<Map<string, { complete: number; incomplete: number }>>; +// How long a scrape may take before the poll goes on without that tracker's answer. +export const SCRAPE_TIMEOUT_MS = 20_000; + // One scrape request per tracker, for every infohash at once. -export const scrapeTracker: ScrapeFn = (announce, infoHashes) => +// +// THE SCRAPE'S CLIENT IS DESTROYED ON EVERY OUTCOME. bittorrent-tracker's +// static `Client.scrape` destroys its client only on an answer: on an error or +// a warning (a WebSocket tracker that dropped the connection, a malformed +// reply) it calls back and leaves the client alive — for a ws:// tracker a +// consumer of the process-wide socket it shares with the seeder's own client, +// with a reconnect loop behind it. Each failed poll leaked one: the socket +// outlived every client that was destroyed, and with it the process. And a +// tracker that never answers no longer holds the poll forever. +export const scrapeTracker: ScrapeFn = (announce, infoHashes, timeoutMs: number = SCRAPE_TIMEOUT_MS) => new Promise((resolve, reject) => { if (infoHashes.length === 0) return resolve(new Map()); - TrackerClient.scrape({ announce, infoHash: infoHashes }, (err, data) => { - if (err) return reject(err); - const rows: ScrapeData[] = - infoHashes.length === 1 ? [data as ScrapeData] : Object.values(data as Record<string, ScrapeData>); - resolve(new Map(rows.map((r) => [r.infoHash, { complete: r.complete, incomplete: r.incomplete }]))); - }); + let settled = false; + let client: TrackerClient | null = null; + const finish = (err: Error | null, value?: Map<string, { complete: number; incomplete: number }>) => { + if (settled) return; + settled = true; + clearTimeout(timer); + // Idempotent: an answered scrape has destroyed it already. + client?.destroy(); + if (err) reject(err); + else resolve(value!); + }; + const timer = setTimeout(() => finish(new Error(`no scrape answer from ${announce} in ${Math.round(timeoutMs / 1000)}s`)), timeoutMs); + try { + client = TrackerClient.scrape({ announce, infoHash: infoHashes }, (err, data) => { + if (err) return finish(err); + const rows: ScrapeData[] = + infoHashes.length === 1 ? [data as ScrapeData] : Object.values(data as Record<string, ScrapeData>); + finish(null, new Map(rows.map((r) => [r.infoHash, { complete: r.complete, incomplete: r.incomplete }]))); + }); + } catch (err) { + finish(err as Error); + } + // A callback that came synchronously ran before `client` was set. + if (settled) client?.destroy(); }); // Several trackers' answers for one torrent → one: the most seeders and the diff --git a/common/testing/jobs/quiesce.ts b/common/testing/jobs/quiesce.ts @@ -0,0 +1,86 @@ +// A TEST'S TEARDOWN, BEFORE IT REMOVES ITS TEMP CORPUS. +// +// A managed job's status reads `done` (registry.finalize) BEFORE the job has +// stopped writing: its `.finally` still flushes the log and rewrites the +// sidecar in `.jobs/`, and its end arms the snapshot scheduler's debounce +// (jobs/snapshotScheduler.ts, ~1 s on the default preset), whose +// refresh-report job then writes `channels/<slug>/snapshot.json` and a job +// of its own. A test that polls the status and then `rm`s its temp dir races +// all of that — `ENOTEMPTY: rmdir …/channels/<slug>` when the regen lands +// mid-removal, which a loaded machine makes likely. +// +// `quiesceJobs` waits until no job is queued or running, the scheduler has no +// regeneration pending or starting (a pending one is fired now, not waited +// out), and every job's sidecar on disk says it ended. `settleJob` waits for +// one job the same way. Both are bounded by a deadline that is a backstop +// against a real hang (it throws, naming what is still live), not a measure +// of how long a job should take. + +import { getRegistry, type JobStatus } from "../../jobs/registry"; +import { stat } from "node:fs/promises"; +import { metaPath, readJobMeta } from "../../jobs/jobMeta"; +import { flushChannelSnapshotsNow } from "../../jobs/snapshotScheduler"; +import { getPaths, type Paths } from "../../lib/paths"; + +const LIVE: ReadonlySet<JobStatus> = new Set<JobStatus>(["queued", "running"]); +const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms)); + +// A job's end is on disk: its sidecar names a terminal status. A job with no +// sidecar at all (a record a test registered by hand) has nothing left to +// write; one mid-rewrite reads as unparseable, which is not ended yet. +async function endedOnDisk(paths: Paths, id: string): Promise<boolean> { + const meta = await readJobMeta(paths, id); + if (meta) return !LIVE.has(meta.status); + try { + await stat(metaPath(paths, id)); + return false; // there, but not readable yet: being rewritten + } catch { + return true; + } +} + +function schedulerBusy(): boolean { + const s = globalThis.__yttSnapshotScheduler__; + return !!s && (s.timer !== null || s.dirty.size > 0 || s.starting.size > 0); +} + +export async function settleJob( + id: string, + opts: { paths?: Paths; timeoutMs?: number } = {}, +): Promise<JobStatus | undefined> { + const paths = opts.paths ?? getPaths(); + const deadline = Date.now() + (opts.timeoutMs ?? 120_000); + for (;;) { + const status = getRegistry().get(id)?.status; + if (status === undefined) return undefined; + if (!LIVE.has(status) && (await endedOnDisk(paths, id))) return status; + if (Date.now() > deadline) throw new Error(`job ${id} still ${status} after ${opts.timeoutMs ?? 120_000} ms`); + await sleep(25); + } +} + +export async function quiesceJobs(opts: { paths?: Paths; timeoutMs?: number } = {}): Promise<void> { + const paths = opts.paths ?? getPaths(); + const timeoutMs = opts.timeoutMs ?? 120_000; + const deadline = Date.now() + timeoutMs; + for (;;) { + // A pending regeneration is fired now and awaited (its stream drained). + await flushChannelSnapshotsNow(); + const jobs = getRegistry().list(); + const live = jobs.filter((j) => LIVE.has(j.status)); + let unwritten: string[] = []; + if (live.length === 0 && !schedulerBusy()) { + const ended = await Promise.all(jobs.map((j) => endedOnDisk(paths, j.id))); + unwritten = jobs.filter((_, i) => !ended[i]).map((j) => j.id); + if (unwritten.length === 0 && !schedulerBusy()) return; + } + if (Date.now() > deadline) { + throw new Error( + `jobs still live after ${timeoutMs} ms: ` + + [...live.map((j) => `${j.kind} ${j.id} ${j.status}`), ...unwritten.map((id) => `${id} (sidecar not terminal)`)].join(", ") + + (schedulerBusy() ? "; a report regeneration is pending" : ""), + ); + } + await sleep(25); + } +} diff --git a/common/testing/seeder/fixture.ts b/common/testing/seeder/fixture.ts @@ -0,0 +1,56 @@ +// The seeder tests' fixture (controller/seeder.test.ts, webrtcScenario.ts): a +// tracker on 127.0.0.1 tracking one synthetic playable torrent, and WebTorrent +// clients that find peers through it and nowhere else. + +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import WebTorrent from "webtorrent"; +import { DEFAULT_SEEDER_SETTINGS, type SeederSettings } from "../../lib/seederSettings"; +import { makePlayableTorrent } from "../../controller/preparePlayable"; +import { startTracker, type SeedTarget } from "../../controller/seeder"; + +export const SEED_ID = "aaaaaaaaaaa"; + +export async function until(pred: () => boolean, ms: number, what: string): Promise<void> { + const t0 = Date.now(); + while (!pred()) { + if (Date.now() - t0 > ms) throw new Error(`timed out waiting for ${what}`); + await new Promise((r) => setTimeout(r, 100)); + } +} + +export const newClient = () => + new WebTorrent({ + dht: false, + lsd: false, + natUpnp: false, + natPmp: false, + utp: false, + webSeeds: false, + tracker: { rtcConfig: { iceServers: [] } }, + }); + +export const destroyClient = (c: WebTorrent) => + c.destroyed ? Promise.resolve() : new Promise<void>((resolve) => c.destroy(() => resolve())); + +export async function seederFixture(trackerUrl: (port: number) => string) { + const dir = await mkdtemp(path.join(tmpdir(), "ttb-seeder-")); + const seedDir = path.join(dir, "playable", "demo", SEED_ID); + await mkdir(seedDir, { recursive: true }); + const bytes = Buffer.from(Array.from({ length: 600_000 }, (_, i) => (i * 13 + 7) & 0xff)); + const file = path.join(seedDir, `${SEED_ID}.mp4`); + await writeFile(file, bytes); + let allowed = new Set<string>(); + const tracker = await startTracker({ host: "127.0.0.1", port: 0, allowed: () => allowed }); + const made = await makePlayableTorrent({ file, name: `${SEED_ID}.mp4`, bytes: bytes.length, trackers: [trackerUrl(tracker.port)] }); + allowed = new Set([made.infoHash]); + const torrentPath = path.join(seedDir, `${SEED_ID}.torrent`); + await writeFile(torrentPath, made.torrent); + const target: SeedTarget = { slug: "demo", id: SEED_ID, infoHash: made.infoHash, torrentPath, file, dir: seedDir, bytes: bytes.length }; + return { dir, bytes, tracker, made, target }; +} + +export function seederSettings(): SeederSettings { + return { ...DEFAULT_SEEDER_SETTINGS, sites: ["demo-site"], maxConnections: 10 }; +} diff --git a/common/testing/seeder/webrtcScenario.ts b/common/testing/seeder/webrtcScenario.ts @@ -0,0 +1,94 @@ +// THE SEEDER'S WEBRTC SCENARIO, RUN AS ITS OWN PROCESS (controller/seeder.test.ts). +// +// A WebSocket tracker on 127.0.0.1, the seeder, and a leecher that reaches it +// over WebRTC (node-datachannel), a few hundred KB of synthetic bytes — the +// test that used to run inside the test file. It runs here because twice, on a +// loaded machine, the file's process did not finish: once it never exited after +// the test passed, once its event loop stopped mid-test (no timer fired for 90 s, +// the test's own timeout among them). What a native WebRTC stack does to its +// process cannot be bounded from inside it; from the parent it can — the +// parent kills this process and fails, saying what it last reported. +// +// Protocol, one line each on stdout: +// RESULT {"ok":true,"wires":[...]} | RESULT {"ok":false,"error":"…"} +// OPEN {"resources":[...],"wsPool":[...]} after the teardown +// STILL-ALIVE {...} 5 s later, only if it has not exited +// It must then exit by itself: everything it opened is closed. + +import { mkdir, readFile, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import WebTorrent from "webtorrent"; +import type { Paths } from "../../lib/paths"; +import { runSeeder } from "../../controller/seeder"; +import { destroyClient, newClient, seederFixture, seederSettings, until } from "./fixture"; + +const say = (tag: string, v: unknown) => process.stdout.write(`${tag} ${JSON.stringify(v)}\n`); + +async function wsPool(): Promise<string[]> { + const dir = path.dirname(fileURLToPath(import.meta.resolve("bittorrent-tracker"))); + const mod = (await import(pathToFileURL(path.join(dir, "lib/client/websocket-tracker.js")).href)) as { + default: { _socketPool: Record<string, unknown> }; + }; + return Object.keys(mod.default._socketPool); +} + +async function main(): Promise<void> { + if (!WebTorrent.WEBRTC_SUPPORT) { + say("RESULT", { ok: true, skipped: "no WebRTC in this node" }); + return; + } + const f = await seederFixture((port) => `ws://127.0.0.1:${port}`); + const ac = new AbortController(); + const log: string[] = []; + const seederClient = newClient(); + const peer = newClient(); + const running = runSeeder({ + paths: {} as Paths, + settings: seederSettings(), + onLog: (l) => log.push(l), + signal: ac.signal, + deps: { + targets: async () => [f.target], + pollMs: 1000, + policy: { standbyAfterSeconds: 3600, resumeAfterSeconds: 3600 }, + client: seederClient, + }, + }); + try { + // The leecher announces AFTER the seeder's announce is in. Two peers whose + // WebSocket offers cross in flight each answer the other's and each keep + // the connection the other dropped — an artefact of starting both in the + // same instant, which a browser arriving at a running seeder does not do. + await until(() => (f.tracker.swarm(f.made.infoHash)?.complete ?? 0) >= 1, 60_000, "the seeder's announce"); + const out = path.join(f.dir, "leech"); + await mkdir(out); + const tor = peer.add(f.made.torrent, { path: out }); + await new Promise<void>((resolve, reject) => { + tor.once("done", () => resolve()); + tor.once("error", reject); + setTimeout(() => reject(new Error(`the leecher did not finish; seeder log: ${log.join(" | ")}`)), 90_000).unref(); + }); + const same = Buffer.compare(await readFile(path.join(out, f.target.id + ".mp4")), f.bytes) === 0; + say("RESULT", same ? { ok: true, wires: tor.wires.map((w) => w.type) } : { ok: false, error: "the leeched bytes differ" }); + } catch (err) { + say("RESULT", { ok: false, error: (err as Error).message }); + } finally { + ac.abort(); + await running.catch(() => {}); + await destroyClient(peer); + await destroyClient(seederClient); + await f.tracker.close(); + await rm(f.dir, { recursive: true, force: true }); + } +} + +await main(); +say("OPEN", { resources: process.getActiveResourcesInfo(), wsPool: await wsPool() }); +setTimeout(() => { + const handles = (process as unknown as { _getActiveHandles(): unknown[] })._getActiveHandles().map((h) => { + const o = h as { constructor?: { name?: string }; remoteAddress?: string; remotePort?: number; localPort?: number }; + return [o.constructor?.name, o.remoteAddress, o.remotePort, o.localPort].filter((x) => x !== undefined).join(" "); + }); + say("STILL-ALIVE", { resources: process.getActiveResourcesInfo(), handles }); +}, 5000).unref(); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,19 @@ # Changelog ## [Unreleased] +- **umtool: a `take --priority` or `render-mode on -- …` signalled while it turns render mode on lets it go before it exits.** + The signal handlers used to go on only after the claim (the state file and the editor's lanes, held over HTTP), so a + signal in that time killed the process with its hold and its lanes left for the heartbeat to find. Now the claim + finishes, is released, and the process exits 128+signal; the take's work never starts. +- **umtool: `umtool queue wait` and `status` no longer call a step failed in the moment after it exits.** Between the + step's exit and the runner writing its end, a reader saw "the step's process is gone", so `queue wait` could exit 1 + on a step that then read done. A step whose runner is alive is running until that runner records its end; the + runner's start time is now recorded on the step, so a reused pid is not taken for it. + - The queue lock is no longer broken while another process is writing its pid into it (an empty lock file is + waited for; one empty for 5 s is a dead holder's). +- **Seeder: a scrape that fails no longer leaks a tracker client.** On an error or a warning, bittorrent-tracker's + scrape left its client alive, sharing the WebSocket tracker's socket and reconnecting forever. Every outcome now + destroys it, and a tracker that does not answer in 20 s is given up on for that poll. - **umtool: parts of a recording's picture can be hidden on every clip of it.** This covers things like a stream layout's chat overlay or a window showing other people's accounts. - `render.censor` (`umtool censor <p> --video <id> --box x,y,w,h[@from-to]`, or the clip editor's diff --git a/editor/app/api/media/fetch-window/route.remote.test.ts b/editor/app/api/media/fetch-window/route.remote.test.ts @@ -62,7 +62,14 @@ globalThis.fetch = (async (input: RequestInfo | URL) => { return url in DOCS ? new Response(JSON.stringify(DOCS[url]), { status: 200 }) : new Response("nope", { status: 404 }); }) as typeof fetch; const { POST } = await import("./route"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its sidecar, and the +// report regeneration it arms — snapshot.json in the channel dir): waited for +// before the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const post = async (body: Record<string, unknown>) => { const res = await POST( @@ -112,7 +119,6 @@ test("a page URL two parsers read differently is refused (400) before any reques }); test("what reaches yt-dlp is the URL the check parsed, written back — never the record's own string", async () => { - const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const res = await POST( new Request("http://localhost/api/media/fetch-window", { method: "POST", @@ -122,12 +128,8 @@ test("what reaches yt-dlp is the URL the check parsed, written back — never th ); const body = (await res.json()) as { jobId?: string; error?: string }; assert.equal(res.status, 202, body.error); - const reg = getRegistry(); - for (let i = 0; i < 200; i++) { - const s = reg.get(body.jobId!)?.status; - if (s !== "queued" && s !== "running") break; - await new Promise((r) => setTimeout(r, 50)); - } + // The job's end, its sidecar written: bounded by the job, not by 200 polls a loaded machine outlasts. + await settleJob(body.jobId!); const runs = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]); assert.ok(runs.length > 0, "yt-dlp was asked"); for (const args of runs) { diff --git a/editor/app/api/media/fetch-window/route.storedUrl.test.ts b/editor/app/api/media/fetch-window/route.storedUrl.test.ts @@ -80,7 +80,14 @@ await video("n1", false); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +// The jobs' ends still write after their status reads done — the sidecars, and +// the report regeneration each end arms (snapshot.json in the channel dir): all +// of it is waited for before the corpus is removed. +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); function post(body: Record<string, unknown>): Promise<Response> { return POST( @@ -101,15 +108,9 @@ const targets = async () => .filter(Boolean) .map((l) => (JSON.parse(l) as string[]).at(-1)); -async function settle(jobId: string): Promise<string | undefined> { - const reg = getRegistry(); - for (let i = 0; i < 200; i++) { - const s = reg.get(jobId)?.status; - if (s !== "queued" && s !== "running") break; - await new Promise((res) => setTimeout(res, 50)); - } - return reg.get(jobId)?.status; -} +// The job's end, its sidecar written — bounded by the job's own end, not a +// fixed number of polls a loaded machine can outlast. +const settle = (jobId: string) => settleJob(jobId); test("a storedUrl that is not a mode is refused with 400", async () => { const res = await ask("s1", { storedUrl: "always" }); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts @@ -65,7 +65,14 @@ const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { recordDownloadBackoff } = await import("yt-dlp-transcript-common/jobs/downloadBackoff"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); await recordDownloadBackoff("youtube", getPaths()); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its sidecar, and the +// report regeneration it arms — snapshot.json in the channel dir): waited for +// before the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const items = [ { slug: SLUG, id: "held1", from: 1, to: 3, clipId: "r#1" }, @@ -100,11 +107,8 @@ test("a real run cuts the held window in a saved-video job while the cooling pla assert.deepEqual(r.refused.map((x) => x.platform), ["youtube"]); const jobId = r.jobs[0].jobId; const reg = getRegistry(); - for (let i = 0; i < 200; i++) { - const s = reg.get(jobId)?.status; - if (s !== "queued" && s !== "running") break; - await new Promise((res) => setTimeout(res, 50)); - } + // The job's end, its sidecar written: bounded by the job, not by 200 polls a loaded machine outlasts. + await settleJob(jobId); assert.equal(reg.get(jobId)?.status, "done", `job ${jobId}: ${reg.get(jobId)?.status}`); assert.deepEqual((await readdir(path.join(HELD, "clips"))).sort(), ["1.00-3.00.json", "1.00-3.00.mp4"]); const sidecar = JSON.parse(await readFile(path.join(HELD, "clips", "1.00-3.00.json"), "utf8")); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts @@ -78,7 +78,14 @@ const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { recordDownloadBackoff } = await import("yt-dlp-transcript-common/jobs/downloadBackoff"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); await recordDownloadBackoff("odysee", getPaths()); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its sidecar, and the +// report regeneration it arms — snapshot.json in the channel dir): waited for +// before the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const items = [ { slug: SLUG, id: "s1", from: 1, to: 3, clipId: "r#1" }, @@ -123,11 +130,8 @@ test("only: the window with a stored URL runs on clips:odysee and is cut from it assert.match(r.refused[0].error, /cooldown.*\(1 window\(s\) with no stored media URL; 1 cut from the stored URL\)/); const jobId = r.jobs[0].jobId; const reg = getRegistry(); - for (let i = 0; i < 200; i++) { - const s = reg.get(jobId)?.status; - if (s !== "queued" && s !== "running") break; - await new Promise((res) => setTimeout(res, 50)); - } + // The job's end, its sidecar written: bounded by the job, not by 200 polls a loaded machine outlasts. + await settleJob(jobId); assert.equal(reg.get(jobId)?.status, "done", `job ${jobId}: ${reg.get(jobId)?.status}`); assert.equal(reg.get(jobId)?.spec?.params?.storedUrl, "only", "a Retry keeps the mode"); assert.deepEqual(await targets(), [cdn("s1")], "no page request"); diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -81,10 +81,16 @@ function runLock(args, env = {}) { } // Resolves once `check()` is true (a holder.json written: a run has acquired). -async function until(check, ms = 10_000) { +// The deadline is a backstop against a run that never gets there, not a +// measure: what it waits on is a fresh node process starting, loading +// queue-lock.mjs and spawning flock, which took over 10 s (the old deadline) +// under a full test:scripts run beside a render. Every wait in queue-lock +// itself is flock blocking in the kernel or a poll (HEAVY_POLL_MS), so a slow +// start is late, never lost. +async function until(check, ms = 120_000) { const t0 = Date.now(); while (!check()) { - if (Date.now() - t0 > ms) throw new Error("timed out waiting"); + if (Date.now() - t0 > ms) throw new Error(`timed out waiting (${ms} ms)`); await delay(20); } } @@ -108,7 +114,7 @@ function markerCmd(logFile, id, holdMs) { // the second run sometimes started after the first had already ended.) The // cap keeps a run that should have been admitted, and was not, from hanging // the test: it ends, and the order assertion names what went wrong. -function gateCmd(logFile, id, gateFile, maxMs = 20_000) { +function gateCmd(logFile, id, gateFile, maxMs = 120_000) { return [ process.execPath, "-e", diff --git a/umtool/lib/queue/store.mjs b/umtool/lib/queue/store.mjs @@ -22,7 +22,7 @@ // // step: { qid, seq, label, argv, cwd, after, target: { project, take } | null, // state, createdAt, by, startedAt, endedAt, exitCode, signal, pid, pidStart, -// host, runnerPid, jobId, attempts, error, blockedBy, cancelRequested, timeoutMin } +// host, runnerPid, runnerStart, jobId, attempts, error, blockedBy, cancelRequested, timeoutMin } // // state queued waits for its turn (and for `after`, when it names a step) // running the app's runner started it (its pid is the step's process) @@ -30,6 +30,8 @@ // failed a non-zero exit or a signal -- or the app died while it ran: a // running step the runner does not hold and whose process is gone // reads, and is then written, failed ("the step's process is gone"). +// (Not while the runner that started it is alive: a step whose +// process has just exited is running until that runner records its end.) // It is NEVER re-run on its own: `umtool queue retry <qid>` does that. // blocked `after` names a step that failed, was cancelled or is blocked; // `blockedBy` and `error` say which and why. A retry of that step @@ -113,9 +115,14 @@ export async function withQueueLock(dir, fn, { timeoutMs = 15_000 } = {}) { break; } catch (err) { if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") throw err; - const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch(() => ""); + const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch(() => null); + if (text === null) continue; // released meanwhile: try again const [pid, host, at] = text.trim().split(" "); - const stale = (host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || !text; + // An EMPTY lock is one another process has created and not yet written + // its pid into (open, then write): it was broken at once, and both held + // the lock. It is a dead holder's only once it has stayed empty a while. + const emptyFor = text ? 0 : await stat(/* turbopackIgnore: true */ file).then((st) => Date.now() - st.mtimeMs, () => 0); + const stale = (host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || emptyFor > 5_000; if (stale) { await unlink(file).catch(() => {}); continue; @@ -151,12 +158,26 @@ const putStep = (dir, step) => writeJson(stepFile(dir, step.qid), step); * runner (`owned`), its process gone -> failed. Pure but for `alive`. * * @param {Record<string, any>} step - * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean, owned?: Set<string> }} [o] + * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean, owned?: Set<string>, self?: number | null }} [o] */ -export function resolveStep(step, { host = os.hostname(), alive = processAlive, owned = new Set() } = {}) { +export function resolveStep(step, { host = os.hostname(), alive = processAlive, owned = new Set(), self = null } = {}) { if (step.state !== "running" || owned.has(step.qid)) return step; if (step.host && step.host !== host) return step; if (step.pid && alive(Number(step.pid), step.pidStart ?? null)) return step; + // Its process has exited and the runner that started it is alive — and is + // not the reader: the runner is recording the end (the log's tail, under the + // lock) and the step is running until it has. A reader used to call it + // failed in that moment ("the process is gone"), so `queue wait` could exit 1 + // on a step that then read done. Only a runner whose start time was recorded + // counts (a reused pid is not the runner); the runner itself (`self`) knows + // what it holds, so one it does not hold is gone. + if ( + step.pid && + step.runnerPid && + step.runnerStart != null && + Number(step.runnerPid) !== self && + alive(Number(step.runnerPid), step.runnerStart) + ) return step; // Marked running a moment ago, its pid not written yet, by a runner that is alive: running. if (!step.pid && step.runnerPid && alive(Number(step.runnerPid)) && Date.now() - Date.parse(step.startedAt ?? 0) < 30_000) return step; // A step marked running whose process never started (the app died between the @@ -375,6 +396,7 @@ async function markStarted(dir, step, { pid, runnerPid, jobId, now }) { pidStart: pid ? procStartTime(pid) : null, host: os.hostname(), runnerPid, + runnerStart: runnerPid ? procStartTime(runnerPid) : null, jobId: jobId ?? null, attempts: (step.attempts ?? 0) + 1, error: null, @@ -476,7 +498,7 @@ export async function queueTick(dir, exec, state) { const owned = new Set(state.held.keys()); // Recovery: a running step this runner does not hold, its process gone, is failed -- never re-run. for (const s of steps) { - const r = resolveStep(s, { owned, alive }); + const r = resolveStep(s, { owned, alive, self: runnerPid }); if (r !== s && r.state === "failed") { Object.assign(s, { state: "failed", endedAt: now().toISOString(), error: r.error, exitCode: null }); await putStep(dir, s); diff --git a/umtool/lib/queue/store.test.mjs b/umtool/lib/queue/store.test.mjs @@ -24,7 +24,9 @@ import { retryStep, stepExitCode, stepFile, + withQueueLock, } from "./store.mjs"; +import { procStartTime } from "../report/renderRecord.mjs"; import { queueCommand, takeStatus } from "./cli.mjs"; const tmp = () => mkdtemp(path.join(os.tmpdir(), "umtool-queue-")); @@ -59,8 +61,9 @@ function spawnExec({ busy = () => null } = {}) { }; } -/** Run turns until no step is queued or running (or the deadline). */ -async function drain(dir, exec, state, { ms = 15_000 } = {}) { +/** Run turns until no step is queued or running (or the deadline: a backstop against a + * queue that never drains, not a measure — a loaded machine took 15 s for five 60 ms steps). */ +async function drain(dir, exec, state, { ms = 120_000 } = {}) { const until = Date.now() + ms; for (;;) { await queueTick(dir, exec, state); @@ -222,6 +225,72 @@ test("restart recovery: a running step whose process is gone is failed with its } }); +test("a step whose process has exited reads running while its runner is alive and records the end", () => { + // What a reader saw between the step's exit and the runner's write of its end + // (the log's tail, the lock) on a loaded machine: running on disk, pid gone. + // It read failed ("the process is gone"), so `queue wait` exited 1 and the + // runner then wrote done. + const dead = Number(spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"], { encoding: "utf8" }).stdout); + const step = { qid: "q1", seq: 1, state: "running", pid: dead, pidStart: null, host: os.hostname(), runnerPid: process.pid, runnerStart: procStartTime(process.pid), startedAt: new Date().toISOString() }; + assert.equal(resolveStep(step).state, "running", "a reader: its runner is alive"); + assert.equal(resolveStep(step, { self: process.pid }).state, "failed", "the runner itself, not holding it: gone"); + assert.equal(resolveStep({ ...step, runnerStart: procStartTime(process.pid) + 1 }).state, "failed", "a reused pid is not the runner"); + assert.equal(resolveStep({ ...step, runnerStart: null }).state, "failed", "a record with no runner start reads as before"); + assert.equal(resolveStep({ ...step, runnerPid: dead }).state, "failed", "its runner gone too: failed"); +}); + +test("the runner records its own start; a step it ran ends done to a reader that raced its end", async () => { + const dir = await tmp(); + try { + const a = await addStep(dir, { argv: js("0"), label: "quick" }); + const state = { held: new Map() }; + // The end is held back: onEnd waits until the reader has looked. + let release = () => {}; + const gate = new Promise((r) => (release = r)); + const base = spawnExec(); + const exec = { ...base, start: (step, o) => base.start(step, { ...o, onEnd: (end) => void gate.then(() => o.onEnd(end)) }) }; + await queueTick(dir, exec, state); + const running = await getStep(dir, a.qid); + assert.equal(running?.runnerPid, process.pid); + assert.equal(running?.runnerStart, procStartTime(process.pid)); + // The process exits; its end is not written yet. A reader (no runner) looks. + const exited = () => { + try { + process.kill(Number(running?.pid), 0); + return false; + } catch { + return true; + } + }; + assert.ok(running?.pid, "its pid is written"); + for (let i = 0; i < 6000 && !exited(); i += 1) await sleep(10); + assert.equal(resolveStep(/** @type {any} */ (await getStep(dir, a.qid))).state, "running", "not failed: its runner has not recorded the end"); + release(); + const steps = await drain(dir, exec, state); + assert.equal(steps.find((s) => s.qid === a.qid)?.state, "done"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the queue lock: an empty lock file is one being written, not a dead holder's", async () => { + const dir = await tmp(); + try { + await withQueueLock(dir, async () => {}); // makes the dirs + const lock = path.join(dir, ".lock"); + await writeFile(lock, ""); + // Fresh and empty: another process has created it and not yet written its pid. Waited for, not broken. + await assert.rejects(withQueueLock(dir, async () => "mine", { timeoutMs: 300 }), /the queue is locked/); + // Empty for long: whoever made it is gone. Broken. + const old = new Date(Date.now() - 60_000); + const { utimes } = await import("node:fs/promises"); + await utimes(lock, old, old); + assert.equal(await withQueueLock(dir, async () => "mine", { timeoutMs: 300 }), "mine"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("the lease: one runner per queue dir; a dead holder's lease is taken", async () => { const dir = await tmp(); try { diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs @@ -109,24 +109,13 @@ export async function withRenderHold(o, fn) { const env = o.env ?? process.env; const file = o.file ?? renderModeFile(env); const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env)); - const on = await renderModeOn({ - file, - holder: o.holder, - by: o.by, - forMs: o.forMs ?? null, - note: o.note ?? null, - editor: lanes ? editorConfig(env).url : null, - lanes, - ...(o.token ? { token: o.token } : {}), - }); - if (!on.ok || !on.state) return { ran: false, held: on.held ?? null }; - const token = on.state.token; - env[RENDER_PRIORITY_TOKEN_ENV] = token; - o.onLine?.(on.state); - + /** @type {string | null} the claimed hold's token, once the claim is in */ + let token = null; let ended = false; + /** @type {NodeJS.Signals | null} */ + let signalled = null; const end = async () => { - if (ended) return; + if (ended || token === null) return; ended = true; if (env[RENDER_PRIORITY_TOKEN_ENV] === token) delete env[RENDER_PRIORITY_TOKEN_ENV]; try { @@ -141,28 +130,74 @@ export async function withRenderHold(o, fn) { }; // A signal ends the hold before this process goes (the job runner's Cancel // signals the group; Ctrl-C the same). Then exit as the signal would. + // + // THE HANDLERS GO ON BEFORE THE CLAIM. The claim writes the state file and + // holds the editor's lanes over HTTP (seconds, on a loaded machine); a signal + // in that time used to take Node's default action — this process gone, its + // hold and its lanes left for the heartbeat to find. Now a signal at any + // point waits for the claim to settle, ends what it claimed, then exits; + // `fn` is never started after one. + /** @type {Promise<any>} */ + let claim = Promise.resolve(null); /** @type {Array<[NodeJS.Signals, () => void]>} */ const handlers = []; if (o.signals !== false) { for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) { const h = () => { const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[sig] ?? 0); + signalled ??= sig; try { o.onSignal?.(sig); } catch { /* the child is gone already */ } setTimeout(() => process.exit(code), 10_000).unref(); - void end().finally(() => process.exit(code)); + void claim + .catch(() => null) + .then(() => end()) + .finally(() => process.exit(code)); }; handlers.push([sig, h]); process.on(sig, h); } } + const unhook = () => { + for (const [sig, h] of handlers) process.off(sig, h); + }; + claim = renderModeOn({ + file, + holder: o.holder, + by: o.by, + forMs: o.forMs ?? null, + note: o.note ?? null, + editor: lanes ? editorConfig(env).url : null, + lanes, + ...(o.token ? { token: o.token } : {}), + }).then((on) => { + // Set here, so a handler's continuation of the claim (chained later) sees it. + if (on.ok && on.state) token = on.state.token; + return on; + }); + let on; + try { + on = await claim; + } catch (e) { + unhook(); + throw e; + } + // Signalled while claiming: the handler ends the hold and exits; nothing starts. + if (signalled) return new Promise(() => {}); + if (!on.ok || !on.state) { + unhook(); + return { ran: false, held: on.held ?? null }; + } + env[RENDER_PRIORITY_TOKEN_ENV] = /** @type {string} */ (token); + o.onLine?.(on.state); + try { - return { ran: true, value: await fn(token) }; + return { ran: true, value: await fn(/** @type {string} */ (token)) }; } finally { - for (const [sig, h] of handlers) process.off(sig, h); + unhook(); await end(); } } diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs @@ -80,7 +80,13 @@ test("take --priority: a failed take lets go too", async () => { assert.equal(existsSync(file), false); }); -test("take --priority killed by a signal: the hold ends before the process does", async () => { +/** + * A `take --priority` in a child process over fake lanes that log to a file. + * `slowLane`: that lane's hold prints `holding <lane>` and takes 400 ms — a + * signal sent then lands mid-claim. The child is killed whatever the test does + * (`stop`), so a failed assertion cannot leave it holding the runner open. + */ +function spawnTake({ slowLane = null } = {}) { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-sig-")); const file = path.join(dir, "state.json"); const log = path.join(dir, "lanes.log"); @@ -89,29 +95,85 @@ test("take --priority killed by a signal: the hold ends before the process does" script, `import { appendFileSync } from "node:fs"; import { withTakePriority } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))}; +const slow = ${JSON.stringify(slowLane)}; const lanes = { isHeld: async () => false, - hold: async (l) => appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"), + hold: async (l) => { + appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"); + if (l === slow) { + console.log("holding " + l); + await new Promise((r) => setTimeout(r, 400)); + } + }, release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"), }; -await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => console.log(l), env: {}, file: ${JSON.stringify(file)}, lanes }, () => new Promise(() => setInterval(() => {}, 1000))); +await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => console.log(l), env: {}, file: ${JSON.stringify(file)}, lanes }, async () => { + console.log("rendering"); + await new Promise(() => setInterval(() => {}, 1000)); +}); `, ); const child = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] }); let out = ""; child.stdout.on("data", (d) => (out += d)); child.stderr.on("data", (d) => (out += d)); - const t0 = Date.now(); - while (!/render mode on for this take/.test(out)) { - if (Date.now() - t0 > 15_000) throw new Error(`never went on: ${out}`); - await new Promise((r) => setTimeout(r, 20)); + const exited = new Promise((r) => child.on("exit", (c, sig) => r({ code: c, signal: sig }))); + return { + file, + log, + child, + exited, + out: () => out, + // A loaded machine can take many seconds to start node and import the + // module; this is a backstop against a child that never gets there, not + // a measure of how fast it should. + async waitFor(re, ms = 90_000) { + const t0 = Date.now(); + while (!re.test(out)) { + if (child.exitCode !== null || child.signalCode !== null) throw new Error(`exited before ${re}: ${out}`); + if (Date.now() - t0 > ms) throw new Error(`no ${re} after ${ms} ms: ${out}`); + await new Promise((r) => setTimeout(r, 20)); + } + }, + async stop() { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + await exited; + await rm(dir, { recursive: true, force: true }); + }, + }; +} + +test("take --priority killed by a signal: the hold ends before the process does", { timeout: 180_000 }, async () => { + const take = spawnTake(); + try { + await take.waitFor(/render mode on for this take/); + assert.equal(readRenderPriority(take.file).held, true); + take.child.kill("SIGTERM"); + const { code, signal } = await take.exited; + assert.equal(code, 143, `exited ${code ?? signal}: ${take.out()}`); + assert.equal(existsSync(take.file), false); + assert.equal(readFileSync(take.log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); + } finally { + await take.stop(); + } +}); + +test("take --priority signalled while it claims: the claim finishes, is let go, and the take never starts", { timeout: 180_000 }, async () => { + // The window the old order left open: the handlers went on only after the + // claim, so a signal while the lanes were being held killed the process + // with its state file and lanes still held. + const take = spawnTake({ slowLane: "download" }); + try { + await take.waitFor(/holding download/); + take.child.kill("SIGTERM"); + const { code, signal } = await take.exited; + assert.equal(code, 143, `exited ${code ?? signal}: ${take.out()}`); + assert.equal(existsSync(take.file), false, "the state file is gone"); + assert.equal(readFileSync(take.log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); + assert.doesNotMatch(take.out(), /rendering/, "the take's work never started"); + } finally { + await take.stop(); } - assert.equal(readRenderPriority(file).held, true); - child.kill("SIGTERM"); - const code = await new Promise((r) => child.on("exit", (c) => r(c))); - assert.equal(code, 143); - assert.equal(existsSync(file), false); - assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); }); test("a take inside a manual window joins it (flag or not) and leaves it on; beside another render it takes nothing", async () => { @@ -330,7 +392,7 @@ test("render-mode on -- <cmd>: --print-token puts the token alone on stdout; a f assert.equal(await renderModeCommand(["off"], io), 0); }); -test("render-mode on -- <cmd> signalled: the signal reaches the command and the hold ends", async () => { +test("render-mode on -- <cmd> signalled: the signal reaches the command and the hold ends", { timeout: 240_000 }, async () => { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-sig-")); const file = path.join(dir, "state.json"); const log = path.join(dir, "lanes.log"); @@ -353,21 +415,44 @@ process.exit(await renderModeCommand(["on", "--", process.execPath, "-e", child] let out = ""; proc.stdout.on("data", (d) => (out += d)); proc.stderr.on("data", (d) => (out += d)); - const t0 = Date.now(); - while (!/render mode ON for/.test(out) || !existsSync(childLog)) { - if (Date.now() - t0 > 15_000) throw new Error(`never went on: ${out}`); - await new Promise((r) => setTimeout(r, 20)); + const exited = new Promise((r) => proc.on("exit", (c, sig) => r({ code: c, signal: sig }))); + let commandPid = null; + try { + // Backstops, not measures: a loaded machine can take many seconds to start + // two node processes, and as long again for the command to log its TERM. + const t0 = Date.now(); + while (!/render mode ON for/.test(out) || !existsSync(childLog)) { + if (proc.exitCode !== null || proc.signalCode !== null) throw new Error(`exited before it went on: ${out}`); + if (Date.now() - t0 > 90_000) throw new Error(`never went on: ${out}`); + await new Promise((r) => setTimeout(r, 20)); + } + const held = readRenderPriority(file); + assert.equal(held.held, true); + commandPid = held.state.holder.pid; + assert.notEqual(commandPid, proc.pid, "the holder is the command, not umtool"); + proc.kill("SIGTERM"); + const { code, signal } = await exited; + assert.equal(code, 143, `exited ${code ?? signal}: ${out}`); + assert.equal(existsSync(file), false); + assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); + const t1 = Date.now(); + while (!readFileSync(childLog, "utf8").includes("TERM") && Date.now() - t1 < 60_000) await new Promise((r) => setTimeout(r, 20)); + assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal"); + } finally { + // Whatever failed, neither process is left running (the command would + // otherwise outlive the suite, holding nothing but a CPU slot). + if (proc.exitCode === null && proc.signalCode === null) proc.kill("SIGKILL"); + await exited; + // (Only one that never logged its TERM: one that did has exited, and its pid is not ours to signal.) + if (commandPid && !(existsSync(childLog) && readFileSync(childLog, "utf8").includes("TERM"))) { + try { + process.kill(commandPid, "SIGKILL"); + } catch { + /* gone already */ + } + } + await rm(dir, { recursive: true, force: true }); } - const held = readRenderPriority(file); - assert.equal(held.held, true); - assert.notEqual(held.state.holder.pid, proc.pid, "the holder is the command, not umtool"); - proc.kill("SIGTERM"); - const code = await new Promise((r) => proc.on("exit", (c) => r(c))); - assert.equal(code, 143); - assert.equal(existsSync(file), false); - assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); - for (let i = 0; i < 100 && !readFileSync(childLog, "utf8").includes("TERM"); i += 1) await new Promise((r) => setTimeout(r, 20)); - assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal"); }); test("a take started under render-mode on -- … is part of that hold (no 'waits for it')", async () => {