Archilyzer · Source

archilyzer

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

commit 5917853f536b3d443f722f0f9427068d7e6dba29
parent f5c7264941a9cb5bbb0229b79cef23b78ed7bd9d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 23:45:49 -0400

common: the managed download reads the stored media URL — storedUrl never|fallback|only (the channel's storedUrlDownloads by default): only goes straight to it, fallback after a rate-limited prefetch or download; one new file per platform per 20-minute rest (platformGap stored-url:<platform>); the outcome sidecar, archive line, media tier and corrupt refetch as for any download; a stored-URL success never settles the platform clean (batch, lane)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/controller/autoRunner.ts | 21++++++++++++++++++++-
Mcommon/jobs/unitOutcome.test.ts | 23+++++++++++++++++++++++
Mcommon/jobs/unitOutcome.ts | 15+++++++++++++++
Mcommon/lib/downloadOutcome.ts | 14++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 408+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/ytdlp/managedDownloadsSleep.test.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/runYtdlp.ts | 24++++++++++++++++++++++++
Acommon/ytdlp/storedUrlManaged.test.ts | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 814 insertions(+), 31 deletions(-)

diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -89,7 +89,11 @@ import { type DownloadFailureClass } from "../lib/availability"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { isAutoSubsOnly } from "../lib/subtitleProvenance"; import { readVideoFiles } from "../lib/videoStatus"; -import { type DownloadOutcomeStatus } from "../lib/downloadOutcome"; +import { + storedUrlAttemptOf, + type DownloadOutcomeStatus, + type StoredUrlAttempt, +} from "../lib/downloadOutcome"; import { downloadQueueKey } from "../lib/queueKeys"; import { isGateHeld } from "../lib/pauseGates"; import { @@ -2037,6 +2041,7 @@ async function runLoop( channelSlug, outcome: result.outcome, ...(result.failureClass ? { failureClass: result.failureClass } : {}), + ...(result.viaStoredUrl ? { viaStoredUrl: true } : {}), }, settledAt, Math.random, @@ -2167,6 +2172,8 @@ type LaunchArgs = { type UnitResult = { outcome: "transcribed" | "skipped" | "failed"; failureClass?: DownloadFailureClass; + // The media came from the record's stored URL (release 32 R7). + viaStoredUrl?: boolean; }; // Whether this unit is an auto-captions replacement: the video's only @@ -2272,6 +2279,7 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> { // reads them after `await res.done` resolves (single-threaded → no race). let unitStatus: DownloadOutcomeStatus | undefined; let unitFailureClass: DownloadFailureClass | undefined; + let unitStored: StoredUrlAttempt | null = null; const res = await runManagedFunction({ kind: AUTO_DOWNLOAD_UNIT_KIND, @@ -2312,6 +2320,7 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> { }); unitStatus = record.status; unitFailureClass = record.failureClass; + unitStored = storedUrlAttemptOf(record); // Land a failed download as a failed JOB (red row) rather than a silent // "done"; the runner reads the captured status/class regardless. A // short-audio download kept its file (so it won't be re-queued) but @@ -2353,6 +2362,16 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> { if (unitStatus === "corrupt-full-source") return { outcome: "skipped" }; // A success whose SUBTITLE fetch alone answered 429 says so: the runner // defers the video's subtitles and leaves the platform alone (release 17). + // Set inside the child job's fn; TS cannot see the assignment from here. + const stored = unitStored as StoredUrlAttempt | null; + if (unitStatus && unitStatus.startsWith("ok") && stored) { + // From the stored media URL (release 32 R7): after a rate-limited page + // lookup the platform backs off as for any 429; otherwise (`only`, held) + // the platform was not asked and is not settled clean. + return stored.why === "rate-limited" + ? { outcome: "transcribed", failureClass: "rate_limit" } + : { outcome: "transcribed", viaStoredUrl: true }; + } if (unitStatus && unitStatus.startsWith("ok")) { return unitFailureClass === "subs_rate_limit" ? { outcome: "transcribed", failureClass: "subs_rate_limit" } diff --git a/common/jobs/unitOutcome.test.ts b/common/jobs/unitOutcome.test.ts @@ -300,3 +300,26 @@ test("a hold reached through network failures alone is worded as failing, not ra applyUnitOutcome(s, unit("r", { failureClass: "rate_limit" }), 20, noJitter, pacing); assert.equal(s.platformHolds.youtube.rateLimited, true); }); + +// Release 32 R7: a download through the record's stored media URL asked the +// CDN, not the platform — it retires the video and settles nothing. +test("viaStoredUrl: a success retires the video and leaves the platform's backoff and hold alone", () => { + const s = empty(); + const now = 5_000_000; + s.platformBackoff.odysee = { until: now + 60_000, fails: 3 }; + s.platformHolds.odysee = { since: now - 1, probeAt: now + 60_000, rateLimited: true }; + const r = applyUnitOutcome( + s, + unit("v9", { platform: "odysee", outcome: "transcribed", viaStoredUrl: true }), + now, + noJitter, + ); + assert.equal(r.markCompleted, true); + assert.deepEqual(s.platformBackoff.odysee, { until: now + 60_000, fails: 3 }); + assert.ok(s.platformHolds.odysee); + assert.match(r.line ?? "", /downloaded from its stored media URL; odysee is not settled clean/); + // Without the flag the same success clears both. + applyUnitOutcome(s, unit("v10", { platform: "odysee", outcome: "transcribed" }), now, noJitter); + assert.equal(s.platformBackoff.odysee, undefined); + assert.equal(s.platformHolds.odysee, undefined); +}); diff --git a/common/jobs/unitOutcome.ts b/common/jobs/unitOutcome.ts @@ -17,6 +17,10 @@ // - anything else retires it; a success (`transcribed`) also clears the // platform's cooldown. // - every branch prunes lapsed deferrals, keeping the map bounded. +// - a success through the record's stored media URL (release 32 R7, +// `viaStoredUrl`) retires the video and settles nothing: the platform was +// not asked. One whose page lookup was rate-limited first comes in as a +// `rate_limit` and backs the platform off like any other. // // Release 17, slice RL (see platformBackoff.ts, "The adaptive pace"): // - `rate_limit` also doubles the platform's pace, and a backoff that has @@ -66,6 +70,9 @@ export type FinishedUnit = { channelSlug: string; outcome: "transcribed" | "skipped" | "failed"; failureClass?: DownloadFailureClass; + // Release 32 R7: the media came from the record's stored URL (its CDN), not + // the platform — a success that is not a clean probe of the platform. + viaStoredUrl?: boolean; }; export type UnitOutcomeEffect = { @@ -143,6 +150,14 @@ export function applyUnitOutcome( line: `Auto-download: ${unit.videoId} downloaded; its subtitles were rate-limited (${d.count}×) — ${left}. ${pf ?? "the platform"} is not backed off.`, }; } + if (pf !== null && unit.outcome === "transcribed" && unit.viaStoredUrl) { + // The CDN answered, the platform was not asked: its backoff, hold and + // pace stay as they are. + return { + markCompleted: true, + line: `Auto-download: ${unit.videoId} downloaded from its stored media URL; ${pf} is not settled clean by it.`, + }; + } if (pf !== null && unit.outcome === "transcribed") { const fx = settlePlatformClean(state, pf, { baseSeconds: staticSleepRequestsSeconds(pf), diff --git a/common/lib/downloadOutcome.ts b/common/lib/downloadOutcome.ts @@ -198,3 +198,17 @@ export type DownloadOutcomeRecord = { }; export const DOWNLOAD_OUTCOME_FILENAME = "download-outcome.json"; + +// The stored-URL attempt a download ended with (release 32 R7), or null. +export function storedUrlAttemptOf(record: Pick<DownloadOutcomeRecord, "attempts">): StoredUrlAttempt | null { + const last = record.attempts.at(-1); + return last?.kind === "stored-url-ranged" ? (last.storedUrl ?? null) : null; +} + +// Did the download ask the PLATFORM anything (a page, its API, yt-dlp)? A +// stored-URL download asked only its CDN — `only`, a held platform, or `only` +// with no stored URL at all asks nothing. A run whose downloads asked the +// platform nothing says nothing about it: it must not settle it clean. +export function askedPlatform(record: Pick<DownloadOutcomeRecord, "attempts">): boolean { + return record.attempts.some((a) => a.kind !== "stored-url-ranged"); +} diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -104,6 +104,23 @@ import { type SourceVideoQuality, } from "./downloadFormat"; import { DOWNLOAD_PROGRESS_TEMPLATE } from "../jobs/progressParsers"; +import { + resolveStoredUrlMode, + STORED_URL_NEW_FILE_GAP_MS, + storedUrlGapKey, + storedUrlWhyText, + type StoredMediaUrl, + type StoredUrlMode, + type StoredUrlWhy, +} from "../lib/storedMediaUrl"; +import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import type { DownloadFailureClass } from "../lib/availability"; +import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; +import { + storedUrlDownload, + type StoredUrlDownloadDeps, + type StoredUrlDownloadResult, +} from "./storedUrlDownload"; // The `--print` archive marker below implies `--quiet`, which otherwise @@ -203,6 +220,23 @@ export type ManagedDownloadOpts = { // Test seam: how the corrupt-source refetch measures a file's decodable // seconds (ytdlp/corruptRefetch.ts). Every production caller passes none. corruptRefetchDeps?: CorruptRefetchDeps; + // THE STORED MEDIA URL (release 32 R7, ytdlp/storedUrlDownload.ts): a full + // download may read the media URL the record's metadata.info.json already + // stores, the way the platform's player does — `never` | `fallback` (the page + // first; on its rate limit, the stored URL) | `only` (no page request). + // Absent = the channel's `storedUrlDownloads`, else never. Transcribe + // handling, STORED_URL_PLATFORMS only. + storedUrl?: StoredUrlMode; + // The platform is HELD and the caller's door let this run through as + // `only` (the log and the attempt say "held" rather than "only"). + storedUrlHeld?: boolean; + // Test seam: the CDN fetch, the chunk, the audio check's knobs, and the gap + // between two stored-URL files (default STORED_URL_NEW_FILE_GAP_MS) with + // its sleep. Every production caller passes none. + storedUrlDeps?: StoredUrlDownloadDeps & { + gapMs?: number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; + }; }; // When `reuseInfoJson` is true, the real download reuses the metadata the @@ -779,6 +813,30 @@ async function runManagedDownload( // (e.g. lbry -> odysee), which is the authoritative signal. let resolvedPlatform: Platform | null = opts.channelConfig.platform ?? detectPlatform(opts.videoUrl); + // ---------- The stored media URL (release 32 R7) ---------- + // Read BEFORE the prefetch rewrites metadata.info.json: a prefetch the + // platform refused writes nothing useful, and the stored URL is the record's. + const storedMode = resolveStoredUrlMode(opts.storedUrl, opts.channelConfig.storedUrlDownloads); + const storedDir = canonicalId ? path.join(channelDir, "data", canonicalId) : null; + const stored = + storedMode !== "never" && opts.channelConfig.handling === "transcribe" && storedDir + ? await storedMediaUrl(storedDir) + : null; + if (storedMode === "only" && canonicalId && storedDir) { + if (stored) { + return runStoredUrlDownload(opts, { + videoDir: storedDir, + videoId: canonicalId, + channelDir, + startedAt, + stored, + why: opts.storedUrlHeld ? "held" : "only", + attempts, + }); + } + return noStoredUrlOutcome(opts, storedDir, canonicalId, startedAt, attempts); + } + if (canonicalId && !opts.signal.aborted) { const videoDir = path.join(channelDir, "data", canonicalId); // In "always" mode the prefetch (like every other invocation) carries the @@ -890,6 +948,22 @@ async function runManagedDownload( classifyDownloadFailure(lastFullTail, lastPrefetch.availabilityClass) === "rate_limit" ) { + if (stored && storedMode === "fallback") { + opts.onLog( + `Metadata prefetch for ${canonicalId} was rate-limited by the source; ` + + `downloading from the stored media URL instead (the platform still backs off).\n`, + ); + return runStoredUrlDownload(opts, { + videoDir, + videoId: canonicalId, + channelDir, + startedAt, + stored, + why: "rate-limited", + attempts, + lastFullTail, + }); + } opts.onLog( `Metadata prefetch for ${canonicalId} was rate-limited by the source; ` + `not attempting the download (the platform backs off instead).\n`, @@ -1428,6 +1502,34 @@ async function runManagedDownload( } } + // A RATE-LIMITED DOWNLOAD FALLS BACK TO THE STORED URL (release 32 R7): the + // measured case — yt-dlp's own fetch of Odysee's original file answered 429 + // while the player's ranged reads of it answered 206. + if ( + !lastSucceeded && + stored && + storedMode === "fallback" && + canonicalId && + storedDir && + !opts.signal.aborted && + classifyDownloadFailure(lastFullTail, attempts.at(-1)?.availabilityClass) === "rate_limit" + ) { + opts.onLog( + `The download of ${canonicalId} was rate-limited by the source; ` + + `downloading from the stored media URL instead (the platform still backs off).\n`, + ); + return runStoredUrlDownload(opts, { + videoDir: storedDir, + videoId: canonicalId, + channelDir, + startedAt, + stored, + why: "rate-limited", + attempts, + lastFullTail, + }); + } + const videoDir = audioCheckVideoDir ?? path.join(channelDir, "data", canonicalId ?? "unknown"); @@ -1450,35 +1552,7 @@ async function runManagedDownload( // livestreams (unreliable durations), short videos, and unmeasurable files // (probe failure -> null -> no false positive). The file is left on disk; the // caller marks the download failed-short-audio so it isn't transcribed. - const probeShortAudio = async (): Promise< - NonNullable<DownloadOutcomeRecord["shortAudio"]> | null - > => { - const meta = await loadRawMetadataFromDir(videoDir); - const expected = meta?.duration; - if ( - !meta || - isLivestreamMetadata(meta) || - typeof expected !== "number" || - expected < INCOMPLETE_TRANSCRIPT_MIN_DURATION_SEC - ) { - return null; - } - const audioDurationSec = await probeMediaDurationSec({ - ffprobeBin: opts.paths.ffprobeBin, - file: path.join(videoDir, `audio.${fmt}`), - signal: opts.signal, - onLog: opts.onLog, - }); - if (!isShortAudio(audioDurationSec, expected, { isLivestream: false })) { - return null; - } - const a = audioDurationSec as number; - return { - audioDurationSec: Math.round(a * 10) / 10, - expectedDurationSec: expected, - coverage: Math.round((a / expected) * 1000) / 1000, - }; - }; + const probeShortAudio = () => probeShortAudioIn(opts, videoDir, fmt); // ---------- App-side extraction (transcribe handling) ---------- // After a successful non-audio-check transcribe download in app mode, produce @@ -1799,6 +1873,9 @@ async function writeOutcome( shortAudio?: DownloadOutcomeRecord["shortAudio"]; // The subtitle fetch alone answered 429 and the download went on. subsRateLimited?: boolean; + // A failure's class when the caller knows it better than the tail does + // (the stored-URL download: a 403 from the CDN is its rate limit). + failureClass?: DownloadFailureClass; }, ): Promise<DownloadOutcomeRecord> { const { status, attempts } = o; @@ -1810,7 +1887,7 @@ async function writeOutcome( // its caller defers the subtitles (release 17, slice RL). const isFailure = status === "failed" || status === "failed-corrupt-source"; const failureClass = isFailure - ? classifyDownloadFailure(o.lastFullTail, attempts.at(-1)?.availabilityClass) + ? (o.failureClass ?? classifyDownloadFailure(o.lastFullTail, attempts.at(-1)?.availabilityClass)) : o.subsRateLimited && status.startsWith("ok") ? ("subs_rate_limit" as const) : undefined; @@ -1868,3 +1945,274 @@ async function writeOutcome( return record; } + +// Download-time duration guard: probe the produced audio.<fmt> and compare its +// actual length to the metadata duration. A large shortfall means the source +// served a truncated stream (e.g. a CDN-truncated HLS rung) even though yt-dlp +// exited 0. Returns the shortfall metrics when tripped, else null. Skips +// livestreams (unreliable durations), short videos, and unmeasurable files +// (probe failure -> null -> no false positive). The file is left on disk; the +// caller marks the download failed-short-audio so it isn't transcribed. +async function probeShortAudioIn( + opts: ManagedDownloadOpts, + videoDir: string, + fmt: AudioFormat, +): Promise<NonNullable<DownloadOutcomeRecord["shortAudio"]> | null> { + const meta = await loadRawMetadataFromDir(videoDir); + const expected = meta?.duration; + if ( + !meta || + isLivestreamMetadata(meta) || + typeof expected !== "number" || + expected < INCOMPLETE_TRANSCRIPT_MIN_DURATION_SEC + ) { + return null; + } + const audioDurationSec = await probeMediaDurationSec({ + ffprobeBin: opts.paths.ffprobeBin, + file: path.join(videoDir, `audio.${fmt}`), + signal: opts.signal, + onLog: opts.onLog, + }); + if (!isShortAudio(audioDurationSec, expected, { isLivestream: false })) { + return null; + } + const a = audioDurationSec as number; + return { + audioDurationSec: Math.round(a * 10) / 10, + expectedDurationSec: expected, + coverage: Math.round((a / expected) * 1000) / 1000, + }; +} + +// ---------- The stored media URL's whole-file download (release 32 R7) ---------- + +// TEST-ONLY: E2E_STORED_URL_GAP_MS replaces the gap between two stored-URL +// files on a platform (the e2e server's own). +function storedUrlGapMs(override: number | undefined): number { + if (override !== undefined) return override; + const raw = Number(process.env.E2E_STORED_URL_GAP_MS); + return Number.isFinite(raw) && raw >= 0 && process.env.E2E_STORED_URL_GAP_MS !== undefined + ? raw + : STORED_URL_NEW_FILE_GAP_MS; +} + +// What a stored-URL download ended as, for the outcome record. +function storedUrlStatus( + r: StoredUrlDownloadResult, + audioCheck: boolean, +): { status: DownloadOutcomeStatus; failureClass?: DownloadFailureClass } { + switch (r.kind) { + case "ok": + return { status: audioCheck ? "ok-audio-checked" : "ok" }; + case "failed-corrupt-source": + return { status: "failed-corrupt-source", failureClass: "unknown" }; + case "corrupt-full-source": + return { status: "corrupt-full-source" }; + case "rate-limited": + return { status: "failed", failureClass: "rate_limit" }; + case "network": + return { status: "failed", failureClass: "network" }; + case "http-error": + return { + status: "failed", + failureClass: r.httpStatus !== undefined && r.httpStatus >= 500 ? "network" : "per_video", + }; + case "aborted": + case "extract-failed": + return { status: "failed", failureClass: "unknown" }; + } +} + +// The archive line the yt-dlp run would have printed (`%(extractor)s %(id)s`), +// read off the record's metadata. +async function storedArchiveLine(videoDir: string): Promise<string | null> { + try { + const info = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as Record< + string, + unknown + >; + const extractor = + typeof info.extractor === "string" + ? info.extractor + : typeof info.extractor_key === "string" + ? info.extractor_key.toLowerCase() + : null; + const id = typeof info.id === "string" ? info.id : null; + return extractor && id ? `${extractor} ${id}` : null; + } catch { + return null; + } +} + +async function runStoredUrlDownload( + opts: ManagedDownloadOpts, + ctx: { + videoDir: string; + videoId: string; + channelDir: string; + startedAt: string; + stored: StoredMediaUrl; + why: StoredUrlWhy; + attempts: DownloadAttempt[]; + lastFullTail?: string; + }, +): Promise<DownloadOutcomeRecord> { + const { stored, why, attempts, videoDir, videoId } = ctx; + const deps = opts.storedUrlDeps; + const key = storedUrlGapKey(stored.platform); + const gapMs = storedUrlGapMs(deps?.gapMs); + const fmt: AudioFormat = opts.audioFormatOverride ?? opts.channelConfig.audioFormat ?? "mp3"; + // Keyed on the PAGE url, as every download path's check is. + const audioCheck = audioCheckApplies(opts.channelConfig, opts.videoUrl); + opts.onLog( + `Downloading ${videoId} from the stored media URL (${stored.host}) ` + + `${storedUrlWhyText(why, stored.platform)}.\n`, + ); + const attemptBase = { + n: 1, + kind: "stored-url-ranged" as const, + handling: opts.channelConfig.handling, + usedCookies: false, + }; + // ONE NEW FILE PER PLATFORM PER REST: the gap since the last stored-URL + // download on this platform, waited out here, so a batch waits rather than + // 429s. Set again when this one ends. + try { + await waitForPlatformGap({ + label: `A download from the stored media URL (${stored.platform})`, + remainingMs: () => platformGapRemainingMs(key), + signal: opts.signal, + onLog: (line) => opts.onLog(`${line}\n`), + ...(deps?.sleep ? { sleep: deps.sleep } : {}), + }); + } catch { + attempts.push({ + ...attemptBase, + ytdlpExitCode: 1, + error: "cancelled while waiting for the gap between stored-URL files", + storedUrl: { host: stored.host, why, bytes: 0 }, + }); + return writeOutcome(opts, videoDir, { + videoId, + status: "failed", + startedAt: ctx.startedAt, + attempts, + lastFullTail: "", + failureClass: "unknown", + }); + } + notePlatformGap(key, gapMs); + let r: StoredUrlDownloadResult; + try { + r = await storedUrlDownload({ + paths: opts.paths, + videoDir, + stored, + channelConfig: opts.channelConfig, + audioFormat: fmt, + audioCheck, + onLog: opts.onLog, + signal: opts.signal, + ...(deps ? { deps } : {}), + }); + } finally { + notePlatformGap(key, gapMs); + } + if (gapMs > 0) { + opts.onLog( + `The next download from ${stored.platform}'s stored media URLs waits ${Math.round(gapMs / 60_000)} min ` + + `(one new file per rest).\n`, + ); + } + const ok = r.kind === "ok"; + attempts.push({ + ...attemptBase, + ytdlpExitCode: ok ? 0 : 1, + ...(r.error ? { error: r.error } : {}), + ...(audioCheck + ? { + audioCheck: { + checkpoints: r.checkpoints.length, + rollbacks: r.rollbacks, + restarts: r.restarts, + ...(r.finalProbeVerdict ? { finalProbeVerdict: r.finalProbeVerdict } : {}), + }, + } + : {}), + storedUrl: { + host: stored.host, + why, + bytes: r.bytes, + ...(r.totalBytes !== null ? { totalBytes: r.totalBytes } : {}), + ...(r.resumedFrom > 0 ? { resumedFrom: r.resumedFrom } : {}), + ...(r.httpStatus !== undefined ? { httpStatus: r.httpStatus } : {}), + }, + }); + let { status, failureClass } = storedUrlStatus(r, audioCheck); + let shortAudio: DownloadOutcomeRecord["shortAudio"]; + if (ok && !opts.signal.aborted) { + const short = await probeShortAudioIn(opts, videoDir, fmt); + if (short) { + shortAudio = short; + status = "failed-short-audio"; + failureClass = undefined; + opts.onLog( + `Short audio for ${videoId}: ${short.audioDurationSec}s of ${short.expectedDurationSec}s ` + + `(${Math.round(short.coverage * 100)}% of the video). Keeping the file and flagging it.\n`, + ); + } + } + if (status.startsWith("ok") && opts.appendArchive !== false) { + const line = await storedArchiveLine(videoDir); + if (line) { + try { + await appendArchiveLine(ctx.channelDir, line); + } catch (err) { + opts.onLog(`Archive append failed (${line}): ${(err as Error).message}\n`); + } + } + } + return writeOutcome(opts, videoDir, { + videoId, + status, + startedAt: ctx.startedAt, + attempts, + lastFullTail: r.error ?? ctx.lastFullTail ?? "", + shortAudio, + ...(failureClass ? { failureClass } : {}), + }); +} + +// `only`, and the record stores no media URL the allowlist trusts (or the +// channel is not transcribe handling): nothing is asked of anyone. A per-video +// failure, so a batch goes on to the next video. +async function noStoredUrlOutcome( + opts: ManagedDownloadOpts, + videoDir: string, + videoId: string, + startedAt: string, + attempts: DownloadAttempt[], +): Promise<DownloadOutcomeRecord> { + const why = + opts.channelConfig.handling !== "transcribe" + ? "a stored-URL download is for transcribe handling" + : "the record stores no media URL on its platform's CDN"; + opts.onLog(`No download for ${videoId} (stored URL only): ${why}. Nothing was requested.\n`); + attempts.push({ + n: 1, + kind: "stored-url-ranged", + handling: opts.channelConfig.handling, + usedCookies: false, + ytdlpExitCode: 1, + error: `stored URL only: ${why}`, + }); + return writeOutcome(opts, videoDir, { + videoId, + status: "failed", + startedAt, + attempts, + lastFullTail: "", + failureClass: "per_video", + }); +} diff --git a/common/ytdlp/managedDownloadsSleep.test.ts b/common/ytdlp/managedDownloadsSleep.test.ts @@ -304,3 +304,59 @@ test("a subtitle 429 on a success is recorded as a subtitle deferral, and the ba assert.deepEqual(r.deferred, ["c/s1"]); assert.deepEqual(r.slept, [30_000]); }); + +// Release 32 R7: a download from the stored media URL. After a rate-limited +// page lookup, its success still backs the platform off; a run of `only` +// downloads asked the platform nothing and does not settle it clean. +const STORED = (why: "rate-limited" | "only"): DownloadAttempt => ({ + n: 1, + kind: "stored-url-ranged", + handling: "transcribe", + usedCookies: false, + ytdlpExitCode: 0, + storedUrl: { host: "player.odycdn.com", why, bytes: 10 }, +}); + +async function storedRun(outcomes: DownloadOutcomeRecord[]): Promise<{ backoffs: string[]; cleans: number }> { + const backoffs: string[] = []; + let cleans = 0; + let i = 0; + const channelConfig = { handling: "transcribe", url: "https://odysee.com/@c:1" } as never; + const requestCounter = { n: 0 }; + await runManagedDownloads( + { + channelSlug: "c", + mode: "download-missing" as never, + channelConfig, + paths: getPaths(), + onLog: () => {}, + signal: new AbortController().signal, + abortOnError: false, + requestCounter, + onPlatformBackoff: (c) => { + backoffs.push(c); + }, + }, + outcomes.map((_, n) => `https://odysee.com/s:${String(n).padStart(40, "0")}`), + channelConfig, + undefined, + { downloadOne: async () => outcomes[i++], sleep: async () => {} }, + ); + // runYtdlpMode settles clean only when requests were made and nothing backed off. + if (requestCounter.n > 0 && backoffs.length === 0) cleans++; + return { backoffs, cleans }; +} + +test("stored URL after a rate-limited lookup: the success backs the platform off", async () => { + const r = await storedRun([ + outcome("ok-audio-checked", [{ ...PREFETCH, handling: "transcribe", ytdlpExitCode: 1 }, STORED("rate-limited")]), + ]); + assert.deepEqual(r.backoffs, ["rate_limit"]); + assert.equal(r.cleans, 0); +}); + +test("stored URL only: the platform was not asked — no backoff and no clean settle", async () => { + const r = await storedRun([outcome("ok-audio-checked", [STORED("only")]), outcome("ok", [STORED("only")])]); + assert.deepEqual(r.backoffs, []); + assert.equal(r.cleans, 0, "a run that asked the platform nothing is not a clean probe"); +}); diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -33,8 +33,11 @@ import { } from "../lib/availability"; import { DOWNLOAD_OUTCOME_FILENAME, + askedPlatform, + storedUrlAttemptOf, type DownloadOutcomeRecord, } from "../lib/downloadOutcome"; +import type { StoredUrlMode } from "../lib/storedMediaUrl"; import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; import { alwaysCookies, @@ -191,6 +194,11 @@ export type RunYtdlpOpts = { // backoff and any hold clear; release 17 review H2). Returns a line for the // log, or null. onPlatformClean?: () => Promise<string | null>; + // Release 32 R7: the stored-media-URL mode for every managed download in + // the run (downloadOneManaged's `storedUrl`; absent = the channel's), and + // whether the door let a held platform through as `only`. + storedUrl?: StoredUrlMode; + storedUrlHeld?: boolean; // Internal: how many requests this run made of the source (a listing, a // per-video download, a raw spawn). Set by runYtdlpMode and shared through // every `{...opts}` copy by reference; a run that asked nothing is not clean @@ -1175,6 +1183,8 @@ export async function runManagedDownloads( extractImmediately: opts.extractImmediately, audioFormatOverride: opts.audioFormatOverride, downloadFormatPreset, + ...(opts.storedUrl ? { storedUrl: opts.storedUrl } : {}), + ...(opts.storedUrlHeld ? { storedUrlHeld: true } : {}), onFilterRejected: (id, entry) => { filterRejections[id] = entry; }, @@ -1192,6 +1202,20 @@ export async function runManagedDownloads( /* shared-state write is best-effort */ } } + // A DOWNLOAD FROM THE STORED MEDIA URL (release 32 R7). Its CDN answered, + // not the platform: a success after the page lookup was rate-limited + // still backs the platform off, and a download that asked the + // platform nothing (`only`, a held platform) is not a request of it — + // a run of those must not settle the platform clean. + const storedAttempt = storedUrlAttemptOf(outcome); + if (storedAttempt?.why === "rate-limited" && outcome.status.startsWith("ok")) { + try { + await opts.onPlatformBackoff?.("rate_limit"); + } catch { + /* shared-state write is best-effort */ + } + } + if (opts.requestCounter && !askedPlatform(outcome)) opts.requestCounter.n--; if (outcome.status === "skipped-filtered") { skippedCount++; } else if (outcome.status === "chat-only") { diff --git a/common/ytdlp/storedUrlManaged.test.ts b/common/ytdlp/storedUrlManaged.test.ts @@ -0,0 +1,284 @@ +// downloadOneManaged with a stored media URL (release 32 R7): `only`, +// `fallback` after a rate-limited prefetch or download, no stored URL, the gap +// between two files, a mid-file 429, and the corrupt-full-source refetch. A +// fake yt-dlp (a shell script) and a fake CDN on loopback; real ffmpeg for the +// probes and extraction (skipped without it). No real network. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs"; +import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { askedPlatform, storedUrlAttemptOf } from "../lib/downloadOutcome"; +import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap"; +import { storedUrlGapKey } from "../lib/storedMediaUrl"; +import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged"; + +const FF = hasFfmpeg(); +const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; +const FILE_PATH = `/v6/streams/${CLAIM}/a1b2c3.mp4`; +const PAGE = `https://odysee.com/synthetic-stream:${CLAIM}`; +const FAST = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 }; + +type Fixture = { + root: string; + channelsDir: string; + channelDir: string; + videoDir: string; + ytdlpLog: string; + paths: Paths; + cdn: FakeRangedCdn; + clean: Buffer; +}; + +// A fake yt-dlp: logs its argv; `prefetch` / `download` say how each pass ends. +async function fixture(opts: { + prefetch?: "ok" | "429"; + download?: "ok" | "429"; + formats?: unknown[]; + cdn?: Parameters<typeof startFakeRangedCdn>[0]; +} = {}): Promise<Fixture> { + const root = await mkdtemp(path.join(os.tmpdir(), "stored-managed-")); + const channelsDir = path.join(root, "channels"); + const channelDir = path.join(channelsDir, "c"); + const videoDir = path.join(channelDir, "data", CLAIM); + await mkdir(videoDir, { recursive: true }); + const clean = FF ? await readFile(makeToneFile(path.join(root, "src.mp4"), { duration: 60, faststart: true })) : Buffer.alloc(1); + const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, ...(opts.cdn ?? {}) }); + await writeFile( + path.join(videoDir, "metadata.info.json"), + JSON.stringify({ + id: CLAIM, + extractor: "lbry", + extractor_key: "LBRY", + title: "A synthetic stream", + webpage_url: PAGE, + duration: 60, + formats: opts.formats ?? [{ url: cdn.url(FILE_PATH), protocol: "https", ext: "mp4" }], + }), + ); + const ytdlpLog = path.join(root, "ytdlp.log"); + const bin = path.join(root, "fake-ytdlp.sh"); + const line429 = `echo "WARNING: [lbry] ${CLAIM}: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; echo "ERROR: [lbry] ${CLAIM}: No video formats found!" >&2; exit 1`; + await writeFile( + bin, + `#!/bin/sh\necho "$@" >> ${JSON.stringify(ytdlpLog)}\n` + + `case "$*" in *--skip-download*) ${opts.prefetch === "429" ? line429 : "exit 0"} ;; esac\n` + + `${opts.download === "429" ? line429 : "exit 0"}\n`, + ); + await chmod(bin, 0o755); + const paths = { channelsDir, ytdlpBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; + return { root, channelsDir, channelDir, videoDir, ytdlpLog, paths, cdn, clean }; +} + +async function ytdlpCalls(f: Fixture): Promise<string[]> { + return (await readFile(f.ytdlpLog, "utf8").catch(() => "")).split("\n").filter(Boolean); +} + +function run(f: Fixture, over: Partial<ManagedDownloadOpts> = {}, log: { s: string } = { s: "" }) { + return downloadOneManaged({ + channelSlug: "c", + channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth:1", audioFormat: "mp3" } as ChannelConfig, + paths: f.paths, + videoUrl: PAGE, + onLog: (s) => (log.s += s), + signal: new AbortController().signal, + storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0 }, + ...over, + }); +} + +async function done(f: Fixture) { + clearPlatformGaps(); + await f.cdn.close(); + await rm(f.root, { recursive: true, force: true }); +} + +async function readOutcome(dir: string): Promise<DownloadOutcomeRecord> { + return JSON.parse(await readFile(path.join(dir, "download-outcome.json"), "utf8")); +} + +test("only: the whole file from the stored URL — no yt-dlp, the audio check, the archive line, the sidecar", { skip: !FF }, async () => { + const f = await fixture(); + try { + const log = { s: "" }; + const record = await run(f, { storedUrl: "only" }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.deepEqual(await ytdlpCalls(f), [], "yt-dlp was never run"); + assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"]); + const st = storedUrlAttemptOf(record); + assert.equal(st?.why, "only"); + assert.equal(st?.host, "player.odycdn.com"); + assert.equal(st?.bytes, f.clean.length); + assert.equal(record.attempts[0].audioCheck?.finalProbeVerdict, "clean"); + assert.equal(askedPlatform(record), false); + assert.match(log.s, /from the stored media URL \(player\.odycdn\.com\) \(asked: only\)/); + assert.equal((await readOutcome(f.videoDir)).status, "ok-audio-checked"); + assert.equal(await readFile(path.join(f.channelDir, "archive"), "utf8"), `lbry ${CLAIM}\n`); + const entries = await readdir(f.videoDir); + assert.ok(entries.includes("audio.mp3")); + assert.ok(!entries.includes("audio.mp4"), "the container is not kept"); + } finally { + await done(f); + } +}); + +test("the channel's storedUrlDownloads is the default; a request's storedUrl overrides it", { skip: !FF }, async () => { + const f = await fixture(); + try { + const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "only" } as ChannelConfig; + const a = await run(f, { channelConfig: cfg }); + assert.equal(storedUrlAttemptOf(a)?.why, "only"); + assert.deepEqual(await ytdlpCalls(f), []); + const b = await run(f, { channelConfig: cfg, storedUrl: "never" }); + assert.ok((await ytdlpCalls(f)).length > 0, "never: the page, as always"); + assert.equal(storedUrlAttemptOf(b), null); + } finally { + await done(f); + } +}); + +test("fallback: a rate-limited prefetch goes to the stored URL; the record says why", { skip: !FF }, async () => { + const f = await fixture({ prefetch: "429" }); + try { + const log = { s: "" }; + const record = await run(f, { storedUrl: "fallback" }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.deepEqual(record.attempts.map((a) => a.kind), ["metadata-prefetch", "stored-url-ranged"]); + assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited"); + assert.equal(askedPlatform(record), true); + assert.equal((await ytdlpCalls(f)).length, 1, "only the prefetch asked the platform"); + assert.match(log.s, /odysee lookup rate-limited/); + // The metadata the prefetch could not refresh is the one the URL came from. + const info = JSON.parse(await readFile(path.join(f.videoDir, "metadata.info.json"), "utf8")); + assert.equal(info.id, CLAIM); + } finally { + await done(f); + } +}); + +test("fallback: a download yt-dlp got 429 on goes to the stored URL (the audio check off: it stays off)", { skip: !FF }, async () => { + const f = await fixture({ download: "429" }); + try { + const cfg = { + handling: "transcribe", + url: "https://odysee.com/@synth:1", + audioCheck: { enabled: false }, + } as ChannelConfig; + const record = await run(f, { channelConfig: cfg, storedUrl: "fallback" }); + assert.equal(record.status, "ok"); + assert.deepEqual(record.attempts.map((a) => a.kind), ["metadata-prefetch", "primary", "stored-url-ranged"]); + assert.equal(record.attempts.at(-1)?.audioCheck, undefined); + assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited"); + } finally { + await done(f); + } +}); + +test("fallback with no rate limit: the page download stands, the stored URL is never read", async () => { + const f = await fixture(); + try { + const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", audioCheck: { enabled: false } } as ChannelConfig; + const record = await run(f, { channelConfig: cfg, storedUrl: "fallback" }); + assert.equal(storedUrlAttemptOf(record), null); + assert.equal(f.cdn.requests.length, 0); + } finally { + await done(f); + } +}); + +test("only, and the record stores no trusted media URL: a per-video failure, nothing asked", async () => { + const f = await fixture({ + formats: [ + { url: "https://player.odycdn.com/a.mp4", protocol: "https" }, + { url: "https://player.odycdn.com/b.mp4", protocol: "https" }, + ], + }); + try { + const log = { s: "" }; + const record = await run(f, { storedUrl: "only" }, log); + assert.equal(record.status, "failed"); + assert.equal(record.failureClass, "per_video"); + assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"]); + assert.equal(askedPlatform(record), false); + assert.deepEqual(await ytdlpCalls(f), []); + assert.equal(f.cdn.requests.length, 0); + assert.match(log.s, /Nothing was requested/); + } finally { + await done(f); + } +}); + +test("a 429 from the CDN mid-file: failed, rate_limit, the partial kept for the next run", { skip: !FF }, async () => { + const f = await fixture({ cdn: { refuseAfterBytes: 40 * 1024 } }); + try { + const record = await run(f, { storedUrl: "only" }); + assert.equal(record.status, "failed"); + assert.equal(record.failureClass, "rate_limit"); + assert.equal(storedUrlAttemptOf(record)?.httpStatus, 429); + const entries = await readdir(f.videoDir); + assert.ok(entries.includes("audio.mp4.stored.part")); + // After the rest, the next run resumes and finishes. + f.cdn.allowAgain(); + const again = await run(f, { storedUrl: "only" }); + assert.equal(again.status, "ok-audio-checked"); + assert.ok((storedUrlAttemptOf(again)?.resumedFrom ?? 0) > 0); + } finally { + await done(f); + } +}); + +test("one new file per rest: the second stored-URL download on a platform waits out the gap", { skip: !FF }, async () => { + const f = await fixture(); + try { + const waits: number[] = []; + const sleep = async (ms: number) => { + waits.push(ms); + clearPlatformGaps(); + }; + const deps = { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 60_000, sleep }; + const log = { s: "" }; + await run(f, { storedUrl: "only", storedUrlDeps: deps }, log); + assert.deepEqual(waits, [], "the first asks no gap"); + assert.ok(platformGapRemainingMs(storedUrlGapKey("odysee")) > 55_000, "the gap is set when it ends"); + await run(f, { storedUrl: "only", storedUrlDeps: deps }, log); + assert.equal(waits.length, 1); + assert.ok(waits[0] > 55_000 && waits[0] <= 60_000); + assert.match(log.s, /A download from the stored media URL \(odysee\) asks for a gap between videos: waiting \d+s/); + } finally { + await done(f); + } +}); + +test("a corrupt full source refetched from the stored URL: clean, the kept file goes, the history says so", { skip: !FF }, async () => { + const f = await fixture(); + try { + await writeFile(path.join(f.videoDir, "audio.mp4"), "OLD-MALFORMED"); + const previous: DownloadOutcomeRecord = { + videoId: CLAIM, + webpageUrl: PAGE, + status: "corrupt-full-source", + startedAt: "2026-10-15T00:00:00.000Z", + finishedAt: "2026-10-15T01:00:00.000Z", + attempts: [{ n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }], + }; + await writeFile(path.join(f.videoDir, "download-outcome.json"), JSON.stringify(previous)); + const record = await run(f, { + storedUrl: "only", + corruptRefetchDeps: { measure: async () => null }, + }); + assert.equal(record.status, "ok-audio-checked"); + const disk = await readOutcome(f.videoDir); + assert.equal(disk.corruptRefetches?.at(-1)?.result, "clean"); + const entries = await readdir(f.videoDir); + assert.ok(entries.includes("audio.mp3")); + assert.ok(!entries.some((e) => e.endsWith(".corrupt-kept")), "the kept file is gone"); + } finally { + await done(f); + } +});