commit ef2ea5d10d2a3ec0a342627ac3a771b784ee994e
parent f57df351ce3e5fb3f9707ef5fb3d9c1823691fe7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 17 Oct 2026 03:31:01 -0400
common: a stored-URL download survives a dropped connection — a continuation of the same file, not a new one
Within one run, a mid-file network failure (the fetch throwing, the body cut
short, a 2xx with no bytes) and a 429/403 that follows bytes served since the
last page open bring the next probe forward, save the resume state, pause
STORED_URL_DROP_PAUSE_MS (45 s), reopen the player's page and read on from the
last clean byte — at most STORED_URL_MAX_DROPS (6) continuations since the last
progress, then the partial is kept as before. A 429 straight after an open still
gives up at once. No new-file rest between continuations; one attempt on the
record. The attempt records `continuations`. The fake CDN cuts connections
(dropAfterBytes / drops / dropGapBytes) and can lock again; README row.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 504 insertions(+), 32 deletions(-)
diff --git a/common/lib/downloadOutcome.ts b/common/lib/downloadOutcome.ts
@@ -126,6 +126,9 @@ export type StoredUrlAttempt = {
// How many times the player's page was opened first (Odysee's CDN serves a
// file only after a player opened its page; ytdlp/storedUrlPageOpen.ts).
pageOpens?: number;
+ // How many times the read went on after a dropped connection (or a refusal
+ // that followed served bytes) within this one attempt (release 32 R10).
+ continuations?: number;
};
// ONE RETRY OF A corrupt-full-source VIDEO (release 30, lane Q), appended to
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -24,6 +24,7 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. |
| `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. |
| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. |
+| `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. |
| `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. |
| `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. |
| `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). |
diff --git a/common/testing/web/fakeRangedCdn.d.mts b/common/testing/web/fakeRangedCdn.d.mts
@@ -8,6 +8,8 @@ export type FakeCdnRequest = {
ua: string | null;
status: number;
bytes: number;
+ // The connection was cut while (or before) this request was answered.
+ dropped: boolean;
at: number;
};
@@ -19,6 +21,7 @@ export type FakeRangedCdn = {
refuseAfterBytes(n: number): void;
unlocks: number;
unlock(): void;
+ lock(): void;
allowAgain(): void;
close(): Promise<void>;
};
@@ -32,4 +35,7 @@ export function startFakeRangedCdn(opts?: {
allowUnranged?: boolean;
requireUnlock?: boolean;
unlockBytes?: number;
+ dropAfterBytes?: number;
+ drops?: number;
+ dropGapBytes?: number;
}): Promise<FakeRangedCdn>;
diff --git a/common/testing/web/fakeRangedCdn.mjs b/common/testing/web/fakeRangedCdn.mjs
@@ -25,7 +25,17 @@
// - opts.ignoreRange: answer every GET 200 with the whole file.
// - opts.requireUnlock (2026-10-17's finding): every read answers 429 until
// `cdn.unlock()` — what a player opening the video's page does — and, with
-// opts.unlockBytes, the unlock lapses after that many bytes are served.
+// opts.unlockBytes, the unlock lapses after that many bytes are served;
+// `cdn.lock()` takes it back at once.
+// - opts.dropAfterBytes / opts.drops / opts.dropGapBytes (release 32 R10,
+// 2026-10-17's `fetch failed` mid-file): once that many bytes have been
+// served in all, the connection is CUT — mid-body (the 206 headers and part
+// of the body sent, then the socket destroyed: undici's body read throws
+// "terminated"), or before any response when the cut falls on a request's
+// first byte (the fetch throws "fetch failed"). `drops` cuts in all
+// (default 1, Infinity allowed), `dropGapBytes` bytes served between two
+// cuts (default dropAfterBytes; 0 = every later request is cut before its
+// first byte). A cut request is recorded `dropped: true` with the bytes it sent.
import http from "node:http";
@@ -38,6 +48,9 @@ export async function startFakeRangedCdn(opts = {}) {
const refuseStatus = opts.refuseStatus ?? 429;
const corrupt = opts.corruptOnce ? { ...opts.corruptOnce, used: false } : null;
let unlockedBudget = opts.requireUnlock ? 0 : null;
+ let dropsLeft = typeof opts.dropAfterBytes === "number" ? (opts.drops ?? 1) : 0;
+ let dropBudget = typeof opts.dropAfterBytes === "number" ? opts.dropAfterBytes : 0;
+ const dropGap = typeof opts.dropGapBytes === "number" ? opts.dropGapBytes : (opts.dropAfterBytes ?? 0);
const server = http.createServer((req, res) => {
const u = new URL(req.url ?? "/", "http://x");
@@ -50,6 +63,7 @@ export async function startFakeRangedCdn(opts = {}) {
ua: req.headers["user-agent"] ?? null,
status: 0,
bytes: 0,
+ dropped: false,
at: Date.now(),
};
requests.push(rec);
@@ -78,11 +92,35 @@ export async function startFakeRangedCdn(opts = {}) {
corrupt.used = true;
body = Buffer.from(corrupt.buf.subarray(from, last + 1));
}
- if (refuseBudget !== null) refuseBudget -= body.length;
- if (unlockedBudget !== null && unlockedBudget !== Infinity) unlockedBudget -= body.length;
- rec.bytes = body.length;
+ // The cut, if one falls inside this body.
+ let cutAt = -1;
+ if (dropsLeft > 0 && body.length > dropBudget) {
+ cutAt = dropBudget;
+ dropsLeft--;
+ dropBudget = dropGap;
+ } else if (dropsLeft > 0) {
+ dropBudget -= body.length;
+ }
+ const sent = cutAt >= 0 ? cutAt : body.length;
+ if (refuseBudget !== null) refuseBudget -= sent;
+ if (unlockedBudget !== null && unlockedBudget !== Infinity) unlockedBudget -= sent;
+ rec.bytes = sent;
const h = { "content-type": "video/mp4", "accept-ranges": "bytes", "content-length": String(body.length), ...headers };
if (status === 206) h["content-range"] = `bytes ${from}-${from + body.length - 1}/${total}`;
+ if (cutAt === 0) {
+ rec.dropped = true;
+ req.socket.destroy();
+ return;
+ }
+ if (cutAt > 0) {
+ rec.dropped = true;
+ rec.status = status;
+ res.writeHead(status, h);
+ res.write(body.subarray(0, cutAt), () => {
+ setTimeout(() => req.socket.destroy(), 20);
+ });
+ return;
+ }
end(status, h, body);
};
if (opts.ignoreRange) return serve(200, 0, total - 1, {});
@@ -112,6 +150,9 @@ export async function startFakeRangedCdn(opts = {}) {
this.unlocks++;
unlockedBudget = typeof opts.unlockBytes === "number" ? opts.unlockBytes : Infinity;
},
+ lock: () => {
+ unlockedBudget = 0;
+ },
allowAgain: () => {
refuseBudget = null;
},
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -2157,7 +2157,8 @@ async function runStoredUrlDownload(
channelConfig: opts.channelConfig,
audioFormat: fmt,
audioCheck,
- // Opened before the first read, and again on a mid-file refusal.
+ // Opened before the first read, and again on a mid-file refusal or a
+ // dropped connection (a continuation of this file: no rest between).
pageUrl: opts.videoUrl,
openPage:
deps?.openPage !== undefined
@@ -2201,6 +2202,7 @@ async function runStoredUrlDownload(
...(r.resumedFrom > 0 ? { resumedFrom: r.resumedFrom } : {}),
...(r.httpStatus !== undefined ? { httpStatus: r.httpStatus } : {}),
...(r.pageOpens > 0 ? { pageOpens: r.pageOpens } : {}),
+ ...(r.continuations > 0 ? { continuations: r.continuations } : {}),
},
});
let { status, failureClass } = storedUrlStatus(r, audioCheck);
diff --git a/common/ytdlp/storedUrlDownload.test.ts b/common/ytdlp/storedUrlDownload.test.ts
@@ -13,7 +13,7 @@ import { startFakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs";
import type { ChannelConfig } from "../lib/channelConfig";
import type { Paths } from "../lib/paths";
import { storedMediaUrlFromInfo, STORED_MEDIA_USER_AGENT } from "../lib/storedMediaUrl";
-import { storedContainerExt, storedPartNames, storedUrlDownload } from "./storedUrlDownload";
+import { STORED_URL_DROP_PAUSE_MS, STORED_URL_MAX_DROPS, storedContainerExt, storedPartNames, storedUrlDownload } from "./storedUrlDownload";
const FF = hasFfmpeg();
const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567";
@@ -451,11 +451,14 @@ test("an unlock that lapses mid-file: the page is opened again and the read goes
openPage: fakeOpener(cdn, calls),
onLog: (s) => (log += s),
signal: new AbortController().signal,
- deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK },
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK, dropPauseMs: 0 },
});
assert.equal(r.kind, "ok", log);
assert.ok(r.pageOpens >= 3, `opened ${r.pageOpens}×`);
- assert.match(log, /HTTP Error 429 at \d+ bytes after \d+ served since the page was opened; opening it again/);
+ // Each lapse made progress: the count never climbs past 1 (release 32 R10).
+ assert.equal(r.continuations, r.pageOpens - 1);
+ assert.doesNotMatch(log, /\(2 of \d+\)/);
+ assert.match(log, /HTTP Error 429 at \d+ bytes after \d+ served since the page was opened — opening it again and resuming \(1 of 6\)/);
assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean);
} finally {
await cdn.close();
@@ -492,3 +495,223 @@ test("an open that does not unlock: one open, then rate-limited — no loop of o
await rm(root, { recursive: true, force: true });
}
});
+
+// RELEASE 32 R10 — A DROPPED CONNECTION IS THE SAME FILE (2026-10-17: a
+// 3.3 GB file's ranged reads ended `fetch failed` at 344 MB, then again 100 MB
+// into the resume). The fake CDN cuts the socket mid-body or before any
+// response; the injected opener stands for the page; the pause is a recorded
+// fake. No browser, no real network.
+
+const M4A_PATH = `/v6/streams/${CLAIM}/d4e5f6.m4a`;
+
+test("the constants: a 45 s pause, 6 continuations without progress", () => {
+ assert.equal(STORED_URL_DROP_PAUSE_MS, 45_000);
+ assert.equal(STORED_URL_MAX_DROPS, 6);
+});
+
+test("dropped mid-body three times: the same run pauses, reopens the page, resumes from the last clean byte, finishes", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean } = await recording(root);
+ const cut = Math.floor(clean.length / 5);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, requireUnlock: true, dropAfterBytes: cut, drops: 3 });
+ const calls: string[] = [];
+ const pauses: number[] = [];
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: { ...config, keepSourceVideo: true },
+ audioFormat: "mp3",
+ audioCheck: true,
+ pageUrl: PAGE,
+ openPage: fakeOpener(cdn, calls),
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ // Large reads, so each cut lands inside a body; at most 2 in a row
+ // without progress — fewer than the drops, which each made progress.
+ deps: {
+ fetch: cdn.fetch,
+ chunkBytes: 64 * 1024,
+ knobs: EVERY_CHUNK,
+ dropPauseMs: 1234,
+ maxDrops: 2,
+ sleep: async (ms) => {
+ pauses.push(ms);
+ },
+ },
+ });
+ assert.equal(r.kind, "ok", log);
+ assert.equal(cdn.requests.filter((q) => q.dropped).length, 3, "the CDN cut three reads");
+ assert.equal(r.continuations, 3);
+ assert.equal(r.pageOpens, 4, "the first open, then one per continuation");
+ assert.deepEqual(pauses, [1234, 1234, 1234], "one pause per continuation, nothing else waited");
+ assert.equal((log.match(/Connection dropped at \d+ bytes — reopening the page and resuming \(1 of 2\)/g) ?? []).length, 3, log);
+ assert.doesNotMatch(log, /\(2 of 2\)/, "each drop made progress: the count starts again");
+ // Each read after a cut asks from where the partial stood once judged —
+ // the probe brought forward found the bytes clean, so nothing re-read.
+ let expect = 0;
+ for (const q of cdn.requests) {
+ assert.match(q.range ?? "", new RegExp(`^bytes=${expect}-`), JSON.stringify(cdn.requests));
+ expect += q.bytes;
+ }
+ assert.match(log, /resuming from \d+ bytes \(the last probed-clean byte\)/);
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean, "byte-identical to the source");
+ assert.deepEqual((await readdir(videoDir)).sort(), ["audio.mp3", "audio.mp4"], "no scratch left");
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("audio check off: a cut before any response (the fetch throws) and one mid-body, both resumed at the exact byte", async () => {
+ const { root, videoDir } = await setup();
+ const buf = Buffer.alloc(96 * 1024);
+ for (let i = 0; i < buf.length; i++) buf[i] = (i * 7) % 251;
+ // The first cut falls on a request's first byte (24 KiB = three 8 KiB
+ // reads): the fetch throws. The next, 20 KiB later, inside a body.
+ const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, dropAfterBytes: 24 * 1024, drops: 2, dropGapBytes: 20 * 1024 });
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(M4A_PATH)),
+ channelConfig: { ...config, keepSourceVideo: true },
+ audioFormat: "m4a",
+ audioCheck: false,
+ pageUrl: PAGE,
+ openPage: null,
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, dropPauseMs: 0 },
+ });
+ assert.equal(r.kind, "ok", log);
+ assert.equal(r.continuations, 2);
+ assert.equal(r.pageOpens, 0, "no opener: nothing opened");
+ assert.match(log, /Connection dropped at 24576 bytes — resuming \(1 of 6\): the ranged read at 24576 failed: fetch failed/);
+ assert.match(log, /Connection dropped at 45056 bytes — resuming \(1 of 6\): the read at 40960 ended early at 45056/);
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.m4a")), buf);
+ assert.deepEqual(await readdir(videoDir), ["audio.m4a"]);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("drops with no progress: after the limit the run gives up as network, the partial and its state kept", async () => {
+ const { root, videoDir } = await setup();
+ const buf = Buffer.alloc(96 * 1024, 5);
+ // 20 KiB come down, then every request is cut before its first byte.
+ const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, dropAfterBytes: 20 * 1024, drops: Infinity, dropGapBytes: 0 });
+ const opens: number[] = [];
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(M4A_PATH)),
+ channelConfig: config,
+ audioFormat: "m4a",
+ audioCheck: false,
+ pageUrl: PAGE,
+ openPage: async () => {
+ opens.push(1);
+ return { ok: true, mediaStatuses: [206] };
+ },
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, dropPauseMs: 0 },
+ });
+ assert.equal(r.kind, "network", log);
+ assert.equal(r.bytes, 20 * 1024);
+ // The first drop followed progress (1 of 6); five more made none (2…6);
+ // the seventh gives up.
+ assert.equal(r.continuations, STORED_URL_MAX_DROPS);
+ assert.equal(r.pageOpens, 1 + STORED_URL_MAX_DROPS);
+ assert.equal(cdn.requests.filter((q) => q.dropped).length, STORED_URL_MAX_DROPS + 1);
+ assert.match(log, /\(6 of 6\)/);
+ assert.match(log, /6 continuations since the last progress; giving up with the partial kept at 20480 bytes/);
+ assert.match(r.error ?? "", /fetch failed/);
+ const state = JSON.parse(await readFile(path.join(videoDir, "audio.m4a.stored.part.json"), "utf8"));
+ assert.equal(state.goodBytes, 20 * 1024, "the next run resumes there");
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a 429 straight after the reopen that followed a drop gives up at once (rate-limited, no second open)", async () => {
+ const { root, videoDir } = await setup();
+ const buf = Buffer.alloc(96 * 1024, 9);
+ const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, requireUnlock: true, dropAfterBytes: 20 * 1024 });
+ let opens = 0;
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(M4A_PATH)),
+ channelConfig: config,
+ audioFormat: "m4a",
+ audioCheck: false,
+ pageUrl: PAGE,
+ // The first open unlocks; the reopen after the drop does not.
+ openPage: async () => {
+ opens++;
+ if (opens === 1) cdn.unlock();
+ else cdn.lock();
+ return { ok: opens === 1, mediaStatuses: [opens === 1 ? 206 : 429] };
+ },
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, dropPauseMs: 0 },
+ });
+ assert.equal(r.kind, "rate-limited", log);
+ assert.equal(r.httpStatus, 429);
+ assert.equal(r.continuations, 1);
+ assert.equal(opens, 2);
+ assert.equal(r.pageOpens, 2);
+ assert.match(log, /Connection dropped at 20480 bytes — reopening the page and resuming \(1 of 6\)/);
+ assert.match(log, /the CDN refused the read at 20480 bytes; the partial is kept/);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a cancel during a continuation's pause stops with the partial kept", async () => {
+ const { root, videoDir } = await setup();
+ const buf = Buffer.alloc(96 * 1024, 2);
+ const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, dropAfterBytes: 20 * 1024 });
+ const ac = new AbortController();
+ try {
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(M4A_PATH)),
+ channelConfig: config,
+ audioFormat: "m4a",
+ audioCheck: false,
+ pageUrl: PAGE,
+ openPage: null,
+ onLog: () => {},
+ signal: ac.signal,
+ deps: {
+ fetch: cdn.fetch,
+ chunkBytes: 8 * 1024,
+ sleep: async () => {
+ ac.abort();
+ },
+ },
+ });
+ assert.equal(r.kind, "aborted");
+ const state = JSON.parse(await readFile(path.join(videoDir, "audio.m4a.stored.part.json"), "utf8"));
+ assert.equal(state.goodBytes, 20 * 1024);
+ assert.equal((await stat(path.join(videoDir, "audio.m4a.stored.part"))).size, 20 * 1024);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/ytdlp/storedUrlDownload.ts b/common/ytdlp/storedUrlDownload.ts
@@ -17,6 +17,21 @@
// another URL) is discarded — its provenance is unknown;
// - a 429 or 403 mid-file stops with the partial KEPT (resume later) and the
// caller backs the platform off; the abort signal stops it the same way;
+// - A DROPPED CONNECTION IS THE SAME FILE, NOT A NEW ONE (release 32 R10,
+// measured 2026-10-17: a 3.3 GB file's ranged reads ended `fetch failed` at
+// 344 MB, and again 100 MB into the resume). Within one run a mid-file
+// network failure — the fetch throwing (ECONNRESET, socket hang up,
+// ETIMEDOUT), the body ending early, a 2xx with no bytes — and a 429/403
+// that follows bytes served since the last page open, are CONTINUATIONS:
+// the next probe is brought forward (the bytes down so far are judged
+// now), the resume state saved, a pause (STORED_URL_DROP_PAUSE_MS), the
+// player's page opened again, and the read goes on from the last clean
+// byte. At most STORED_URL_MAX_DROPS continuations since the last
+// progress (the resume point passing its furthest so far); the next one
+// gives up with the partial kept. A 429 straight after an open still gives
+// up at once. The caller's new-file rest is not waited out between
+// continuations (they are inside this one call), and the whole run is one
+// attempt on the record however many continuations it took;
// - THE AUDIO CHECK, the same pipeline as the audio-checked yt-dlp download
// (audioCheckedDownload.ts), on a producer of its own: its knobs and AIMD
// cadence (resolveKnobs, audioCheckCadence.ts), a periodic probe of the
@@ -47,12 +62,19 @@ import { resolveKnobs, type CheckpointRecord, type Knobs } from "./audioCheckedD
import { backoffInterval, formatInterval, recoverInterval, type CadenceParams } from "./audioCheckCadence";
import type { StreamVerdict } from "./ffmpegStreamClassify";
import { probeAudioStream } from "./ffmpegStreamProbe";
-import type { PageOpener } from "./storedUrlPageOpen";
+import { abortableWait, type PageOpener } from "./storedUrlPageOpen";
// One ranged read. The player asks for a few MiB at a time; 8 MiB keeps a 3 GB
// file to ~400 requests of one connection each, one after another.
export const STORED_URL_CHUNK_BYTES = 8 * 1024 * 1024;
+// A CONTINUATION (release 32 R10): the pause before the page is reopened and
+// the read resumed after a dropped connection (or a refusal after served
+// bytes), and how many continuations in a row may make no progress before the
+// run gives up.
+export const STORED_URL_DROP_PAUSE_MS = 45_000;
+export const STORED_URL_MAX_DROPS = 6;
+
export const STORED_PART_SUFFIX = ".stored.part";
export const STORED_STATE_SUFFIX = ".stored.part.json";
@@ -87,6 +109,9 @@ export type StoredUrlDownloadResult = {
container: string;
// How many times the player's page was opened (storedUrlPageOpen.ts).
pageOpens: number;
+ // How many times the read went on after a dropped connection or a refusal
+ // that followed served bytes (release 32 R10).
+ continuations: number;
};
export type StoredUrlDownloadDeps = {
@@ -98,6 +123,12 @@ export type StoredUrlDownloadDeps = {
// small size gate).
knobs?: Partial<Knobs>;
now?: () => number;
+ // A continuation's pause (default STORED_URL_DROP_PAUSE_MS) and how it is
+ // waited (default an abortable timer). Tests pass 0.
+ dropPauseMs?: number;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+ // Continuations in a row without progress (default STORED_URL_MAX_DROPS).
+ maxDrops?: number;
};
export type StoredUrlDownloadOpts = {
@@ -205,6 +236,16 @@ function isAbort(err: unknown, signal: AbortSignal): boolean {
return signal.aborted || (err as Error)?.name === "AbortError";
}
+// undici's "fetch failed" / "terminated" with the socket's reason when it has
+// one (ECONNRESET, "other side closed", UND_ERR_SOCKET, ETIMEDOUT).
+function errorText(err: unknown): string {
+ const e = err as Error & { cause?: { code?: string; message?: string } };
+ const msg = e?.message ?? String(err);
+ const cause = e?.cause;
+ const why = cause ? (cause.code ?? cause.message ?? "") : "";
+ return why && !msg.includes(why) ? `${msg} (${why})` : msg;
+}
+
export async function storedUrlDownload(
opts: StoredUrlDownloadOpts,
): Promise<StoredUrlDownloadResult> {
@@ -212,6 +253,9 @@ export async function storedUrlDownload(
const fetchImpl = opts.deps?.fetch ?? ((u: string, i: RequestInit) => fetch(u, i));
const chunkBytes = Math.max(1, opts.deps?.chunkBytes ?? STORED_URL_CHUNK_BYTES);
const now = opts.deps?.now ?? Date.now;
+ const dropPauseMs = Math.max(0, opts.deps?.dropPauseMs ?? STORED_URL_DROP_PAUSE_MS);
+ const maxDrops = Math.max(0, opts.deps?.maxDrops ?? STORED_URL_MAX_DROPS);
+ const sleep = opts.deps?.sleep ?? ((ms: number, s?: AbortSignal) => abortableWait(ms, s ?? signal));
const knobs: Knobs = { ...resolveKnobs({ channelConfig: opts.channelConfig }), ...(opts.deps?.knobs ?? {}) };
const names = storedPartNames(stored.url);
const partFile = path.join(videoDir, names.part);
@@ -237,6 +281,7 @@ export async function storedUrlDownload(
// ---- The player's page ----
let pageOpens = 0;
+ let continuations = 0;
// Bytes read since the last open: a refusal with none means the open did
// not unlock the file, and a second open will not either.
let bytesSinceOpen = 0;
@@ -301,6 +346,7 @@ export async function storedUrlDownload(
...(finalProbeVerdict ? { finalProbeVerdict } : {}),
container: names.container,
pageOpens,
+ continuations,
});
// A stop that keeps the partial for a resume: the good bytes recorded.
@@ -419,6 +465,77 @@ export async function storedUrlDownload(
);
};
+ const tooManyRollbacks = (): StoredUrlDownloadResult => {
+ onLog(
+ `More than ${knobs.maxRollbacks} rollbacks in a row: the source keeps serving malformed audio. ` +
+ `The partial is kept at ${goodBytes} bytes.\n`,
+ );
+ return result("failed-corrupt-source", { error: "the source served malformed audio at every attempt" });
+ };
+
+ // ---- A continuation of the same file (release 32 R10) ----
+ // A dropped connection, or a refusal after bytes served since the last open:
+ // judge what came down, pause, reopen the page, read on. Null = go on from
+ // `offset`; a result = give up with it.
+ let dropsSinceProgress = 0;
+ // The furthest resume point of this run: a continuation that does not pass
+ // it made no progress.
+ let furthestResume = offset;
+ const continueSameFile = async (cause: {
+ kind: "network" | "rate-limited";
+ error: string;
+ httpStatus?: number;
+ // What happened, e.g. "Connection dropped at 343932928 bytes".
+ what: string;
+ // The verb of the log line: "reopening the page and resuming".
+ verb: string;
+ }): Promise<StoredUrlDownloadResult | null> => {
+ // The next probe brought forward, so the read resumes from a clean byte.
+ // Under the size gate, or before the container can be opened at all, the
+ // bytes stay unjudged (as between any two checkpoints) and the next probe
+ // judges them.
+ if (opts.audioCheck && offset > goodBytes && (await sizeOf(partFile)) !== null) {
+ const c = await checkpoint();
+ if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
+ if (c === "too-many") return tooManyRollbacks();
+ }
+ if (!opts.audioCheck) goodBytes = offset;
+ if ((await sizeOf(partFile)) !== null) await saveState().catch(() => {});
+ if (offset > furthestResume) {
+ furthestResume = offset;
+ dropsSinceProgress = 0;
+ }
+ dropsSinceProgress++;
+ const extra = { error: cause.error, ...(cause.httpStatus !== undefined ? { httpStatus: cause.httpStatus } : {}) };
+ if (dropsSinceProgress > maxDrops) {
+ onLog(
+ `${cause.what} — ${maxDrops} continuation${maxDrops === 1 ? "" : "s"} since the last progress; ` +
+ `giving up with the partial kept at ${offset} bytes: ${cause.error}\n`,
+ );
+ return keepPartial(cause.kind, extra);
+ }
+ continuations++;
+ onLog(
+ `${cause.what} — ${cause.verb} (${dropsSinceProgress} of ${maxDrops}): ${cause.error}. ` +
+ `Pausing ${Math.round(dropPauseMs / 1000)} s; resuming from ${offset} bytes` +
+ (opts.audioCheck && offset === goodBytes ? " (the last probed-clean byte)" : "") +
+ ".\n",
+ );
+ await sleep(dropPauseMs, signal);
+ if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
+ await openPage();
+ windowStartAt = now();
+ windowStartBytes = offset;
+ return null;
+ };
+ const dropped = (error: string): Promise<StoredUrlDownloadResult | null> =>
+ continueSameFile({
+ kind: "network",
+ error,
+ what: `Connection dropped at ${offset} bytes`,
+ verb: opts.openPage ? "reopening the page and resuming" : "resuming",
+ });
+
onLog(
`Reading ${stored.url} in ranges of ${chunkBytes} bytes, as the player does ` +
`(Referer ${stored.referer}); audio check ${opts.audioCheck ? "on" : "off"}.\n`,
@@ -447,18 +564,23 @@ export async function storedUrlDownload(
});
} catch (err) {
if (isAbort(err, signal)) return keepPartial("aborted", { error: "cancelled" });
- return keepPartial("network", { error: `the ranged read at ${offset} failed: ${(err as Error).message}` });
+ const stop = await dropped(`the ranged read at ${offset} failed: ${errorText(err)}`);
+ if (stop) return stop;
+ continue;
}
if (res.status === 429 || res.status === 403) {
await res.body?.cancel().catch(() => {});
// The unlock may have lapsed: open the page again and ask once more —
// unless nothing was read since the last open.
if (opts.openPage && bytesSinceOpen > 0 && !signal.aborted) {
- onLog(
- `HTTP Error ${res.status} at ${offset} bytes after ${bytesSinceOpen} served since the page was opened; ` +
- `opening it again.\n`,
- );
- await openPage();
+ const stop = await continueSameFile({
+ kind: "rate-limited",
+ httpStatus: res.status,
+ error: `HTTP Error ${res.status} from ${stored.host} at ${offset} bytes`,
+ what: `HTTP Error ${res.status} at ${offset} bytes after ${bytesSinceOpen} served since the page was opened`,
+ verb: "opening it again and resuming",
+ });
+ if (stop) return stop;
continue;
}
onLog(
@@ -508,26 +630,44 @@ export async function storedUrlDownload(
// Append the body.
const before = offset;
const fh = await open(partFile, offset === 0 ? "w" : "a");
+ // A write that fails (the disk) is not a dropped connection: no retry.
+ let writeError: Error | null = null;
+ let readError: unknown = null;
try {
if (res.body) {
for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
if (signal.aborted) break;
- await fh.write(chunk);
+ try {
+ await fh.write(chunk);
+ } catch (err) {
+ writeError = err as Error;
+ break;
+ }
offset += chunk.byteLength;
bytesSinceOpen += chunk.byteLength;
progress();
}
}
} catch (err) {
- await fh.close().catch(() => {});
- if (isAbort(err, signal)) return keepPartial("aborted", { error: "cancelled" });
- return keepPartial("network", { error: `the read at ${before} ended early: ${(err as Error).message}` });
+ readError = err;
+ }
+ await fh.close().catch(() => {});
+ if (signal.aborted || (readError !== null && isAbort(readError, signal))) {
+ return keepPartial("aborted", { error: "cancelled" });
+ }
+ if (writeError) {
+ return keepPartial("network", { error: `writing ${names.part} at ${offset} failed: ${writeError.message}` });
+ }
+ if (readError !== null) {
+ const stop = await dropped(`the read at ${before} ended early at ${offset}: ${errorText(readError)}`);
+ if (stop) return stop;
+ continue;
}
- await fh.close();
- if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
if (whole && total === null) total = offset;
if (offset === before) {
- return keepPartial("network", { error: `the CDN sent no bytes at ${offset}` });
+ const stop = await dropped(`the CDN sent no bytes at ${offset}`);
+ if (stop) return stop;
+ continue;
}
if (!opts.audioCheck) {
goodBytes = offset;
@@ -539,15 +679,7 @@ export async function storedUrlDownload(
if (opts.audioCheck && !done && now() - lastCheckAt >= currentIntervalMs) {
const c = await checkpoint();
if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
- if (c === "too-many") {
- onLog(
- `More than ${knobs.maxRollbacks} rollbacks in a row: the source keeps serving malformed audio. ` +
- `The partial is kept at ${goodBytes} bytes.\n`,
- );
- windowStartAt = now();
- windowStartBytes = offset;
- return result("failed-corrupt-source", { error: "the source served malformed audio at every attempt" });
- }
+ if (c === "too-many") return tooManyRollbacks();
if (c === "rolled-back") {
windowStartAt = now();
windowStartBytes = offset;
diff --git a/common/ytdlp/storedUrlManaged.test.ts b/common/ytdlp/storedUrlManaged.test.ts
@@ -15,6 +15,7 @@ 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 { fullAudioAttemptsOf } from "../lib/fullAudioFirst";
import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap";
import { storedUrlGapKey } from "../lib/storedMediaUrl";
import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged";
@@ -309,6 +310,68 @@ test("the managed download opens the player's page (the injected opener) and rec
}
});
+// Release 32 R10: a dropped connection is a continuation of the same file
+// inside the one call — not a new file (no 20-minute rest) and not another
+// attempt on the record.
+test("drops mid-file inside one managed download: one attempt, its continuations, no new-file rest waited", { skip: !FF }, async () => {
+ const f = await fixture({ cdn: { dropAfterBytes: 24 * 1024, drops: 2 } });
+ try {
+ const waits: number[] = [];
+ const log = { s: "" };
+ const record = await run(
+ f,
+ {
+ storedUrl: "only",
+ storedUrlDeps: {
+ fetch: f.cdn.fetch,
+ chunkBytes: 64 * 1024,
+ knobs: FAST,
+ // A rest that would show if a continuation waited it out.
+ gapMs: 60_000,
+ dropPauseMs: 777,
+ sleep: async (ms: number) => {
+ waits.push(ms);
+ },
+ openPage: async () => ({ ok: true, mediaStatuses: [206] }),
+ },
+ },
+ log,
+ );
+ assert.equal(record.status, "ok-audio-checked", log.s);
+ assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"], "one attempt");
+ const st = storedUrlAttemptOf(record);
+ assert.equal(st?.continuations, 2);
+ assert.equal(st?.pageOpens, 3);
+ assert.equal(st?.bytes, f.clean.length);
+ assert.deepEqual(waits, [777, 777], "the continuations' pauses, and no rest");
+ assert.match(log.s, /Connection dropped at \d+ bytes — reopening the page and resuming \(1 of 6\)/);
+ } finally {
+ await done(f);
+ }
+});
+
+test("a run exhausted by drops after progress is ONE full-audio attempt on the corrupt record (R8's count)", { skip: !FF }, async () => {
+ const f = await fixture({ cdn: { dropAfterBytes: 40 * 1024, drops: Infinity, dropGapBytes: 0 } });
+ try {
+ await corruptPrevious(f, 0);
+ const record = await run(f, {
+ corruptRefetchDeps: { measure: async () => null },
+ storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, dropPauseMs: 0, openPage: null },
+ });
+ assert.equal(record.status, "failed");
+ assert.equal(record.failureClass, "network");
+ const st = storedUrlAttemptOf(record);
+ assert.equal(st?.continuations, 6);
+ assert.ok((st?.bytes ?? 0) > 0, "it made progress before the drops");
+ const disk = await readOutcome(f.videoDir);
+ assert.equal(disk.status, "corrupt-full-source", "the bucket stays");
+ assert.equal(fullAudioAttemptsOf(disk), 1, "one attempt, however many continuations");
+ assert.ok((await readdir(f.videoDir)).includes("audio.mp4.stored.part"), "the partial is kept for the next attempt");
+ } finally {
+ await done(f);
+ }
+});
+
// Release 32 R8 — FULL AUDIO BEFORE A SALVAGE: a corrupt full source's refetch
// reads the stored URL by itself (no storedUrl asked, none on the channel)
// until FULL_AUDIO_ATTEMPTS stored-URL downloads are on record; then the page,
diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts
@@ -36,7 +36,8 @@ export type PageOpener = (opts: {
onLog: (s: string) => void;
}) => Promise<PageOpenResult>;
-function abortableWait(ms: number, signal: AbortSignal): Promise<void> {
+// A wait the signal ends early (resolves, never rejects).
+export function abortableWait(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (signal.aborted) return resolve();
const t = setTimeout(() => {