commit 9e36f024d3da55716a15cb39b23c5db02e0f6398
parent 8fd8b79b59f61d45ec94018b6b06dc2c23b32f85
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 17 Oct 2026 12:19:52 -0400
Merge r32/ranged-resume: a stored-URL download survives mid-file connection drops — probe, pause, reopen the player's page and resume from the last clean byte, up to 6 drops without progress; one attempt for the full-audio count
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
12 files changed, 648 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(() => {
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A full download from Odysee's stored media URL survives a dropped connection.** When the connection to the file's server drops mid-file (`fetch failed`, a reset, a timeout, a body cut short), the same download now checks what came down, pauses 45 seconds, opens the video's page again and goes on from the last clean byte — it no longer ends the job. Each one is in the job log as "Connection dropped at <bytes> — reopening the page and resuming (k of 6)". After six drops in a row with no progress the download stops and keeps what it has for the next run, as before. A refusal that follows bytes the server served is handled the same way; a refusal straight after the page was opened still stops at once. A continuation is not a new file: it does not wait the 20-minute rest between files, and the whole run is still one attempt on the video's record (one of the two full-audio attempts before a salvage). The attempt records how many continuations it took. Needs a restart of the editor.
- **Partial transcripts wait for the full audio first.** A video whose download completed with malformed audio (a corrupt full source) used to get a salvage transcript, with gaps, as soon as anyone pressed Transcribe. When the video's record stores an Odysee media URL, Transcribe and the corrupt full sources' Retry now download from that URL first, up to two times and 20 minutes apart. The salvage transcript is made only if neither download comes back clean. A clean download is transcribed in full. **Salvage** (`transcribe-one {"salvage": true}`) still makes the partial transcript at once. The channel's line shows **awaiting full audio** for the videos still waiting, and the salvaged transcripts read **salvaged — full audio attempts: n**. The video page's salvaged notice gives the same count, the video list marks a salvaged transcript amber, and the MCP's `get_transcripts` marks it partial as `get_transcript` already did.
- **find-copy no longer reports a Wayback copy that has no video.** The Wayback Machine's video index can list a video whose file it does not hold, and such a copy then failed to fetch (404). A copy now counts as found only when one of its video files answers a request for its first bytes. Otherwise the lookup says **page captured, no video**, archive.org is tried next, and the video is recorded as none found, not as a copy that failed. Looking up copies for an article's cited windows now records none found too, as the channel and site lookup already did.
- **The verdict bench shows the model what you read, and rules each part of a claim.** A claim's cited posts and pages now go to the model beside the transcript, quoted with who posted them and when. A section heading that names a verdict is no longer shown to the model. A claim that repeats an earlier one (the same words over the same clips, as in a re-cut report) is still asked each time; `--dedupe` (the body's `"dedupe": true`) asks it once instead. The model no longer picks a verdict. It lists the claim's parts and says of each whether the evidence shows it, shows it wrong, or does not show it, and the verdict follows from those answers: every part shown is CORROBORATED, some shown and some not is PARTLY, nothing shown but a part shown wrong is CONTRADICTED, nothing shown is NOT_FOUND. What each verdict means (REPORT.md, the bench page) now says this. A part the evidence does not show makes a claim PARTLY again, as your rulings do. Proposed verdicts use the same rule. umtool's `/tools/bench` shows under each claim what the model saw (its transcript lines, its posts and pages), and under each answer its parts. This is prompt version 3. Needs a restart of the editor and umtool.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10347,3 +10347,35 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
- Test kit: `testing/web/fakeOdyseePage.mjs` — `syntheticChannel`, `syntheticClaim`, `pageUrlOf`, `channelUrlOf`,
`cdnUrlOf` (`/v6/streams/<claim>/<sd_hash[:6]>.mp4`), `resolveAnswer`, `claimSearchAnswer`, `getAnswer`,
`refusedAnswer`, `videoPageRead`, `channelPageRead`, `fakePageReader` (`.calls`).
+
+## Release 32 lane R10: a stored-URL download survives a dropped connection (verified 2026-10-17, branch `r32/ranged-resume`)
+
+- Observed live (2026-10-17, one 3.3 GB Odysee file): the ranged reads ran ~4 min to 344 MB, then
+ `the ranged read at 343932928 failed: fetch failed` (undici, no HTTP status); the resume (page reopened) restarted at
+ the last probed-clean byte 277 MB and dropped the same way at 377 MB. Before R10 a drop ended the run (`network`).
+- **A continuation** (`ytdlp/storedUrlDownload.ts` `continueSameFile`): within ONE `storedUrlDownload` call, a mid-file
+ network failure — the fetch throwing (`fetch failed`, ECONNRESET, socket hang up, ETIMEDOUT), the body read throwing
+ (`terminated`), a 2xx with no bytes — and a 429/403 that follows bytes served since the last page open (R7/R9's rule)
+ go on with the same file: the next probe is brought forward (audio check on: `checkpoint()` at the drop point —
+ clean → the drop point is the last clean byte; malformed → the usual roll-back, counted against `maxRollbacks`;
+ under the size gate or not yet readable → the bytes stay unjudged as between any two checkpoints), the resume state
+ saved, `STORED_URL_DROP_PAUSE_MS` (45 s) waited (abortable), the page reopened (the injected `PageOpener`; none when
+ null), and the read goes on from `offset`. Log: `Connection dropped at <bytes> — reopening the page and resuming
+ (k of N): <error>. Pausing 45 s; resuming from <bytes> bytes[ (the last probed-clean byte)].` (`— resuming` with no
+ opener); a refusal: `HTTP Error 429 at <b> bytes after <n> served since the page was opened — opening it again and
+ resuming (k of N): …`.
+- **Progress** = the resume point passing the run's furthest resume point (starts at `resumedFrom`); progress resets
+ k to 1. `STORED_URL_MAX_DROPS` (6) continuations since the last progress; the next drop gives up with the partial
+ and its state kept — kind `network` (or `rate-limited` for a refusal), the last error. A 429/403 straight after an
+ open (no bytes since) still gives up at once (`rate-limited`, no second open). A failed WRITE of the partial is not
+ a drop (no retry; kind `network`, "writing … failed").
+- Result `continuations` (count); the attempt's `storedUrl.continuations?` (> 0 only). Test seams on
+ `StoredUrlDownloadDeps` (and so `storedUrlDeps`): `dropPauseMs`, `sleep(ms, signal?)` (the managed download's `sleep`
+ is the same function for its gap and the pause), `maxDrops`. `abortableWait` is exported from `storedUrlPageOpen.ts`.
+- **Not a new file:** the 20-minute `stored-url:<platform>` rest is waited before the call and noted at its start and
+ end, never between continuations. **One attempt:** however many continuations, a run is one `stored-url-ranged`
+ attempt — R8's `fullAudioAttemptsOf` counts a run exhausted by drops (after progress) as one of `FULL_AUDIO_ATTEMPTS`.
+- Test kit: `testing/web/fakeRangedCdn.mjs` `dropAfterBytes` / `drops` (default 1, `Infinity` allowed) /
+ `dropGapBytes` (default `dropAfterBytes`; 0 = every later request cut before its first byte): the cut is mid-body
+ (headers + part of the body, then the socket destroyed) or, on a request's first byte, before any response; a cut
+ request is `dropped: true` with the bytes it sent. `cdn.lock()` takes an unlock back.
diff --git a/plans/release-32/ranged-resume.md b/plans/release-32/ranged-resume.md
@@ -0,0 +1,111 @@
+# Release 32 lane R10 — a stored-URL download survives mid-file network drops (as shipped)
+
+Observed live (2026-10-17, one 3.3 GB Odysee file): the page opened (18 s, the player's reads 200/206), the ranged
+8 MiB reads ran ~4 min to 344 MB, then `the ranged read at 343932928 failed: fetch failed` (undici, no HTTP status).
+The resume (page reopened) restarted at the last probed-clean byte, 277 MB, read ~100 MB in under a minute, and failed
+the same way at 377 MB. R7 reopened the page only on a 429; a network drop ended the job and, under R8, spent one of
+the two full-audio attempts.
+
+## What
+
+- **A dropped connection is a continuation of the same file** (`common/ytdlp/storedUrlDownload.ts`,
+ `continueSameFile`). Within one run, these go on with the same file: a mid-file network failure (the fetch throwing:
+ `fetch failed`, ECONNRESET, socket hang up, ETIMEDOUT; the body read throwing: `terminated`, an aborted body; a 2xx
+ with no bytes) and a 429/403 that follows bytes served since the last page open (R9's rule). A continuation is not a
+ new file and not a spent attempt:
+ 1. The next probe is brought forward (audio check on). A clean verdict makes the drop point the last clean byte. A
+ malformed one is the usual roll-back, counted against `maxRollbacks`. Under the size gate, or before the container
+ can be opened at all, the bytes stay unjudged, as between any two checkpoints.
+ 2. The resume state is saved.
+ 3. A pause of `STORED_URL_DROP_PAUSE_MS` (45 s, abortable).
+ 4. The player's page is reopened (the injected opener; none when null).
+ 5. The read goes on from the resume point.
+- **The limit:** at most `STORED_URL_MAX_DROPS` (6) continuations since the last progress, where progress is the
+ resume point passing the run's furthest so far, and progress resets the count. The next drop gives up with the
+ partial and its state kept, as `network` (or `rate-limited` for a refusal). **A 429 straight after an open still
+ gives up at once** (no second open), including the open that followed a drop.
+- **The log**, one line each: `Connection dropped at <bytes> — reopening the page and resuming (k of N): <error>.
+ Pausing 45 s; resuming from <bytes> bytes (the last probed-clean byte).` A refusal: `HTTP Error 429 at <b> bytes
+ after <n> served since the page was opened — opening it again and resuming (k of N): …`. Giving up: `… — 6
+ continuations since the last progress; giving up with the partial kept at <bytes> bytes: <error>`.
+- **The 20-minute new-file rest does not apply to a continuation**: it is waited before the call and noted at its
+ start and end (`downloadOneManaged`), never between continuations inside it.
+- **R8's attempt count is unchanged:** however many continuations it took, a run is one `stored-url-ranged` attempt.
+ A run that made progress and then ran out of drops counts as one of `FULL_AUDIO_ATTEMPTS`, as before. The attempt
+ records `storedUrl.continuations` (> 0 only).
+- A failed write of the partial (the disk) is not a drop: no retry, `network` with "writing … failed".
+- **Test kit:** `testing/web/fakeRangedCdn.mjs` cuts the connection, either mid-body or before any response:
+ `dropAfterBytes`, `drops`, `dropGapBytes`. `cdn.lock()` takes an unlock back. The fake is now in the testing README.
+
+## Files
+
+`common/ytdlp/storedUrlDownload.ts`, `common/ytdlp/storedUrlPageOpen.ts` (`abortableWait` exported),
+`common/ytdlp/downloadOneManaged.ts` (the attempt's `continuations`, a comment), `common/lib/downloadOutcome.ts`
+(`StoredUrlAttempt.continuations?`), `common/testing/web/fakeRangedCdn.{mjs,d.mts}`, `common/testing/README.md`,
+`editor/CHANGELOG.md`, `plans/FACTS.md`.
+Tests: `common/ytdlp/storedUrlDownload.test.ts` (+6, and the lapse test's pause zeroed with two more assertions),
+`common/ytdlp/storedUrlManaged.test.ts` (+2).
+
+| Commit | What |
+| --- | --- |
+| `9755b0fe` | common: the continuation (probe forward, pause, reopen, resume from the last clean byte; the no-progress limit), the attempt's `continuations`, the fake CDN's cuts, the tests |
+| (this commit) | this record, FACTS, CHANGELOG |
+
+## Gates
+
+Everything ran through the shared heavy lock (`r31-locked.sh`) from the worktree root, at `9755b0fe`:
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean.
+- common: 4594 at the branch's start (4593 pass + 1 skipped: `main` `17207fb8` is R8's gated tree `d135dee1`, the same
+ tree, so it was not run again) → **4602 (4601 pass, 0 fail, 1 skipped)**.
+- The two touched files alone first: `storedUrlDownload.test.ts` + `storedUrlManaged.test.ts` **35/35** on the first
+ run (real ffmpeg present, nothing skipped).
+- editor unit: **346/346** (unchanged count; nothing in the editor changed but the CHANGELOG).
+- `docs files --check`, `docs env --check`: clean. No CLI row, env var, settings or file schema changed (`docs cli`,
+ `settings example` not needed). mcp, test:scripts and umtool are not touched and were not run.
+- e2e: none. No UI changed; the behaviour shows only in a job's log and the outcome record.
+
+## Rulings followed
+
+- R7's: one stream, real gaps. A continuation pauses 45 s and reopens the page; it never runs two reads at once, and
+ "a 429 straight after an open gives up" still holds.
+- R9's: a 429 after served bytes opens the page again. It now pauses first and counts toward the same limit.
+- R8's: `FULL_AUDIO_ATTEMPTS` counts runs. A run exhausted by drops is one attempt, as the brief asked and as before.
+- No model, and no live network or browser in any test (a fake CDN on loopback, an injected opener, a recorded fake
+ pause). Records state rulings.
+
+## Decisions I made
+
+- **The probe is brought forward at a drop.** The brief says to resume "from the resume file's last clean byte". With
+ the audio check on, that byte trailed the drop by up to one probe interval: live, 344 → 277 MB. Probing at the drop
+ makes it the drop point whenever what came down is clean. A malformed verdict rolls back, as any checkpoint does.
+- **Unjudged bytes are kept across a continuation.** That covers bytes under the size gate, and bytes before an MP4
+ whose index is not down yet can be opened at all. Truncating them would lose the same bytes again at every drop, and
+ a file whose container cannot be opened before its end could never progress. Within one run those bytes are an
+ in-order prefix of the server's answer, the same trust the loop already gives bytes between two checkpoints, and
+ the next probe judges them. The resume FILE still records only the clean byte, so a later run truncates to it, as
+ R7 did.
+- **Progress is the resume point passing the run's furthest resume point**, not "some bytes were read". A drop whose
+ bytes are rolled back (malformed) is not progress, and the count terminates. A limit of 6 means: the first drop
+ after progress is 1 of 6, five more with no progress are 2–6, and the seventh gives up.
+- **A refusal after served bytes pauses too**, as the brief's "same for a 429 that follows bytes" reads. The 45 s is
+ extra politeness on a CDN that just refused.
+- **A 2xx with no body bytes is a drop**, the brief's "aborted body". **A failed write is not**: no retry for a full
+ disk.
+- **No opener (a non-Odysee platform):** a drop still pauses and resumes, without a page open. A 429 with no opener
+ gives up at once, as before (R9's rule is about the open).
+- The managed download's test seam `sleep` waits out both the gap and the pause. The test that asserts no rest is
+ waited relies on that.
+
+## What the live run must confirm
+
+- The first live drop says `Connection dropped at <bytes> — reopening the page and resuming (1 of 6): the ranged read
+ at <bytes> failed: fetch failed (…)` and the next reads go on from that byte, or from the last clean byte. The
+ attempt's `storedUrl.continuations` counts them.
+- If the CDN drops faster than one probe per drop can follow, each continuation costs a probe of the whole partial
+ (ffmpeg decodes it) plus 45 s plus a page open (~18 s). The log shows the probe durations
+ (`DLOM_PROBE status=done durationMs=…`).
+
+## Owed
+
+- The clip cut (fetchWindowManaged's ffmpeg path) is not touched: a window is short and ffmpeg reads it in one
+ request, so a drop there is still a failed window.