Archilyzer · Source

archilyzer

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

commit 1f63880440d6a104ed4653a39f16526ad8276408
parent 5b10ecfdfd3c4c0054ade5b71b8403b0ab903b18
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 06:42:03 -0500

Flaky-test follow-ups: one release however many signals, a step whose end cannot be written is let go, the queue lock never spins, every job-running test waits for its jobs' writes

- render hold (renderMode.mjs): the release is one memoised promise that every caller awaits. A second signal
  used to find `ended` set and exit at once, cutting the first one's lane release short. The exit code is the
  first signal's, and the finally unhooks only after the release. New test: TERM, then INT during the release.
  It releases once, the state file is gone, and the exit is 143; on the old code it fails.
- queue store: a step's end is recorded through recordEnd, which retries finishStep (3 tries, a 2 s pause) and
  always lets go of the step in a finally. When the write kept failing (the lock's timeout) the step stayed
  held and read running until the app restarted. Now the runner's next turn marks it failed. Tested with a
  write that fails once (done) and one that always fails (failed, process gone).
- withQueueLock: only ENOENT re-tries at once. Another read error (EISDIR, EACCES) is waited on until the
  deadline and named in the error; it used to spin with no sleep. An empty lock whose mtime is 5 s or more in
  the future (the clock stepped back) is stale. Tested; the unreadable-lock test hangs on the old code.
- seeder.test.ts: childExecArgv (testing/seeder/fixture.ts) drops a --test-* flag's value when it is written
  after a space too; unit-tested.
- quiesce is imported as yt-dlp-transcript-common/testing/jobs/quiesce.js. Under moduleResolution bundler,
  TypeScript maps the .js to the .ts through the package's exports, and tsx does the same. A bare `.ts`
  specifier needs allowImportingTsExtensions (TS5097). common/testing/README.md lists jobs/quiesce.ts and
  seeder/*. It also notes that `tsx --test` on a `[slug]` path runs 0 tests and exits 0, and that a bare
  `tsx <file>` is no substitute: it skips the NODE_TEST_CONTEXT guards.
- New `pnpm test:files <pkg> <file>…` (scripts/test-files.mjs, unit-tested) escapes glob characters in a path
  that names a file and fails a run of 0 tests.
- The two stored-URL editor tests name an empty E2E_ODYSEE_PAGE_FIXTURE. Run as a bare `tsx <file>` they had
  the real player-page opener launch headless Chromium on odysee.com.
- quiesceJobs/settleJob in every test whose jobs carry a channel slug and that then removes its corpus:
  whisperFromContainer, ops/{browser-lookup,transcribe-one,fetch-windows,local-media-import,attach-media,
  evict-clips,remote-listing,build-cues,transcribe-bucket,prepare-playable}, _frameScan,
  media/fetch-window/route.test, common mirrorScan and waybackScan. resumeInterrupted's 50x20 ms sidecar poll
  is now settleJob. Several of these read a job's log right after the registry said done, before the log was
  flushed; settleJob waits for the sidecar, which is written after the flush.

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

Diffstat:
Mcommon/controller/mirrorScan.test.ts | 9++++++++-
Mcommon/controller/seeder.test.ts | 12++++++++++--
Mcommon/controller/waybackScan.test.ts | 5+++++
Mcommon/jobs/resumeInterrupted.test.ts | 19++++++++-----------
Mcommon/testing/README.md | 17+++++++++++++++++
Mcommon/testing/seeder/fixture.ts | 18++++++++++++++++++
Meditor/CHANGELOG.md | 7++++++-
Meditor/app/api/media/fetch-window/route.remote.test.ts | 2+-
Meditor/app/api/media/fetch-window/route.storedUrl.test.ts | 8+++++++-
Meditor/app/api/media/fetch-window/route.test.ts | 9++++++++-
Meditor/app/api/ops/_frameScan.test.ts | 5+++++
Meditor/app/api/ops/attach-media/route.test.ts | 15+++++++++------
Meditor/app/api/ops/browser-lookup/route.test.ts | 15+++++++++------
Meditor/app/api/ops/build-cues/route.test.ts | 15+++++++++------
Meditor/app/api/ops/evict-clips/route.test.ts | 15+++++++++------
Meditor/app/api/ops/fetch-windows/route.test.ts | 9++++++++-
Meditor/app/api/ops/local-media-import/route.test.ts | 15+++++++++------
Meditor/app/api/ops/prepare-playable/route.test.ts | 15+++++++++------
Meditor/app/api/ops/remote-listing/route.test.ts | 15+++++++++------
Meditor/app/api/ops/transcribe-bucket/route.test.ts | 9++++++++-
Meditor/app/api/ops/transcribe-one/route.test.ts | 5+++++
Meditor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts | 9++++++++-
Meditor/app/channels/[slug]/videos/fetchWindowsAction.test.ts | 2+-
Meditor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts | 8+++++++-
Mpackage.json | 1+
Ascripts/test-files.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/test-files.test.mjs | 17+++++++++++++++++
Mumtool/lib/queue/store.mjs | 72+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/queue/store.test.mjs | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/renderMode.mjs | 41++++++++++++++++++++++++-----------------
Mumtool/lib/report/renderMode.test.mjs | 30++++++++++++++++++++++++++++--
31 files changed, 428 insertions(+), 97 deletions(-)

diff --git a/common/controller/mirrorScan.test.ts b/common/controller/mirrorScan.test.ts @@ -32,7 +32,14 @@ const PINNED: Record<string, string> = { }; Object.assign(process.env, PINNED); delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; -after(() => rmSync(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("../testing/jobs/quiesce"); +after(async () => { + await quiesceJobs(); + rmSync(ROOT, { recursive: true, force: true }); +}); const { getPaths } = await import("../lib/paths"); const { buildIndex } = await import("./buildIndex"); diff --git a/common/controller/seeder.test.ts b/common/controller/seeder.test.ts @@ -9,7 +9,7 @@ import WebTorrent from "webtorrent"; import type { Paths } from "../lib/paths"; 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"; +import { childExecArgv, 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 // @@ -39,6 +39,14 @@ test("unit: scrape answers merge by max, and an absent interface is absent", () assert.equal(interfacePresent("wg0", { wg0: [{ address: "10.2.0.2", internal: false } as never] }), true); }); +test("unit: a child is started without the test runner's flags, values written with a space included", () => { + const loader = ["--require", "/x/preflight.cjs", "--import", "file:///x/loader.mjs"]; + assert.deepEqual(childExecArgv([...loader, "--test-name-pattern=WebRTC"]), loader); + assert.deepEqual(childExecArgv([...loader, "--test-name-pattern", "WebRTC", "--test-reporter", "tap"]), loader); + assert.deepEqual(childExecArgv(["--test", ...loader, "--test-only", "--experimental-test-coverage"]), loader); + assert.deepEqual(childExecArgv([...loader, "--test-timeout", "5000", "--max-old-space-size=3072"]), [...loader, "--max-old-space-size=3072"]); +}); + test("unconfigured, it refuses to start", async () => { await assert.rejects( runSeeder({ paths: {} as Paths, settings: DEFAULT_SEEDER_SETTINGS, onLog: () => {} }), @@ -173,7 +181,7 @@ test("WebRTC: a peer reaching it through the WebSocket tracker completes (node-d return; } // The same loader this file runs under (tsx), without the test runner's flags. - const execArgv = process.execArgv.filter((a) => !a.startsWith("--test")); + const execArgv = childExecArgv(); const child = spawn(process.execPath, [...execArgv, SCENARIO], { stdio: ["ignore", "pipe", "pipe"] }); const lines: string[] = []; let buf = ""; diff --git a/common/controller/waybackScan.test.ts b/common/controller/waybackScan.test.ts @@ -25,7 +25,12 @@ const { isNewRow } = await import("../lib/waybackPages/scanFile"); const { getRegistry } = await import("../jobs/registry"); const wb = await startFakeWayback({ captures: SCAN_CAPTURES }); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("../testing/jobs/quiesce"); after(async () => { + await quiesceJobs(); await wb.close(); await rm(ROOT, { recursive: true, force: true }); }); diff --git a/common/jobs/resumeInterrupted.test.ts b/common/jobs/resumeInterrupted.test.ts @@ -9,6 +9,7 @@ import type { JobSpec } from "./jobSpec"; import { INTERRUPTED_REASON, settleRunningJobMetas, type RequeueFn } from "./bootQueuedJobs"; import { getRegistry } from "./registry"; import { runManagedFunction } from "./streamCommand"; +import { settleJob } from "../testing/jobs/quiesce"; import { MAX_RESUMES_IN_A_ROW, RESUME_WINDOW_MS, @@ -108,17 +109,13 @@ test("the resumed job carries the chain, and its log opens with what it resumes" assert.equal(record?.resumeCount, 1); const log = await fx.log(newId); assert.match(log.split("\n")[0], /^\[resume\] Resumes refresh-report job R1 on h3, interrupted when the process running it stopped: the channel's report is regenerated\.$/); - // On disk too, for the next boot. - for (let i = 0; i < 50; i++) { - const m = await fx.read(newId).catch(() => null); - if (m?.status === "done") { - assert.equal(m.resumedFrom, "R1"); - assert.equal(m.resumeCount, 1); - return; - } - await new Promise((r) => setTimeout(r, 20)); - } - assert.fail("the resumed job's meta never reached done"); + // On disk too, for the next boot. (`done` settles before the last sidecar + // write lands: waited for by the sidecar, not by 50 polls of 20 ms.) + await settleJob(newId, { paths: fx.paths }); + const m = await fx.read(newId); + assert.equal(m?.status, "done"); + assert.equal(m?.resumedFrom, "R1"); + assert.equal(m?.resumeCount, 1); } finally { await rm(fx.root, { recursive: true, force: true }); } diff --git a/common/testing/README.md b/common/testing/README.md @@ -40,3 +40,20 @@ As committed at S0, the `paragraphs` manifest showed two owed bugs: the title ca the Coverage section became a bare chapter card. Release 27 S7 fixed both and regenerated the files: every title card has `foot: ""`, and a section with nothing to show (Coverage; `posts-only`'s Posts) gets no chapter card. + +## Jobs and the seeder + +| File | What it is | +| --- | --- | +| `jobs/quiesce.ts` | `quiesceJobs()` and `settleJob(id)` for a test that runs managed jobs over a temp corpus. A job's status reads `done` before it stops writing: its log and sidecar, and the report regeneration its end arms, about 1 s later (`channels/<slug>/snapshot.json`). `quiesceJobs` waits for all of it, firing a pending regeneration at once, before the test removes the corpus. `settleJob` waits for one job's end and sidecar. Their deadlines are backstops that throw naming what is still live. Import it as `yt-dlp-transcript-common/testing/jobs/quiesce.js`: TypeScript maps the `.js` to the `.ts` through the package's `exports`, tsx does the same, and `quiesce.ts` would need `allowImportingTsExtensions`. | +| `seeder/fixture.ts` | The seeder tests' tracker, synthetic playable torrent and WebTorrent clients (`seederFixture`, `newClient`, `destroyClient`, `until`), and `childExecArgv()`: this process's flags without the test runner's, a value written after a space included. | +| `seeder/webrtcScenario.ts` | The WebRTC seed-and-leech scenario as its own process. `controller/seeder.test.ts` runs it and reads its `RESULT`, `OPEN` and `STILL-ALIVE` lines. The child must report every tracker socket closed and exit by itself, or the parent kills it and fails saying what it last reported. | + +**A test file under a `[slug]` directory, run by path, runs nothing.** `tsx --test <path>` reads each path as a +glob, so `[slug]` is a character class: no file matches, 0 tests run, and the run exits 0. The package's own +`test` script is unaffected (its `app/**/*.test.ts` walks into the directory). For a few files by path, use +`pnpm test:files <package> <file>…` (`scripts/test-files.mjs`): it escapes the path and fails a run of 0 +tests. **Do not run a test file with a bare `tsx <file>` instead.** It runs, but outside the test runner +`NODE_TEST_CONTEXT` is unset, and guards keyed on it are off. Under it the Odysee player-page opener +(`ytdlp/storedUrlPageOpen.ts`) launches headless Chromium on odysee.com. The two stored-URL editor tests now +name an empty `E2E_ODYSEE_PAGE_FIXTURE`, which keeps it closed whichever way they run. diff --git a/common/testing/seeder/fixture.ts b/common/testing/seeder/fixture.ts @@ -54,3 +54,21 @@ export async function seederFixture(trackerUrl: (port: number) => string) { export function seederSettings(): SeederSettings { return { ...DEFAULT_SEEDER_SETTINGS, sites: ["demo-site"], maxConnections: 10 }; } + +// The flags a child of a test file should run with: this process's (the tsx +// loader), less the test runner's own — `--test-name-pattern=x` and +// `--test-name-pattern x` alike (the value too). The flags that take no value +// are named; every other `--test-*` written without `=` takes the next word. +const TEST_FLAGS_WITHOUT_VALUE = new Set(["--test", "--test-only", "--test-force-exit", "--test-update-snapshots"]); +export function childExecArgv(execArgv: readonly string[] = process.execArgv): string[] { + const out: string[] = []; + for (let i = 0; i < execArgv.length; i += 1) { + const a = execArgv[i]; + if (!a.startsWith("--test") && !a.startsWith("--experimental-test")) { + out.push(a); + continue; + } + if (!a.includes("=") && !TEST_FLAGS_WITHOUT_VALUE.has(a) && !a.startsWith("--experimental-test") && i + 1 < execArgv.length && !execArgv[i + 1].startsWith("-")) i += 1; + } + return out; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -5,12 +5,17 @@ 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. + - A second signal (Ctrl-C twice) waits for the first one's release instead of cutting it off, and the exit + code is the first signal's. - **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). + waited for; one empty for 5 s is a dead holder's, and so is one whose time is 5 s ahead, after the clock was + stepped back). A lock file that cannot be read is waited for until the timeout, never spun on. + - A step whose end cannot be written (the lock's timeout) is retried twice. If it still fails, the runner lets + go of the step and its next turn marks it failed. Before, the step read running until the app restarted. - **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. diff --git a/editor/app/api/media/fetch-window/route.remote.test.ts b/editor/app/api/media/fetch-window/route.remote.test.ts @@ -65,7 +65,7 @@ const { POST } = await import("./route"); // 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"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); diff --git a/editor/app/api/media/fetch-window/route.storedUrl.test.ts b/editor/app/api/media/fetch-window/route.storedUrl.test.ts @@ -51,6 +51,12 @@ process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.YTDLP_BIN = YTDLP; process.env.FFMPEG_BIN = FFMPEG; +// NO BROWSER, HOWEVER THIS FILE IS RUN. The real player-page opener stays off +// under `node --test` (NODE_TEST_CONTEXT), but a bare `tsx <file>` sets no such +// thing, and this file's stored-URL cuts then opened odysee.com in headless +// Chromium. With a (empty) page fixture named, the opener opens nothing. +process.env.E2E_ODYSEE_PAGE_FIXTURE = path.join(ROOT, "odysee-pages.json"); +await writeFile(process.env.E2E_ODYSEE_PAGE_FIXTURE, "{}"); // The fallback's pause, as on the e2e server. process.env.E2E_CLIP_WINDOW_GAP_MS = "0"; await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); @@ -80,7 +86,7 @@ await video("n1", false); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); // 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. diff --git a/editor/app/api/media/fetch-window/route.test.ts b/editor/app/api/media/fetch-window/route.test.ts @@ -27,7 +27,14 @@ await writeFile( JSON.stringify({ name: "Demo", handling: "youtube", url: "https://www.youtube.com/@demo" }), ); 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 log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); function post(body: Record<string, unknown>): Promise<Response> { return POST( diff --git a/editor/app/api/ops/_frameScan.test.ts b/editor/app/api/ops/_frameScan.test.ts @@ -57,7 +57,12 @@ before(async () => { gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 } }); }); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); after(async () => { + await quiesceJobs(); await api.close(); await rm(tmp, { recursive: true, force: true }); }); diff --git a/editor/app/api/ops/attach-media/route.test.ts b/editor/app/api/ops/attach-media/route.test.ts @@ -19,7 +19,14 @@ process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const CH = path.join(ROOT, "channels"); await mkdir(path.join(CH, "tism", "data", "aaaaaaaaaaa"), { recursive: true }); @@ -76,11 +83,7 @@ test("a dry run is a job whose log classifies the archive and writes nothing", a const r = await post({ slug: "tism", source: ZIP, fillDates: true, dryRun: true }); assert.equal(r.status, 200, JSON.stringify(r.json)); assert.ok(r.json.jobId); - for (let i = 0; i < 100; i++) { - const status = getRegistry().get(r.json.jobId!)?.status; - if (status === "done" || status === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(r.json.jobId!); assert.equal(getRegistry().get(r.json.jobId!)?.status, "done"); const log = await readFile(path.join(getPaths().jobsDir, `${r.json.jobId}.log`), "utf8"); const summary = JSON.parse(log.split("\n").find((l) => l.startsWith("summary: "))!.slice("summary: ".length)); diff --git a/editor/app/api/ops/browser-lookup/route.test.ts b/editor/app/api/ops/browser-lookup/route.test.ts @@ -58,7 +58,14 @@ await writeFile( const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); function post(body: Record<string, unknown>): Promise<Response> { return POST( @@ -72,11 +79,7 @@ function post(body: Record<string, unknown>): Promise<Response> { async function settle(jobId: string): Promise<string | undefined> { const reg = getRegistry(); - for (let i = 0; i < 400; i++) { - const s = reg.get(jobId)?.status; - if (s !== "queued" && s !== "running") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); return reg.get(jobId)?.status; } diff --git a/editor/app/api/ops/build-cues/route.test.ts b/editor/app/api/ops/build-cues/route.test.ts @@ -35,7 +35,14 @@ await video(path.join(corpus.transcripts, "channels", "other-yt", "data", "vid00 const { POST } = await import("./route"); const { GET } = await import("../transcript/route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); const exists = (p: string) => stat(p).then(() => true, () => false); test("build-cues refusals: keys, ids, a stray id, a channel that does not exist", async () => { @@ -84,11 +91,7 @@ test("build-cues writes cues.json for the named ids only; transcript then reads const r = await callPost(POST, { slug: "demo-yt", ids: ["vid00000001"] }); assert.equal(r.status, 200, JSON.stringify(r.body)); const jobId = r.body.jobId as string; - for (let i = 0; i < 200; i++) { - const s = getRegistry().get(jobId)?.status; - if (s === "done" || s === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); assert.equal(getRegistry().get(jobId)?.status, "done"); const cues = JSON.parse(await readFile(path.join(DATA, "vid00000001", "transcript.cues.json"), "utf8")); assert.equal(cues.cues.length, 2); diff --git a/editor/app/api/ops/evict-clips/route.test.ts b/editor/app/api/ops/evict-clips/route.test.ts @@ -27,16 +27,19 @@ await window("vid00000002", "10.00-40.00"); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); const exists = (p: string) => stat(p).then(() => true, () => false); const clip = (id: string, name: string) => path.join(DATA, id, "clips", name); async function settle(jobId: string): Promise<string | undefined> { - for (let i = 0; i < 200; i++) { - const s = getRegistry().get(jobId)?.status; - if (s === "done" || s === "failed") return s; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); return getRegistry().get(jobId)?.status; } diff --git a/editor/app/api/ops/fetch-windows/route.test.ts b/editor/app/api/ops/fetch-windows/route.test.ts @@ -17,7 +17,14 @@ process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); 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 log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); // Channels on two platforms, one video each, the YouTube one with a window // already on disk. diff --git a/editor/app/api/ops/local-media-import/route.test.ts b/editor/app/api/ops/local-media-import/route.test.ts @@ -25,7 +25,14 @@ const routes = { "local-media-link": (await import("../local-media-link/route")).POST, }; const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const CH = path.join(ROOT, "transcripts", "channels"); const LIB = path.join(ROOT, "library"); @@ -62,11 +69,7 @@ async function post(action: keyof typeof routes, body: Record<string, unknown>): return { status: res.status, json: (await res.json()) as Json }; } async function waitJob(id: string): Promise<string | undefined> { - for (let i = 0; i < 200; i++) { - const status = getRegistry().get(id)?.status; - if (status === "done" || status === "failed") return status; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(id); return getRegistry().get(id)?.status; } diff --git a/editor/app/api/ops/prepare-playable/route.test.ts b/editor/app/api/ops/prepare-playable/route.test.ts @@ -17,7 +17,14 @@ process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); await mkdir(path.join(ROOT, "channels", "tism", "data", "aaaaaaaaaaa"), { recursive: true }); await writeFile(path.join(ROOT, "channels", "tism", "config.json"), JSON.stringify({ handling: "youtube", name: "tism" })); @@ -54,11 +61,7 @@ test("refusals before any job", async () => { test("a dry run over a channel with no saved containers is a job that says so", async () => { const r = await post({ slug: "tism", dryRun: true, root: path.join(ROOT, "playable"), trackers: ["wss://tracker.example/announce"] }); assert.equal(r.status, 200, JSON.stringify(r.json)); - for (let i = 0; i < 100; i++) { - const s = getRegistry().get(r.json.jobId!)?.status; - if (s === "done" || s === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(r.json.jobId!); assert.equal(getRegistry().get(r.json.jobId!)?.status, "done"); const log = await readFile(path.join(getPaths().jobsDir, `${r.json.jobId}.log`), "utf8"); assert.match(log, /0 video\(s\) with a saved container/); diff --git a/editor/app/api/ops/remote-listing/route.test.ts b/editor/app/api/ops/remote-listing/route.test.ts @@ -26,7 +26,14 @@ await mkdir(path.join(DATA, "imported-elsewhere"), { recursive: true }); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); test("refusals before any job: keys, slug, channel, platform, url", async () => { const cases: [Record<string, unknown>, RegExp][] = [ @@ -49,11 +56,7 @@ test("a listing is a job whose last line is the diff against what is held", asyn const r = await callPost(POST, { slug: "demo-odysee" }); assert.equal(r.status, 200, JSON.stringify(r.body)); const jobId = r.body.jobId as string; - for (let i = 0; i < 200; i++) { - const s = getRegistry().get(jobId)?.status; - if (s === "done" || s === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); const log = await readFile(path.join(getPaths().jobsDir, `${jobId}.log`), "utf8"); assert.equal(getRegistry().get(jobId)?.status, "done", log); const line = log.split("\n").find((l) => l.startsWith("@@remote-listing ")); diff --git a/editor/app/api/ops/transcribe-bucket/route.test.ts b/editor/app/api/ops/transcribe-bucket/route.test.ts @@ -36,7 +36,14 @@ await writeFile(path.join(dir, "audio.mp3"), Buffer.alloc(4096, 1)); const { POST } = await import("./route"); const { getRegistry, newJobId } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); test("ids the stale report does not hold: the report is regenerated, and the job starts", async () => { const registry = getRegistry(); diff --git a/editor/app/api/ops/transcribe-one/route.test.ts b/editor/app/api/ops/transcribe-one/route.test.ts @@ -33,8 +33,13 @@ const POST = (await import("./route")).POST as Post; const { downloadVideoPipelineAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool"); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { getWorkerPool().resumeAll(); + await quiesceJobs(); await corpus.cleanup(); }); diff --git a/editor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts b/editor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts @@ -82,7 +82,14 @@ async function videoWith(id: string, container: string | null | undefined): Prom const { whisperVideoAction } = await import("./videoActions"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); async function ytdlpCalls(): Promise<number> { return (await readFile(YTDLP_LOG, "utf8").catch(() => "")).split("\n").filter(Boolean).length; diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts @@ -68,7 +68,7 @@ await recordDownloadBackoff("youtube", getPaths()); // 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"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts @@ -49,6 +49,12 @@ process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.YTDLP_BIN = YTDLP; process.env.FFMPEG_BIN = FFMPEG; +// NO BROWSER, HOWEVER THIS FILE IS RUN. The real player-page opener stays off +// under `node --test` (NODE_TEST_CONTEXT), but a bare `tsx <file>` sets no such +// thing, and this file's stored-URL cuts then opened odysee.com in headless +// Chromium. With a (empty) page fixture named, the opener opens nothing. +process.env.E2E_ODYSEE_PAGE_FIXTURE = path.join(ROOT, "odysee-pages.json"); +await writeFile(process.env.E2E_ODYSEE_PAGE_FIXTURE, "{}"); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); await writeFile( @@ -81,7 +87,7 @@ await recordDownloadBackoff("odysee", getPaths()); // 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"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); diff --git a/package.json b/package.json @@ -24,6 +24,7 @@ "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", + "test:files": "node scripts/test-files.mjs", "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", diff --git a/scripts/test-files.mjs b/scripts/test-files.mjs @@ -0,0 +1,56 @@ +#!/usr/bin/env node +// Run some test files of a package by path — and fail when none ran. +// +// node scripts/test-files.mjs <package dir> <file> [<file>…] +// pnpm test:files editor "app/channels/[slug]/videos/fetchWindowsAction.test.ts" +// +// `tsx --test <path>` (node's test runner) reads each path as a GLOB, so a +// Next route directory like `[slug]` is a character class: the file matches +// nothing, 0 tests run, and it exits 0 — a green run that tested nothing. Here +// a path that names a file is escaped to match only itself, and a run whose +// summary says 0 tests is a failure. +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +/** A path written so node's test-runner glob matches exactly that file. */ +export function literalGlob(p) { + return p.replace(/[[*?{}()+@]/g, (c) => `[${c}]`); +} + +/** The top-level `# tests N` of a TAP run, or null when there is none. */ +export function testsRan(tap) { + const all = [...tap.matchAll(/^# tests (\d+)$/gm)]; + return all.length ? Number(all.at(-1)[1]) : null; +} + +async function main(argv) { + const [pkg, ...files] = argv; + if (!pkg || files.length === 0) { + process.stderr.write("usage: node scripts/test-files.mjs <package dir> <test file> [<test file>…]\n"); + return 2; + } + const cwd = path.resolve(ROOT, pkg); + const args = files.map((f) => (fs.existsSync(path.resolve(cwd, f)) ? literalGlob(f) : f)); + const tsx = path.join(ROOT, "node_modules", ".bin", "tsx"); + const child = spawn(tsx, ["--test", ...args], { cwd, stdio: ["ignore", "pipe", "inherit"] }); + let out = ""; + child.stdout.on("data", (d) => { + out += d; + process.stdout.write(d); + }); + const code = await new Promise((r) => child.on("close", (c) => r(c ?? 1))); + const ran = testsRan(out); + if (code === 0 && !ran) { + process.stderr.write(`test-files: no test ran (${ran === null ? "no summary" : "0 tests"}) — check the paths: ${files.join(" ")}\n`); + return 1; + } + return code; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + process.exit(await main(process.argv.slice(2))); +} diff --git a/scripts/test-files.test.mjs b/scripts/test-files.test.mjs @@ -0,0 +1,17 @@ +// scripts/test-files.mjs: a test file named by a path with glob characters +// ([slug]) runs, and a run of nothing fails. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { literalGlob, testsRan } from "./test-files.mjs"; + +test("a Next route path is escaped to match only itself", () => { + assert.equal(literalGlob("app/channels/[slug]/videos/a.test.ts"), "app/channels/[[]slug]/videos/a.test.ts"); + assert.equal(literalGlob("app/(group)/x?.test.ts"), "app/[(]group[)]/x[?].test.ts"); + assert.equal(literalGlob("lib/plain.test.ts"), "lib/plain.test.ts"); +}); + +test("the run's own summary is what counts, and 0 is no run", () => { + assert.equal(testsRan("TAP version 13\n# tests 0\n# pass 0\n"), 0); + assert.equal(testsRan("ok 1 - x\n # tests 9\n# tests 4\n# pass 4\n"), 4); + assert.equal(testsRan("nothing here"), null); +}); diff --git a/umtool/lib/queue/store.mjs b/umtool/lib/queue/store.mjs @@ -115,19 +115,36 @@ 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(() => null); - if (text === null) continue; // released meanwhile: try again - const [pid, host, at] = text.trim().split(" "); + /** @type {NodeJS.ErrnoException | null} */ + let readError = null; + const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch((e) => { + if (e?.code === "ENOENT") return null; + readError = e; + return null; + }); + if (text === null && !readError) continue; // released meanwhile: try again + // A lock that cannot be read (EACCES, EIO…) is waited for up to the + // deadline like a held one — never spun on, never broken. + const [pid, host, at] = (text ?? "").trim().split(" "); // 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; + // the lock. It is a dead holder's only once it has stayed empty a while — + // either way: an mtime in the future is a clock stepped back. + const emptyFor = text === "" ? await stat(/* turbopackIgnore: true */ file).then((st) => Date.now() - st.mtimeMs, () => 0) : 0; + const stale = + text !== null && + ((host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || Math.abs(emptyFor) > 5_000); if (stale) { await unlink(file).catch(() => {}); continue; } - if (Date.now() > deadline) throw new Error(`the queue is locked by pid ${pid} (${file})`); + if (Date.now() > deadline) { + throw new Error( + readError + ? `the queue lock cannot be read (${/** @type {NodeJS.ErrnoException} */ (readError).code ?? readError}) (${file})` + : `the queue is locked by pid ${pid} (${file})`, + ); + } await sleep(25 + Math.random() * 50); } } @@ -483,7 +500,9 @@ export async function releaseLease(dir, { pid = process.pid } = {}) { * @param {{ busy: () => string | null, start: (step: any, o: { logFile: string, onEnd: (end: any) => void }) => { pid: number | null, jobId?: string | null, cancel: () => void }, * describe?: (step: any) => Promise<string | null> }} exec * @param {{ held: Map<string, any>, now?: () => Date, runnerPid?: number, alive?: (pid: number, start?: number | null) => boolean, - * onChange?: () => void }} state + * onChange?: () => void, + * endWrite?: { tries?: number, pauseMs?: number, before?: (qid: string, attempt: number) => void | Promise<void> } }} state + * `endWrite`: how recording a step's end is retried (`before`, a test's fault, runs ahead of each try) * @returns {Promise<{ started: string | null, recovered: string[], blocked: string[], waiting: string | null }>} */ export async function queueTick(dir, exec, state) { @@ -545,12 +564,11 @@ export async function queueTick(dir, exec, state) { started = exec.start(step, { logFile, onEnd: (end) => { - void finishStep(dir, step.qid, end, exec, state).catch(() => {}); + void recordEnd(dir, step.qid, end, exec, state).catch(() => {}); }, }); } catch (e) { - state.held.delete(step.qid); - await finishStep(dir, step.qid, { exitCode: null, error: e instanceof Error ? e.message : String(e) }, exec, state, { notStarted: true }); + await recordEnd(dir, step.qid, { exitCode: null, error: e instanceof Error ? e.message : String(e) }, exec, state, { notStarted: true }).catch(() => {}); return out; } handle.cancel = started.cancel; @@ -593,8 +611,36 @@ async function finishStep(dir, qid, end, exec, state, { notStarted = false } = { await putStep(dir, s); if (r.state !== "done") await blockDependents(dir, s); }); - state.held.delete(qid); - state.onChange?.(); +} + +export const END_WRITE_TRIES = 3; +export const END_WRITE_PAUSE_MS = 2_000; + +/** + * Record a step's end (finishStep), a few times if writing it fails (the queue + * lock's timeout on a loaded machine) — and, whatever happens, let go of the + * step: a step this runner no longer holds and whose process is gone is the + * runner's own recovery's to mark failed on its next turn. It used to stay + * held when the write threw, reading running until the app restarted. + */ +async function recordEnd(dir, qid, end, exec, state, opts = {}) { + const tries = state.endWrite?.tries ?? END_WRITE_TRIES; + const pauseMs = state.endWrite?.pauseMs ?? END_WRITE_PAUSE_MS; + try { + for (let attempt = 1; ; attempt += 1) { + try { + await state.endWrite?.before?.(qid, attempt); + await finishStep(dir, qid, end, exec, state, opts); + return; + } catch (e) { + if (attempt >= tries) throw e; + await sleep(pauseMs); + } + } + } finally { + state.held.delete(qid); + state.onChange?.(); + } } /** diff --git a/umtool/lib/queue/store.test.mjs b/umtool/lib/queue/store.test.mjs @@ -291,6 +291,56 @@ test("the queue lock: an empty lock file is one being written, not a dead holder } }); +test("recording a step's end is retried; one that cannot be recorded is let go, and the runner's recovery fails it", async () => { + const dir = await tmp(); + try { + // Fails once (the lock's timeout on a loaded machine), then records: done. + const a = await addStep(dir, { argv: js("0"), label: "once" }); + const tries = []; + const once = { held: new Map(), endWrite: { tries: 3, pauseMs: 10, before: (qid, n) => { tries.push(n); if (n === 1) throw new Error("the queue is locked"); } } }; + const steps = await drain(dir, spawnExec(), once); + assert.equal(steps.find((s) => s.qid === a.qid)?.state, "done"); + assert.deepEqual(tries, [1, 2]); + assert.equal(once.held.size, 0); + + // Never records: let go after the tries, and the next turn's recovery + // marks it failed — it does not read running until the app restarts. + const b = await addStep(dir, { argv: js("0"), label: "never" }); + const c = await addStep(dir, { argv: js("0"), label: "after it" }); + const never = { held: new Map(), endWrite: { tries: 2, pauseMs: 10, before: () => { throw new Error("the queue is locked"); } } }; + const after = await drain(dir, spawnExec(), never); + const bb = after.find((s) => s.qid === b.qid); + assert.equal(bb?.state, "failed"); + assert.match(bb?.error ?? "", /process is gone/); + assert.equal(after.find((s) => s.qid === c.qid)?.state, "failed", "it too: every end write fails"); + assert.equal(never.held.size, 0); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the queue lock: an unreadable lock is waited for to the deadline, not spun on; an empty one from the future is stale", async () => { + const dir = await tmp(); + try { + await withQueueLock(dir, async () => {}); // makes the dirs + const lock = path.join(dir, ".lock"); + // A directory where the lock file should be: open(wx) says EEXIST, read says EISDIR. + const { mkdir, utimes } = await import("node:fs/promises"); + await mkdir(lock); + const t0 = Date.now(); + await assert.rejects(withQueueLock(dir, async () => "mine", { timeoutMs: 300 }), /the queue lock cannot be read \(EISDIR\)/); + assert.ok(Date.now() - t0 >= 300, "waited to the deadline"); + await rm(lock, { recursive: true }); + // Empty, its mtime an hour ahead: the clock was stepped back. Broken. + await writeFile(lock, ""); + const ahead = new Date(Date.now() + 3_600_000); + await utimes(lock, ahead, ahead); + 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 @@ -111,23 +111,28 @@ export async function withRenderHold(o, fn) { const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env)); /** @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 || token === null) return; - ended = true; - if (env[RENDER_PRIORITY_TOKEN_ENV] === token) delete env[RENDER_PRIORITY_TOKEN_ENV]; - try { - const off = await renderModeOff({ file, token, lanes }); - o.log( - `render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` + - (off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""), - ); - } catch (e) { - o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`); - } - }; + // ONE RELEASE, AWAITED BY EVERY CALLER. A second signal (Ctrl-C twice, a + // runner's TERM then its group's) used to find `ended` set, return at once + // and exit — cutting off the first caller's release of the lanes mid-way. + /** @type {Promise<void> | null} */ + let ending = null; + const end = () => + (ending ??= (async () => { + if (token === null) return; + const t = token; + if (env[RENDER_PRIORITY_TOKEN_ENV] === t) delete env[RENDER_PRIORITY_TOKEN_ENV]; + try { + const off = await renderModeOff({ file, token: t, lanes }); + o.log( + `render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` + + (off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""), + ); + } catch (e) { + o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`); + } + })()); // 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. // @@ -144,8 +149,9 @@ export async function withRenderHold(o, fn) { 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; + // The FIRST signal's code, whichever handler's exit runs. + const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[signalled] ?? 0); try { o.onSignal?.(sig); } catch { @@ -197,8 +203,9 @@ export async function withRenderHold(o, fn) { try { return { ran: true, value: await fn(/** @type {string} */ (token)) }; } finally { - unhook(); + // Unhooked only once the release is done: a signal meanwhile joins it. await end(); + unhook(); } } diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs @@ -86,7 +86,7 @@ test("take --priority: a failed take lets go too", async () => { * 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 } = {}) { +function spawnTake({ slowLane = null, slowRelease = null } = {}) { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-sig-")); const file = path.join(dir, "state.json"); const log = path.join(dir, "lanes.log"); @@ -96,6 +96,7 @@ function spawnTake({ slowLane = null } = {}) { `import { appendFileSync } from "node:fs"; import { withTakePriority } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))}; const slow = ${JSON.stringify(slowLane)}; +const slowRelease = ${JSON.stringify(slowRelease)}; const lanes = { isHeld: async () => false, hold: async (l) => { @@ -105,7 +106,13 @@ const lanes = { await new Promise((r) => setTimeout(r, 400)); } }, - release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"), + release: async (l) => { + if (l === slowRelease) { + console.log("releasing " + l); + await new Promise((r) => setTimeout(r, 400)); + } + 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 }, async () => { console.log("rendering"); @@ -158,6 +165,25 @@ test("take --priority killed by a signal: the hold ends before the process does" } }); +test("take --priority signalled twice: the second signal waits for the first's release, and the exit is the first's", { timeout: 180_000 }, async () => { + // The second signal used to find the release begun, return at once and + // exit — mid-way through letting the lanes go. + const take = spawnTake({ slowRelease: "download" }); + try { + await take.waitFor(/rendering/); + take.child.kill("SIGTERM"); + await take.waitFor(/releasing download/); + take.child.kill("SIGINT"); + 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.equal(take.out().match(/render mode off/g)?.length, 1, `released once: ${take.out()}`); + } 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