commit 6729ed86d3ed4ca452049385317cd87afa133750
parent 1b258d99ffc1313732d7caede84773fd956b063a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 10 Nov 2026 09:11:48 -0500
Merge lane/drive-stall: a media drive that stops answering is shown as such and holds only the work on it -- slow vs not answering on /storage, get storage and a dashboard banner; transcription and backfill pause and heal themselves; persists stop cleanly (overnight E3; a flaw logged by the logo-branding session)
Most of the stall guard was already on main (releases 15 and 17). This adds what was missing: the drive's latency,
last answer and a two-reading "slow" state; a hold on a stalled drive's transcription and backfill that re-probes the
root out of process and releases itself (logging while it holds); one isMediaDriveHeld skip that is never a failed
transcription; persist-videos and persist-kept stop before downloading into a store that does not answer; the storage
watch's auto-pause write under the settings lock.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
45 files changed, 1967 insertions(+), 52 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -281,7 +281,9 @@ job resume-interrupted does by hand what the editor does at boot: re-queues
get settings [<key>] is settings.json as the editor reads it (migrated and
defaulted; a secret is "<redacted>"), or one top-level key of it.
-get storage is /storage: each location, mounted or not, free space, tiers.
+get storage is /storage: each location, mounted or not, free space, tiers,
+ and its drive's health (rows[].drive: ok | slow | stalled | unmounted,
+ since, lastOkAt, latencyMs, the cause and the one-line text).
get saved-alternates [<slug>] lists every saved video holding two copies:
a download over a container already in the store keeps both — an
explicit persist (persist-videos, Persist source video, a whole-recording
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -106,7 +106,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `AUDIO_CHECK_BACKOFF_FACTOR` | the built-in factor | The audio check's interval backoff factor, in (0, 1], for a one-off run. | common/ytdlp/audioCheckedDownload.ts |
| `ARCHILYZER_STATS_ALLOW_DOWNGRADE` | off | `1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions. | common/controller/buildStats.ts |
| `ARCHILYZER_INDEX_ALLOW_HELD` | off | `1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel. | common/controller/buildIndex.ts |
-| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh) |
+| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and `dev`, the archilyzer-editor.service unit `archilyzer service install` writes, and docker/entrypoint.sh) |
| `MCP_IO_STATS` | off | `1` turns on per-call I/O accounting, for `mcp/bench`. | common/lib/archive/io-stats.ts |
| `ARCHILYZER_EDITOR_URL` | `http://localhost:3001` | Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it. | scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts |
| `ARCHILYZER_AGENT` | `cli` | Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`. | scripts/archilyzer-ops.mjs |
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,16 @@ 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",
+ { reloadConfig: () => readChannelMediaConfig(opts.paths, opts.channelSlug) },
+ );
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 +1863,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/persistKept.test.ts b/common/controller/persistKept.test.ts
@@ -59,6 +59,7 @@ test("persistKept is a no-op when keep-latest is off", async () => {
persisted: 0,
failed: 0,
skippedNoUrl: 0,
+ skippedStoreUnavailable: 0,
skippedLowDisk: 0,
});
});
@@ -83,3 +84,35 @@ test("persistKept counts in-window videos already saved without re-downloading",
assert.equal(res.skippedNoUrl, 0);
});
});
+
+// A STORE THAT CANNOT TAKE A CONTAINER STOPS THE PASS BEFORE ANY FETCH (review
+// of lane drive-stall): the store's drive is not answering, so nothing is
+// downloaded to land nowhere; every unsaved kept video is counted skipped.
+test("persistKept stops before fetching when the saved-video store's drive is not answering", async () => {
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ await withPaths(async (paths) => {
+ for (const id of ["20240101_a", "20240202_b", "20240303_c"]) {
+ await mkdir(path.join(paths.channelsDir, "alpha", "data", id), { recursive: true });
+ }
+ recordLocationHealth(
+ { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) },
+ "stalled",
+ );
+ const lines: string[] = [];
+ try {
+ const res = await persistKept({
+ paths,
+ channelSlug: "alpha",
+ channelConfig: { handling: "transcribe", keepLatest: 2 },
+ onLog: (l: string) => lines.push(l),
+ });
+ assert.equal(res.kept, 2);
+ assert.equal(res.persisted, 0);
+ assert.equal(res.failed, 0);
+ assert.equal(res.skippedStoreUnavailable, 2);
+ assert.match(lines.join("\n"), /The saved-video store's drive "Store drive" is not answering .* — stopping/);
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
diff --git a/common/controller/persistKept.ts b/common/controller/persistKept.ts
@@ -5,6 +5,8 @@ import { getSettings } from "../lib/settings";
import { diskGate } from "../lib/diskSpace";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { isSavedVideo } from "../lib/savedVideo-server";
+import { savedVideoDir } from "../lib/savedVideo";
+import { savedVideosStoreRefusal } from "../lib/savedVideoStore";
import { computeKeptVideoIds } from "./keptVideos";
import { findVideoSourceUrl } from "./undownloadedVideos";
import {
@@ -40,6 +42,9 @@ export type PersistKeptResult = {
failed: number;
// No resolvable source URL (no metadata + not in the playlist).
skippedNoUrl: number;
+ // Not attempted because the saved-video store could not take a container
+ // (its drive not answering, or mid-move) — asked before each fetch.
+ skippedStoreUnavailable: number;
// Not attempted because free disk fell under the floor part-way through. A
// refusal to start, not a failure — these videos are still kept, still
// unpersisted, and the next pass picks them up.
@@ -81,6 +86,7 @@ export async function persistKept({
failed: 0,
skippedNoUrl: 0,
skippedLowDisk: 0,
+ skippedStoreUnavailable: 0,
};
if (keptIds.size === 0) {
log(
@@ -105,17 +111,35 @@ export async function persistKept({
// Set once the disk gate closes mid-pass. Everything after it is counted as
// skipped rather than attempted, so the log says how much was left.
let lowDisk = false;
+ let storeUnavailable = false;
for (const videoId of ordered) {
if (signal?.aborted) break;
if (lowDisk) {
result.skippedLowDisk += 1;
continue;
}
+ if (storeUnavailable) {
+ result.skippedStoreUnavailable += 1;
+ continue;
+ }
const videoDir = path.join(dataDir, videoId);
if (await isSavedVideo(videoDir)) {
result.alreadySaved += 1;
continue;
}
+ // THE STORE MUST BE ABLE TO TAKE IT (review of lane drive-stall): asked
+ // before the fetch, so a stalled store drive or a store mid-move stops the
+ // pass instead of downloading containers that land nowhere.
+ const refusal = await savedVideosStoreRefusal(
+ paths,
+ savedVideoDir(paths, channelConfig, channelSlug, videoId),
+ );
+ if (refusal) {
+ storeUnavailable = true;
+ result.skippedStoreUnavailable += 1;
+ log(` ${videoId}: ${refusal.message} — stopping; remaining videos skipped.`);
+ continue;
+ }
// PER ITEM, not once at the start. This pass writes full source containers —
// the largest files the app produces — so the twentieth video must not
// inherit the first one's headroom. Same shape as backfillReacquire's
@@ -175,6 +199,9 @@ export async function persistKept({
(result.skippedLowDisk > 0
? `, ${result.skippedLowDisk} skipped (low disk)`
: "") +
+ (result.skippedStoreUnavailable > 0
+ ? `, ${result.skippedStoreUnavailable} skipped (saved-video store unavailable)`
+ : "") +
` of ${result.kept} kept.`,
);
return result;
diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts
@@ -538,3 +538,30 @@ test("a dry run buckets every item and fetches nothing", async () => {
assert.equal(res.plan.willFetch, 2);
});
});
+
+// A STORE THAT CANNOT TAKE A CONTAINER STOPS THE RUN BEFORE THE FETCH (review
+// of lane drive-stall): its drive is not answering, so no container is
+// downloaded only to be left in the data dir.
+test("a saved-video store whose drive is not answering stops the run before any fetch", async () => {
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ await withPaths(async (paths) => {
+ for (const id of ["aaa111", "bbb222"]) await seedVideo(paths, "demo-channel", id);
+ recordLocationHealth(
+ { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) },
+ "stalled",
+ );
+ try {
+ const h = harness(paths);
+ const res = await persistVideos({
+ paths,
+ items: ["aaa111", "bbb222"].map((id) => ({ slug: "demo-channel", id })),
+ deps: h.deps,
+ });
+ assert.deepEqual(h.downloads, []);
+ assert.equal(res.stopped, "store-unavailable");
+ assert.deepEqual(res.notAttempted.map((i) => i.id), ["aaa111", "bbb222"]);
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts
@@ -5,9 +5,10 @@ import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
import { getSettings } from "../lib/settings";
import { diskGate, type DiskGateStatus } from "../lib/diskSpace";
+import { savedVideosStoreRefusal } from "../lib/savedVideoStore";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
-import type { SavedVideoPointer } from "../lib/savedVideo";
+import { savedVideoDir, type SavedVideoPointer } from "../lib/savedVideo";
import {
loadSavedVideo,
restoreSavedVideoProvenance,
@@ -94,7 +95,15 @@ export type PersistVideosPlan = {
willFetch: number;
};
-export type PersistVideosStop = "low-disk" | "rate-limit" | "cancelled" | "drained";
+// `store-unavailable`: the saved-video store cannot take a container (its
+// drive is not answering, or it is being moved) — the run stops before
+// downloading one only to leave it in the data dir.
+export type PersistVideosStop =
+ | "low-disk"
+ | "rate-limit"
+ | "store-unavailable"
+ | "cancelled"
+ | "drained";
export type PersistVideosResult = {
plan: PersistVideosPlan;
@@ -459,6 +468,18 @@ export async function persistVideos({
stop("low-disk", i);
break;
}
+ // THE STORE MUST BE ABLE TO TAKE IT, asked before the fetch: a stalled
+ // drive or a store mid-move would refuse the container after a whole
+ // download. Memory and the corpus disk only.
+ const refusal = await savedVideosStoreRefusal(
+ paths,
+ savedVideoDir(paths, config, p.slug, p.id),
+ );
+ if (refusal) {
+ log(` ${label(p)}: ${refusal.message} — stopping; the rest are left for a later run.`);
+ stop("store-unavailable", i);
+ break;
+ }
const replacing = p.bucket === "wrongHeight";
log(
` ${label(p)}: ${replacing ? "replacing the saved container" : "fetching the source container"} (${quality})…`,
diff --git a/common/controller/storageWatch.test.ts b/common/controller/storageWatch.test.ts
@@ -24,6 +24,7 @@ import {
import { inspectChannelMedia } from "../lib/channelMedia";
import {
applyHealthTimings,
+ driveHealthView,
healthTimings,
locationHealth,
resetStorageHealth,
@@ -661,3 +662,98 @@ test("DT: a changed pass interval re-arms the armed pass; an explicit interval f
}
});
});
+
+// THE PASS'S WRITE WAITS FOR THE SETTINGS LOCK (lane drive-stall). The
+// editor's priority writer holds the per-process lock on settings.json for its
+// whole read-modify-write (editor/app/settings/saveSettings.ts,
+// `withSettingsLock`); a pass that wrote in the middle of it would be written
+// over by the writer's stale document, and the pause lost.
+test("the pass writes under the settings lock: a writer holding it is not interleaved", async () => {
+ const { withJsonFileLock } = await import("../lib/jsonFile-server");
+ const { getPaths } = await import("../lib/paths");
+ await withTmp(async (h) => {
+ await seedRelocated(h, "gone", { targetExists: false });
+ await seedRelocated(h, "other", { targetExists: true });
+ const pass = () => runStorageWatchPass({ paths: h.paths, io: h.io, bins: h.paths });
+ await pass(); // the suspicion
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const order: string[] = [];
+ // The "priority writer": reads, waits while holding the lock, writes.
+ const writer = withJsonFileLock(getPaths().settingsFile, async () => {
+ const before = h.io.read();
+ await gate;
+ order.push("writer");
+ await h.io.write({
+ ...before,
+ channelPriority: sanitizeChannelPriority({
+ ...before.channelPriority,
+ channels: { ...before.channelPriority.channels, other: { tier: "low" } },
+ }),
+ });
+ });
+ const confirming = pass().then((r) => {
+ order.push("pass");
+ return r;
+ });
+ // Give the pass every chance to write while the lock is held.
+ await new Promise((r) => setTimeout(r, 50));
+ assert.equal(h.writes, 0, "the pass did not write while the lock was held");
+ release();
+ await writer;
+ const second = await confirming;
+ assert.deepEqual(second.paused, ["gone"]);
+ assert.deepEqual(order, ["writer", "pass"]);
+ // Both survive: the writer's tier and the pass's pause.
+ assert.equal(tierOf(h, "other"), "low");
+ assert.equal(tierOf(h, "gone"), "paused");
+ });
+});
+
+// THE PROBE'S STATE MACHINE WITH A FAKE PROBER (lane drive-stall): the
+// verdicts a detector gives, pass by pass, and the view every surface reports
+// from them — ok, slow (an answer at half the budget or more), stalled (no
+// answer: the gate refuses), ok again after two clean passes. No drive, no
+// subprocess: the probe is a script.
+test("a fake prober walks the drive ok -> slow -> stalled -> ok, and the gate follows only the stall", async () => {
+ await withTmp(async (h) => {
+ await seedRelocated(h, "on-cold", { targetExists: true });
+ const verdicts = [
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 4 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_100 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_200 },
+ { answer: "stalled" as const, detector: "stat" as const, cause: "a stat of its root did not answer within 3 s" },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 6 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 5 },
+ ];
+ let i = 0;
+ const probe = async () => verdicts[Math.min(i++, verdicts.length - 1)];
+ const loc = { id: "cold", label: "Cold" };
+ const view = () => driveHealthView(loc, locationHealth("cold"));
+ const pass = () => runStorageHealthPass({ io: h.io, probe });
+
+ await pass();
+ assert.equal(view().state, "ok");
+ assert.equal(view().latencyMs, 4);
+ assert.equal(typeof view().lastOkAt, "number");
+
+ await pass(); // one slow reading: not yet slow
+ assert.equal(view().state, "ok");
+ await pass();
+ assert.equal(view().state, "slow");
+ assert.match(String(view().cause), /^a stat of its root took 2.2 s$/);
+ // Slow is shown, never acted on: the channel's media still answers ok.
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok");
+
+ await pass();
+ assert.equal(view().state, "stalled");
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "stalled");
+
+ await pass(); // one clean answer: still stalled
+ assert.equal(view().state, "stalled");
+ await pass(); // two in a row: answering again, and not slow
+ assert.equal(view().state, "ok");
+ assert.equal(view().latencyMs, 5);
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok");
+ });
+});
diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts
@@ -1,4 +1,5 @@
import { getPaths, type Paths } from "../lib/paths";
+import { withJsonFileLock } from "../lib/jsonFile-server";
import {
getSettings,
writeSettings,
@@ -34,6 +35,7 @@ import {
NOT_ANSWERING,
applyHealthTimings,
healthTimings,
+ noteDriveAnswer,
noteLocationDetector,
onPassIntervalChange,
pruneLocationHealth,
@@ -297,6 +299,29 @@ export async function runStorageWatchPass(
if (out.paused.length === 0 && out.restored.length === 0) return out;
if (opts.write === false) return out;
+ // UNDER THE SETTINGS LOCK (lane drive-stall, after lane editor-gaps). The
+ // editor's other read-modify-write of `channelPriority` — the priority
+ // writer, which also clears `autoPaused` on a manual tier change — runs inside
+ // `withSettingsLock` (editor/app/settings/saveSettings.ts), which is this same
+ // per-process lock on settings.json. Without it the two interleave: the
+ // operator's tier change lands between this pass's read and its write and is
+ // written over, or the pass's pause is. The lock is not re-entrant, and
+ // nothing called inside it takes it.
+ await withJsonFileLock(getPaths().settingsFile, () =>
+ writePassResult(io, paths, configs, out, pauseCauses),
+ );
+ out.wrote = true;
+ return out;
+}
+
+// THE PASS'S ONE WRITE, with the settings lock held by the caller.
+async function writePassResult(
+ io: NonNullable<StorageWatchOpts["io"]>,
+ paths: Paths,
+ configs: ReadonlyArray<{ slug: string }>,
+ out: StorageWatchResult,
+ pauseCauses: ReadonlyMap<string, AutoPauseCause>,
+): Promise<void> {
// ONE WRITE PER PASS, whatever the pass found. Ten channels on one drive that
// vanished is one settings write and one pulse bump, not ten.
//
@@ -349,8 +374,6 @@ export async function runStorageWatchPass(
}
}
await io.write({ ...latest, channelPriority: merged, autoQueue });
- out.wrote = true;
- return out;
}
// Five minutes. A drive does not come and go on a timescale a person would
@@ -436,12 +459,23 @@ function recordVerdict(
if (verdict.detector) noteLocationDetector(loc.id, verdict.detector, device);
return null;
}
- return recordLocationHealth(loc, verdict.answer, {
+ const t = recordLocationHealth(loc, verdict.answer, {
now,
cause: verdict.cause ?? statCause(),
...(verdict.detector ? { detector: verdict.detector } : {}),
...(device !== undefined ? { device } : {}),
});
+ // How long it took, when the detector measured it (lane drive-stall): the
+ // counters' average per request, or the child stat's round trip.
+ if (verdict.answer === "ok" && verdict.latencyMs !== undefined) {
+ noteDriveAnswer(
+ loc.id,
+ verdict.latencyMs,
+ verdict.detector === "counters" ? "counters" : "stat",
+ now,
+ );
+ }
+ return t;
}
export async function runStorageHealthPass(
diff --git a/common/controller/transcribeError.ts b/common/controller/transcribeError.ts
@@ -17,3 +17,25 @@ 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 {
+ // Read by `isMediaDriveHeld`, which also answers for a copy of this class
+ // from another module instance (instanceof does not).
+ readonly mediaDriveHeld = true;
+ constructor(message: string) {
+ super(message, "no-audio");
+ }
+}
+
+// A transcription refused because its channel's media drive is not answering:
+// a skip for every caller, never a failed transcription or a failed download.
+export function isMediaDriveHeld(err: unknown): err is MediaDriveHeldError {
+ return (
+ err instanceof MediaDriveHeldError ||
+ (err instanceof Error && (err as { mediaDriveHeld?: unknown }).mediaDriveHeld === true)
+ );
+}
diff --git a/common/controller/transcribeOne.test.ts b/common/controller/transcribeOne.test.ts
@@ -71,3 +71,68 @@ 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 });
+ }
+});
+
+// Every caller reads a held transcription as a skip through ONE predicate,
+// which also answers for a copy of the class from another module instance.
+test("isMediaDriveHeld: the held class, by instance or by its flag; nothing else", async () => {
+ const { isMediaDriveHeld, MediaDriveHeldError } = await import("./transcribeError");
+ assert.equal(isMediaDriveHeld(new MediaDriveHeldError("the media drive \"x\" is not answering")), true);
+ const foreign = Object.assign(new Error("copy"), { mediaDriveHeld: true });
+ assert.equal(isMediaDriveHeld(foreign), true);
+ assert.equal(isMediaDriveHeld(new TranscribeError("no audio file", "no-audio")), false);
+ assert.equal(isMediaDriveHeld(new Error("boom")), false);
+ assert.equal(isMediaDriveHeld(null), false);
+});
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -2,6 +2,7 @@ import path from "node:path";
import fs from "fs-extra";
import { execa } from "execa";
import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
import type { Worker } from "../lib/workers";
import { getTranscriptionApp } from "../lib/transcriptionApps";
import { detectTranscriptFormat } from "../lib/whisper";
@@ -16,7 +17,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";
@@ -67,6 +70,23 @@ async function resolveAudioFile(
return null;
}
+// THE CHANNEL'S CONFIG FOR THE STALL CHECK, read at most once per 10 s per
+// channel (review of lane drive-stall): a batch transcribes a channel's videos
+// one after another, and each asked config.json again. Its media targets are
+// all the check reads, and a move rewrites them seldom; ten seconds late is
+// within the health pass's own cadence.
+const STALL_CONFIG_TTL_MS = 10_000;
+const stallConfigMemo = new Map<string, { at: number; config: ChannelConfig | null }>();
+
+async function channelConfigForStall(file: string): Promise<ChannelConfig | null> {
+ const now = Date.now();
+ const hit = stallConfigMemo.get(file);
+ if (hit && now - hit.at < STALL_CONFIG_TTL_MS) return hit.config;
+ const config = await readChannelConfigFile(file).catch(() => null);
+ stallConfigMemo.set(file, { at: now, config });
+ return config;
+}
+
// A CONTAINER TO TRANSCRIBE FROM, before any audio download (release 23 F2).
//
// The page's Transcribe (and `pnpm ops transcribe-one`) used to download the
@@ -200,6 +220,21 @@ 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 stall = channelMediaStall(
+ await channelConfigForStall(
+ path.join(path.dirname(path.dirname(opts.videoDir)), "config.json"),
+ ),
+ );
+ 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 { isMediaDriveHeld, 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 (isMediaDriveHeld(err)) {
+ 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,17 @@ 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 check is memory; the config is re-read in the background.
+ const stallHold = mediaStallHold(
+ await readChannelMediaConfig(paths, channelSlug),
+ log,
+ "transcription",
+ // Re-read in the background (at most every 10 s): a move mid-batch is
+ // held by the drive the media is on now.
+ { reloadConfig: () => readChannelMediaConfig(paths, channelSlug) },
+ );
const runOne = async (videoDir: string, runSignal: AbortSignal): Promise<void> => {
const res = await transcribeOneFromQueue({
paths,
@@ -250,7 +263,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/envVars.ts b/common/lib/envVars.ts
@@ -142,7 +142,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "AUDIO_CHECK_BACKOFF_FACTOR", audience: "runtime", default: "the built-in factor", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "The audio check's interval backoff factor, in (0, 1], for a one-off run." },
{ name: "ARCHILYZER_STATS_ALLOW_DOWNGRADE", audience: "runtime", default: "off", readBy: "common/controller/buildStats.ts", doc: "`1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions." },
{ name: "ARCHILYZER_INDEX_ALLOW_HELD", audience: "runtime", default: "off", readBy: "common/controller/buildIndex.ts", doc: "`1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel." },
- { name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." },
+ { name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and `dev`, the archilyzer-editor.service unit `archilyzer service install` writes, and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." },
{ name: "MCP_IO_STATS", audience: "runtime", default: "off", readBy: "common/lib/archive/io-stats.ts", doc: "`1` turns on per-call I/O accounting, for `mcp/bench`." },
{ name: "ARCHILYZER_EDITOR_URL", audience: "runtime", default: "`http://localhost:3001`", readBy: "scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts", doc: "Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it." },
{ name: "ARCHILYZER_AGENT", audience: "runtime", default: "`cli`", readBy: "scripts/archilyzer-ops.mjs", doc: "Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`." },
diff --git a/common/lib/mediaStallHold.test.ts b/common/lib/mediaStallHold.test.ts
@@ -0,0 +1,172 @@
+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\)$/);
+});
+
+// ── the hold heals itself (review of lane drive-stall) ──────────────────────
+
+const tick = () => new Promise((r) => setImmediate(r));
+
+test("held past reprobeAfterMs with no pass keeping the record: one out-of-process probe answers and clears it", async () => {
+ const { locationHealth } = await import("./storageHealth");
+ let t = 1_000_000;
+ registerLocationHealth([USB], t);
+ // Recorded once, long ago — no pass refreshes it (a CLI, an idle record).
+ recordLocationHealth(USB, "stalled", { now: t });
+ const probed: string[] = [];
+ const lines: string[] = [];
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/chan/media" }, (l) => lines.push(l), "transcription", {
+ now: () => t,
+ reprobeAfterMs: 60_000,
+ stillHoldingEveryMs: 600_000,
+ reprobe: async (root) => {
+ probed.push(root);
+ return "ok";
+ },
+ });
+ assert.ok(hold.check());
+ t += 30_000;
+ assert.ok(hold.check());
+ await tick();
+ assert.deepEqual(probed, [], "not before reprobeAfterMs");
+ t += 31_000;
+ assert.ok(hold.check(), "the probe is asynchronous: this pull is still held");
+ await tick();
+ await tick();
+ assert.deepEqual(probed, ["/mnt/usb"]);
+ assert.notEqual(locationHealth("usb")?.state, "stalled", "a stale record is cleared by the answer");
+ assert.equal(hold.check(), null, "and the next pull resumes");
+ assert.match(lines.join("\n"), /answered a stat of its root after 1 min held — no health pass was keeping its stall record/);
+ assert.equal(lines.at(-1), `The media drive "USB drive" answers again — resuming.`);
+});
+
+test("a record a pass still keeps: the probe's answer counts once, and the pass decides", async () => {
+ const { locationHealth } = await import("./storageHealth");
+ let t = Date.now();
+ registerLocationHealth([USB], t);
+ recordLocationHealth(USB, "stalled", { now: t });
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, () => {}, "x", {
+ now: () => t,
+ reprobeAfterMs: 1_000,
+ reprobe: async () => "ok",
+ });
+ hold.check();
+ t += 1_500;
+ // A pass answered moments ago (the counters still say stalled).
+ recordLocationHealth(USB, "stalled", { now: t });
+ hold.check();
+ await tick();
+ await tick();
+ const h = locationHealth("usb");
+ assert.equal(h?.state, "stalled", "one clean answer does not clear (two are needed)");
+ assert.equal(h?.cleanStreak, 1);
+});
+
+test("a drive that does not answer the probe stays held, and 'still holding' is logged every interval", async () => {
+ let t = 5_000_000;
+ registerLocationHealth([USB], t);
+ recordLocationHealth(USB, "stalled", { now: t });
+ const lines: string[] = [];
+ let probes = 0;
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, (l) => lines.push(l), "x", {
+ now: () => t,
+ reprobeAfterMs: 300_000,
+ stillHoldingEveryMs: 600_000,
+ reprobe: async () => {
+ probes++;
+ return "stalled";
+ },
+ });
+ for (let i = 0; i < 25; i++) {
+ hold.check();
+ await tick();
+ t += 60_000;
+ }
+ assert.ok(hold.check());
+ const still = lines.filter((l) => l.startsWith("Still holding"));
+ assert.deepEqual(still, [
+ `Still holding: the media drive "USB drive" has not answered after 10 min.`,
+ `Still holding: the media drive "USB drive" has not answered after 20 min.`,
+ ]);
+ // Once per reprobeAfterMs (5 min) after the first 5 min: at 5, 10, 15, 20, 25.
+ assert.equal(probes, 5);
+});
+
+test("the config is re-read: a channel moved off the stalled drive mid-batch resumes", async () => {
+ let t = 0;
+ registerLocationHealth([USB], t);
+ recordLocationHealth(USB, "stalled", { now: t });
+ let config = { mediaDir: "/mnt/usb/c/media" };
+ const hold = mediaStallHold(config, () => {}, "x", {
+ now: () => t,
+ reloadEveryMs: 10_000,
+ reloadConfig: async () => config,
+ });
+ assert.ok(hold.check());
+ config = { mediaDir: "/mnt/other/c/media" };
+ t += 5_000;
+ hold.check();
+ await tick();
+ assert.ok(hold.check(), "not re-read before reloadEveryMs");
+ t += 6_000;
+ hold.check();
+ await tick();
+ assert.equal(hold.check(), null);
+});
+
+test("pruning a location no longer configured clears its record, and a hold on it releases", async () => {
+ const { pruneLocationHealth, locationHealth } = await import("./storageHealth");
+ registerLocationHealth([USB]);
+ recordLocationHealth(USB, "stalled");
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, () => {}, "x");
+ assert.ok(hold.check());
+ pruneLocationHealth(["some-other-location"]);
+ assert.equal(locationHealth("usb"), undefined);
+ assert.equal(hold.check(), null);
+});
diff --git a/common/lib/mediaStallHold.ts b/common/lib/mediaStallHold.ts
@@ -0,0 +1,179 @@
+import { channelMediaStall, type ChannelMediaConfig } from "./channelMedia";
+import {
+ healthTimings,
+ locationHealth,
+ recordLocationHealth,
+ sinceText,
+ type LocationHealth,
+ type LocationHealthState,
+} from "./storageHealth";
+import { probeLocationHealth } from "./storageVolumes";
+
+// 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.
+//
+// THE CHECK IS MEMORY: `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, and "still holding" every
+// `stillHoldingEveryMs` (10 min) between.
+//
+// IT HEALS ITSELF (review of lane drive-stall). The record is cleared by the
+// health pass; a process with no pass covering the location (a CLI, a stall
+// recorded for a location the pass no longer covers) would otherwise hold for
+// ever. So once the hold has lasted `reprobeAfterMs` (5 min), and at most once
+// per that interval, it asks the drive itself — OUT OF PROCESS, a child `stat`
+// of the root raced against the probe timeout, which holds no thread of ours.
+// When the root answers:
+// - a record no pass has refreshed for three pass intervals is stale: the
+// answer clears it (as many clean answers as the clear rule needs), and
+// the batch resumes;
+// - a record a pass still keeps counts the answer once, as /storage's
+// Refresh does, and the pass decides: a child `stat` can be answered from
+// the kernel's cache while the device's own counters say stalled.
+//
+// THE CONFIG IS RE-READ (`reloadConfig`, at most every `reloadEveryMs`, 10 s,
+// in the background): a channel moved to another location mid-batch is held
+// by the drive its media is on now.
+
+export type MediaStallHold = {
+ // The stalled location now, or null. Logs on each edge.
+ check: () => LocationHealth | null;
+};
+
+export type MediaStallHoldOptions = {
+ // Re-read the channel's targets (default: never). The check uses the last
+ // answer; a read that fails keeps the one before.
+ reloadConfig?: () => Promise<ChannelMediaConfig | null | undefined>;
+ reloadEveryMs?: number;
+ // The out-of-process probe of a root (default: a child `stat`,
+ // `probeLocationHealth`). Test seam.
+ reprobe?: (root: string) => Promise<LocationHealthState>;
+ reprobeAfterMs?: number;
+ stillHoldingEveryMs?: number;
+ now?: () => number;
+};
+
+export const MEDIA_HOLD_REPROBE_AFTER_MS = 5 * 60_000;
+export const MEDIA_HOLD_STILL_EVERY_MS = 10 * 60_000;
+const RELOAD_EVERY_MS = 10_000;
+
+function minutesText(ms: number): string {
+ const m = Math.max(0, Math.round(ms / 60_000));
+ return `${m} min`;
+}
+
+export function mediaStallHold(
+ initialConfig: ChannelMediaConfig | null | undefined,
+ log: (line: string) => void,
+ what: string,
+ opts: MediaStallHoldOptions = {},
+): MediaStallHold {
+ const now = opts.now ?? Date.now;
+ const reprobeAfter = opts.reprobeAfterMs ?? MEDIA_HOLD_REPROBE_AFTER_MS;
+ const stillEvery = opts.stillHoldingEveryMs ?? MEDIA_HOLD_STILL_EVERY_MS;
+ const reloadEvery = opts.reloadEveryMs ?? RELOAD_EVERY_MS;
+ const reprobe = opts.reprobe ?? ((root: string) => probeLocationHealth({ root }));
+ let config = initialConfig;
+ let lastReload = now();
+ let reloading = false;
+ let holding: LocationHealth | null = null;
+ let heldAt = 0;
+ let lastStill = 0;
+ let lastReprobe = 0;
+ let reprobing = false;
+
+ const maybeReload = () => {
+ if (!opts.reloadConfig || reloading || now() - lastReload < reloadEvery) return;
+ reloading = true;
+ lastReload = now();
+ void opts
+ .reloadConfig()
+ .then(
+ (next) => {
+ if (next !== undefined) config = next;
+ },
+ () => {},
+ )
+ .finally(() => {
+ reloading = false;
+ });
+ };
+
+ const maybeReprobe = (stall: LocationHealth) => {
+ const t = now();
+ if (reprobing || t - heldAt < reprobeAfter || t - lastReprobe < reprobeAfter) return;
+ reprobing = true;
+ lastReprobe = t;
+ void reprobe(stall.root)
+ .then(
+ (answer) => {
+ if (answer === "stalled") return;
+ const current = locationHealth(stall.id);
+ if (!current || current.root !== stall.root || current.state !== "stalled") return;
+ const loc = { id: stall.id, label: stall.label, root: stall.root };
+ const stale = now() - current.checkedAt >= healthTimings().passIntervalMs * 3;
+ // Stale: no pass is keeping it, and the drive answered — enough
+ // clean answers to clear it. Kept by a pass: one answer.
+ const answers = stale ? healthTimings().clearAfterCleanPasses : 1;
+ for (let i = 0; i < answers; i++) {
+ recordLocationHealth(loc, answer, { detector: "stat", device: null });
+ }
+ log(
+ `The media drive "${stall.label}" answered a stat of its root after ` +
+ `${minutesText(t - heldAt)} held` +
+ (stale
+ ? " — no health pass was keeping its stall record, so the stall is cleared."
+ : "; its health pass decides when the stall ends."),
+ );
+ },
+ () => {},
+ )
+ .finally(() => {
+ reprobing = false;
+ });
+ };
+
+ return {
+ check: () => {
+ maybeReload();
+ const stall = channelMediaStall(config);
+ const t = now();
+ if (stall && !holding) {
+ heldAt = t;
+ lastStill = t;
+ 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) {
+ if (t - lastStill >= stillEvery) {
+ lastStill = t;
+ log(
+ `Still holding: the media drive "${stall.label}" has not answered after ${minutesText(t - heldAt)}.`,
+ );
+ }
+ } else if (!stall && holding) {
+ log(`The media drive "${holding.label}" answers again — resuming.`);
+ }
+ holding = stall;
+ if (stall) maybeReprobe(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)})`;
+}
diff --git a/common/lib/savedVideoStore.test.ts b/common/lib/savedVideoStore.test.ts
@@ -166,3 +166,53 @@ async function exists(p: string): Promise<boolean> {
return (err as NodeJS.ErrnoException).code === "EISDIR";
}
}
+
+// A STORE ON A DRIVE THAT IS NOT ANSWERING IS NOT WRITTEN (lane drive-stall):
+// the corpus store through its link, a channel's own store as given; the
+// container stays in the video dir, and nothing touches the stalled drive.
+test("a store whose drive is not answering refuses the write, and the container stays put", async () => {
+ const { symlink } = await import("node:fs/promises");
+ const { recordLocationHealth, resetStorageHealth } = await import("./storageHealth");
+ const { SavedVideosStoreNotAnsweringError } = await import("./savedVideoStore");
+ await withTmp(async (paths, videoDir) => {
+ const platter = path.join(path.dirname(paths.transcriptsDir), "platter");
+ const target = path.join(platter, "saved-videos");
+ await mkdir(target, { recursive: true });
+ await rm(paths.savedVideosDir, { recursive: true, force: true });
+ await symlink(target, paths.savedVideosDir);
+ const loc = { id: "platter", label: "Platter", root: platter };
+ try {
+ // Answering: the guard passes.
+ recordLocationHealth(loc, "ok");
+ await assertSavedVideosStoreWritable(paths, path.join(paths.savedVideosDir, "chan"));
+ // Not answering: refused, for the corpus store and for a channel store on it.
+ recordLocationHealth(loc, "stalled", { cause: "test" });
+ await assert.rejects(
+ assertSavedVideosStoreWritable(paths, path.join(paths.savedVideosDir, "chan")),
+ (err: unknown) =>
+ err instanceof SavedVideosStoreNotAnsweringError &&
+ /^The saved-video store's drive "Platter" is not answering \(since \d\d:\d\d\)/.test(err.message),
+ );
+ await assert.rejects(
+ assertSavedVideosStoreWritable(paths, path.join(platter, "own-store")),
+ SavedVideosStoreNotAnsweringError,
+ );
+ // A store elsewhere is not held by this drive.
+ await assertSavedVideosStoreWritable(paths, path.join(paths.transcriptsDir, "elsewhere"));
+ await writeFile(path.join(videoDir, "source-media.mp4"), "container");
+ await assert.rejects(
+ persistSourceVideo({
+ videoDir,
+ sourceFilename: "source-media.mp4",
+ storeDir: path.join(paths.savedVideosDir, "chan"),
+ keepReason: "pin",
+ paths,
+ }),
+ SavedVideosStoreNotAnsweringError,
+ );
+ assert.equal(await readFile(path.join(videoDir, "source-media.mp4"), "utf8"), "container");
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
diff --git a/common/lib/savedVideoStore.ts b/common/lib/savedVideoStore.ts
@@ -1,7 +1,8 @@
import path from "node:path";
-import { readFile } from "node:fs/promises";
+import { readFile, readlink } from "node:fs/promises";
import type { Paths } from "./paths";
import type { RelocationMarker } from "./channelMedia";
+import { sinceText, stalledLocationForPath, type LocationHealth } from "./storageHealth";
// IS THE SAVED-VIDEO STORE SAFE TO WRITE INTO RIGHT NOW?
//
@@ -109,7 +110,58 @@ export async function assertSavedVideosStoreWritable(
paths: Pick<Paths, "transcriptsDir" | "savedVideosDir">,
storeDir: string,
): Promise<void> {
- if (!isInCorpusSavedVideoStore(paths, storeDir)) return;
+ const corpus = isInCorpusSavedVideoStore(paths, storeDir);
+ // A STORE ON A DRIVE THAT IS NOT ANSWERING IS NOT WRITTEN (lane drive-stall).
+ // The move into it is in-process (`moveFileCrossDevice`), and on a stalled
+ // drive every call of it holds one of Node's file threads until the kernel
+ // gives up. Memory only: the health record, matched against the store's
+ // path — a channel's own store as given, the corpus store through its link
+ // (`readlink` reads the corpus disk, never the target).
+ const where = corpus
+ ? await readlink(paths.savedVideosDir).catch(() => paths.savedVideosDir)
+ : storeDir;
+ const stall = stalledLocationForPath(where);
+ if (stall) throw new SavedVideosStoreNotAnsweringError(stall);
+ if (!corpus) return;
const marker = await readSavedVideosMarker(paths);
if (marker) throw new SavedVideosStoreInTransitionError(marker);
}
+
+// Thrown by assertSavedVideosStoreWritable when the store's drive is not
+// answering. Every persist caller already catches a refusal here and leaves
+// the container where it is, to be persisted on a later pass.
+export class SavedVideosStoreNotAnsweringError extends Error {
+ readonly health: LocationHealth;
+ constructor(health: LocationHealth) {
+ super(
+ `The saved-video store's drive "${health.label}" is not answering ` +
+ `(${sinceText(health.since)}) — nothing is written into it until it answers.`,
+ );
+ this.name = "SavedVideosStoreNotAnsweringError";
+ this.health = health;
+ }
+}
+
+// THE STORE'S REFUSAL, AS A VALUE (review of lane drive-stall): the error the
+// guard above would throw for a write into `storeDir` — the store's drive not
+// answering, or the store mid-move — or null. A batch that FETCHES before it
+// persists (persist-videos, persist-kept: a whole source container per video)
+// asks this before each download, so a store that cannot take the container
+// stops the run instead of downloading one only to leave it in the data dir.
+export async function savedVideosStoreRefusal(
+ paths: Pick<Paths, "transcriptsDir" | "savedVideosDir">,
+ storeDir: string,
+): Promise<SavedVideosStoreNotAnsweringError | SavedVideosStoreInTransitionError | null> {
+ try {
+ await assertSavedVideosStoreWritable(paths, storeDir);
+ return null;
+ } catch (err) {
+ if (
+ err instanceof SavedVideosStoreNotAnsweringError ||
+ err instanceof SavedVideosStoreInTransitionError
+ ) {
+ return err;
+ }
+ throw err;
+ }
+}
diff --git a/common/lib/storageHealth.test.ts b/common/lib/storageHealth.test.ts
@@ -3,6 +3,10 @@ import assert from "node:assert/strict";
import {
DriveNotAnsweringError,
allLocationHealth,
+ driveHealthView,
+ noteDriveAnswer,
+ slowThresholdMs,
+ slowWindowMs,
applyHealthTimings,
driveCallsInFlight,
healthTimings,
@@ -689,3 +693,108 @@ test("rootOfUnknownPath strips <root>/<slug>/media (release 17) and the retired
assert.equal(rootOfUnknownPath("/mnt/p/chan/data"), "/mnt/p");
assert.equal(rootOfUnknownPath("/mnt/p/chan/other"), "/mnt/p/chan/other");
});
+
+// ── answering, slow, not answering, not mounted (lane drive-stall) ──────────
+
+test("the drive's four words: ok → slow → stalled → ok, from what the watchdog measured", async () => {
+ registerLocationHealth([USB], 1_000);
+ const fresh = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(fresh.state, "ok");
+ assert.equal(fresh.lastOkAt, undefined, "a registration is not an answer");
+ assert.equal(fresh.text, "answering (not asked yet)");
+
+ // A quick unit: answered, measured, ok.
+ setDriveCallBudget(200);
+ assert.equal(slowThresholdMs(), 100);
+ await onDrive(USB, async () => "quick");
+ const ok = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(ok.state, "ok");
+ assert.equal(typeof ok.lastOkAt, "number");
+ assert.equal(ok.latencyFrom, "call");
+ assert.match(ok.text, /^answering — \d+ ms \(a read in the editor\), last at \d\d:\d\d$/);
+
+ // A unit past half the budget: answered. One is not slow (a big unit, a
+ // spin-up); two in a row are. Nothing refuses either.
+ const lateUnit = () => onDrive(USB, () => new Promise((r) => setTimeout(() => r("late"), 130)));
+ assert.equal(await lateUnit(), "late");
+ assert.equal(driveHealthView(USB, locationHealth("usb")).state, "ok", "one slow reading is not slow");
+ assert.equal(await lateUnit(), "late");
+ const slow = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(slow.state, "slow");
+ assert.match(String(slow.cause), /^a read in the editor took \d+ ms$/);
+ assert.match(slow.text, /^slow at \d\d:\d\d — a read in the editor took/);
+ assert.equal(stalledLocation(USB), null, "slow is shown, never acted on");
+
+ // A unit that never answers: stalled, and the stall supersedes slow.
+ await assert.rejects(onDrive(USB, () => new Promise(() => {})), DriveNotAnsweringError);
+ const stalled = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(stalled.state, "stalled");
+ assert.match(stalled.text, /^not answering since \d\d:\d\d — a read in the editor did not answer/);
+
+ // Two clean answers clear it — and it is ok, not slow, after.
+ recordLocationHealth(USB, "ok");
+ recordLocationHealth(USB, "ok");
+ const back = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(back.state, "ok");
+ assert.equal(locationHealth("usb")?.slowAt, undefined);
+});
+
+test("slow lasts two passes from its last sighting, then reads ok again", () => {
+ registerLocationHealth([USB], 0);
+ noteDriveAnswer("usb", 2_000, "stat", 9_000);
+ assert.equal(locationHealth("usb")?.slowAt, undefined, "one reading is not slow");
+ noteDriveAnswer("usb", 2_000, "stat", 10_000);
+ const h = locationHealth("usb");
+ assert.equal(h?.slowAt, 10_000);
+ assert.equal(h?.lastOkAt, 10_000);
+ assert.equal(slowWindowMs(), 30_000);
+ assert.equal(driveHealthView(USB, h, { now: 10_000 + 29_999 }).state, "slow");
+ assert.equal(driveHealthView(USB, h, { now: 10_000 + 30_000 }).state, "ok");
+ // The counters' average is the disk's own figure: it sets the latency and
+ // can be slow, but it is not an answer to us.
+ noteDriveAnswer("usb", 5, "counters", 50_000);
+ const after = locationHealth("usb");
+ assert.equal(after?.latencyMs, 5);
+ assert.equal(after?.latencyFrom, "counters");
+ assert.equal(after?.lastOkAt, 10_000);
+ // A location with no entry records nothing.
+ noteDriveAnswer("nowhere", 9_000, "call");
+ assert.equal(locationHealth("nowhere"), undefined);
+});
+
+test("not mounted: the health record's `absent`, or the mount probe's word; a stall wins over both", () => {
+ recordLocationHealth(USB, "absent", { now: 7 });
+ const gone = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(gone.state, "unmounted");
+ assert.equal(gone.since, 7);
+ assert.equal(gone.text, "not mounted");
+ resetStorageHealth();
+ registerLocationHealth([USB]);
+ assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "unmounted");
+ assert.equal(driveHealthView(USB, undefined, { mounted: false }).state, "unmounted");
+ recordLocationHealth(USB, "stalled", { cause: "no answer" });
+ assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "stalled");
+});
+
+test("the watchdog's slow refusal is a sighting of slow, and marks nothing", async () => {
+ registerLocationHealth([USB]);
+ setDriveCallBudget(60);
+ let completed = 0;
+ setCounterReader(() => ({ completed: (completed += 5), inFlight: 1 }));
+ recordLocationHealth(USB, "ok", { detector: "counters", device: "sdz" });
+ await assert.rejects(onDrive(USB, () => new Promise(() => {})), /drive slow/);
+ const h = locationHealth("usb");
+ assert.equal(h?.state, "ok");
+ assert.match(String(h?.slowCause), /did not answer within .*still completing others/);
+ assert.equal(driveHealthView(USB, h).state, "slow");
+});
+
+test("a fast reading between two slow ones starts the count again", () => {
+ registerLocationHealth([USB], 0);
+ noteDriveAnswer("usb", 2_000, "call", 1);
+ noteDriveAnswer("usb", 3, "call", 2);
+ noteDriveAnswer("usb", 2_000, "call", 3);
+ assert.equal(locationHealth("usb")?.slowAt, undefined);
+ noteDriveAnswer("usb", 2_000, "call", 4);
+ assert.equal(locationHealth("usb")?.slowAt, 4);
+});
diff --git a/common/lib/storageHealth.ts b/common/lib/storageHealth.ts
@@ -102,6 +102,28 @@ export type LocationHealth = {
// The block device the counters detector reads for this location, when it
// could name one. The watchdog reads its counters too (see `onDrive`).
device?: string;
+ // WHEN THE DRIVE LAST ANSWERED, ms since epoch (lane drive-stall): a pass's
+ // clean verdict that found the root (`ok`), or a call through `onDrive` that
+ // answered within its budget. Absent: not yet, in this process.
+ lastOkAt?: number;
+ // HOW LONG IT TOOK, the latest measurement, in ms, and what measured it:
+ // `call`, a whole unit through `onDrive`; `stat`, the health pass's child
+ // `stat` of the root (its round trip, process start included); `counters`,
+ // the block device's own average per completed request over the pass's
+ // sample interval (`/sys/class/block/<dev>/stat` fields 4 and 8, the time
+ // its reads and writes took, over the requests that completed).
+ latencyMs?: number;
+ latencyFrom?: "call" | "stat" | "counters";
+ // WHEN IT WAS LAST SEEN SLOW, and why: answering, but two measurements in a row reached
+ // `slowThresholdMs()` (half the budget), or the watchdog refused a call as
+ // slow (its disk still completing others). Slow is shown, never acted on:
+ // nothing refuses a slow drive that the budget does not.
+ slowAt?: number;
+ slowCause?: string;
+ // Consecutive measurements at or past `slowThresholdMs()`. Slow is sighted
+ // at SLOW_READINGS_IN_A_ROW (2): one long unit (a big walk, a cold spin-up)
+ // is not a slow drive.
+ slowStreak?: number;
};
// THE DEFAULTS, and why they are what they are (lib/storageHealthTimings.ts
@@ -259,7 +281,9 @@ export function recordLocationHealth(
device?: string | null;
} = {},
): HealthTransition | null {
- const t = recordAnswer(loc, answer, opts);
+ // Every answer recorded here is a detector's (a pass, a Refresh, the
+ // watchdog); `registerLocationHealth` creates entries without one.
+ const t = recordAnswer(loc, answer, { ...opts, answered: true });
// EVERY TRANSITION TO STALLED refuses the calls waiting for a slot on the
// location, whoever decided it (the pass, the watchdog, a Refresh): they
// would otherwise wait for a slot held by a call the drive is not answering.
@@ -277,6 +301,8 @@ function recordAnswer(
cause?: string;
detector?: HealthDetector;
device?: string | null;
+ // A detector's answer, not a registration: an `ok` then sets `lastOkAt`.
+ answered?: boolean;
},
): HealthTransition | null {
const now = opts.now ?? Date.now();
@@ -296,11 +322,14 @@ function recordAnswer(
checkedAt: now,
cleanStreak: 0,
...(answer === "stalled" && opts.cause ? { cause: opts.cause } : {}),
+ ...(answer === "ok" && opts.answered ? { lastOkAt: now } : {}),
});
return { id: loc.id, from: null, to: answer };
}
prev.label = label;
prev.checkedAt = now;
+ // An `ok` from a detector is the drive answering (a registration is not).
+ if (answer === "ok" && opts.answered) prev.lastOkAt = now;
if (opts.detector) prev.detector = opts.detector;
if (opts.device === null) delete prev.device;
else if (opts.device) prev.device = opts.device;
@@ -311,6 +340,11 @@ function recordAnswer(
prev.state = "stalled";
prev.since = now;
if (opts.cause) prev.cause = opts.cause;
+ // A stall supersedes slow: once it clears, the drive starts answering
+ // afresh, and an old slow sighting is not what it is doing now.
+ delete prev.slowAt;
+ delete prev.slowCause;
+ delete prev.slowStreak;
return { id: loc.id, from, to: "stalled" };
}
if (prev.state === "stalled") {
@@ -344,7 +378,8 @@ export function registerLocationHealth(
prev.label = loc.label || loc.id;
continue;
}
- recordLocationHealth(loc, "ok", { now });
+ // Not an answer: an entry with no `lastOkAt` (nothing has asked yet).
+ recordAnswer(loc, "ok", { now });
}
}
@@ -408,10 +443,10 @@ export function stalledLocation(
return h && h.state === "stalled" && h.root === loc.root ? { ...h } : null;
}
-// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the
-// stall began on another day than `now`.
-export function sinceText(since: number, now: number = Date.now()): string {
- const d = new Date(since);
+// "11:35" in the server's clock, or "2026-09-28 11:35" when `at` is on another
+// day than `now`.
+export function clockText(at: number, now: number = Date.now()): string {
+ const d = new Date(at);
const n = new Date(now);
const pad = (x: number) => String(x).padStart(2, "0");
const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
@@ -419,9 +454,13 @@ export function sinceText(since: number, now: number = Date.now()): string {
d.getFullYear() === n.getFullYear() &&
d.getMonth() === n.getMonth() &&
d.getDate() === n.getDate();
- return sameDay
- ? `since ${hm}`
- : `since ${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`;
+ return sameDay ? hm : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`;
+}
+
+// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the
+// stall began on another day than `now`.
+export function sinceText(since: number, now: number = Date.now()): string {
+ return `since ${clockText(since, now)}`;
}
// "not answering since 11:35" — the one line /storage, the /channels volume bar
@@ -431,6 +470,162 @@ export function notAnsweringText(h: Pick<LocationHealth, "since">, now?: number)
}
// ---------------------------------------------------------------------------
+// Answering, slow, not answering, not mounted: the four words a surface shows
+// ---------------------------------------------------------------------------
+//
+// THE STATE ABOVE IS WHAT THE GATE ACTS ON (`stalled` or not). A person asking
+// "is the drive all right" wants two more facts: whether it is there at all
+// (an unmounted drive answers at once, with ENOENT — not a stall, and not
+// health), and whether it is answering SLOWLY — a disk grinding through a long
+// write answers every read, a second late. Slow is shown and never acted on:
+// the budget is what refuses, and a slow drive under it is still working.
+
+// A measurement at or past this is slow: half the watchdog's budget (1.5 s by
+// default). A unit at half its budget is half way to being refused.
+export function slowThresholdMs(): number {
+ return Math.round(driveCallBudget() / 2);
+}
+
+// How long one slow measurement keeps a drive "slow": two passes (30 s by
+// default), so a single slow read is visible for a pass or two and a drive
+// slow on every read stays slow.
+export function slowWindowMs(): number {
+ return healthTimings().passIntervalMs * 2;
+}
+
+// "12 ms", "1.4 s".
+export function latencyText(ms: number): string {
+ return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
+}
+
+const LATENCY_WORDS: Record<NonNullable<LocationHealth["latencyFrom"]>, string> = {
+ call: "a read in the editor",
+ stat: "a stat of its root",
+ counters: "its disk's average request",
+};
+
+// THE DRIVE ANSWERED: a measurement of how long it took. Recorded for a
+// location that has an entry (registered or answered); a path on no
+// configured location has none, and this does nothing for it. The second
+// measurement in a row at or past `slowThresholdMs()` is a sighting of slow.
+export function noteDriveAnswer(
+ id: string,
+ latencyMs: number,
+ from: NonNullable<LocationHealth["latencyFrom"]>,
+ now: number = Date.now(),
+): void {
+ const h = healthState().byId.get(id);
+ if (!h || !Number.isFinite(latencyMs) || latencyMs < 0) return;
+ h.latencyMs = Math.round(latencyMs);
+ h.latencyFrom = from;
+ // An average per request is the disk's own figure, not an answer to us; the
+ // other two are the drive answering.
+ if (from !== "counters") h.lastOkAt = now;
+ if (latencyMs >= slowThresholdMs()) {
+ h.slowStreak = (h.slowStreak ?? 0) + 1;
+ if (h.slowStreak >= SLOW_READINGS_IN_A_ROW) {
+ h.slowAt = now;
+ h.slowCause = `${LATENCY_WORDS[from]} took ${latencyText(latencyMs)}`;
+ }
+ } else {
+ h.slowStreak = 0;
+ }
+}
+
+// Two slow measurements in a row before a drive reads slow (review of lane
+// drive-stall): one long unit must not flash the banner.
+export const SLOW_READINGS_IN_A_ROW = 2;
+
+// THE DRIVE IS SLOW, NOT STALLED: the watchdog refused a call past its budget
+// while the disk was still completing others (`onDrive`, `acquireSlot`).
+export function noteDriveSlow(id: string, cause: string, now: number = Date.now()): void {
+ const h = healthState().byId.get(id);
+ if (!h) return;
+ h.slowAt = now;
+ h.slowCause = cause;
+}
+
+export type DriveHealthState = "ok" | "slow" | "stalled" | "unmounted";
+
+// ONE LOCATION'S DRIVE, as every surface and `pnpm ops get storage` reports it.
+export type DriveHealthView = {
+ id: string;
+ label: string;
+ state: DriveHealthState;
+ // stalled: when it stopped answering; slow: when it was last seen slow;
+ // unmounted: when the health record last found the root missing (absent
+ // when only the mount probe says so).
+ since?: number;
+ // When the drive last answered (see `LocationHealth.lastOkAt`).
+ lastOkAt?: number;
+ latencyMs?: number;
+ latencyFrom?: LocationHealth["latencyFrom"];
+ detector?: HealthDetector;
+ // stalled: what did not answer; slow: what was slow.
+ cause?: string;
+ // The one line: "answering — 12 ms (a read in the editor) at 11:42",
+ // "slow at 11:42 — a read in the editor took 2.1 s", "not answering since
+ // 11:35 — …", "not mounted".
+ text: string;
+};
+
+// The view of one location's drive. `mounted: false` is the mount probe's
+// answer (`StorageLocationStatus` other than available or stalled), which
+// the health record does not carry when the counters detector watches it;
+// omitted, only the record decides.
+export function driveHealthView(
+ loc: Pick<StorageLocation, "id" | "label">,
+ h: LocationHealth | undefined,
+ opts: { now?: number; mounted?: boolean } = {},
+): DriveHealthView {
+ const now = opts.now ?? Date.now();
+ const base = {
+ id: loc.id,
+ label: loc.label || loc.id,
+ ...(h?.lastOkAt !== undefined ? { lastOkAt: h.lastOkAt } : {}),
+ ...(h?.latencyMs !== undefined ? { latencyMs: h.latencyMs } : {}),
+ ...(h?.latencyFrom ? { latencyFrom: h.latencyFrom } : {}),
+ ...(h?.detector ? { detector: h.detector } : {}),
+ };
+ if (h?.state === "stalled") {
+ return {
+ ...base,
+ state: "stalled",
+ since: h.since,
+ ...(h.cause ? { cause: h.cause } : {}),
+ text: `${notAnsweringText(h, now)}${h.cause ? ` — ${h.cause}` : ""}`,
+ };
+ }
+ if (h?.state === "absent" || opts.mounted === false) {
+ return {
+ ...base,
+ state: "unmounted",
+ ...(h?.state === "absent" ? { since: h.since } : {}),
+ text: "not mounted",
+ };
+ }
+ if (h?.slowAt !== undefined && now - h.slowAt < slowWindowMs()) {
+ return {
+ ...base,
+ state: "slow",
+ since: h.slowAt,
+ ...(h.slowCause ? { cause: h.slowCause } : {}),
+ text: `slow at ${clockText(h.slowAt, now)}${h.slowCause ? ` — ${h.slowCause}` : ""}`,
+ };
+ }
+ const measured =
+ h?.latencyMs !== undefined && h.latencyFrom
+ ? ` — ${latencyText(h.latencyMs)} (${LATENCY_WORDS[h.latencyFrom]})`
+ : "";
+ const last = h?.lastOkAt !== undefined ? `, last at ${clockText(h.lastOkAt, now)}` : "";
+ return {
+ ...base,
+ state: "ok",
+ text: h?.lastOkAt === undefined && !measured ? "answering (not asked yet)" : `answering${measured}${last}`,
+ };
+}
+
+// ---------------------------------------------------------------------------
// The watchdog: every call the gate covers, raced against the budget
// ---------------------------------------------------------------------------
//
@@ -589,11 +784,11 @@ async function acquireSlot(r: Resolved): Promise<void> {
const oldest = overdue.reduce((a, b) => (b.startedAt < a.startedAt ? b : a));
const now = readDeviceCounters(r.loc);
if (oldest.before && now && now.completed > oldest.before.completed) {
- throw new DriveNotAnsweringError(
- null,
- `drive slow (${overdue.length} reads on it are past ` +
- `${secondsText(driveCallBudget())}, while its disk is still completing others)`,
- );
+ const detail =
+ `${overdue.length} reads on it are past ` +
+ `${secondsText(driveCallBudget())}, while its disk is still completing others`;
+ if (r.loc) noteDriveSlow(r.loc.id, detail);
+ throw new DriveNotAnsweringError(null, `drive slow (${detail})`);
}
let health: LocationHealth | null = null;
if (r.loc) {
@@ -768,6 +963,9 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise<
}
if (answer !== TIMED_OUT) {
release();
+ // THE DRIVE ANSWERED, and how long the unit took. A call that threw
+ // answered too, but its time says nothing (ENOENT is instant).
+ if (r.loc) noteDriveAnswer(r.loc.id, Date.now() - startedAt, "call");
return answer;
}
// The call is still waiting on the drive. Its slot stays held, and counted
@@ -784,11 +982,11 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise<
const after = readDeviceCounters(r.loc);
if (before && after && after.completed > before.completed) {
// SLOW, NOT STALLED: the disk completed requests while this call waited.
- throw new DriveNotAnsweringError(
- null,
- `drive slow (a read did not answer within ${secondsText(budget)}, ` +
- `while its disk was still completing others)`,
- );
+ const detail =
+ `a read did not answer within ${secondsText(budget)}, ` +
+ `while its disk was still completing others`;
+ if (r.loc) noteDriveSlow(r.loc.id, detail);
+ throw new DriveNotAnsweringError(null, `drive slow (${detail})`);
}
if (r.loc) {
recordLocationHealth(r.loc, "stalled", {
diff --git a/common/lib/storageHealthCounters.test.ts b/common/lib/storageHealthCounters.test.ts
@@ -5,6 +5,8 @@ import { tmpdir } from "node:os";
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import {
blockDeviceName,
+ blockStatTicksMs,
+ countersLatencyMs,
detectLocationHealth,
minCounterIntervalMs,
resetHealthDetector,
@@ -193,9 +195,13 @@ test("no device → the child stat, and the verdict says so", async () => {
const opts = { sysBlockDir: h.sys, now: 0 };
// A tmpfs or network source names no block device.
await h.control({ source: "tmpfs" });
- assert.deepEqual(await detectLocationHealth(loc(h.root), h.bins, opts), {
+ // The verdict carries the child's round trip (lane drive-stall).
+ const viaStat = await detectLocationHealth(loc(h.root), h.bins, opts);
+ assert.equal(typeof viaStat.latencyMs, "number");
+ assert.deepEqual({ ...viaStat, latencyMs: 0 }, {
answer: "ok",
detector: "stat",
+ latencyMs: 0,
});
// findmnt cannot say (no such path, a container without it).
await h.control({ exit: 1 });
@@ -258,3 +264,45 @@ test("a device already named is read without findmnt; findmnt again only when it
assert.ok(globalThis.__yttHealthDetector__);
});
});
+
+// ── the disk's own latency (lane drive-stall) ───────────────────────────────
+
+test("the stat line's request time: fields 4 + 8 (+ 15 + 17), and the average per completed request", () => {
+ // The real line above: 80435430 ms reading, 167469727 writing, 4100450
+ // discarding, 1212688 flushing.
+ assert.equal(blockStatTicksMs(LINE), 80435430 + 167469727 + 4100450 + 1212688);
+ // An 11-field line has no discard or flush time.
+ assert.equal(blockStatTicksMs("10 0 0 40 5 0 0 20 3 0 0"), 60);
+ assert.equal(blockStatTicksMs("1 2 3"), null);
+ // 30 requests completed in 900 ms of request time: 30 ms each.
+ assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 130, ticksMs: 1900 }), 30);
+ // Nothing completed: no latency to report (an idle disk, or a stalled one).
+ assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 100, ticksMs: 1000 }), undefined);
+ // No time fields on one side: nothing.
+ assert.equal(countersLatencyMs({ completed: 100 }, { completed: 130, ticksMs: 5 }), undefined);
+});
+
+test("counters: an ok verdict carries the disk's average request time; a stalled one none", async () => {
+ await withHarness(async (h) => {
+ await h.control({ source: "/dev/fakedisk2", uuid: "u-2" });
+ const at = (i: number) => ({ sysBlockDir: h.sys, now: i * 15_000 });
+ const line = async (completed: number, readMs: number, inFlight: number) => {
+ await mkdir(path.join(h.sys, "fakedisk2"), { recursive: true });
+ await writeFile(
+ path.join(h.sys, "fakedisk2", "stat"),
+ `${completed} 0 0 ${readMs} 0 0 0 0 ${inFlight} 0 0 0 0 0 0 0 0\n`,
+ );
+ };
+ await line(100, 1_000, 1);
+ assert.equal((await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(1))).answer, null);
+ // 10 completed in 20 s of request time: 2 s each — a slow disk, answering.
+ await line(110, 21_000, 1);
+ const slow = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(2));
+ assert.equal(slow.answer, "ok");
+ assert.equal(slow.latencyMs, 2_000);
+ await line(110, 21_000, 1);
+ const stuck = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(3));
+ assert.equal(stuck.answer, "stalled");
+ assert.equal(stuck.latencyMs, undefined);
+ });
+});
diff --git a/common/lib/storageVolumes.ts b/common/lib/storageVolumes.ts
@@ -377,6 +377,10 @@ export type HealthVerdict = {
cause?: string;
// The block device the counters were read from.
device?: string;
+ // How long the drive took (lib/storageHealth.ts `noteDriveAnswer`): the
+ // counters' average per completed request between the two samples, or the
+ // child `stat`'s round trip. Absent when nothing was measured.
+ latencyMs?: number;
};
// What the health pass asks about a location. A bare state is a verdict with
@@ -473,7 +477,31 @@ export function minCounterIntervalMs(): number {
return counterSampleMinimumMs(healthTimings().passIntervalMs);
}
-type CounterSample = BlockStatSample & { device: string; at: number };
+// `ticksMs`: fields 4 + 8 (+ 15 + 17 on kernels that count discards and
+// flushes) — the milliseconds the device's completed requests took, summed.
+type CounterSample = BlockStatSample & { device: string; at: number; ticksMs?: number };
+
+// The time the device's completed requests took, summed, from a stat line:
+// fields 4 (reads), 8 (writes) and, where counted, 15 (discards) and 17
+// (flushes). Null on a line too short to carry them.
+export function blockStatTicksMs(line: string): number | null {
+ const f = line.trim().split(/\s+/).map(Number);
+ if (f.length < 9 || !Number.isFinite(f[3]) || !Number.isFinite(f[7])) return null;
+ const opt = (i: number) => (Number.isFinite(f[i]) ? f[i] : 0);
+ return f[3] + f[7] + opt(14) + opt(16);
+}
+
+// THE DISK'S OWN AVERAGE per completed request between two samples, or
+// undefined when none completed (an idle disk has no latency to report).
+export function countersLatencyMs(
+ prev: Pick<CounterSample, "completed" | "ticksMs">,
+ cur: Pick<CounterSample, "completed" | "ticksMs">,
+): number | undefined {
+ const done = cur.completed - prev.completed;
+ if (done <= 0 || prev.ticksMs === undefined || cur.ticksMs === undefined) return undefined;
+ const ticks = cur.ticksMs - prev.ticksMs;
+ return ticks >= 0 ? ticks / done : undefined;
+}
type DetectorState = {
samples: Map<string, CounterSample>;
@@ -594,9 +622,13 @@ async function blockDeviceOfRoot(
async function readBlockStat(
device: string,
sysBlockDir: string,
-): Promise<BlockStatSample | null> {
+): Promise<(BlockStatSample & { ticksMs?: number }) | null> {
try {
- return parseBlockStat(await readFile(path.join(sysBlockDir, device, "stat"), "utf8"));
+ const line = await readFile(path.join(sysBlockDir, device, "stat"), "utf8");
+ const sample = parseBlockStat(line);
+ if (!sample) return null;
+ const ticksMs = blockStatTicksMs(line);
+ return ticksMs === null ? sample : { ...sample, ticksMs };
} catch {
return null;
}
@@ -637,10 +669,12 @@ export async function detectLocationHealth(
return { answer: null, detector: "counters", device };
}
const answer = countersVerdict(prev, sample);
+ const latencyMs = answer === "ok" ? countersLatencyMs(prev, sample) : undefined;
return {
answer,
detector: "counters",
device,
+ ...(latencyMs !== undefined ? { latencyMs } : {}),
...(answer === "stalled"
? {
cause:
@@ -652,10 +686,12 @@ export async function detectLocationHealth(
}
}
detector.samples.delete(loc.id);
+ const asked = Date.now();
const answer = await probeLocationHealth(loc, opts);
return {
answer,
detector: "stat",
+ ...(answer === "ok" ? { latencyMs: Date.now() - asked } : {}),
...(answer === "stalled"
? { cause: `a stat of its root did not answer within ${secondsText(timeoutMs)}` }
: {}),
@@ -732,11 +768,24 @@ export type MemoizedProbe = StorageLocationProbe & {
export const PROBE_MEMO_MS = 10_000;
type MemoEntry = { root: string; probedAt: number; probe: StorageLocationProbe };
-const probeMemo = new Map<string, MemoEntry>();
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttStorageProbeMemo__: Map<string, MemoEntry> | undefined;
+}
+
+// ON globalThis, the house pattern (lane drive-stall): a page, a poll and the
+// e2e `invalidate-cache` route can each be a different copy of this module,
+// and a reset in one copy that leaves another's map standing answers the next
+// page with a root that is no longer there — for up to ten seconds.
+function probeMemo(): Map<string, MemoEntry> {
+ globalThis.__yttStorageProbeMemo__ ??= new Map();
+ return globalThis.__yttStorageProbeMemo__;
+}
// Test seam, and the escape hatch for a process that has just written a root.
export function resetStorageProbeMemo(): void {
- probeMemo.clear();
+ probeMemo().clear();
}
// Probe a location, at most once per PROBE_MEMO_MS.
@@ -765,7 +814,7 @@ export async function probeLocationMemo(
if (stalledLocation(loc)) {
return { status: "stalled", identity: { known: false }, probedAt: now };
}
- const hit = probeMemo.get(loc.id);
+ const hit = probeMemo().get(loc.id);
if (
!opts.refresh &&
hit &&
@@ -775,6 +824,6 @@ export async function probeLocationMemo(
return { ...hit.probe, probedAt: hit.probedAt };
}
const probe = await probeLocation(loc, bins, opts);
- probeMemo.set(loc.id, { root: loc.root, probedAt: now, probe });
+ probeMemo().set(loc.id, { root: loc.root, probedAt: now, probe });
return { ...probe, probedAt: now };
}
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -30,6 +30,10 @@ export const VIEW_NAMES = [
// /review's X run console (common/controller/xRun.ts xRunConsole): the
// latest run, the X posts channels, the jar's age. Reads disk only.
"xRun",
+ // The dashboard's drive banner (editor/app/storage/lib/driveHealth.ts):
+ // every storage location whose drive is slow, not answering or not mounted.
+ // The health record is memory; the mount half is /storage's 10 s probe memo.
+ "driveHealth",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -58,4 +62,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
cleanable: "construct",
cookieAlerts: "construct",
xRun: "construct",
+ driveHealth: "construct",
};
diff --git a/common/views/storage.test.ts b/common/views/storage.test.ts
@@ -507,3 +507,60 @@ test("a location whose drive is not answering reads so, and says since when", ()
}).rows[0];
assert.equal(quiet.notAnswering, undefined);
});
+
+// THE DRIVE'S HEALTH ON EACH ROW (lane drive-stall) — what `pnpm ops get
+// storage` reports: the shell's view, carried as it is; the internal row has
+// none. `probeMounted` is the mount half of it.
+test("each location row carries its drive's health view; the internal row none", async () => {
+ const { driveHealthView, recordLocationHealth, registerLocationHealth, noteDriveAnswer, locationHealth, resetStorageHealth } =
+ await import("../lib/storageHealth");
+ const { probeMounted } = await import("./storage");
+ resetStorageHealth();
+ const cold = loc("cold", "/mnt/cold");
+ const warm = loc("warm", "/mnt/warm");
+ const gone = loc("gone", "/mnt/gone");
+ registerLocationHealth([cold, warm, gone], NOW);
+ recordLocationHealth(cold, "stalled", { now: NOW, cause: "its disk (sdz) had 1 request(s) in flight and completed none in 15 s" });
+ noteDriveAnswer("warm", 2_400, "call", NOW - 1);
+ noteDriveAnswer("warm", 2_400, "call", NOW);
+ const probes = {
+ cold: { status: "stalled" as const, identity: { known: false as const }, probedAt: NOW },
+ warm: { status: "available" as const, identity: { known: false as const }, probedAt: NOW },
+ gone: { status: "unmounted" as const, identity: { known: false as const }, probedAt: NOW },
+ };
+ const drives = Object.fromEntries(
+ [cold, warm, gone].map((l) => [
+ l.id,
+ driveHealthView(l, locationHealth(l.id), { now: NOW, mounted: probeMounted(probes[l.id as keyof typeof probes].status) }),
+ ]),
+ );
+ const { rows } = buildStorageRows({
+ locations: [cold, warm, gone],
+ defaultLocationId: "",
+ probes,
+ drives,
+ rollups: {},
+ internal: { root: "/corpus/channels" },
+ registry: NO_JOBS,
+ now: NOW,
+ });
+ const by = Object.fromEntries(rows.map((r) => [r.id, r]));
+ assert.equal(by.internal.drive, undefined);
+ assert.equal(by.cold.drive?.state, "stalled");
+ assert.equal(by.cold.drive?.since, NOW);
+ assert.match(String(by.cold.drive?.text), /^not answering since \d\d:\d\d — its disk \(sdz\)/);
+ assert.equal(by.warm.drive?.state, "slow");
+ assert.equal(by.warm.drive?.latencyMs, 2_400);
+ assert.equal(by.warm.drive?.lastOkAt, NOW);
+ assert.match(String(by.warm.drive?.text), /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/);
+ assert.equal(by.gone.drive?.state, "unmounted");
+ assert.equal(by.gone.drive?.text, "not mounted");
+ // The mount half: available is mounted, stalled did not ask, the rest are not.
+ assert.equal(probeMounted("available"), true);
+ assert.equal(probeMounted("stalled"), undefined);
+ assert.equal(probeMounted(undefined), undefined);
+ for (const st of ["unmounted", "absent", "missing", "mounted-elsewhere"] as const) {
+ assert.equal(probeMounted(st), false);
+ }
+ resetStorageHealth();
+});
diff --git a/common/views/storage.ts b/common/views/storage.ts
@@ -9,6 +9,7 @@ import type {
} from "../controller/storageLocations";
import type { SavedVideosStoreStatus } from "../controller/relocateSavedVideos";
import type { RegistryReader } from "./inputs";
+import type { DriveHealthView } from "../lib/storageHealth";
// THE /storage PAYLOAD — one row per storage location, and for each row the
// list of things the operator may do to it and why the rest are withheld.
@@ -115,6 +116,12 @@ export type StorageRow = {
// "not answering since 11:35 — …", while the health probe finds this
// location's drive not answering (lib/storageHealth.ts). Absent otherwise.
notAnswering?: string;
+ // THE DRIVE'S HEALTH (lane drive-stall): answering, slow, not answering or
+ // not mounted, with when it last answered and how fast
+ // (lib/storageHealth.ts `driveHealthView`). What `pnpm ops get storage`
+ // reports per location. Absent on the internal row, and when the shell
+ // passed none.
+ drive?: DriveHealthView;
warning?: string;
candidateRoot?: string;
// Why every action on this row is withheld, or null. One re-point runs at a
@@ -235,6 +242,9 @@ export type StorageRowsInputs = {
// Worded by the shell (lib/storageHealth.ts's `notAnsweringText`), because
// this module takes types only from lib/.
notAnswering?: Record<string, string | undefined>;
+ // By location id: the drive's health view, built by the shell from the
+ // health record and this probe (`driveHealthView`).
+ drives?: Record<string, DriveHealthView | undefined>;
rollups: Record<string, LocationRollup | undefined>;
registry: RegistryReader;
udisksctlAvailable?: boolean;
@@ -254,6 +264,14 @@ export const STORAGE_STATUS_LABEL: Record<StorageLocationStatus, string> = {
stalled: "Not answering",
};
+// WHETHER A PROBE STATUS MEANS THE DRIVE IS MOUNTED, for the drive's health
+// view: `available` is, `stalled` did not ask (the health record decides), and
+// every other status is a root that is not there. Undefined for no probe.
+export function probeMounted(status: StorageLocationStatus | undefined): boolean | undefined {
+ if (status === undefined || status === "stalled") return undefined;
+ return status === "available";
+}
+
export const REPOINT_JOB_KIND = "repoint-storage-location";
export const SAVED_VIDEOS_JOB_KIND = "relocate-saved-videos";
@@ -453,6 +471,7 @@ export function buildStorageRows(i: StorageRowsInputs): StorageRowsPayload {
...(i.notAnswering?.[loc.id]
? { notAnswering: i.notAnswering[loc.id] }
: {}),
+ ...(i.drives?.[loc.id] ? { drive: i.drives[loc.id] } : {}),
...(probe?.warning ? { warning: probe.warning } : {}),
...(candidateRoot ? { candidateRoot } : {}),
busy,
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -87,6 +87,7 @@ import {
} from "../lib/transcriptCoverage";
import type { Paths } from "../lib/paths";
import { transcribeWithWorker } from "../controller/transcribeOne";
+import { isMediaDriveHeld } from "../controller/transcribeError";
import { extractVideoId, outputArgsForUrl } from "./runYtdlp";
import { channelExtraArgs, channelPaceSeconds } from "./channelArgs";
import {
@@ -1855,11 +1856,21 @@ async function runManagedDownload(
});
status = "ok-auto-transcribed";
} catch (err) {
- opts.onLog(
- `Whisper failed after no-subs fallback: ${(err as Error).message}\n`,
- );
- status = "failed";
- lastSucceeded = false;
+ if (isMediaDriveHeld(err)) {
+ // THE AUDIO IS HERE; ITS DRIVE IS NOT ANSWERING (lane
+ // drive-stall). The download succeeded — the status stays the
+ // attempt's, as when inline whisper is off, and the transcription
+ // lane picks the video up once the drive answers.
+ opts.onLog(
+ `Audio downloaded for ${videoId}; not transcribed inline: ${(err as Error).message}.\n`,
+ );
+ } else {
+ opts.onLog(
+ `Whisper failed after no-subs fallback: ${(err as Error).message}\n`,
+ );
+ status = "failed";
+ lastSucceeded = false;
+ }
}
} else {
opts.onLog(
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text.
+- **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it.
+- **The drive watch no longer overwrites a tier you change while it is pausing channels.** The five-minute storage watch, which pauses the channels on a drive that went away and restores them when it comes back, could save its change in the middle of yours and undo it. It now waits for the same settings lock that the channel-priority save uses. The editor's `dev` script also gives Node 16 file-access threads, as `start`, the systemd unit and the container already do.
- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, each as a `patchSite` under that site's lock, so a concurrent edit of the site is not written over (a rename already re-points them through the same writer). The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`).
- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, a channel's `groupId` that names none of the site's groups, unknown keys and keys of the wrong type are refused before anything is written. The existence check, the read of the stored site and the save are one read-modify-write under the site's lock (`withSiteLock`). The site form's own Save now takes the same lock, so neither it nor an update is written over a concurrent edit such as a Reports-tab pages patch. It answers the saved site.
- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
diff --git a/editor/app/api/test/drive-health/route.ts b/editor/app/api/test/drive-health/route.ts
@@ -0,0 +1,53 @@
+import { NextResponse } from "next/server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ noteDriveSlow,
+ recordLocationHealth,
+ registerLocationHealth,
+} from "yt-dlp-transcript-common/lib/storageHealth";
+import { forgetChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia";
+import { resetStorageProbeMemo } from "yt-dlp-transcript-common/controller/storageLocations";
+import { testRouteDenied } from "../_guard";
+
+export const dynamic = "force-dynamic";
+
+// E2E test harness only (guarded by `E2E_TEST_ROUTES`, see _guard.ts).
+//
+// A STALLED DRIVE WITHOUT A HUNG MOUNT. No fixture can make a real drive stop
+// answering, and none should: this records what a detector would have said
+// about a configured location — `stalled` (one answer marks it, as the
+// counters or the watchdog would) or `slow` (the watchdog's slow refusal) —
+// into the process's health record, which every gate, page and poll reads.
+// The health pass then sees the fixture's drive answering and clears a stall
+// after `clearAfterCleanPasses` passes (30 s at the defaults), so a spec
+// asserts within that window. `/api/test/invalidate-cache` forgets it all.
+//
+// POST {"id": "<location id>", "state": "stalled" | "slow", "cause"?: "…"}
+export async function POST(req: Request) {
+ const denied = testRouteDenied();
+ if (denied) return denied;
+ const body = (await req.json().catch(() => ({}))) as {
+ id?: string;
+ state?: string;
+ cause?: string;
+ };
+ const loc = getSettings().storage.locations.find((l) => l.id === body.id);
+ if (!loc) {
+ return NextResponse.json({ error: `no storage location "${body.id}"` }, { status: 404 });
+ }
+ registerLocationHealth([loc]);
+ if (body.state === "stalled") {
+ recordLocationHealth(loc, "stalled", {
+ cause: body.cause ?? "a read in the editor did not answer within 3 s",
+ });
+ } else if (body.state === "slow") {
+ noteDriveSlow(loc.id, body.cause ?? "a read in the editor took 2.4 s");
+ } else {
+ return NextResponse.json({ error: `state must be "stalled" or "slow"` }, { status: 400 });
+ }
+ // The channels' five-second answers and the ten-second probes, so the next
+ // page sees the drive as it is now.
+ forgetChannelMedia();
+ resetStorageProbeMemo();
+ return NextResponse.json({ ok: true });
+}
diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts
@@ -55,7 +55,7 @@ const PAIRS: Array<[string, string]> = [
// Views born after the consolidation: there is no old path to rewrite, so
// they are served only at /api/view/<name>.
-const NEW_VIEWS = ["cookieAlerts", "xRun"];
+const NEW_VIEWS = ["cookieAlerts", "xRun", "driveHealth"];
async function view(name: string): Promise<number> {
const res = await GET(new Request(`http://localhost/api/view/${name}`), {
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
import { loadCookieAlerts } from "../../lib/cookieAlerts";
+import { buildDriveHealthPayload } from "../../storage/lib/driveHealth";
import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
import {
loadActionableSummary,
@@ -83,6 +84,11 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// recorded job's status.
cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())),
+ // The dashboard's drive banner: the storage locations whose drive is slow,
+ // not answering or not mounted. Polled slow; the health record is memory and
+ // the mount probe is memoised 10 s (no drive is asked in-process).
+ driveHealth: async () => NextResponse.json(await buildDriveHealthPayload()),
+
// /review's X run console: the latest run (each channel's state, the
// summary), the X posts channels in the default order and the jar's age
// against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X.
diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts
@@ -122,7 +122,11 @@ export async function persistChannelVideosAction(
safeRevalidate([`/channels/${slug}`, "/saved-videos"]);
// A run that stopped short or lost a video did not do what it was asked:
// the job says so, and the re-run picks up the rest.
- if (result.stopped === "low-disk" || result.stopped === "rate-limit") {
+ if (
+ result.stopped === "low-disk" ||
+ result.stopped === "rate-limit" ||
+ result.stopped === "store-unavailable"
+ ) {
throw new Error(
`Stopped (${result.stopped}) with ${result.notAttempted.length} video(s) not attempted — run it again later.`,
);
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -82,7 +82,10 @@ import {
unpersistSavedVideo,
type DropSavedAlternateResult,
} from "yt-dlp-transcript-common/lib/savedVideo-server";
-import { SavedVideosStoreInTransitionError } from "yt-dlp-transcript-common/lib/savedVideoStore";
+import {
+ SavedVideosStoreInTransitionError,
+ SavedVideosStoreNotAnsweringError,
+} from "yt-dlp-transcript-common/lib/savedVideoStore";
import {
savedVideoPath,
type SavedVideoOrigin,
@@ -1457,7 +1460,11 @@ export async function dropSavedAlternateAction(
paths,
});
} catch (e) {
- if (e instanceof SavedAlternateRefusal || e instanceof SavedVideosStoreInTransitionError) {
+ if (
+ e instanceof SavedAlternateRefusal ||
+ e instanceof SavedVideosStoreInTransitionError ||
+ e instanceof SavedVideosStoreNotAnsweringError
+ ) {
return { ok: false, error: e.message };
}
throw e;
diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx
@@ -10,6 +10,8 @@ import { NeedsWorkPanel } from "./NeedsWorkPanel";
import { QuickAddPanel } from "./QuickAddPanel";
import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel";
import { CookieAlertsPanel } from "./CookieAlertsPanel";
+import { DriveHealthBanner } from "./DriveHealthBanner";
+import type { DriveHealthPayload } from "../../storage/lib/driveHealth";
import type { ServiceCookieAlertsPayload } from "yt-dlp-transcript-common/lib/serviceCookies";
import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow";
import { ChannelsTable } from "../../channels/components/ChannelsTable";
@@ -40,9 +42,12 @@ export type DashboardCockpitInitial = {
firstRun?: FirstRunState | null;
// The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this.
cookieAlerts?: ServiceCookieAlertsPayload;
+ // The drive banner (storage/lib/driveHealth.ts), polled SLOW after this.
+ driveHealth?: DriveHealthPayload;
};
const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] };
+const NO_DRIVE_TROUBLE: DriveHealthPayload = { drives: [] };
// The mission-control cockpit. A server component (app/page.tsx) SSRs the
// initial payloads for a flicker-free first paint; this client shell then polls
@@ -87,9 +92,17 @@ export function DashboardCockpit({
initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS,
);
+ const { data: driveHealth } = usePolledPayload<DriveHealthPayload>(
+ "/api/view/driveHealth",
+ true,
+ SLOW_MS,
+ initial.driveHealth ?? NO_DRIVE_TROUBLE,
+ );
+
return (
<div className="flex flex-col gap-6">
<h1 className="sr-only">Dashboard</h1>
+ <DriveHealthBanner data={driveHealth ?? NO_DRIVE_TROUBLE} />
<CookieAlertsPanel
data={cookieAlerts ?? EMPTY_COOKIE_ALERTS}
onChange={() => void refetchCookieAlerts()}
diff --git a/editor/app/components/dashboard/DriveHealthBanner.tsx b/editor/app/components/dashboard/DriveHealthBanner.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+// THE DRIVE BANNER (lane drive-stall): one card per storage location whose
+// drive is not answering, slow, or not mounted with channels on it — the
+// dashboard's top slot, beside the cookie banners. Not answering and not
+// mounted are different troubles with different fixes, so they read
+// differently: a drive that is here and stalled (a USB enclosure resetting)
+// is waited out, or unplugged and replugged; a drive that is not mounted is
+// mounted. The words come from the server (lib/storageHealth.ts
+// `driveHealthView`), so /storage and this banner cannot disagree.
+
+import Link from "next/link";
+import type {
+ DriveHealthBannerRow,
+ DriveHealthPayload,
+} from "../../storage/lib/driveHealth";
+
+const HEADLINE: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = {
+ stalled: "is not answering",
+ slow: "is answering slowly",
+ unmounted: "is not mounted",
+};
+
+const WHAT_HAPPENS: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = {
+ stalled:
+ "Pages and polls skip it and its channels' jobs are held until it answers again; nothing else in the editor waits on it.",
+ slow: "Everything still runs; reads on it take longer than they should.",
+ unmounted: "Its channels' jobs are held until it is back.",
+};
+
+function DriveCard({ drive }: { drive: DriveHealthBannerRow }) {
+ if (drive.state === "ok") return null;
+ const severe = drive.state !== "slow";
+ return (
+ <section
+ role={severe ? "alert" : "status"}
+ aria-label={`drive ${drive.id}`}
+ data-state={drive.state}
+ className={`rounded-md border bg-card px-4 py-3 ${
+ severe ? "border-destructive/50" : "border-amber-500/50"
+ }`}
+ >
+ <p
+ className={`text-sm font-medium ${
+ severe ? "text-destructive" : "text-amber-700 dark:text-amber-300"
+ }`}
+ >
+ The media drive {drive.label} {HEADLINE[drive.state]}
+ </p>
+ <p className="text-xs" aria-label={`drive ${drive.id} health`}>
+ {drive.text}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {WHAT_HAPPENS[drive.state]}
+ {" · "}
+ <Link href="/storage" className="underline underline-offset-2 hover:text-foreground">
+ Storage
+ </Link>
+ {drive.channels > 0 && (
+ <>
+ {" · "}
+ <Link
+ href={drive.channelsHref}
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ {drive.channels} channel(s) on it
+ </Link>
+ </>
+ )}
+ </p>
+ </section>
+ );
+}
+
+export function DriveHealthBanner({ data }: { data: DriveHealthPayload }) {
+ if (data.drives.length === 0) return null;
+ return (
+ <div aria-label="drive health" className="flex flex-col gap-2">
+ {data.drives.map((d) => (
+ <DriveCard key={d.id} drive={d} />
+ ))}
+ </div>
+ );
+}
diff --git a/editor/app/page.tsx b/editor/app/page.tsx
@@ -20,6 +20,7 @@ import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSyn
import { widgetSyncInputs } from "./widget/lib/syncInputs";
import { DashboardCockpit } from "./components/dashboard/DashboardCockpit";
import { loadCookieAlerts } from "./lib/cookieAlerts";
+import { buildDriveHealthPayload } from "./storage/lib/driveHealth";
import {
buildChannelRowView,
channelVolumeOf,
@@ -134,10 +135,11 @@ export default async function Dashboard({
// active site for the SSR seed.
const actionable = buildWidgetActionablePayload(widgetActionableRows(rows));
- const [jobs, sync, cookieAlerts] = await Promise.all([
+ const [jobs, sync, cookieAlerts, driveHealth] = await Promise.all([
buildActiveJobsPayload(),
widgetSyncInputs().then(buildWidgetSyncPayload),
loadCookieAlerts(paths),
+ buildDriveHealthPayload(),
]);
const workers = buildWorkersPayload();
const changelogSource = loadChangelog();
@@ -153,6 +155,7 @@ export default async function Dashboard({
changelogSource,
firstRun: summary.rows.length === 0 ? firstRunState(paths) : null,
cookieAlerts,
+ driveHealth,
}}
/>
);
diff --git a/editor/app/storage/buildStorage.ts b/editor/app/storage/buildStorage.ts
@@ -4,11 +4,14 @@ import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { getFreeBytes } from "yt-dlp-transcript-common/lib/diskSpace";
import { udisksctlAvailable } from "yt-dlp-transcript-common/lib/storageVolumes";
import {
+ driveHealthView,
healthTimings,
isDriveNotAnswering,
+ locationHealth,
notAnsweringText,
onDrive,
stalledLocation,
+ type DriveHealthView,
} from "yt-dlp-transcript-common/lib/storageHealth";
import { clearRuleText } from "yt-dlp-transcript-common/lib/storageHealthTimings";
import { listChannelBriefs } from "yt-dlp-transcript-common/controller/channels";
@@ -24,6 +27,7 @@ import {
import { pathExists } from "yt-dlp-transcript-common/controller/relocateDir";
import {
buildStorageRows,
+ probeMounted,
type StorageRowsPayload,
} from "yt-dlp-transcript-common/views/storage";
@@ -136,6 +140,18 @@ export async function buildStorage(): Promise<StorageRowsPayload> {
`Pages and polls skip this drive until it answers ${clears}.${watched}`;
}
}
+ // EACH DRIVE'S HEALTH, from memory and this render's probe: answering, slow,
+ // not answering or not mounted (lib/storageHealth.ts `driveHealthView`). A
+ // record for another root under the same id (a re-point the pass has not
+ // seen yet) is not this drive's.
+ const drives: Record<string, DriveHealthView> = {};
+ for (const loc of locations) {
+ const h = locationHealth(loc.id);
+ drives[loc.id] = driveHealthView(loc, h && h.root === loc.root ? h : undefined, {
+ now,
+ mounted: probeMounted(probes[loc.id]?.status),
+ });
+ }
const store = await inspectSavedVideosStore(paths, settings);
// A store on a location walks that location's drive: through the watchdog,
// so a drive that stops answering mid-walk leaves the size at 0 (the store's
@@ -173,6 +189,7 @@ export async function buildStorage(): Promise<StorageRowsPayload> {
defaultLocationId: settings.storage.defaultLocationId,
probes,
notAnswering,
+ drives,
rollups,
registry: getRegistry(),
udisksctlAvailable: udisksctl,
diff --git a/editor/app/storage/components/StorageLocationsTable.tsx b/editor/app/storage/components/StorageLocationsTable.tsx
@@ -173,6 +173,17 @@ function LocationCard({
>
{row.statusLabel}
</span>
+ {/* SLOW IS NOT A STATUS: the drive is there and answering, a beat
+ late (lib/storageHealth.ts `driveHealthView`). A chip beside the
+ status, so "Available" stays true and the slowness is still seen. */}
+ {row.drive?.state === "slow" && (
+ <span
+ aria-label="location slow"
+ className="rounded-full border border-amber-500/50 bg-amber-500/10 px-2 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-300"
+ >
+ slow
+ </span>
+ )}
{row.isDefault && (
<span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
default
@@ -264,6 +275,16 @@ function LocationCard({
</dd>
<dt className="text-muted-foreground">Last probe</dt>
<dd aria-label="location last probe">{formatAge(row.lastProbeAgeMs)}</dd>
+ {/* THE DRIVE'S HEALTH in one line: answering (how fast, when last),
+ slow, not answering since, or not mounted. */}
+ {row.drive && (
+ <>
+ <dt className="text-muted-foreground">Drive</dt>
+ <dd aria-label="location drive" className="text-xs">
+ {row.drive.text}
+ </dd>
+ </>
+ )}
</dl>
{row.notAnswering && (
diff --git a/editor/app/storage/lib/driveHealth.ts b/editor/app/storage/lib/driveHealth.ts
@@ -0,0 +1,71 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { locationOfDataDir } from "yt-dlp-transcript-common/lib/storageLocations";
+import {
+ driveHealthView,
+ locationHealth,
+ type DriveHealthView,
+} from "yt-dlp-transcript-common/lib/storageHealth";
+import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { probeAllLocations } from "yt-dlp-transcript-common/controller/storageLocations";
+import {
+ channelsHrefForLocation,
+ probeMounted,
+} from "yt-dlp-transcript-common/views/storage";
+
+// THE DASHBOARD'S DRIVE BANNER — every storage location whose drive is slow,
+// not answering or not mounted, and how many channels have their media there.
+//
+// NOTHING HERE ASKS A DRIVE IN-PROCESS. The health record is memory (the
+// health pass and the watchdog write it, lib/storageHealth.ts), and the mount
+// half is the same probe /storage renders from: memoised 10 s, a stalled
+// location answered without a call. The channel configs are read only when
+// some drive is in trouble — the corpus disk, one small file per channel —
+// because a drive nobody's media is on is not worth a banner when it is merely
+// unplugged.
+//
+// SERVER ONLY (it reaches the controller, which imports execa).
+
+export type DriveHealthBannerRow = DriveHealthView & {
+ // Channels whose media is on this location (by `mediaDir`, or a legacy
+ // channel's retired `dataDir`).
+ channels: number;
+ // `/channels?location=<id>`: the list of them.
+ channelsHref: string;
+};
+
+export type DriveHealthPayload = { drives: DriveHealthBannerRow[] };
+
+export async function buildDriveHealthPayload(): Promise<DriveHealthPayload> {
+ const paths = getPaths();
+ const locations = getSettings().storage.locations;
+ if (locations.length === 0) return { drives: [] };
+ const probes = await probeAllLocations(locations, paths);
+ const now = Date.now();
+ const troubled = locations
+ .map((loc) => {
+ const h = locationHealth(loc.id);
+ return driveHealthView(loc, h && h.root === loc.root ? h : undefined, {
+ now,
+ mounted: probeMounted(probes[loc.id]?.status),
+ });
+ })
+ .filter((v) => v.state !== "ok");
+ if (troubled.length === 0) return { drives: [] };
+ const counts = new Map<string, number>();
+ for (const { config } of await listChannelConfigs(paths)) {
+ const dir = config.mediaDir?.trim() || config.dataDir?.trim();
+ const loc = dir ? locationOfDataDir(dir, locations) : null;
+ if (loc) counts.set(loc.id, (counts.get(loc.id) ?? 0) + 1);
+ }
+ return {
+ drives: troubled
+ .map((v) => ({
+ ...v,
+ channels: counts.get(v.id) ?? 0,
+ channelsHref: channelsHrefForLocation(v.id),
+ }))
+ // An unplugged drive with nobody's media on it is not news.
+ .filter((v) => v.state !== "unmounted" || v.channels > 0),
+ };
+}
diff --git a/editor/e2e/drive-health.spec.ts b/editor/e2e/drive-health.spec.ts
@@ -0,0 +1,162 @@
+import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { test, expect, type Page } from "@playwright/test";
+import { baseUrl } from "./baseUrl";
+import { readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+
+// A DRIVE THAT IS NOT ANSWERING, ONE THAT IS SLOW, ONE THAT IS NOT MOUNTED —
+// and that /storage and the dashboard tell them apart (lane drive-stall).
+//
+// NO FIXTURE HANGS A MOUNT. `/api/test/drive-health` records what a detector
+// would have said about a configured location (a stall, or the watchdog's
+// slow refusal) into the editor's health record, which every gate, page and
+// poll reads; the health pass then sees the fixture's drive answering and
+// clears a stall after two clean passes (15–30 s), so each step marks the
+// drive again just before it looks. "Not mounted" is real: the location's
+// root is removed. The detectors and the state machine are unit-tested
+// (common/lib/storageHealth.test.ts, controller/storageWatch.test.ts).
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "test-youtube";
+const VIDEO = "20240101_test1234567";
+
+const channelDir = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+
+// The fixture channel's media tier on `root`, as a finished move leaves it
+// (storage-locations.spec.ts builds it the same way).
+async function relocateOnDisk(root: string): Promise<void> {
+ const target = join(root, SLUG, "media");
+ await mkdir(join(target, VIDEO), { recursive: true });
+ await writeFile(join(target, VIDEO, "audio.mp3"), "ID3audio");
+ await symlink(
+ join("..", "..", "media", VIDEO, "audio.mp3"),
+ join(channelDir(), "data", VIDEO, "audio.mp3"),
+ );
+ await symlink(target, join(channelDir(), "media"));
+ const config = await readJson<Record<string, unknown>>(
+ `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`,
+ );
+ await writeFile(
+ join(channelDir(), "config.json"),
+ JSON.stringify({ ...config, mediaDir: target }, null, 2) + "\n",
+ );
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+}
+
+async function mark(id: string, state: "stalled" | "slow"): Promise<void> {
+ const res = await fetch(`${baseUrl}/api/test/drive-health`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ id, state }),
+ });
+ expect(res.ok, await res.clone().text()).toBe(true);
+}
+
+async function setUp(root: string): Promise<void> {
+ await resetData("one-youtube-channel-with-data");
+ await mkdir(root, { recursive: true });
+ await relocateOnDisk(root);
+ await writeSettings({
+ adminTitle: "Test Admin",
+ minFreeDiskGB: 0,
+ storage: {
+ locations: [{ id: "cold", label: "Cold", root, autoRepoint: false }],
+ defaultLocationId: "cold",
+ },
+ });
+}
+
+function row(page: Page, id: string) {
+ return page.getByLabel(`storage location: ${id}`);
+}
+
+test("a stalled drive reads 'not answering' on /storage and the dashboard; an unmounted one 'not mounted'", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ const root = testInfo.outputPath("platter");
+ await setUp(root);
+
+ // --- not answering ------------------------------------------------------
+ await mark("cold", "stalled");
+ await page.goto("/storage");
+ const cold = row(page, "cold");
+ await expect(cold.getByLabel("location status")).toHaveText("Not answering");
+ await expect(cold.getByLabel("location drive")).toHaveText(/^not answering since \d\d:\d\d — /);
+ await expect(cold.getByLabel("location slow")).toHaveCount(0);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await cold.screenshot({ path: testInfo.outputPath("storage-not-answering.png") });
+
+ await mark("cold", "stalled");
+ await page.goto("/");
+ const card = page.getByLabel("drive cold", { exact: true });
+ await expect(card).toBeVisible();
+ await expect(card).toHaveAttribute("data-state", "stalled");
+ await expect(card).toHaveAttribute("role", "alert");
+ await expect(card).toContainText("The media drive Cold is not answering");
+ await expect(page.getByLabel("drive cold health")).toHaveText(/^not answering since \d\d:\d\d/);
+ await expect(card.getByRole("link", { name: "1 channel(s) on it" })).toHaveAttribute(
+ "href",
+ /^\/channels\?location=cold(&|$)/,
+ );
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.screenshot({ path: testInfo.outputPath("dashboard-not-answering.png") });
+
+ // --- the drive answers again: no banner -----------------------------------
+ await fetch(`${baseUrl}/api/test/invalidate-cache`);
+ await page.goto("/");
+ await expect(page.getByRole("heading", { name: "Dashboard" })).toBeAttached();
+ await expect(page.getByLabel("drive health")).toHaveCount(0);
+
+ // --- not mounted (the root is gone; its channel's media was on it) --------
+ await rm(root, { recursive: true, force: true });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`);
+ await page.goto("/");
+ const gone = page.getByLabel("drive cold", { exact: true });
+ await expect(gone).toHaveAttribute("data-state", "unmounted");
+ await expect(gone).toContainText("The media drive Cold is not mounted");
+ await expect(page.getByLabel("drive cold health")).toHaveText("not mounted");
+ await page.goto("/storage");
+ await expect(row(page, "cold").getByLabel("location status")).not.toHaveText("Not answering");
+ await expect(row(page, "cold").getByLabel("location drive")).toHaveText("not mounted");
+});
+
+test("a slow drive stays Available with a slow chip, and its dashboard card is a status, not an alert", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ const root = testInfo.outputPath("platter");
+ await setUp(root);
+
+ await mark("cold", "slow");
+ await page.goto("/storage");
+ const cold = row(page, "cold");
+ await expect(cold.getByLabel("location status")).toHaveText("Available");
+ await expect(cold.getByLabel("location slow")).toHaveText("slow");
+ await expect(cold.getByLabel("location drive")).toHaveText(
+ /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/,
+ );
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await cold.screenshot({ path: testInfo.outputPath("storage-slow.png") });
+
+ await mark("cold", "slow");
+ await page.goto("/");
+ const card = page.getByLabel("drive cold", { exact: true });
+ await expect(card).toHaveAttribute("data-state", "slow");
+ await expect(card).toHaveAttribute("role", "status");
+ await expect(card).toContainText("The media drive Cold is answering slowly");
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.screenshot({ path: testInfo.outputPath("dashboard-slow.png") });
+
+ // `pnpm ops get storage` reports the same view per location.
+ await mark("cold", "slow");
+ const res = await page.request.get(`${baseUrl}/api/ops/storage`, { headers: AUTH });
+ expect(res.ok(), await res.text()).toBe(true);
+ const body = (await res.json()) as {
+ storage: { rows: Array<{ id: string; drive?: { state: string; text: string; lastOkAt?: number } }> };
+ };
+ const drive = body.storage.rows.find((r) => r.id === "cold")?.drive;
+ expect(drive?.state).toBe("slow");
+ expect(drive?.text).toMatch(/^slow at /);
+ expect(body.storage.rows.find((r) => r.id === "internal")?.drive).toBeUndefined();
+});
diff --git a/editor/package.json b/editor/package.json
@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"scripts": {
- "dev": "next dev --port ${EDITOR_PORT:-3001}",
+ "dev": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next dev --port ${EDITOR_PORT:-3001}",
"dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}",
"start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}",
"build": "next build",
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -8147,6 +8147,52 @@ shipped". Anchors are at slice DT's tip (`r15/drive-timings`).
stalled at boot before the second counter sample, unless a page reaches it; per-click server
actions; the file route's stream; the corpus disk itself.
+### Lane drive-stall additions (2026-11-09, branch `lane/drive-stall`)
+
+- **The record says more than ok | stalled | absent.** `LocationHealth` gains `lastOkAt` (a pass's
+ clean `ok`, or an `onDrive` call answered in its budget; a registration sets none), `latencyMs` +
+ `latencyFrom` (`call`: the unit's time; `stat`: the child stat's round trip, process start
+ included; `counters`: the device's own average per completed request, Δ(fields 4 + 8 (+ 15 + 17)) /
+ Δcompleted between two samples — `blockStatTicksMs`, `countersLatencyMs` in `storageVolumes.ts`;
+ `parseBlockStat`'s shape is unchanged), and `slowAt`/`slowCause` (a measurement ≥
+ `slowThresholdMs()` = budget / 2 TWICE IN A ROW (`slowStreak`, `SLOW_READINGS_IN_A_ROW`; a fast one resets it), or either of the watchdog's "drive slow" refusals at once, `noteDriveSlow`). A
+ transition to stalled deletes slowAt. `noteDriveAnswer` writes only to an existing entry.
+- **`driveHealthView(loc, health, { mounted })`** (`lib/storageHealth.ts`, pure) is the one view:
+ `stalled` (the record) > `unmounted` (record `absent`, or `mounted: false`) > `slow` (slowAt within
+ `slowWindowMs()` = 2 × passIntervalMs) > `ok`. `probeMounted(status)` (`views/storage.ts`):
+ available → true, stalled/undefined → undefined, the rest → false. Slow is shown, never acted on.
+- **Surfaces.** `StorageRow.drive` (the shell passes `drives`, a record for another root under the
+ same id is dropped) → `pnpm ops get storage` `rows[].drive`; /storage's Drive line
+ (`aria-label="location drive"`) and `slow` chip (`location slow`). The dashboard banner: view
+ `driveHealth` (`storage/lib/driveHealth.ts`, `DriveHealthBanner`, cards `aria-label="drive <id>"`,
+ `data-state`, role alert for stalled/unmounted, status for slow); unmounted shows only with ≥ 1
+ channel's media on the location; configs are read only when a drive is in trouble.
+- **Batches hold mid-run.** `mediaStallHold(config, log, what)` (`lib/mediaStallHold.ts`, memory
+ only, edge-logged) is asked in the pool `limit()` of `runWhisperBatch` and of the backfill lane of
+ `runOperationBatch` (not digest): 0 while the channel's media location is stalled, so runPool
+ pauses (its idle poll is unref'd — a unit test needs a keep-alive). It heals itself: after `MEDIA_HOLD_REPROBE_AFTER_MS` (5 min) held, at most once per 5 min, a child
+ `stat` of the root (`probeLocationHealth`); answering clears a STALE record (no pass refreshed it for
+ 3 pass intervals) or counts once on a kept one. "Still holding" every 10 min; `reloadConfig` re-reads
+ the channel's targets at most every 10 s. Persist-videos and persist-kept ask
+ `savedVideosStoreRefusal` before each fetch and stop (`store-unavailable`, `skippedStoreUnavailable`);
+ `isMediaDriveHeld` is the one predicate (downloadOneManaged's inline whisper keeps the download's status). It gates DISPATCH only: the
+ batch's classification reads `data/` (readdir, the corpus disk) and never waits. The autoRunner
+ lanes were already held at pick time (`buildChannelWork`). `transcribeOneVideo` refuses before
+ `resolveAudioFile` with `MediaDriveHeldError` (`failureClass` "no-audio": skipped, never
+ failed-transcriptions; `transcribeOneFromQueue` logs its message).
+- **The five-minute watch writes under the settings lock** (`withJsonFileLock(getPaths().settingsFile)`,
+ the lock `editor/app/settings/saveSettings.ts` `withSettingsLock` takes). `storageLocations.ts`'s and
+ `relocateSavedVideos.ts`'s settings writers still do not take it.
+- **`/api/test/drive-health`** (`POST {id, state: "stalled"|"slow", cause?}`, E2E_TEST_ROUTES only)
+ records a detector's answer for a configured location; the pass clears a stall in 15–30 s.
+- **The persist guard asks the record too.** `assertSavedVideosStoreWritable` throws
+ `SavedVideosStoreNotAnsweringError` for a store on a stalled location (the corpus store via
+ `readlink(savedVideosDir)`, a channel store by its path) before the marker check; persist callers
+ already catch and leave the container in `data/<id>/`.
+- **The location probe memo is on `globalThis.__yttStorageProbeMemo__`** (was a module Map): a
+ `resetStorageProbeMemo()` from the e2e `invalidate-cache` route did not reach the page's copy, which
+ answered "available" for a removed root for up to 10 s.
+
## The source's history (stagit) (verified 2026-09-30, branch `r15/stagit`)
Release 15 slice SG ([`release-15.md`](release-15.md)); the operator-facing doc is `PUBLISH.md`, "The
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1097,7 +1097,9 @@ export function usage() {
"",
"get settings [<key>] is settings.json as the editor reads it (migrated and",
" defaulted; a secret is \"<redacted>\"), or one top-level key of it.",
- "get storage is /storage: each location, mounted or not, free space, tiers.",
+ "get storage is /storage: each location, mounted or not, free space, tiers,",
+ " and its drive's health (rows[].drive: ok | slow | stalled | unmounted,",
+ " since, lastOkAt, latencyMs, the cause and the one-line text).",
"get saved-alternates [<slug>] lists every saved video holding two copies:",
" a download over a container already in the store keeps both — an",
" explicit persist (persist-videos, Persist source video, a whole-recording",