commit 5d2b18aceea14e8bece2138e96ae586c089dedc7
parent 6489ec1e98a2e66a203cc2bec37d150e0e3aec6d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 21:51:51 -0500
jobs: a batch over a channel's media holds while its drive is not answering
The start-of-work guard refuses a job whose channel's drive is already
stalled, but a batch that started while it answered kept pulling: each next
unit opened its audio in-process, held a file thread for the ~30 s the drive
takes to give up, and failed. Now:
- whisperBatch and the backfill lane of runOperationBatch ask
mediaStallHold (lib/mediaStallHold.ts, memory only) before each pull; while
the channel's media location is stalled their pool limit is 0 (the pool
pauses, as with every worker disabled), edge-logged "Holding: the media
drive "<label>" is not answering (since HH:MM) — no new … starts" and
"… answers again — resuming."
- transcribeOneVideo refuses before it looks for the audio, with
MediaDriveHeldError (a "no-audio" skip, never failed-transcriptions); the
queue logs the drive, not "no audio file".
- readChannelMediaConfig (lib/channelMedia.ts) reads a channel's targets for
a caller with only a slug.
Tests: the hold's edges; a backfill batch held mid-run and resumed (a fake
engine, /bin/false); the transcription refusal with the engine never run.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 289 insertions(+), 3 deletions(-)
diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts
@@ -41,8 +41,10 @@ import { isGateHeld } from "../lib/pauseGates";
import {
assertChannelMediaReachable,
assertChannelTextReadable,
+ readChannelMediaConfig,
readRelocationMarker,
} from "../lib/channelMedia";
+import { mediaStallHold } from "../lib/mediaStallHold";
import { runPool } from "../jobs/concurrentRunner";
import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
@@ -1601,6 +1603,11 @@ export async function runOperationBatch(
} else {
await assertChannelMediaReachable(opts.paths, opts.channelSlug);
}
+ // THE BACKFILL LANE OPENS MEDIA, so it holds while the channel's media drive
+ // is not answering (lib/mediaStallHold.ts); the digest lane reads text only.
+ const stallHold = run.digest
+ ? null
+ : mediaStallHold(await readChannelMediaConfig(opts.paths, opts.channelSlug), log, "backfill unit");
const dataDir = path.join(opts.paths.channelsDir, opts.channelSlug, "data");
const allDirs = await readdir(dataDir).catch(() => [] as string[]);
const onDisk = new Set(allDirs);
@@ -1851,6 +1858,7 @@ export async function runOperationBatch(
next,
run: runOne,
limit: () => {
+ if (stallHold?.check()) return 0;
const live = operationLaneLive(run, opts.concurrency);
const verdict = laneLimit(getSettings(), live);
if (verdict.hold) {
diff --git a/common/controller/operationBatchRelocation.test.ts b/common/controller/operationBatchRelocation.test.ts
@@ -26,6 +26,9 @@ const ROOT = mkdtempSync(path.join(os.tmpdir(), "batch-relocation-"));
process.env.TRANSCRIPTS_DIR = ROOT;
const SETTINGS_FILE = path.join(ROOT, "settings.json");
process.env.SETTINGS_FILE = SETTINGS_FILE;
+// No engine ever runs: the one case that dispatches (the drive-stall hold,
+// below) gets an "engine" that exits 1 at once.
+process.env.DIARIZE_BIN = "/bin/false";
// The backfill lane armed with ONE operation, and that operation's cheapest
// classification: every seeded video has a transcript and no audio, so
@@ -141,3 +144,70 @@ test("a marker written mid-run ends the batch instead of racing the copy", async
assert.ok(stop, `expected a stop line, got:\n${lines.join("\n")}`);
assert.match(stop as string, /\(out\) of omni to \/platter\/omni\/data/);
});
+
+// A DRIVE THAT STOPS ANSWERING MID-RUN HOLDS THE BATCH (lane drive-stall). The
+// start-of-work guard passed (the drive answered); the second pull finds the
+// channel's media location stalled in the health record, and the pool's limit
+// is 0 until it answers again — nothing is dispatched onto a drive that would
+// hold a file thread per unit, nothing is failed, and the run resumes.
+test("a media drive that stops answering mid-run holds the backfill batch until it answers", async () => {
+ const {
+ recordLocationHealth,
+ registerLocationHealth,
+ resetStorageHealth,
+ } = await import("../lib/storageHealth");
+ resetStorageHealth();
+ await seed("held", ["v1", "v2"]);
+ const platter = path.join(ROOT, "platter");
+ const mediaDir = path.join(platter, "held", "media");
+ await mkdir(mediaDir, { recursive: true });
+ const channelDir = path.join(getPaths().channelsDir, "held");
+ const { symlink } = await import("node:fs/promises");
+ await symlink(mediaDir, path.join(channelDir, "media"));
+ await writeFile(
+ path.join(channelDir, "config.json"),
+ JSON.stringify({ handling: "transcribe", url: "https://example.com/c", mediaDir }),
+ );
+ // Audio on both, so diarization dispatches (and fails on the fixture's
+ // missing models — what is under test is when it is dispatched).
+ for (const id of ["v1", "v2"]) {
+ await writeFile(path.join(channelDir, "data", id, "audio.mp3"), "ID3audio");
+ }
+ const loc = { id: "platter", label: "Platter", root: platter };
+ registerLocationHealth([loc]);
+
+ // The pool's idle poll is unref'd (a server keeps the loop alive; a test
+ // process would exit under a paused pool).
+ const keepAlive = setInterval(() => {}, 1_000);
+ let progressCalls = 0;
+ const lines: string[] = [];
+ const result = await runOperationBatch({
+ lane: "backfill",
+ channelSlug: "held",
+ paths: getPaths(),
+ operationIds: ["diarization"],
+ onLog: (m) => lines.push(m),
+ setProgress: () => {
+ progressCalls++;
+ if (progressCalls !== 2) return;
+ recordLocationHealth(loc, "stalled", { cause: "test: no answer" });
+ // It answers again a moment later: two clean answers clear it.
+ setTimeout(() => {
+ recordLocationHealth(loc, "ok");
+ recordLocationHealth(loc, "ok");
+ }, 300);
+ },
+ });
+ clearInterval(keepAlive);
+ // Both videos were dispatched in the end (and failed on the fake engine):
+ // held, not dropped.
+ assert.equal(result.attempted, 2);
+ const at = (prefix: string) => lines.findIndex((l) => l.startsWith(prefix));
+ const v1 = at("Diarize v1 start");
+ const hold = at("Holding: the media drive");
+ const resume = at(`The media drive "Platter" answers again — resuming.`);
+ const v2 = at("Diarize v2 start");
+ assert.ok(v1 >= 0 && hold > v1 && resume > hold && v2 > resume, `the order was:\n${lines.join("\n")}`);
+ assert.match(lines[hold], /"Platter" is not answering \(since \d\d:\d\d\) — no new backfill unit starts/);
+ resetStorageHealth();
+});
diff --git a/common/controller/transcribeError.ts b/common/controller/transcribeError.ts
@@ -17,3 +17,13 @@ export class TranscribeError extends Error {
this.name = "TranscribeError";
}
}
+
+// THE CHANNEL'S MEDIA DRIVE IS NOT ANSWERING (lane drive-stall): the audio is
+// not opened, and the video is skipped like a "no-audio" one — never recorded
+// in failed-transcriptions, transcribed on a later pass once the drive answers.
+// Its own class so a batch's log says the drive, not "no audio file".
+export class MediaDriveHeldError extends TranscribeError {
+ constructor(message: string) {
+ super(message, "no-audio");
+ }
+}
diff --git a/common/controller/transcribeOne.test.ts b/common/controller/transcribeOne.test.ts
@@ -71,3 +71,56 @@ test("an engine that exits 0 with no output, audio gone, is a skip too", async (
assert.ok(err instanceof TranscribeError, `not a TranscribeError: ${err}`);
assert.equal(err.failureClass, "no-audio");
});
+
+// THE TRANSCRIPTION SOURCE IS NOT OPENED ON A DRIVE THAT IS NOT ANSWERING
+// (lane drive-stall). The channel's config names a media location the health
+// record has stalled: the video is refused before its audio is looked for,
+// as a skip (never failed-transcriptions), and the engine never runs.
+test("a channel whose media drive is not answering is refused before its audio is opened", async () => {
+ const { MediaDriveHeldError } = await import("./transcribeError");
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ const { mkdir } = await import("node:fs/promises");
+ const { existsSync } = await import("node:fs");
+ const dir = await mkdtemp(path.join(tmpdir(), "transcribe-held-"));
+ try {
+ const platter = path.join(dir, "platter");
+ const channelDir = path.join(dir, "channels", "held");
+ const videoDir = path.join(channelDir, "data", "vid1");
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(
+ path.join(channelDir, "config.json"),
+ JSON.stringify({ handling: "transcribe", mediaDir: path.join(platter, "held", "media") }),
+ );
+ await writeFile(path.join(videoDir, "audio.mp3"), "not really audio");
+ const ran = path.join(dir, "engine-ran");
+ const bin = path.join(dir, "fake-engine.sh");
+ await writeFile(bin, `#!/bin/sh\ntouch ${ran}\nexit 1\n`, { mode: 0o755 });
+ recordLocationHealth({ id: "platter", label: "Platter", root: platter }, "stalled");
+ const err = await transcribeOneVideo({
+ paths: {} as Paths,
+ videoDir,
+ videoId: "vid1",
+ audioFilename: "audio.mp3",
+ worker: {
+ id: "w1",
+ name: "fake",
+ kind: "local",
+ enabled: true,
+ priority: 0,
+ appId: "whisper-cpp",
+ config: { bin, model: "model.bin" },
+ },
+ onLog: () => {},
+ }).then(
+ (v) => v,
+ (e) => e,
+ );
+ assert.ok(err instanceof MediaDriveHeldError, `not a MediaDriveHeldError: ${err}`);
+ assert.equal(err.failureClass, "no-audio");
+ assert.match(err.message, /^the media drive "Platter" is not answering \(since \d\d:\d\d\) — vid1 is left for when it answers$/);
+ assert.equal(existsSync(ran), false, "the engine never ran");
+ } finally {
+ resetStorageHealth();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -16,7 +16,9 @@ import { normalizeTranscript } from "./normalizeTranscript";
import { diarizeOneVideo } from "./diarizeOne";
import { getSettings } from "../lib/settings";
import { pingRemoteHealth, transcribeViaRemote } from "./remoteTranscribe";
-import { TranscribeError } from "./transcribeError";
+import { MediaDriveHeldError, TranscribeError } from "./transcribeError";
+import { channelMediaStall } from "../lib/channelMedia";
+import { mediaDriveHeldText } from "../lib/mediaStallHold";
import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus";
import { pickPreferredAudio } from "../lib/mediaFiles";
import { heldAudioDamage } from "../lib/audioIntegrity-server";
@@ -200,6 +202,20 @@ export async function transcribeOneVideo(
return "already-exists";
}
+ // NOT OPENED ON A DRIVE THAT IS NOT ANSWERING (lane drive-stall). The audio
+ // is a tierable file, a link onto the channel's media drive; asking for it
+ // there in-process holds one of Node's file threads until the kernel gives
+ // up (~30 s). The health record is memory, the config the corpus disk's.
+ const mediaConfig = await readChannelConfigFile(
+ path.join(path.dirname(path.dirname(opts.videoDir)), "config.json"),
+ ).catch(() => null);
+ const stall = channelMediaStall(mediaConfig);
+ if (stall) {
+ throw new MediaDriveHeldError(
+ `${mediaDriveHeldText(stall)} — ${opts.videoId} is left for when it answers`,
+ );
+ }
+
const resolvedAudio = await resolveAudioFile(
opts.videoDir,
opts.audioFilename,
diff --git a/common/controller/transcribeOneFromQueue.ts b/common/controller/transcribeOneFromQueue.ts
@@ -7,7 +7,7 @@ import {
readVideoFiles,
} from "../lib/videoStatus";
import { transcribeWithWorker } from "./transcribeOne";
-import { TranscribeError } from "./transcribeError";
+import { MediaDriveHeldError, TranscribeError } from "./transcribeError";
import type { TaskTracker } from "../jobs/taskHooks";
const { pathExists, appendFile } = fs;
@@ -157,6 +157,10 @@ export async function transcribeOneFromQueue({
// A missing audio file is a download/source problem, not a transcription
// failure — skip it (it transcribes once a good audio file exists) rather
// than permanently recording it in failed-transcriptions.
+ if (err instanceof MediaDriveHeldError) {
+ log(`Skipping ${videoId}: ${err.message}`);
+ return { attempted: true, outcome: "skipped" };
+ }
if (err instanceof TranscribeError && err.failureClass === "no-audio") {
log(`Skipping ${videoId}: no audio file (download/source problem)`);
return { attempted: true, outcome: "skipped" };
diff --git a/common/controller/whisperBatch.ts b/common/controller/whisperBatch.ts
@@ -13,6 +13,8 @@ import { runPool } from "../jobs/concurrentRunner";
import { pruneFailedTranscriptions } from "./failedTranscriptions";
import { resolveShardItems } from "./shard";
import { countNotYetTranscribed } from "./channels";
+import { mediaStallHold } from "../lib/mediaStallHold";
+import { readChannelMediaConfig } from "../lib/channelMedia";
import { getWorkerPool } from "../jobs/workerPool";
import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
@@ -224,6 +226,14 @@ export async function runWhisperBatch({
// transcribe is shared with the auto-runner via transcribeOneFromQueue.
const NEVER = new AbortController().signal;
let idx = 0;
+ // HELD WHILE THE CHANNEL'S MEDIA DRIVE IS NOT ANSWERING (lib/mediaStallHold.ts):
+ // the limit is 0, the pool pauses, and it resumes when the drive answers.
+ // The config is read once; the check is memory.
+ const stallHold = mediaStallHold(
+ await readChannelMediaConfig(paths, channelSlug),
+ log,
+ "transcription",
+ );
const runOne = async (videoDir: string, runSignal: AbortSignal): Promise<void> => {
const res = await transcribeOneFromQueue({
paths,
@@ -250,7 +260,9 @@ export async function runWhisperBatch({
// Eligible (enabled, non-degraded) worker slots — the real throughput
// ceiling. 0 ⇒ paused until a worker is re-enabled (runPool idle-waits).
limit: () =>
- pool.summary().filter((s) => s.state === "enabled" && !s.degraded).length,
+ stallHold.check()
+ ? 0
+ : pool.summary().filter((s) => s.state === "enabled" && !s.degraded).length,
signal: signal ?? NEVER,
drainSignal: drainSignal ?? NEVER,
finite: true,
diff --git a/common/lib/channelMedia.ts b/common/lib/channelMedia.ts
@@ -271,6 +271,16 @@ function configuredOf(config: ChannelMediaConfig | null | undefined): Configured
// `mediaDir` and the retired `dataDir`, read straight off config.json.
// Deliberately NOT parseChannelConfig: this runs in guards on hot paths and
// must not depend on the controller that owns the rest of the schema.
+// A channel's configured media targets (`mediaDir`, the retired `dataDir`)
+// off its config.json on the corpus disk; `{}` for none or an unreadable file.
+// What a caller with only a slug hands `channelMediaStall`.
+export function readChannelMediaConfig(
+ paths: ChannelMediaPaths,
+ slug: string,
+): Promise<ChannelMediaConfig> {
+ return readConfigured(paths, slug);
+}
+
async function readConfigured(
paths: ChannelMediaPaths,
slug: string,
diff --git a/common/lib/mediaStallHold.test.ts b/common/lib/mediaStallHold.test.ts
@@ -0,0 +1,50 @@
+import { beforeEach, test } from "node:test";
+import assert from "node:assert/strict";
+import { mediaDriveHeldText, mediaStallHold } from "./mediaStallHold";
+import {
+ recordLocationHealth,
+ registerLocationHealth,
+ resetStorageHealth,
+} from "./storageHealth";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/mediaStallHold.test.ts
+//
+// The batch hold (lane drive-stall): memory only, edge-logged.
+
+beforeEach(() => resetStorageHealth());
+
+const USB = { id: "usb", label: "USB drive", root: "/mnt/usb" };
+
+test("the hold follows the channel's media location, and logs once per edge", () => {
+ registerLocationHealth([USB]);
+ const lines: string[] = [];
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/chan/media" }, (l) => lines.push(l), "transcription");
+ assert.equal(hold.check(), null);
+ recordLocationHealth(USB, "stalled", { now: Date.now() });
+ assert.equal(hold.check()?.id, "usb");
+ assert.equal(hold.check()?.id, "usb");
+ recordLocationHealth(USB, "ok");
+ recordLocationHealth(USB, "ok");
+ assert.equal(hold.check(), null);
+ assert.equal(hold.check(), null);
+ assert.equal(lines.length, 2);
+ assert.match(lines[0], /^Holding: the media drive "USB drive" is not answering \(since \d\d:\d\d\) — no new transcription starts until it answers again\.$/);
+ assert.equal(lines[1], `The media drive "USB drive" answers again — resuming.`);
+});
+
+test("a channel in place, or on another location, is never held", () => {
+ registerLocationHealth([USB]);
+ recordLocationHealth(USB, "stalled");
+ const lines: string[] = [];
+ assert.equal(mediaStallHold({}, (l) => lines.push(l), "x").check(), null);
+ assert.equal(mediaStallHold(null, (l) => lines.push(l), "x").check(), null);
+ assert.equal(mediaStallHold({ mediaDir: "/mnt/other/c/media" }, (l) => lines.push(l), "x").check(), null);
+ assert.deepEqual(lines, []);
+ // A legacy channel's retired dataDir on the location is held too.
+ assert.equal(mediaStallHold({ dataDir: "/mnt/usb/c/data" }, () => {}, "x").check()?.id, "usb");
+});
+
+test("the refusal sentence names the drive and since when", () => {
+ assert.match(mediaDriveHeldText({ label: "USB drive", since: Date.now() }), /^the media drive "USB drive" is not answering \(since \d\d:\d\d\)$/);
+});
diff --git a/common/lib/mediaStallHold.ts b/common/lib/mediaStallHold.ts
@@ -0,0 +1,53 @@
+import { channelMediaStall, type ChannelMediaConfig } from "./channelMedia";
+import { sinceText, type LocationHealth } from "./storageHealth";
+
+// A BATCH THAT OPENS MEDIA HOLDS WHILE ITS CHANNEL'S MEDIA DRIVE IS NOT
+// ANSWERING (lane drive-stall).
+//
+// The start-of-work guard (`assertChannelMediaReachable`) refuses a job whose
+// channel's drive is already stalled. A batch that started while the drive
+// answered, and is still pulling videos when it stops, was not asked again:
+// each next unit opened its audio in-process, held one of Node's file threads
+// for the ~30 s the drive takes to give up, and failed — over and over, a
+// thread at a time. So a batch over a channel's media asks this before every
+// pull: while the drive is stalled the pool's limit is 0 (runPool PAUSES, as
+// it does with every worker disabled), and when it answers the batch resumes.
+// The units already in flight finish or fail on their own; nothing cancels a
+// read the kernel holds.
+//
+// NO I/O: `channelMediaStall` reads the process's health record (the health
+// pass and the watchdog write it), never the drive. Edge-logged, once when
+// the hold begins and once when it ends.
+
+export type MediaStallHold = {
+ // The stalled location now, or null. Logs on each edge.
+ check: () => LocationHealth | null;
+};
+
+export function mediaStallHold(
+ config: ChannelMediaConfig | null | undefined,
+ log: (line: string) => void,
+ what: string,
+): MediaStallHold {
+ let holding: LocationHealth | null = null;
+ return {
+ check: () => {
+ const stall = channelMediaStall(config);
+ if (stall && !holding) {
+ log(
+ `Holding: the media drive "${stall.label}" is not answering (${sinceText(stall.since)}) — ` +
+ `no new ${what} starts until it answers again.`,
+ );
+ } else if (!stall && holding) {
+ log(`The media drive "${holding.label}" answers again — resuming.`);
+ }
+ holding = stall;
+ return stall;
+ },
+ };
+}
+
+// The sentence a unit refuses with when its channel's drive is not answering.
+export function mediaDriveHeldText(stall: Pick<LocationHealth, "label" | "since">): string {
+ return `the media drive "${stall.label}" is not answering (${sinceText(stall.since)})`;
+}