commit 8315a4b0678d0f86d83a4bf99c7deecb98ff9236
parent 2e53bd0294066008f078c8f2331e99d2af6141c3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 25 Oct 2026 09:20:42 -0400
The lane's metadata scan runs in batches of 60 with 20 minutes of downloads between; download-missing skips what the scan read as members-only or private
On 2026-10-25 the lane's unbatched scan of h3-podcast (1,163 titles) held
platform:youtube 03:20-06:36 with no download, and a download-missing that
followed tried each of the 277 members-only videos the scan had found four
times and landed nothing.
- runMetadataScan takes maxTargets (a batch in listing order) and reports
`remaining`; the job wrapper passes it through and hands the result back.
- The download lane scans LANE_SCAN_BATCH (60) at a time, rests the platform
LANE_SCAN_REST_MS (20 min) for downloads, and readmits a channel only after a
clean batch with targets left (settleLaneScan, scanSkipPlatforms). A stopped
scan is still not retried by the runner; the operator's Run scans everything.
- scanExclusionsFrom is the one rule for the scan's members-only/private
verdicts: the snapshot uses it, and the batch prefilter (now
partitionDownloadBatch, exported and tested) applies it too, a conclusive
on-disk availability winning. The log counts the ones the scan decided.
- videoOps.test: the look-settings sentence names `blur` (stale since the blur
knob landed).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 561 insertions(+), 70 deletions(-)
diff --git a/common/controller/autoRunner.test.ts b/common/controller/autoRunner.test.ts
@@ -8,8 +8,11 @@ import {
focusHoldLine,
laneDispatchRoot,
makeFocusHoldReporter,
+ LANE_SCAN_REST_MS,
pickMetadataScanChannel,
priorityContextFor,
+ scanSkipPlatforms,
+ settleLaneScan,
resetPriorityContextForTest,
sharedAutoQueueState,
isChannelHeldForLane,
@@ -402,9 +405,10 @@ test("an empty backlog is not work", () => {
});
test("once per runner: a channel already scanned this run is skipped", () => {
- // A scan that left the backlog above zero was stopped by something — a soft
- // block, a cooldown, a batch that ended early. Re-offering it three seconds
- // later would hammer the source that just refused us.
+ // A scan that was stopped by something — a soft block, a cooldown, an
+ // error — stays in the set. Re-offering it three seconds later would hammer
+ // the source that just refused us. (A clean batch with work left is taken
+ // out again: settleLaneScan below.)
assert.equal(
pickMetadataScanChannel(
[work({ slug: "filtered", scanUnscanned: 40, filtered: true })],
@@ -414,6 +418,71 @@ test("once per runner: a channel already scanned this run is skipped", () => {
);
});
+// THE LANE SCANS IN BATCHES (2026-10-25: an unbatched 1,163-video scan held
+// platform:youtube 03:20–06:36 and no download ran). After each batch the
+// platform rests — the downloads' turn — and only a clean batch with targets
+// left puts its channel back in line.
+
+test("a clean batch with work left is readmitted, after the platform rests", () => {
+ const now = 1_000_000;
+ const settled = settleLaneScan(
+ { scanned: 60, errors: 3, targets: 60, remaining: 1103 },
+ now,
+ );
+ assert.deepEqual(settled, {
+ restUntil: now + LANE_SCAN_REST_MS,
+ readmit: true,
+ remaining: 1103,
+ });
+ const rest = new Map([["youtube", settled.restUntil]]);
+ // Resting: the pre-pick sees youtube as skipped, so the readmitted channel
+ // waits while the downloads run.
+ assert.equal(
+ pickMetadataScanChannel(
+ [work({ slug: "filtered", scanUnscanned: 1103, filtered: true })],
+ { ...noSkip, platformSkip: scanSkipPlatforms(new Set(), rest, now + 60_000) },
+ ),
+ null,
+ );
+ // Rested: the next batch is offered.
+ assert.deepEqual(
+ pickMetadataScanChannel(
+ [work({ slug: "filtered", scanUnscanned: 1103, filtered: true })],
+ {
+ ...noSkip,
+ platformSkip: scanSkipPlatforms(new Set(), rest, settled.restUntil),
+ },
+ ),
+ { slug: "filtered", targets: 1103 },
+ );
+});
+
+test("a stopped batch, a finished backlog and a job with no result are not readmitted", () => {
+ const now = 5;
+ for (const result of [
+ { scanned: 12, errors: 0, targets: 60, remaining: 900, stopped: "rate_limit" as const },
+ { scanned: 40, errors: 0, targets: 40, remaining: 0 },
+ null,
+ ]) {
+ const settled = settleLaneScan(result, now);
+ assert.equal(settled.readmit, false);
+ // The platform rests either way: the downloads get their turn.
+ assert.equal(settled.restUntil, now + LANE_SCAN_REST_MS);
+ }
+});
+
+test("the scan's platform skip keeps the downloads' own skips and drops an expired rest", () => {
+ const skip = scanSkipPlatforms(
+ new Set(["rumble"]),
+ new Map([
+ ["youtube", 100],
+ ["odysee", 50],
+ ]),
+ 75,
+ );
+ assert.deepEqual([...skip].sort(), ["rumble", "youtube"]);
+});
+
test("a busy or cooling platform offers no scan either", () => {
// The same gate the downloads honour: the scan is one more thing asking that
// source for titles, and the per-platform cap is one at a time.
diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts
@@ -9,6 +9,7 @@ import { formatBytes } from "../lib/format";
import { detectPlatform } from "../lib/platform";
import { compileDownloadFilter } from "../lib/downloadFilters";
import { runMetadataScanJob } from "./metadataScanJob";
+import type { MetadataScanResult } from "../ytdlp/metadataScan";
import { getWorkerPool } from "../jobs/workerPool";
import { getRegistry } from "../jobs/registry";
import { runManagedFunction } from "../jobs/streamCommand";
@@ -198,6 +199,17 @@ const COMPLETED_CAP = 5000;
export const METADATA_SCAN_UNIT_PREFIX = "metadata-scan ";
export const METADATA_SCAN_LEAF_ID = "metadata-scan";
+// THE LANE SCANS IN BATCHES. A scan holds its platform's download queue for as
+// long as it runs, so an unbatched one over a big backlog is hours of no
+// downloads on that platform: on 2026-10-25 the 1,163-video scan of h3-podcast
+// that started the moment its download pause lifted held platform:youtube from
+// 03:20 to 06:36 (~10 s a title). A batch of 60 is ~10 minutes; then the
+// platform takes no lane scan for LANE_SCAN_REST_MS, which is the downloads'
+// turn (~20 at YouTube's pace), and the channel's next batch is offered after.
+// The operator's Run still scans the whole backlog.
+export const LANE_SCAN_BATCH = 60;
+export const LANE_SCAN_REST_MS = 20 * 60 * 1000;
+
// --- Live status (for /api/auto-queue/status), per kind --------------------
export type AutoRunnerInFlight = {
@@ -1170,6 +1182,34 @@ export function pickMetadataScanChannel(
return null;
}
+// AFTER A LANE SCAN BATCH: the platform rests (the downloads' turn) whatever
+// the batch found, and the channel is offered another batch only when this one
+// ended CLEANLY with targets left. A stopped scan (a soft block, a cooldown, an
+// error), a cancelled or failed job (no result at all) and a finished backlog
+// all leave the channel in `scannedThisRun` — see the pre-pick. Pure, so the
+// rule is testable without a runner.
+export function settleLaneScan(
+ result: MetadataScanResult | null,
+ now: number,
+): { restUntil: number; readmit: boolean; remaining: number } {
+ const remaining = result && !result.stopped ? result.remaining : 0;
+ return { restUntil: now + LANE_SCAN_REST_MS, readmit: remaining > 0, remaining };
+}
+
+// The platforms the scan pre-pick may not use this tick: the downloads' own
+// skip set (busy or cooling) plus every platform still resting after a batch.
+export function scanSkipPlatforms(
+ platformSkip: ReadonlySet<string>,
+ restUntil: ReadonlyMap<string, number>,
+ now: number,
+): Set<string> {
+ const out = new Set(platformSkip);
+ for (const [platform, until] of restUntil) {
+ if (until > now) out.add(platform);
+ }
+ return out;
+}
+
type Picked = {
pick: WorkPick;
channelSlug: string;
@@ -1299,8 +1339,12 @@ async function runLoop(
// restart is itself a gap.
const platformNextStartAt = new Map<string, number>();
// Channels this runner has already scanned (or tried to). See the pre-pick in
- // next() for why a scan is never retried inside one runner's lifetime.
+ // next() for why a STOPPED scan is never retried inside one runner's
+ // lifetime; a clean batch with work left removes its channel again.
const scannedThisRun = new Set<string>();
+ // Platform → epoch ms before which the lane offers that platform no scan:
+ // the downloads' turn between two batches (LANE_SCAN_REST_MS).
+ const scanRestUntil = new Map<string, number>();
// `wayback.auto` channels' new scan rows (release 37 S2): read once a minute
// per channel, each row offered once in this runner's life.
const waybackAuto = WaybackAutoPicker.forPaths(paths);
@@ -1795,20 +1839,32 @@ async function runLoop(
// batch. So it is not another kind of work competing with downloads — it is
// the thing that decides what the downloads ARE, and it goes first.
//
- // ONE PER CHANNEL PER RUNNER, and never a second while one is in flight.
- // `scannedThisRun` is the session's memory: a channel whose scan left the
- // backlog above zero (a soft block, a cooldown, a batch that stopped early)
- // is NOT retried by this runner — the operator's Run button and the next
- // restart both still work, and re-offering it on the next three-second tick
- // would hammer the very source that just refused us.
+ // IN BATCHES, WITH THE DOWNLOADS' TURN BETWEEN THEM. The scan decides what
+ // the downloads are, but it also holds the platform while it runs, so the
+ // lane scans LANE_SCAN_BATCH titles at a time and then gives the platform
+ // LANE_SCAN_REST_MS of downloads (`scanRestUntil`) before the next batch —
+ // an unbatched scan once held YouTube for 3 h 16 m with no download at all.
+ //
+ // A STOPPED SCAN IS NOT RETRIED BY THIS RUNNER, and never a second runs
+ // while one is in flight. `scannedThisRun` is the session's memory: a
+ // channel whose scan stopped (a soft block, a cooldown, an error) is not
+ // re-offered — the operator's Run button and the next restart both still
+ // work, and re-offering it on the next three-second tick would hammer the
+ // very source that just refused us. Only a batch that ended CLEANLY with
+ // targets left takes its channel back out of the set.
//
// It takes a platform slot exactly as a download unit does, so a scan and a
// download never hit one source at once, and it inherits the platform
// cooldown for free: a platform in `platformSkip` offers no scan either.
if (kind === "download") {
+ const scanPlatformSkip = scanSkipPlatforms(
+ platformSkip,
+ scanRestUntil,
+ Date.now(),
+ );
const scanCandidate = pickMetadataScanChannel(channels, {
scanned: scannedThisRun,
- platformSkip,
+ platformSkip: scanPlatformSkip,
platformOf: (slug) => platformKey(slug, slugToPlatform),
...(focus
? {
@@ -1824,8 +1880,9 @@ async function runLoop(
const unitPlatform = platformKey(slug, slugToPlatform);
scannedThisRun.add(slug);
const videoId = `${METADATA_SCAN_UNIT_PREFIX}${slug}`;
- const note = `scanning ${targets} listed video${
- targets === 1 ? "" : "s"
+ const batch = Math.min(targets, LANE_SCAN_BATCH);
+ const note = `scanning ${batch} listed video${batch === 1 ? "" : "s"}${
+ targets > batch ? ` of ${targets}` : ""
} for ${slug}`;
live.idleReason = null;
// No `path`, so no node's active count moves: the scan is not a leaf's
@@ -2083,14 +2140,34 @@ async function runLoop(
return;
}
if (picked.scan) {
+ const scanSlug = picked.scan.slug;
+ let scanResult: MetadataScanResult | null = null;
result = await launchMetadataScan({
paths,
- slug: picked.scan.slug,
+ slug: scanSlug,
targets: picked.scan.targets,
tracker,
onLog,
onChildJob: (jid) => { childJobIds.set(pick.videoId, jid); const u = live.inFlight.get(pick.videoId); if (u) u.jobId = jid; },
+ onResult: (r) => {
+ scanResult = r;
+ },
});
+ const settled = settleLaneScan(
+ scanResult as MetadataScanResult | null,
+ Date.now(),
+ );
+ if (unitPlatform) scanRestUntil.set(unitPlatform, settled.restUntil);
+ if (settled.readmit) {
+ scannedThisRun.delete(scanSlug);
+ onLog(
+ `Auto-download: ${settled.remaining} listed video${
+ settled.remaining === 1 ? "" : "s"
+ } left to scan for ${scanSlug}; the next batch after ${Math.round(
+ LANE_SCAN_REST_MS / 60_000,
+ )} minutes of downloads.`,
+ );
+ }
return;
}
result = isOperationLane(kind)
@@ -2224,6 +2301,7 @@ async function launchMetadataScan(args: {
tracker: ReturnType<typeof makeTaskTracker>;
onLog: (line: string) => void;
onChildJob?: (jobId: string) => void;
+ onResult?: (result: MetadataScanResult) => void;
}): Promise<UnitResult> {
const config = await readChannelConfig(args.paths, args.slug);
if (!config) return { outcome: "skipped" };
@@ -2232,6 +2310,8 @@ async function launchMetadataScan(args: {
slug: args.slug,
channelConfig: config,
background: true,
+ maxTargets: LANE_SCAN_BATCH,
+ ...(args.onResult ? { onResult: args.onResult } : {}),
});
if (!res.ok) {
args.onLog(
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -67,6 +67,7 @@ import {
chatOnlyIdsFrom,
loadMetadataScan,
metadataScanWanted,
+ scanExclusionsFrom,
settledIdsFrom,
type MetadataScanRun,
} from "./metadataScanStore";
@@ -1222,21 +1223,13 @@ export async function generateChannelSnapshot(
// Settled means the MEDIA is not wanted, which is true of these too — what
// this adds is that the video is still a corpus member, as a chat track.
const chatOnlyIds = chatOnlyIdsFrom(metadataScanStore, config);
- // A scan that already read an id as members-only or private is the
- // same answer a failed download records in availability.json — without this
- // the download lane re-learned it, one ~30 s cookie-authed attempt per id
- // (timcast-irl: 28 members-only ids the scan had classified an hour before).
- // Derived like settledIds: a later scan that reads the video deletes the
- // error, and the exclusion lifts with nothing to undo. A conclusive on-disk
+ // The scan's members-only/private verdicts (scanExclusionsFrom — the one
+ // rule the batch prefilter in runYtdlp shares). A conclusive on-disk
// availability is newer evidence and wins; `error` (a cancelled or throttled
- // attempt) is not conclusive. Not the scan's `deleted`: that is
- // inferred from a bare "Video unavailable", which is also how a soft block
- // reads, so it is not evidence enough to stop asking.
- for (const [id, err] of Object.entries(metadataScanStore.errors)) {
+ // attempt) is not conclusive.
+ for (const [id, cls] of scanExclusionsFrom(metadataScanStore)) {
const onDisk = effectiveById.get(id);
if (onDisk && onDisk !== "error") continue;
- const cls = err.class as Availability;
- if (cls !== "members_only" && cls !== "private") continue;
effectiveById.set(id, cls);
excludedById.set(id, cls);
}
diff --git a/common/controller/metadataScanJob.ts b/common/controller/metadataScanJob.ts
@@ -29,7 +29,10 @@ import {
} from "../jobs/streamCommand";
import type { ChannelConfig } from "../lib/channelConfig";
import type { Paths } from "../lib/paths";
-import { runMetadataScan } from "../ytdlp/metadataScan";
+import {
+ runMetadataScan,
+ type MetadataScanResult,
+} from "../ytdlp/metadataScan";
export const METADATA_SCAN_JOB_KIND = "metadata-scan";
@@ -46,6 +49,12 @@ export type MetadataScanJobOpts = {
// Called after a successful scan, inside the job. The editor revalidates its
// three paths here; the runner asks for a snapshot regen instead.
afterRun?: () => void | Promise<void>;
+ // A batch of at most this many targets (runMetadataScan's `maxTargets`). The
+ // download lane passes one; the operator's Run does not.
+ maxTargets?: number;
+ // The scan's own result, inside the job — the lane reads `stopped` and
+ // `remaining` from it to decide when the channel's next batch may run.
+ onResult?: (result: MetadataScanResult) => void;
};
export async function runMetadataScanJob(
@@ -65,7 +74,7 @@ export async function runMetadataScanJob(
params: { queueKey: opts.queueKey },
},
fn: async (onLog, signal, setProgress) => {
- await runMetadataScan({
+ const result = await runMetadataScan({
paths,
channelSlug: slug,
channelConfig,
@@ -73,7 +82,9 @@ export async function runMetadataScanJob(
signal,
setProgress,
onPlatformBackoff: () => recordDownloadBackoff(platform, paths),
+ ...(opts.maxTargets ? { maxTargets: opts.maxTargets } : {}),
});
+ opts.onResult?.(result);
await opts.afterRun?.();
},
});
diff --git a/common/controller/metadataScanStore.ts b/common/controller/metadataScanStore.ts
@@ -297,6 +297,34 @@ export function settledIdsFrom(
return settled;
}
+// THE SCAN'S UNAVAILABILITY VERDICTS, as download exclusions. A scan that read
+// an id as members-only or private reached the same answer a failed download
+// records in availability.json, and every batch that ignores it re-learns it:
+// one prefetch plus a cookie-authed retry per id (timcast-irl: 28 members-only
+// ids an hour after the scan; h3-podcast 2026-10-25: a download-missing spent
+// four yt-dlp runs on each of the 277 the scan had found that night).
+//
+// Derived like settledIdsFrom: a later scan that reads the video deletes the
+// error, and the exclusion lifts with nothing to undo. The one rule for both
+// consumers — the snapshot's buckets (and so the download lane) and the batch
+// prefilter in runYtdlp — each of which lets a CONCLUSIVE on-disk availability
+// win over this, as newer evidence. Not the scan's `deleted`: that is inferred
+// from a bare "Video unavailable", which is also how a soft block reads, so it
+// is not evidence enough to stop asking.
+export type ScanExclusionClass = "members_only" | "private";
+
+export function scanExclusionsFrom(
+ scan: MetadataScan,
+): Map<string, ScanExclusionClass> {
+ const out = new Map<string, ScanExclusionClass>();
+ for (const [id, err] of Object.entries(scan.errors)) {
+ if (err.class === "members_only" || err.class === "private") {
+ out.set(id, err.class);
+ }
+ }
+ return out;
+}
+
// THE CHAT-ONLY SUBSET OF THE SETTLED SET — a strict subset, never a second
// population. `titleFilterRejects` answers true for a chat-only video (see
// DownloadFilterVerdict), so every id here is also in `settledIdsFrom`'s
diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -169,7 +169,7 @@ test("the look ops (release 38): look, slide and room through the look's own rul
assert.match(r.applied[1]!.warnings![0]!, /the slide's knobs show once the join style is blur slide/);
assert.deepEqual(
r.refused.map((x) => x.why),
- ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide)'],
+ ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur)'],
);
assert.equal((manifest.render as { transition: number }).transition, 0.4, "the input is not touched");
});
diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts
@@ -125,6 +125,9 @@ export type MetadataScanResult = {
errors: number;
targets: number;
stopped?: MetadataScanRun["stopped"];
+ // Targets left for a later run because of `maxTargets` (0 when the run took
+ // the whole backlog). A stop is reported by `stopped`, not here.
+ remaining: number;
};
export type RunMetadataScanOpts = {
@@ -140,6 +143,12 @@ export type RunMetadataScanOpts = {
onPlatformBackoff?: (
failureClass: "rate_limit" | "network",
) => void | Promise<void>;
+ // A BATCH, not the backlog: scan at most this many targets (in listing
+ // order) and leave the rest for a later run. The download lane passes one so
+ // a scan holds the platform for minutes rather than hours — on 2026-10-25 an
+ // unbatched 1,163-video scan of h3-podcast held platform:youtube for 3 h 16 m
+ // and no download ran. Absent = the whole backlog (the operator's Run).
+ maxTargets?: number;
};
async function readPlaylistIds(channelDir: string): Promise<string[]> {
@@ -244,7 +253,12 @@ export async function runMetadataScan(
const channelDir = path.join(paths.channelsDir, slug);
const startedAt = new Date().toISOString();
- const targetIds = await metadataScanTargets(paths, slug);
+ const backlog = await metadataScanTargets(paths, slug);
+ const targetIds =
+ opts.maxTargets && opts.maxTargets > 0
+ ? backlog.slice(0, opts.maxTargets)
+ : backlog;
+ const remaining = backlog.length - targetIds.length;
const urlsById = await readPlaylistUrlsById(channelDir);
if (targetIds.length === 0) {
opts.onLog(
@@ -263,11 +277,13 @@ export async function runMetadataScan(
},
new Date().toISOString(),
);
- return { scanned: 0, errors: 0, targets: 0 };
+ return { scanned: 0, errors: 0, targets: 0, remaining: 0 };
}
opts.onLog(
- `Scanning metadata for ${targetIds.length} listed video(s). No media is downloaded and no video directory is created.\n`,
+ `Scanning metadata for ${targetIds.length} listed video(s)${
+ remaining > 0 ? ` — a batch; ${remaining} more wait for a later run` : ""
+ }. No media is downloaded and no video directory is created.\n`,
);
opts.setProgress?.({
metric: "scans",
@@ -751,5 +767,6 @@ export async function runMetadataScan(
errors: errorCount,
targets: targetIds.length,
...(stopped ? { stopped } : {}),
+ remaining,
};
}
diff --git a/common/ytdlp/metadataScanBatch.test.ts b/common/ytdlp/metadataScanBatch.test.ts
@@ -0,0 +1,92 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/metadataScanBatch.test.ts
+//
+// THE LANE'S SCAN IS A BATCH (`maxTargets`). On 2026-10-25 an unbatched scan of
+// h3-podcast's 1,163 unread titles held platform:youtube for 3 h 16 m and no
+// download ran. A batch reads the first N targets in listing order, reports how
+// many it left, and the next batch picks up after them. A fake yt-dlp prints
+// one record per batch-file URL; getPaths() memoizes, so the env is set before
+// anything imports it.
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "scan-batch-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+writeFileSync(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }) + "\n");
+const CALLS = path.join(ROOT, "calls.log");
+const BIN = path.join(ROOT, "fake-ytdlp.sh");
+writeFileSync(
+ BIN,
+ `#!/bin/sh
+batch=""
+while [ $# -gt 0 ]; do
+ if [ "$1" = "-a" ]; then batch="$2"; fi
+ shift
+done
+echo run >> "${CALLS}"
+while read -r url; do
+ [ -z "$url" ] && continue
+ id=\${url##*v=}
+ printf '{"id":"%s","title":"Episode %s","description":"","upload_date":"20261025","webpage_url":"%s"}\\n' "$id" "$id" "$url"
+done < "$batch"
+exit 0
+`,
+);
+chmodSync(BIN, 0o755);
+process.env.YTDLP_BIN = BIN;
+const IDS = ["aaaaaaaaaa1", "bbbbbbbbbb2", "ccccccccccc", "ddddddddddd", "eeeeeeeeeee"];
+mkdirSync(path.join(ROOT, "channels", "c", "data"), { recursive: true });
+writeFileSync(
+ path.join(ROOT, "channels", "c", "playlist"),
+ IDS.map((id) => `https://www.youtube.com/watch?v=${id}`).join("\n") + "\n",
+);
+
+const { runMetadataScan } = await import("./metadataScan");
+const { loadMetadataScan } = await import("../controller/metadataScanStore");
+const { getPaths } = await import("../lib/paths");
+
+const config = { handling: "youtube", url: "https://www.youtube.com/@c/videos" } as never;
+const scan = (maxTargets?: number) =>
+ runMetadataScan({
+ paths: getPaths(),
+ channelSlug: "c",
+ channelConfig: config,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ ...(maxTargets ? { maxTargets } : {}),
+ });
+
+test("a batch reads the first N targets in listing order and reports the rest", async () => {
+ const first = await scan(2);
+ assert.equal(first.targets, 2);
+ assert.equal(first.remaining, 3);
+ assert.equal(first.stopped, undefined);
+ assert.deepEqual(
+ Object.keys((await loadMetadataScan(getPaths(), "c")).entries).sort(),
+ IDS.slice(0, 2),
+ );
+
+ const second = await scan(2);
+ assert.equal(second.targets, 2);
+ assert.equal(second.remaining, 1);
+ assert.deepEqual(
+ Object.keys((await loadMetadataScan(getPaths(), "c")).entries).sort(),
+ IDS.slice(0, 4),
+ );
+});
+
+test("no maxTargets takes the whole backlog (the operator's Run)", async () => {
+ const last = await scan();
+ assert.equal(last.targets, 1);
+ assert.equal(last.remaining, 0);
+ assert.equal(Object.keys((await loadMetadataScan(getPaths(), "c")).entries).length, 5);
+ // One yt-dlp process per batch: 2 + 2 + 1 targets in three runs.
+ assert.equal(readFileSync(CALLS, "utf8").trim().split("\n").length, 3);
+
+ const none = await scan(2);
+ assert.deepEqual(none, { scanned: 0, errors: 0, targets: 0, remaining: 0 });
+});
diff --git a/common/ytdlp/partitionDownloadBatch.test.ts b/common/ytdlp/partitionDownloadBatch.test.ts
@@ -0,0 +1,141 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type { MetadataScan } from "../controller/metadataScanStore";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/partitionDownloadBatch.test.ts
+//
+// THE BATCH PREFILTER HONOURS THE SCAN'S VERDICTS. On 2026-10-25 a
+// download-missing on h3-podcast excluded 2 members-only videos (the two with an
+// availability.json) and walked into the 277 the metadata scan had read as
+// members-only that night: four yt-dlp runs each, nothing landed. The snapshot
+// (and so the download lane) already skipped them; the batch did not.
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "partition-batch-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+writeFileSync(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }) + "\n");
+const DATA = path.join(ROOT, "channels", "c", "data");
+mkdirSync(DATA, { recursive: true });
+
+const { partitionDownloadBatch } = await import("./runYtdlp");
+
+const AT = "2026-10-25T07:00:00.000Z";
+const url = (id: string) => `https://www.youtube.com/watch?v=${id}`;
+
+function onDisk(id: string, availability: string): void {
+ mkdirSync(path.join(DATA, id), { recursive: true });
+ writeFileSync(
+ path.join(DATA, id, "availability.json"),
+ JSON.stringify({ checkedAt: AT, availability }) + "\n",
+ );
+}
+
+function scanWith(
+ errors: Record<string, string>,
+ entries: Record<string, string> = {},
+): MetadataScan {
+ return {
+ version: 1,
+ updatedAt: AT,
+ lastRun: null,
+ entries: Object.fromEntries(
+ Object.entries(entries).map(([id, title]) => [
+ id,
+ { title, description: "", uploadDate: "", scannedAt: AT },
+ ]),
+ ),
+ errors: Object.fromEntries(
+ Object.entries(errors).map(([id, cls]) => [
+ id,
+ { class: cls, message: "Join this channel …", at: AT },
+ ]),
+ ),
+ };
+}
+
+test("the scan's members-only and private verdicts exclude a video with no directory", async () => {
+ const r = await partitionDownloadBatch({
+ urls: ["memberAAAAA", "privateBBBB", "plainCCCCCC"].map(url),
+ dataDir: DATA,
+ scan: scanWith({ memberAAAAA: "members_only", privateBBBB: "private" }),
+ config: null,
+ deferNeedsAuth: false,
+ });
+ assert.deepEqual(r.fetch, [url("plainCCCCCC")]);
+ assert.deepEqual(r.excludedCounts, { members_only: 1, deleted: 0, private: 1 });
+ assert.equal(r.excludedByScan, 2);
+});
+
+test("the scan's `deleted` is not evidence enough (a soft block reads the same)", async () => {
+ const r = await partitionDownloadBatch({
+ urls: [url("deletedDDDD")],
+ dataDir: DATA,
+ scan: scanWith({ deletedDDDD: "deleted" }),
+ config: null,
+ deferNeedsAuth: false,
+ });
+ assert.deepEqual(r.fetch, [url("deletedDDDD")]);
+ assert.equal(r.excludedByScan, 0);
+});
+
+test("a conclusive on-disk availability wins over the scan; an on-disk `error` does not", async () => {
+ onDisk("publicEEEEE", "public");
+ onDisk("errorFFFFFF", "error");
+ const r = await partitionDownloadBatch({
+ urls: [url("publicEEEEE"), url("errorFFFFFF")],
+ dataDir: DATA,
+ scan: scanWith({ publicEEEEE: "members_only", errorFFFFFF: "members_only" }),
+ config: null,
+ deferNeedsAuth: false,
+ });
+ assert.deepEqual(r.fetch, [url("publicEEEEE")]);
+ assert.equal(r.excludedCounts.members_only, 1);
+ assert.equal(r.excludedByScan, 1);
+});
+
+test("an on-disk exclusion is counted, but not as the scan's", async () => {
+ onDisk("diskMemberG", "members_only");
+ const r = await partitionDownloadBatch({
+ urls: [url("diskMemberG")],
+ dataDir: DATA,
+ scan: scanWith({}),
+ config: null,
+ deferNeedsAuth: false,
+ });
+ assert.deepEqual(r.fetch, []);
+ assert.equal(r.excludedCounts.members_only, 1);
+ assert.equal(r.excludedByScan, 0);
+});
+
+test("the download filter's settled set is checked first; needs_auth defers only under defer", async () => {
+ onDisk("needsAuthHH", "needs_auth");
+ const scan = scanWith(
+ { leftoverIII: "members_only" },
+ { leftoverIII: "Leftovers #12", episodeJJJJ: "H3 Podcast #300" },
+ );
+ const config = { downloadFilter: { exclude: "Leftovers (Live )?#\\d+" } };
+ const urls = ["leftoverIII", "episodeJJJJ", "needsAuthHH"].map(url);
+ const deferred = await partitionDownloadBatch({
+ urls,
+ dataDir: DATA,
+ scan,
+ config: config as never,
+ deferNeedsAuth: true,
+ });
+ // The scan read leftoverIII's title before it ever errored — an entry wins
+ // over an error in the store, but either way the filter settles it first.
+ assert.equal(deferred.settledByFilterCount, 1);
+ assert.equal(deferred.deferredAuthCount, 1);
+ assert.deepEqual(deferred.fetch, [url("episodeJJJJ")]);
+ const always = await partitionDownloadBatch({
+ urls,
+ dataDir: DATA,
+ scan,
+ config: config as never,
+ deferNeedsAuth: false,
+ });
+ assert.deepEqual(always.fetch, [url("episodeJJJJ"), url("needsAuthHH")]);
+});
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -48,8 +48,12 @@ import { resolveEffectiveAvailability } from "../lib/availability-server";
import { withMetadataHistory } from "../lib/metadataHistory-server";
import { seedFeedTitles } from "../controller/feedTitlePrefilter";
import {
+ loadMetadataScan,
+ scanExclusionsFrom,
settledByTitleFilterIds,
+ settledIdsFrom,
upsertMetadataScan,
+ type MetadataScan,
type MetadataScanEntry,
} from "../controller/metadataScanStore";
import { backfillAvailabilityFromMetadata } from "../controller/backfillAvailability";
@@ -750,6 +754,81 @@ async function downloadMissing(opts: RunYtdlpOpts): Promise<void> {
type PrefilterMode = "archive" | "destination-exists";
+// WHICH OF A BATCH'S MISSING VIDEOS ARE WORTH ASKING FOR. Exported so the rule
+// is testable without a playlist walk or a yt-dlp. In order:
+//
+// 1. Settled by the channel's download filter (the metadata scan read the
+// title and the CURRENT filter rejects it). Checked first, so a filtered
+// channel's batch doesn't run the metadata prefetch for every non-match on
+// every run just to reach the same verdict the scan already reached.
+// 2. Permanently unavailable (EXCLUDED_FROM_DOWNLOAD): the on-disk
+// availability when it is conclusive, else the scan's members-only /
+// private verdict (scanExclusionsFrom — the same rule the snapshot, and so
+// the download lane, applies). Without the scan's half a download-missing
+// re-learned every one: on 2026-10-25 an h3-podcast batch spent four
+// yt-dlp runs on each of the 277 members-only videos the scan had found
+// that night, and landed nothing.
+// 3. needs_auth under cookie mode "defer".
+export async function partitionDownloadBatch(args: {
+ urls: ReadonlyArray<string>;
+ dataDir: string;
+ scan: MetadataScan;
+ config: Pick<ChannelConfig, "downloadFilter"> | null | undefined;
+ deferNeedsAuth: boolean;
+}): Promise<{
+ fetch: string[];
+ excludedCounts: { members_only: number; deleted: number; private: number };
+ // How many of excludedCounts came from the scan rather than availability.json.
+ excludedByScan: number;
+ deferredAuthCount: number;
+ settledByFilterCount: number;
+}> {
+ const settledByFilter = settledIdsFrom(args.scan, args.config);
+ const scanExcluded = scanExclusionsFrom(args.scan);
+ const excludedCounts = { members_only: 0, deleted: 0, private: 0 };
+ let excludedByScan = 0;
+ let deferredAuthCount = 0;
+ let settledByFilterCount = 0;
+ const fetch: string[] = [];
+ for (const url of args.urls) {
+ const dirId = extractVideoId(url);
+ if (dirId) {
+ if (settledByFilter.has(dirId)) {
+ settledByFilterCount++;
+ continue;
+ }
+ const onDisk = await resolveEffectiveAvailability(
+ path.join(args.dataDir, dirId),
+ );
+ // A conclusive on-disk availability is newer evidence than the scan's
+ // verdict and wins; `error` (a cancelled or throttled attempt) is not.
+ const conclusive = onDisk && onDisk !== "error" ? onDisk : null;
+ const fromScan = conclusive ? undefined : scanExcluded.get(dirId);
+ const cls = conclusive ?? fromScan ?? onDisk;
+ if (
+ cls &&
+ (EXCLUDED_FROM_DOWNLOAD as ReadonlyArray<Availability>).includes(cls)
+ ) {
+ excludedCounts[cls as keyof typeof excludedCounts]++;
+ if (fromScan) excludedByScan++;
+ continue;
+ }
+ if (args.deferNeedsAuth && cls === "needs_auth") {
+ deferredAuthCount++;
+ continue;
+ }
+ }
+ fetch.push(url);
+ }
+ return {
+ fetch,
+ excludedCounts,
+ excludedByScan,
+ deferredAuthCount,
+ settledByFilterCount,
+ };
+}
+
async function downloadPlaylistManaged(
opts: RunYtdlpOpts,
cfg: {
@@ -891,50 +970,29 @@ async function downloadPlaylistManaged(
signal: opts.signal,
}).catch(() => 0);
// ONE read of the channel-level metadata-scan store for the whole batch.
- const settledByFilter = await settledByTitleFilterIds(
- opts.paths,
- opts.channelSlug,
- effectiveChannelConfig,
- );
- const excludedCounts = { members_only: 0, deleted: 0, private: 0 };
- let deferredAuthCount = 0;
- let settledByFilterCount = 0;
- const filteredTofetch: string[] = [];
- for (const url of tofetch) {
- const dirId = extractVideoId(url);
- if (dirId) {
- // Settled by the channel's download filter, from the set resolved once
- // above. Checked FIRST, so a filtered channel's batch doesn't run the
- // metadata prefetch for every non-match on every run just to reach the
- // same verdict the scan already reached.
- if (settledByFilter.has(dirId)) {
- settledByFilterCount++;
- continue;
- }
- const cls = await resolveEffectiveAvailability(
- path.join(dataDir, dirId),
- );
- if (
- cls &&
- (EXCLUDED_FROM_DOWNLOAD as ReadonlyArray<Availability>).includes(cls)
- ) {
- excludedCounts[cls as keyof typeof excludedCounts]++;
- continue;
- }
- if (runCookiePolicy.mode === "defer" && cls === "needs_auth") {
- deferredAuthCount++;
- continue;
- }
- }
- filteredTofetch.push(url);
- }
+ const batch = await partitionDownloadBatch({
+ urls: tofetch,
+ dataDir,
+ scan: await loadMetadataScan(opts.paths, opts.channelSlug),
+ config: effectiveChannelConfig,
+ deferNeedsAuth: runCookiePolicy.mode === "defer",
+ });
+ const {
+ fetch: filteredTofetch,
+ excludedCounts,
+ excludedByScan,
+ deferredAuthCount,
+ settledByFilterCount,
+ } = batch;
const totalExcluded =
excludedCounts.members_only +
excludedCounts.deleted +
excludedCounts.private;
if (totalExcluded > 0) {
opts.onLog(
- `Excluded ${totalExcluded} from this run (members_only=${excludedCounts.members_only}, deleted=${excludedCounts.deleted}, private=${excludedCounts.private}). Clear via Diagnostics > Recheck if a video became public again.\n`,
+ `Excluded ${totalExcluded} from this run (members_only=${excludedCounts.members_only}, deleted=${excludedCounts.deleted}, private=${excludedCounts.private}${
+ excludedByScan > 0 ? `; ${excludedByScan} as the metadata scan read them` : ""
+ }). Clear via Diagnostics > Recheck if a video became public again.\n`,
);
}
if (settledByFilterCount > 0) {
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **The download lane's metadata scan reads 60 titles at a time and lets the downloads run in between.** A filtered channel's scan holds its platform's download queue while it runs, and the lane used to scan the whole backlog in one go: on 2026-10-25 the scan of h3-podcast's 1,163 unread titles, which started the moment the channel's download pause was lifted, held YouTube from 03:20 to 06:36 and nothing downloaded. The lane now scans 60 titles (about 10 minutes on YouTube), gives that platform 20 minutes of downloads, then scans the next 60, and its log says so: "1103 listed videos left to scan for h3-podcast; the next batch after 20 minutes of downloads." A scan that a platform stopped (a soft block, a rate limit) is still not retried until the next restart. **Run** on the metadata-scan operation still scans the whole backlog. Needs a restart of the editor.
+- **Download missing skips the videos the metadata scan read as members-only or private.** The download lane already skipped them; a Download missing run only skipped the ones a failed download had recorded, so on 2026-10-25 a run on h3-podcast tried each of the 277 members-only videos the scan had found that night four times (with and without cookies) and downloaded nothing. The run's log counts them: "Excluded 279 from this run (members_only=279, deleted=0, private=0; 277 as the metadata scan read them)." A video the scan reads again later comes back by itself. Needs a restart of the editor.
- **A Transcribe holds the platform's queue only while it downloads.** The video page's Audio + Whisper and `pnpm ops transcribe-one` used to keep YouTube's (or any platform's) download queue for the whole transcription, so nothing else downloaded on that platform while it waited for a worker and transcribed. Now the audio download runs on the platform's queue and the transcription runs as its own job on the video's queue (`transcribe-one:<slug>:<id>`); with the audio already on disk it starts there at once. The run panel and `pnpm ops … --wait` follow both jobs to the end of the transcription, and the first job's log names the second. `pnpm ops transcribe-one` with `"file"` now runs on the video's own queue unless a download is owed, takes `"queueKey"`, and for a YouTube video whose captions are listed and that has no audio fetches the captions instead (says so, and refuses when the captions are already on disk) unless `"asr": true` is passed. Needs a restart of the editor.
- **umtool's memory no longer creeps up while it sits open.** Its in-memory copies of cue files, track analyses, loudness numbers, media probes, ASR word lists, plans and post archives each keep one copy per file (a changed file replaces its old copy) and a bounded number of files, instead of a new copy beside the old every time a file changed. Needs a restart of umtool.
- **A take of part of a cut (`--at`) no longer refuses to build over the on-screen deck's markers and claim checks.** The take keeps the markers and claims that follow clips inside its window and drops the rest; a goalpost whose steps cross the window's edge keeps the steps inside it. Needs a restart of umtool.