Archilyzer · Source

archilyzer

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

commit 4bb8bbd815285c9650cc849a8a55b05e93cce9f4
parent 40a6b9beb752b13c18adde50f248ba3d55fbf80f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 21:11:51 -0500

Merge main (landing-fix) into lane/live-guard-2: main's landing rules win, resume in place on top

Conflicts resolved:
- recordLive.ts imports: main's (savedVideoPointerPath for storeState).
- ytdlpPart: the lane's options (resume, recovery, restart, insurance,
  watch, stop) plus main's proof; the mark (provenStart) by main's rule
  for a new part, never for a recovery try or a live-edge part; a resume
  keeps the mark the original run earned (this run's part as it is, a
  boot resume carries it from the old row's part).
- the attempts loop: the lane's boot resume and slice-2 start, with main's
  first-attempt flag.
- contained(): main's proven() and like-with-like kinds, plus the lane's
  "never a restart's sibling or a stalled part".
- mayHoldEnd / the covered removal: main's (kinds, proof, duration - 60 s).
- notLanded: main's keep handling (Do not clean, pending keep) plus the
  lane's dropping of a joined file's record.
- the store pre-check: main's storeState (fails closed), plus the lane's
  proven join that includes the stored container; a join's "from the
  start" is proven() now.
- liveCapture.ts LivePart: both sides' fields; the comment says a resume
  keeps its original run's mark.
- tests: main's landing tests and fixtures where they duplicate the lane's
  REVIEW-1 ones; the lane's helpers (landedAtShutdown keeps join: null and
  gains main's request); both test blocks kept. Fixture rows of from-start
  parts recorded by this build carry provenStart. The slice-2 test now
  expects a recovery part unproven: it lands, the live-edge part is kept.
- OPERATING.md, editor/CHANGELOG.md: both texts, without the lane's
  duplicate of main's store bullet.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MOPERATING.md | 18+++++++++++++++---
Mcommon/controller/recordLive.test.ts | 531++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/controller/recordLive.ts | 214++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/controller/xTrendingCooldown.test.ts | 32++++++++++++++++++++++++++++----
Mcommon/jobs/instagramPacing.test.ts | 16++++++++++++++++
Mcommon/lib/doNotCleanGate.test.ts | 5++++-
Mcommon/lib/liveCapture.ts | 10++++++++++
Mcommon/lib/recordingClock-server.test.ts | 43+++++++++++++++++++++++++++++++++++++------
Mcommon/lib/storedText.grep.test.ts | 43++++++++++++++++++++++++++++++++++++++++---
Meditor/CHANGELOG.md | 11++++++++---
10 files changed, 765 insertions(+), 158 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1450,11 +1450,22 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": holds bytes — an earlier run's, one from the live edge, one that cannot be landed as it is, fragments a recorder left — stays in the store's staging dir, listed as `keptParts` (files, sizes, why), and the row needs a person until acknowledged. A later recording does not clear that; nothing removes kept files automatically. On Kick, a - VOD that covers the stream removes the channel's live-edge part; one that does not keeps it. + VOD that covers the stream removes the channel's live-edge part; one that does not keeps it. A part not from the + start (a live-edge part, one no row describes) goes only when the landed file is from the start and at least the + ENDED stream's own duration less 60 s — never on a coverage by the clock. Only a part PROVEN to begin at the start + (`provenStart`: a YouTube `--live-from-start` part (not one that fell to index 0) on a stream under 120 h old; on Rumble, Twitch and the rest only a + first attempt whose playlist read still listed the start; a Kick VOD whose poll began at its first segment) counts as from the start for + a removal, a replacement or the coverage; an index-0 part, the browser path and a part of a row written before the + mark do not. A part with a picture is never "inside" an audio-only landed part, nor one merged here from separate + streams. A retry that wrote only its audio leaves that audio-only part staged beside the landed one, and the row + asks for a person (its sound is not proven inside the landed file). A stored container that cannot be read, or a `source-media` file no pointer names, counts as stored. **A recording already in the store** (an earlier run's landing, a shutdown's included) is replaced + only by a file that holds the whole stream from its start; otherwise nothing lands, every part stays listed + (`keptParts`), the run is `failed` ("not landed: …") and needs a person — and whenever the landing keeps the stored + container, nothing is removed. - **A recording already in the store is never replaced or deleted around by one not proven to hold it.** When the saved-video store already holds a container for the stream (an earlier run's landing — a shutdown's included), a new run lands over it only when its file holds the whole stream from its start (the coverage rule), or when it is a - proven join that includes the stored container (as its base, when the run that stored it landed a part from its + proven join that includes the stored container (as its base, when the run that stored it landed a part PROVEN from its start). Otherwise nothing lands: the store keeps what it holds, every part stays in staging as `keptParts`, the run is `failed` ("not landed: …") and needs a person. And whenever the landing ends up keeping the stored container, nothing is removed. A part is removed only when THIS landing stored and verified a file that holds it; a restart's @@ -1472,7 +1483,8 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": `--live-from-start` download (downloader/fragment.py) and, run again with the same output, continues from the saved fragment. So a from-start recorder that dies, stalls, or is stopped by an editor shutdown is restarted as the SAME part: the same stem, the format pinned to the ids on disk, from where it stopped — no new part, no gap, no second - download (`resumes` on the part). The watchdog and a shutdown stop it with SIGTERM, which leaves the state; a + download (`resumes` on the part). A resumed part keeps the proof of start its original run earned + (`provenStart`); a live-edge or recovery part never has one. The watchdog and a shutdown stop it with SIGTERM, which leaves the state; a person's Cancel is SIGINT, which finishes the file. At a shutdown such a part is not landed: it waits in staging (`awaitingResume`) and the boot's restart resumes it. Only when a resume is impossible (no state: the file was finished; an unreadable state; a stream past 120 h; a resume that writes nothing) does the live-edge fallback below diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -520,14 +520,17 @@ const realLand = { }, freeBytes: async () => 1e15, }; +// What a real live YouTube record carries (the metadata read passes no +// --live-from-start, so no generator formats: HLS only), started two hours ago. const YT_META = (id: string) => ({ id, extractor: "youtube", title: "A YouTube live stream", live_status: "is_live", + release_timestamp: Math.floor(Date.now() / 1000) - 7200, formats: [ - { format_id: "234", protocol: "http_dash_segments_generator", vcodec: "none", acodec: "mp4a.40.2", url: "https://dash.example/234" }, - { format_id: "270", protocol: "http_dash_segments_generator", height: 1080, vcodec: "avc1", acodec: "none", url: "https://dash.example/270" }, + { format_id: "91", protocol: "m3u8_native", height: 144, vcodec: "avc1.4d400c", acodec: "mp4a.40.5", url: "https://manifest.example/91.m3u8" }, + { format_id: "95", protocol: "m3u8_native", height: 720, vcodec: "avc1.4d401f", acodec: "mp4a.40.2", url: "https://manifest.example/95.m3u8" }, ], }); @@ -933,7 +936,7 @@ test("1.1: an earlier run's longer from-start part lands, and this run's live-ed assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 1, "an acknowledgement removes nothing"); }); -test("1.1: of this run's own parts, a shorter from-start part is inside the landed one and goes", async () => { +test("1.1: of this run's own parts, a shorter audio-only from-start part is kept beside the landed one (its sound is not proven inside)", async () => { const id = "exmplkeep02"; // Attempt 1 records audio only for 45 s (one stream missing: retried), // attempt 2 records both from the start. @@ -947,9 +950,11 @@ test("1.1: of this run's own parts, a shorter from-start part is inside the land }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); - assert.deepEqual((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)), []); + // The audio-only part is NOT taken as inside the landed one: that file's + // own sound may be shorter than its length (REVIEW-LF-2 4) — kept, listed. + assert.deepEqual((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).map((n) => /\.f140\.m4a$/.test(n)), [true]); const row = (await rowOf(id))[0]!; - assert.equal(row.keptParts, undefined); + assert.equal(row.keptParts?.length, 1); assert.equal(row.missingStream, undefined, "the second attempt has both"); assert.equal(row.parts[0]!.missingStream, "video"); assert.equal(row.parts[0]!.failureClass, "partial"); @@ -1015,8 +1020,8 @@ test("2.3: only a landed from-start run that covers the stream supersedes; a liv assert.equal((await stillNeeds()).needsAttention, true, "a run from now does not hold the start"); assert.equal((await stillNeeds()).supersededBy, undefined); // (b) from its start, 600 s of a stream that has run two hours: the store - // holds (a)'s recording, which this one is not proven to hold — not landed - // (REVIEW-1 1.2 of live-guard-2), kept, needing a person. + // holds (a)'s recording, which this one is not proven to hold — not landed, + // kept, needing a person. const short = await incidentRun(id, writesAfter(0)); await assert.rejects(short.run, /not landed/); assert.equal((await stillNeeds()).needsAttention, true, "a short partial does not supersede"); @@ -1024,13 +1029,12 @@ test("2.3: only a landed from-start run that covers the stream supersedes; a liv assert.equal(shortRow.keptParts?.length, 1); assert.equal(shortRow.coverage?.covers, false); assert.equal(shortRow.coverage?.basis, "clock"); - // (c) the ended stream's own duration, 610 s, against 600 s captured: covers. // (c) the ended stream's own duration, 710 s, against 700 s captured: covers, - // and it holds the stored live-edge recording too, so it replaces it. + // so it replaces the stored live-edge recording. const whole = await incidentRun( id, async (args) => { - await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=700;"); + await writeFile(`${args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, "")}.mp4`, "format=mov,mp4;seconds=700;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, { meta: { ...YT_META(id), live_status: "post_live", duration: 710 } }, @@ -1107,77 +1111,23 @@ const leftover = async (id: string, seconds: number) => { return f; }; -test("covered (a): a Kick VOD that covers the stream lands, the channel's live-edge part is removed, nobody is asked", async () => { - const KICK = { handling: "transcribe", url: "https://kick.com/synthb/videos", platform: "kick", name: "Synth Kick B" } as ChannelConfig; - const slug = "synth-kick-b"; - await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true }); - await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK)); - const uuid = "01a164b1-0c18-723a-a785-f9637c98aaaa"; - const s = await recordLiveRun({ - paths, - request: { slug, url: "https://kick.com/synthb" }, - plan: { url: "https://kick.com/synthb", platform: "kick", id: null, kickChannel: "synthb" }, - channelConfig: KICK, - cookiePolicy: NO_COOKIES, - onLog: () => {}, - signal: new AbortController().signal, - deps: { - kickVod: async () => ({ id: uuid, url: `https://kick.com/synthb/videos/${uuid}` }), - refresh: refreshWith({ - id: uuid, - extractor: "kick:vod", - live_status: "is_live", - uploader_id: "synthb", - // Started 5000 s ago: the VOD's 5000 s is the whole stream, its own - // duration once ended. - release_timestamp: Math.floor(Date.now() / 1000) - 5000, - duration: 5000, - formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }], - }), - // The channel's live edge: its last 30 s, inside the VOD on the - // stream's clock. - spawn: async ({ args }) => { - await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=30;"); - return { exitCode: 0, stderrTail: "", signalled: false }; - }, - poll: async (o) => { - await writeFile(o.output, "format=mpegts;seconds=5000;"); - return { segments: 500, seconds: 5000, gaps: 0, firstSeq: 0, ended: "the VOD has not grown" }; - }, - land, - freeBytes: async () => 1e15, - handoff, - shuttingDown: () => false, - }, - }); - assert.equal(s.landed?.seconds, 5000); - assert.deepEqual((await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`)), [], "the live-edge part went"); - const { listLiveRecordings } = await import("./liveRecordings"); - const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!; - assert.equal(row.coverage?.covers, true); - assert.equal(row.keptParts, undefined); - assert.equal(row.removedParts?.length, 1); - assert.match(row.removedParts![0]!.why, /holds the whole stream/); - assert.equal(row.needsAttention, false); -}); - test("covered (b): a from-start landing that covers the stream removes an earlier run's partial, nobody is asked", async () => { const id = "exmplcov0b1"; const earlier = await leftover(id, 300); // Its run's row says it was recorded from the start (a part no row - // describes is kept: REVIEW-2 1.1). + // describes may hold the stream's end, and is kept). const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", - startedAt: "2026-11-20T01-00-00.000Z".replace(/T01-00-00/, "T01:00:00"), + startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, - parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem: path.basename(earlier).replace(/\.mp4$/, "") }], + parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem: path.basename(earlier).replace(/\.mp4$/, "") }], }); const { run } = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); assert.equal((await run).status, "landed"); @@ -1206,7 +1156,7 @@ test("not covered (d): a stream whose length cannot be established keeps every o const id = "exmplcov0d1"; const earlier = await leftover(id, 300); // No start time and no duration: the stream's length is not known. - const { run } = await incidentRun(id, writesAfter(0), { meta: YT_META(id) }); + const { run } = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: undefined } }); assert.equal((await run).status, "landed"); assert.ok((await stat(earlier)).size > 0, "kept"); const row = (await rowOf(id))[0]!; @@ -1251,7 +1201,7 @@ const edgeUntil = (ended: Promise<unknown>, seconds = 30) => async (args: string }; const failEmpty = { exitCode: 1, stderrTail: EMPTY, signalled: false }; -test("slice 2: the live edge records, a from-start try beside it recovers the start: landed whole, the live-edge part goes, nobody is asked", async () => { +test("slice 2: the live edge records, a from-start try beside it records from the start; unproven (a recovery part), it lands, the live-edge part is kept for a person", async () => { const id = "exmplrecov1"; let endStream!: () => void; const ended = new Promise<void>((r) => (endStream = r)); @@ -1284,17 +1234,19 @@ test("slice 2: the live edge records, a from-start try beside it recovers the st assert.equal(calls.length, 6, "3 from its start, 1 live edge, 2 recovery tries"); assert.equal(maxActive, 1, "never two from-start recorders at once"); assert.equal(waits.filter((w) => w === RECOVERY_WAIT).length, 2, "each try after a 15 min wait"); - assert.equal(s.landed?.seconds, 7200, "the recovered from-start part lands"); + assert.equal(s.landed?.seconds, 7200, "the from-start try's part, the longest, lands"); assert.ok(log.some((l) => /tried again beside the live edge/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.fallback, "live-edge"); - assert.equal(row.startRecovery?.state, "recovered"); assert.equal(row.startRecovery?.tries, 2); - assert.equal(row.coverage?.covers, true); - assert.equal(row.keptParts, undefined, "the live-edge part is inside the landed whole"); - assert.equal(row.removedParts?.length, 1); - assert.equal(row.needsAttention, false, "the start is not lost"); - assert.match(row.reason, /start recovered/); + // A recovery part never carries the proof of start (main's rule): it lands, + // but it is not taken as the whole stream — the live-edge part is kept and + // a person decides. + assert.equal(row.parts.find((p) => p.recovery && (p.seconds ?? 0) > 0)?.provenStart, undefined); + assert.equal(row.coverage?.covers, false); + assert.equal(row.startRecovery?.state, "recorded"); + assert.ok(row.keptParts?.some((k) => /ytdlp-edge-a4$/.test(k.stem)), "the live-edge part is kept"); + assert.equal(row.needsAttention, true); }); test("slice 2: bounded — 8 failed tries beside the live edge, one at a time, then no more; the start stays lost and needs a person", async () => { @@ -1511,7 +1463,8 @@ const interruptedRow = async (id: string, startedAt: string, parts: { stem: stri fromStart: true, attempts: 1, mustKeep: true, - parts: parts.map((p) => ({ method: "ytdlp" as const, url: ytUrl(id), fromStart: p.fromStart, startedAt, stem: p.stem })), + // (A from-start part recorded by this build carries its proof.) + parts: parts.map((p) => ({ method: "ytdlp" as const, url: ytUrl(id), fromStart: p.fromStart, ...(p.fromStart ? { provenStart: true } : {}), startedAt, stem: p.stem })), restart: { at: startedAt, by: "boot", state: "asked", jobId: `job-${id}` }, }); }; @@ -1893,7 +1846,7 @@ async function joinCase( mustKeep: true, streamStartedAt: iso(0), parts: [ - { method: "ytdlp", url: ytUrl(id), fromStart: true, startedAt: iso(1), stem: a }, + { method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: iso(1), stem: a }, { method: "ytdlp", url: ytUrl(id), fromStart: false, startedAt: iso(o.edgeClock), stem: b }, ], restart: { at: iso(9000), by: "boot", state: "asked" }, @@ -2016,7 +1969,7 @@ const storedSeconds = async (id: string): Promise<number | null> => { }; const okExit = { exitCode: 0, stderrTail: "", signalled: false }; // Run 1: `seconds` from its start, landed by an editor shutdown. -async function landedAtShutdown(id: string, seconds: number) { +async function landedAtShutdown(id: string, seconds: number, request: Record<string, unknown> = {}) { const ac = new AbortController(); const r = await incidentRun( id, @@ -2025,27 +1978,23 @@ async function landedAtShutdown(id: string, seconds: number) { ac.abort(); return { exitCode: null, stderrTail: "", signalled: true }; }, - { signal: ac.signal, deps: { shuttingDown: () => true, join: null } }, + { signal: ac.signal, request, deps: { shuttingDown: () => true, join: null } }, ); assert.equal((await r.run).status, "interrupted"); assert.equal(await storedSeconds(id), seconds); } -test("REVIEW 1.2 + 1.1(b): a later run's live-edge part — longer or shorter — never replaces the stored start and is never deleted: kept, the store untouched, a person asked", { timeout: 60_000 }, async () => { +test("landing 1.2/1.1: a later run's live-edge part — longer or shorter — never replaces the stored start and is never deleted: kept, the store untouched, a person asked", async () => { for (const [id, edge] of [ - ["exmplrv1201", 7000], - ["exmplrv1202", 2000], + ["exmpllf1201", 7000], + ["exmpllf1202", 2000], ] as const) { await landedAtShutdown(id, 3600); - const r = await incidentRun( - id, - async (args, n) => { - if (n <= 3) return failEmpty; - await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${edge};`); - return okExit; - }, - { deps: { join: null } }, - ); + const r = await incidentRun(id, async (args, n) => { + if (n <= 3) return failEmpty; + await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${edge};`); + return okExit; + }); await assert.rejects(r.run, /not landed/); assert.equal(await storedSeconds(id), 3600, `${id}: the stored start is still the stored container`); assert.ok((await left(id)).some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), `${id}: the live-edge part is still on disk`); @@ -2055,9 +2004,8 @@ test("REVIEW 1.2 + 1.1(b): a later run's live-edge part — longer or shorter } }); -test("REVIEW 1.1: when the landing keeps the container already in the store, NOTHING is removed — the unlanded part and every part collected for removal stay, listed", { timeout: 60_000 }, async () => { - const id = "exmplrv1101"; - // Run 1 landed the whole stream, a little longer than run 2's. +test("landing 1.1: when the landing keeps the container already in the store, NOTHING is removed", async () => { + const id = "exmpllf1101"; const one = await incidentRun(id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7300;"); return okExit; @@ -2071,8 +2019,7 @@ test("REVIEW 1.1: when the landing keeps the container already in the store, NOT await assert.rejects(two.run, /not landed/); assert.equal(await storedSeconds(id), 7300); assert.ok((await stat(earlier)).size > 0, "the earlier part is not removed"); - const mine = (await left(id)).filter((n) => n !== path.basename(earlier)); - assert.equal(mine.length, 1, "this run's part is not removed"); + assert.equal((await left(id)).filter((n) => n !== path.basename(earlier)).length, 1, "this run's part is not removed"); const row = (await rowOf(id)).find((x) => x.status === "failed")!; assert.equal(row.removedParts, undefined); assert.equal(row.keptParts?.length, 2); @@ -3012,3 +2959,393 @@ test("DESIGN-3 fallback (REVIEW-4 1.1): the gap recovery's first try waits until assert.ok(recoveryAt > 0, "a recovery try ran"); assert.ok(recoveryAt >= edgeBytesAt, "it began only once the live-edge part held bytes"); }); + +test("landing: an index-0 part is not 'inside' a longer index-0 part of the run (a sliding window): kept", async () => { + const id = "exmpllfidx1"; + const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n"; + const { run } = await incidentRun(id, async (args, n) => { + if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false }; + if (n === 2) { + // Audio only, then the video stream failed: retried. + await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=300;v=none;"); + return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; + } + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); + return okExit; + }); + assert.equal((await run).status, "landed"); + assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the earlier index-0 part is kept"); + const row = (await rowOf(id))[0]!; + assert.ok(row.keptParts?.length); +}); + +test("landing: a live-edge part goes only when the landed file is from the start and as long as the ended stream's own duration less a minute", async () => { + const KICK = { handling: "transcribe", url: "https://kick.com/synthc/videos", platform: "kick", name: "Synth Kick C" } as ChannelConfig; + const slug = "synth-kick-c"; + await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true }); + await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK)); + // The VOD's length against the ended stream's duration: by the clock + // nothing is proven; with a duration the live-edge part goes at exactly + // duration - 60 s, not a second short (the tolerance, 100 s here, covers both). + // (A VOD whose poll did not begin at segment 0 is not proven: kept.) + for (const [uuid, duration, vod, gone, firstSeq] of [ + ["01a164b1-0c18-723a-a785-f9637c98bbb1", null, 5000, false, 0], + ["01a164b1-0c18-723a-a785-f9637c98bbb2", 10000, 9940, true, 0], + ["01a164b1-0c18-723a-a785-f9637c98bbb3", 10000, 9939, false, 0], + ["01a164b1-0c18-723a-a785-f9637c98bbb4", 10000, 9990, false, 40], + ] as const) { + let reads = 0; + const meta = { id: uuid, extractor: "kick:vod", uploader_id: "synthc", release_timestamp: Math.floor(Date.now() / 1000) - (duration ?? 5000), formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }] }; + await recordLiveRun({ + paths, + request: { slug, url: "https://kick.com/synthc" }, + plan: { url: "https://kick.com/synthc", platform: "kick", id: null, kickChannel: "synthc" }, + channelConfig: KICK, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: new AbortController().signal, + deps: { + kickVod: async () => ({ id: uuid, url: `https://kick.com/synthc/videos/${uuid}` }), + // Live at the first read; ended (with its duration, when known) after. + refresh: async (cwd: string, args: string[]) => { + reads++; + const o = args[args.indexOf("-o") + 1]!; + const m = reads === 1 ? { ...meta, live_status: "is_live" } : { ...meta, live_status: "was_live", ...(duration ? { duration } : {}) }; + await writeFile(path.join(cwd, path.dirname(o), "metadata.info.json"), JSON.stringify(m)); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }, + spawn: async ({ args }) => { + await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=30;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + poll: async (o) => { + await writeFile(o.output, `format=mpegts;seconds=${vod};`); + return { segments: 500, seconds: vod, gaps: 0, firstSeq, ended: "the VOD has not grown" }; + }, + land, + freeBytes: async () => 1e15, + handoff, + shuttingDown: () => false, + }, + }); + const files = (await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`)); + assert.equal(files.length === 0, gone, `${uuid}: the channel's live-edge part ${gone ? "goes" : "is kept"}`); + const { listLiveRecordings } = await import("./liveRecordings"); + const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!; + if (gone) { + // (covered (a)'s guarantees: removed, said why, nothing kept, nobody asked.) + assert.equal(row.coverage?.covers, true); + assert.equal(row.removedParts?.length, 1); + assert.match(row.removedParts![0]!.why, /holds the whole stream/); + assert.equal(row.keptParts, undefined); + assert.equal(row.needsAttention, false); + } else { + assert.equal(row.keptParts?.length, 1); + assert.equal(row.needsAttention, true); + } + } +}); + +// --- REVIEW-LF-1 ------------------------------------------------------------------ + +// An earlier run's row describing one part of the stream (a leftover in staging). +async function rowFor(id: string, stem: string, part: Record<string, unknown>) { + const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); + await ytChannel(); + await upsertLiveRecordingRow(paths, YT_SLUG, { + id, + url: ytUrl(id), + platform: "youtube", + startedAt: "2026-11-20T01:00:00.000Z", + status: "failed", + fromStart: true, + attempts: 1, + mustKeep: true, + parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem, ...part }], + } as never); +} +const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n"; +// From its start unsupported: an index-0 part records `seconds`. +const index0Run = (seconds: number) => async (args: string[], n: number) => { + if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false }; + await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`); + return okExit; +}; + +test("LF finding 1: an index-0 part is not proven from the start — it never replaces a stored container nor removes a proven from-start part, on length alone", async () => { + // (a) A stored container from the start; an index-0 run "covers" by length. + const a = "exmpllfidx2"; + await landedAtShutdown(a, 3600); + const r = await incidentRun(a, index0Run(7200), { meta: { ...YT_META(a), live_status: "post_live", duration: 7210 } }); + await assert.rejects(r.run, /not landed/); + assert.equal(await storedSeconds(a), 3600, "the stored start stays"); + // (b) An earlier proven from-start part; an index-0 landing that "covers" leaves it. + const b = "exmpllfidx3"; + const earlier = await leftover(b, 300); + await rowFor(b, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true }); + const rb = await incidentRun(b, index0Run(7200), { meta: { ...YT_META(b), live_status: "post_live", duration: 7210 } }); + assert.equal((await rb.run).status, "landed"); + assert.ok((await stat(earlier)).size > 0, "the proven from-start part is kept"); + assert.equal((await rowOf(b)).find((x) => x.status === "landed")!.coverage?.covers, false); +}); + +test("LF finding 2: a part holding video is never 'inside' a longer audio-only landed part", async () => { + const id = "exmpllfvid1"; + const ac = new AbortController(); + const { run } = await incidentRun( + id, + async (args, n) => { + if (n === 1) { + // Only its audio stream wrote (3 h of backlog); the video failed. + await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=10800;v=none;"); + return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; + } + // Both streams, merged, 1 h — then a Cancel. + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3600;"); + ac.abort(); + return { exitCode: null, stderrTail: "", signalled: true }; + }, + { signal: ac.signal, request: { doNotClean: false, note: undefined } }, + ); + await run; + assert.ok((await left(id)).some((n) => /ytdlp-a2\.mp4$/.test(n)), `the only video stays: ${(await left(id)).join(", ")}`); +}); + +test("LF note 3: no pointer, but a source-media file in the store: a container is stored (fail closed) — nothing lands over it", async () => { + const id = "exmpllfstr1"; + const { savedVideoDir } = await import("../lib/savedVideo"); + const dir = savedVideoDir(paths, YT_CONFIG, YT_SLUG, id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "source-media.mp4"), "format=mov,mp4;seconds=9000;"); + const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); + await assert.rejects(r.run, /not landed/); + assert.equal(await readFile(path.join(dir, "source-media.mp4"), "utf8"), "format=mov,mp4;seconds=9000;", "the unnamed container is untouched"); +}); + +test("LF note 6: a run asked to keep the stream marks it even when nothing landed", async () => { + const id = "exmpllfkep1"; + await landedAtShutdown(id, 3600, { doNotClean: false, note: undefined }); + assert.equal(await isDoNotClean(dataDir(id)), false); + const r = await incidentRun(id, async (args, n) => { + if (n <= 3) return failEmpty; + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;"); + return okExit; + }); + await assert.rejects(r.run, /not landed/); + assert.equal(await isDoNotClean(dataDir(id)), true); +}); + +test("LF note 5: a row's part with no proven-start mark (an older row) is not removed under coverage; marked, it is", async () => { + const id = "exmpllfold1"; + const earlier = await leftover(id, 300); + await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), {}); + const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); + assert.equal((await r.run).status, "landed"); + assert.ok((await stat(earlier)).size > 0, "kept: not proven from its start"); +}); + +test("LF 9/10: landing 1.1 with a part meant for removal — kept when the store keeps its own", async () => { + const id = "exmpllf1102"; + const one = await incidentRun(id, async (args) => { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7300;"); + return okExit; + }); + assert.equal((await one.run).status, "landed"); + const earlier = await leftover(id, 300); + await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true }); + const two = await incidentRun(id, async (args) => { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + return okExit; + }); + await assert.rejects(two.run, /not landed/); + assert.ok((await stat(earlier)).size > 0); + const row = (await rowOf(id)).find((x) => x.status === "failed" && /not landed/.test(x.error ?? ""))!; + assert.ok(row.keptParts?.some((k) => /kept: nothing was landed/.test(k.why)), "the part meant for removal is kept and says so"); + assert.equal(row.removedParts, undefined); +}); + +test("LF 9: with an empty store a short from-start partial lands and does not supersede (2.3's guarantee)", async () => { + const id = "exmpllf2301"; + const first = await incidentRun(id, writesAfter(Infinity)); + await assert.rejects(first.run); + const short = await incidentRun(id, writesAfter(0)); + assert.equal((await short.run).status, "landed"); + assert.ok(short.log.some((l) => /does not supersede/.test(l))); + const rows = await rowOf(id); + assert.equal(rows.find((r) => r.status === "landed")!.coverage?.covers, false); + assert.equal(rows.find((r) => r.status === "failed")!.needsAttention, true); +}); + +// --- REVIEW-LF-2 ------------------------------------------------------------------ + +// Rumble: `--live-from-start` is ffmpeg at the DVR playlist's first LISTED +// segment. A run whose playlist read still lists segment 1 is from the start; +// one that began after the window slid is not. +const DVR_SLID = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:151\n#EXTINF:2,\nm_151.ts\n#EXTINF:2,\nm_152.ts\n"; +async function rumbleRun(id: string, o: { dvr: string; seconds: number; duration: number; stop?: "shutdown" }) { + const ac = new AbortController(); + let reads = 0; + const meta = { ...RUMBLE_META, id, live_status: "is_live", timestamp: Math.floor(Date.now() / 1000) - o.duration }; + return recordLiveRun({ + paths, + request: { slug: SLUG, url: `https://rumble.com/${id}-show.html` }, + plan: { url: `https://rumble.com/${id}-show.html`, platform: "rumble", id }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: ac.signal, + deps: { + refresh: async (cwd: string, args: string[]) => { + reads++; + const out = args[args.indexOf("-o") + 1]!; + const m = reads === 1 ? meta : { ...meta, live_status: "was_live", duration: o.duration }; + await writeFile(path.join(cwd, path.dirname(out), "metadata.info.json"), JSON.stringify(m)); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }, + fetchText: async () => o.dvr, + spawn: async ({ args }) => { + await writeFile(args[args.indexOf("-o") + 1]!, `format=mpegts;seconds=${o.seconds};`); + if (o.stop) { + ac.abort(); + return { exitCode: null, stderrTail: "", signalled: true }; + } + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + land, + freeBytes: async () => 1e15, + handoff, + shuttingDown: () => o.stop === "shutdown", + }, + }); +} +const rumbleStored = async (id: string) => { + const { savedVideoPath } = await import("../lib/savedVideo"); + const p = await loadSavedVideo(path.join(CORPUS, "channels", SLUG, "data", id)); + return p ? ((await fakeProbe(savedVideoPath(p)))?.seconds ?? null) : null; +}; +const rumbleLeft = async (id: string) => (await readdir(path.join(paths.savedVideosDir, SLUG)).catch(() => [] as string[])).filter((n) => n.startsWith(`.${id}.`)); + +test("LF2 finding 1 (Rumble): a from-start run that began after the DVR window slid is not proven — it never replaces the stored start nor removes run 1's part", async () => { + // (a) Run 1 from the true start, landed by a shutdown; run 2 after the slide "covers" by length. + const a = "v7lfslid1"; + await rumbleRun(a, { dvr: DVR, seconds: 3600, duration: 10000, stop: "shutdown" }); + assert.equal(await rumbleStored(a), 3600); + await assert.rejects(rumbleRun(a, { dvr: DVR_SLID, seconds: 9950, duration: 10000 }), /not landed/); + assert.equal(await rumbleStored(a), 3600, "the stored start stays"); + // (b) Run 1's part in staging (its row: proven); run 2 after the slide lands, run 1's part is kept. + const b = "v7lfslid2"; + const stem = `.${b}.live-2026-11-20T01-00-00-000Z.ytdlp`; + await mkdir(path.join(paths.savedVideosDir, SLUG), { recursive: true }); + await writeFile(path.join(paths.savedVideosDir, SLUG, `${stem}.ts`), "format=mpegts;seconds=3600;"); + const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); + await upsertLiveRecordingRow(paths, SLUG, { + id: b, url: `https://rumble.com/${b}-show.html`, platform: "rumble", startedAt: "2026-11-20T01:00:00.000Z", status: "interrupted", + fromStart: true, attempts: 1, mustKeep: false, + parts: [{ method: "ytdlp", url: "u", fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem }], + } as never); + const s = await rumbleRun(b, { dvr: DVR_SLID, seconds: 9950, duration: 10000 }); + assert.equal(s.status, "landed"); + assert.ok((await rumbleLeft(b)).some((n) => n === `${stem}.ts`), "run 1's part is kept"); +}); + +test("LF2 finding 1 (YouTube): a from-start run of a stream older than 120 h is not proven (the generator starts 120 h back)", async () => { + const id = "exmpllf120h"; + await landedAtShutdown(id, 3600); + const old = Math.floor(Date.now() / 1000) - 121 * 3600; + // 7200 s of a stream whose ended duration is 7210 s: it "covers" and is longer than the stored hour. + const r = await incidentRun( + id, + async (args) => { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + return okExit; + }, + { meta: { ...YT_META(id), release_timestamp: old, live_status: "post_live", duration: 7210 } }, + ); + await assert.rejects(r.run, /not landed/); + assert.equal(await storedSeconds(id), 3600); +}); + +test("LF2 note 3: a pointer whose file is gone is 'stored, unknown' when the store folder holds a source-media file; with the folder empty or absent it is an empty store", async () => { + const { savedVideoDir } = await import("../lib/savedVideo"); + // (a) The pointer names source-media.mp4 (gone); source-media.mkv is there. + const a = "exmpllfptr1"; + await landedAtShutdown(a, 3600); + const dirA = savedVideoDir(paths, YT_CONFIG, YT_SLUG, a); + const named = (await readdir(dirA)).find((n) => n.startsWith("source-media."))!; + await rm(path.join(dirA, named)); + await writeFile(path.join(dirA, "source-media.mkv"), "format=matroska;seconds=5000;"); + const ra = await incidentRun(a, writesAfter(0), { meta: { ...YT_META(a), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); + await assert.rejects(ra.run, /not landed/); + assert.ok((await stat(path.join(dirA, "source-media.mkv"))).size > 0); + // (b) The pointer names a file that is gone, the folder empty: lands as an empty store. + const b = "exmpllfptr2"; + await landedAtShutdown(b, 3600); + const dirB = savedVideoDir(paths, YT_CONFIG, YT_SLUG, b); + await rm(dirB, { recursive: true, force: true }); + const rb = await incidentRun(b, writesAfter(0), { meta: { ...YT_META(b), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); + assert.equal((await rb.run).status, "landed"); +}); + +test("LF2 note 4: an audio-only part is not 'inside' a longer part whose own audio may be shorter", async () => { + const id = "exmpllfaud1"; + const ac = new AbortController(); + const { run } = await incidentRun( + id, + async (args, n) => { + if (n === 1) { + // Only its audio (1 h), then the video failed. + await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;v=none;"); + return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; + } + // Both, 4 h on the container's length (its audio may be shorter) — a Cancel. + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=14400;"); + ac.abort(); + return { exitCode: null, stderrTail: "", signalled: true }; + }, + { signal: ac.signal, request: { doNotClean: false, note: undefined } }, + ); + await run; + assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the audio-only part is kept"); +}); + +test("LF2 note 7: with a container stored, a zero-byte file and a fragments-only part's .ytdl are not removed by a run that lands nothing", async () => { + const id = "exmpllfg7a1"; + await landedAtShutdown(id, 3600); + await mkdir(store(), { recursive: true }); + const zero = path.join(store(), `.${id}.live-2026-11-20T02-00-00-000Z.ytdlp.f18.mp4`); + await writeFile(zero, ""); + const frag = `.${id}.live-2026-11-20T03-00-00-000Z.ytdlp.f18.mp4`; + await writeFile(path.join(store(), `${frag}-Frag7`), "bytes of a fragment"); + await writeFile(path.join(store(), `${frag}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: 7 } } })); + const r = await incidentRun(id, async (args, n) => { + if (n <= 3) return failEmpty; + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;"); + return okExit; + }); + await assert.rejects(r.run, /not landed/); + assert.ok(await stat(zero).then(() => true, () => false), "the zero-byte file stays"); + assert.ok(await stat(path.join(store(), `${frag}.ytdl`)).then(() => true, () => false), "the .ytdl stays"); +}); + +test("LF3 note 5: a proven, same-kind, shorter part of this run IS removed after the landing (inside the landed part)", async () => { + const id = "exmpllfcon1"; + // Every attempt writes only its audio (the video fails): the from-start + // attempts 100 s, 200 s, 5000 s, the live-edge ones 10 s each. + const secs = [100, 200, 5000, 10, 10, 10]; + const { run } = await incidentRun( + id, + async (args, n) => { + await writeFile(`${outOf(args)}.f140.m4a`, `format=mp4;seconds=${secs[n - 1]};v=none;`); + return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; + }, + { request: { doNotClean: false, note: undefined } }, + ); + await run.catch(() => {}); + const row = (await rowOf(id))[0]!; + assert.equal(row.parts[row.landedPart ?? -1]?.seconds, 5000, "the longest from-start part landed"); + const gone = (row.removedParts ?? []).filter((r) => /a shorter part of this run from its start/.test(r.why)); + assert.equal(gone.length, 2, "the two shorter from-start audio parts are inside it, and go"); + const files = await left(id); + assert.ok(!files.some((n) => /-a2\.f140|ytdlp\.f140/.test(n)), `removed from staging: ${files.join(", ")}`); + assert.equal(files.filter((n) => /edge/.test(n)).length, 3, "the live-edge parts (not proven) are kept"); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -77,6 +77,7 @@ import { classifyAttempt, extractionRefused, ffmpegLiveArgs, + firstSequenceOf, formatUnavailable, lastErrorLine, liveAttemptSchedule, @@ -116,7 +117,7 @@ import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; import type { Paths } from "../lib/paths"; import { detectPlatform } from "../lib/platform"; import { savedVideoDir, savedVideoPath, savedVideoRoot } from "../lib/savedVideo"; -import { loadSavedVideo } from "../lib/savedVideo-server"; +import { loadSavedVideo, savedVideoPointerPath } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; @@ -1306,6 +1307,23 @@ async function recordLiveRunInner( // the same thing for a DVR playlist); "index0": `--no-live-from-start` with // ffmpeg told index 0 — for an extractor that does not mark a format from // the start; "now": the live edge. + // YouTube (REVIEW-LF-3 1): a `--live-from-start` run there either fails + // "no formats that can be downloaded from the start" (→ index 0, never + // marked) or downloads only the extractor's own fragment generator, which + // begins at fragment 0 for a stream under 120 h old (YoutubeDL.py's + // is_from_start format filter; extractor/youtube/_video.py MAX_DURATION). + // So the proof is the platform plus the age — not the metadata read's + // formats, which never carry the generator protocol (that read passes no + // --live-from-start: a real live record lists HLS formats only). + const youtube = plan.platform === "youtube" || /^youtube/i.test(String(meta?.extractor ?? "")); + const startProvable = (first: boolean): boolean => { + if (youtube) { + // Its age: from its start time, else (an ended stream) its duration. + const age = streamStartSec !== null ? now().getTime() / 1000 - streamStartSec : typeof meta?.duration === "number" ? (meta.duration as number) : null; + return age !== null && age < 120 * 3600; + } + return first && record.reach?.fromStart === true; + }; const ytdlpPart = async ( url: string, tag: string, @@ -1329,7 +1347,9 @@ async function recordLiveRunInner( // DESIGN-3: RESUME IN PLACE — this stem's files and state again (same // `-o`), the format pinned to the ids on disk; this run's part of that // stem, or a new entry for it (a boot restart of an earlier run's part). - resume?: { stem: string; formats: string }; + resume?: { stem: string; formats: string; provenStart?: boolean }; + // The run's first attempt, made with no wait before it (main's proof). + firstAttempt?: boolean; } = {}, ): Promise<RecorderOutcome & { part: LivePart; stem: string; stalled: boolean }> => { const file = opts.resume @@ -1349,6 +1369,16 @@ async function recordLiveRunInner( if (opts.restart) part.restart = opts.restart; if (opts.insurance) part.insurance = true; if (mode === "index0") part.index0 = true; + // PROVEN from the stream's start (main's rule, REVIEW-LF-2/3): by what is + // recorded — a YouTube `--live-from-start` part on a stream under 120 h + // old; another platform's only on the first attempt whose playlist read + // listed the start. A RESUME continues the same file from its saved + // fragment, so it keeps the mark the ORIGINAL run earned (this run's part, + // or the earlier run's by its row) and never earns one itself; a + // recovery try or a live-edge part never gets one. + if (opts.resume) { + if (!known && opts.resume.provenStart) part.provenStart = true; + } else if (mode === "from-start" && !opts.recovery && startProvable(opts.firstAttempt === true)) part.provenStart = true; const stem = part.stem!; opts.onStart?.(stem); await save(); @@ -1564,6 +1594,9 @@ async function recordLiveRunInner( ...(deps.fetchBytes ? { fetchBytes: deps.fetchBytes } : {}), }).then(async (r) => { finish(part, `${r.segments} segment(s) from ${r.firstSeq ?? "?"}, ${r.gaps} gap(s); ${r.ended}`); + // Proven from the start only when the poll's first segment is the + // platform's first (REVIEW-LF-2 2). + if (r.firstSeq !== null && r.firstSeq <= firstSequenceOf("kick")) part.provenStart = true; await save(); }); } else { @@ -1959,7 +1992,7 @@ async function recordLiveRunInner( if (mode === "now" && fromStart && record.fallback === "live-edge" && recovery === null) recovery = recoverStart(index0); // DESIGN-3: a restart after the editor's resumes the interrupted run's // from-start part in place when its state is there. - let bootResume: { stem: string; formats: string } | null = null; + let bootResume: { stem: string; formats: string; provenStart?: boolean } | null = null; if (resumeOf && slot === 0 && mode === "from-start" && n === 1) { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const oldRow = rows.find((r) => r.id === id && r.startedAt === resumeOf); @@ -1967,7 +2000,8 @@ async function recordLiveRunInner( if (!p.stem || !p.fromStart || p.index0 || p.recovery) continue; const st = await resumeStateOf(p.stem); if (st.ok) { - bootResume = { stem: p.stem, formats: st.formats }; + // The mark the interrupted run earned travels with its file. + bootResume = { stem: p.stem, formats: st.formats, ...(p.provenStart ? { provenStart: true } : {}) }; say(`Restart after the editor restart: ${p.stem} is resumed in place from fragment ${st.fragment}.`); break; } @@ -1976,6 +2010,7 @@ async function recordLiveRunInner( const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "", { onStart: onMainStart(mode), onLine: onMainLine, + firstAttempt: n === 1, ...(bootResume ? { resume: bootResume, noWait: true } : {}), }); // This attempt's own part (a try beside it may have begun one since). @@ -2394,9 +2429,50 @@ async function recordLiveRunInner( const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s)); const at = (n: string) => path.join(slugStore, n); // Every part on disk now — this run's and an earlier run's — by its stem. + // WHAT THE STORE HOLDS for this id, failing CLOSED: a pointer that does not + // read, a stored file that cannot be reached, or a source-media file no + // pointer names is "stored, not proven" — never an empty store. + const storeState = async (): Promise<{ kind: "empty" } | { kind: "stored"; path: string } | { kind: "unknown"; why: string }> => { + const pointerFile = savedVideoPointerPath(videoDir); + const pst = await stat(pointerFile).then( + () => "there" as const, + (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? ("absent" as const) : ("error" as const)), + ); + if (pst === "error") return { kind: "unknown", why: "the store's pointer cannot be read" }; + const pointer = pst === "there" ? await loadSavedVideo(videoDir).catch(() => null) : null; + if (pst === "there" && !pointer) return { kind: "unknown", why: "the store's pointer does not read" }; + if (pointer) { + const sp = savedVideoPath(pointer); + const st = await stat(sp).then( + (x) => (x.isFile() ? ("file" as const) : ("other" as const)), + (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? ("absent" as const) : ("error" as const)), + ); + if (st === "file") return { kind: "stored", path: sp }; + if (st !== "absent") return { kind: "unknown", why: `the stored file ${path.basename(sp)} cannot be reached` }; + } + const names = await readdir(storeDir).then( + (x) => x, + (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? [] : null), + ); + if (names === null) return { kind: "unknown", why: "the store's folder cannot be read" }; + const sm = names.find((n) => n.startsWith("source-media.")); + return sm + ? { + kind: "unknown", + why: + `${sm} is in the store with no pointer naming it (a landing stopped between the file and its record?) — ` + + "compare it with the staged parts and land or remove it by hand; until then nothing of this stream lands", + } + : { kind: "empty" }; + }; + // With a container stored, no file of a part is removed before the landing + // decides (the zero-byte files, a fragments-only group's state). + const storeHeld = (await storeState()).kind !== "empty"; const groups = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); const partOf = new Map(parts.map((p) => [p.stem, p.part])); - type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles }; + // video: it holds a picture; merged: record-live merged it from separate + // streams here (its length is the longer stream's). + type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles; video: boolean | null; merged: boolean }; const candidates: Candidate[] = []; const unlandable: string[] = []; const unlandableGroups: { group: LivePartFiles; why: string; part?: LivePart }[] = []; @@ -2408,6 +2484,16 @@ async function recordLiveRunInner( if (stopped?.by === "shutdown") { for (const g of groups) if ((await resumeStateOf(g.stem)).ok) waitsForResume.add(g.stem); } + // A part an earlier run left waiting to be resumed (its row's + // awaitingResume), which this run did not resume, is not this run's to land, + // remove or count: it waits, as it is, while its state is there. + { + const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); + const mine = new Set(parts.map((p) => p.stem)); + for (const stem of rows.filter((r) => r.id === id).flatMap((r) => r.awaitingResume ?? [])) { + if (!mine.has(stem) && (await resumeStateOf(stem)).ok) waitsForResume.add(stem); + } + } for (const g of groups) { const part = partOf.get(g.stem); if (waitsForResume.has(g.stem)) { @@ -2431,10 +2517,15 @@ async function recordLiveRunInner( if (got && "error" in got) { unlandable.push(`${g.stem}: ${got.error}`); unlandableGroups.push({ group: g, why: got.error, ...(part ? { part } : {}) }); - } else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) }); + } else if (got) { + // null: the probe failed — not known, so never "contained" (REVIEW-LF-2 4). + const pv = await probe(got.file, landSignal).catch(() => null); + const video = pv ? Boolean(pv.videoCodec) : null; + candidates.push({ file: got.file, seconds: got.seconds, group: g, video, merged: got.merged === true, ...(part ? { part } : {}) }); + } else { empty.push(g); - for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true }); + if (!storeHeld) for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true }); } } for (const u of unlandable) say(`Not landable: ${u}`); @@ -2463,12 +2554,13 @@ async function recordLiveRunInner( }); }; // Every part that is not the landed one, and why it would be kept. - type Other = { group: LivePartFiles; why: string; seconds?: number | null; part?: LivePart; extra?: string[] }; + // video: what the candidate holds (undefined: not a candidate, not probed). + type Other = { group: LivePartFiles; why: string; seconds?: number | null; part?: LivePart; extra?: string[]; video?: boolean | null }; const others: Other[] = []; for (const u of unlandableGroups) others.push({ group: u.group, why: `not landable as it is: ${u.why}`, ...(u.part ? { part: u.part } : {}) }); for (const g of empty) { // Fragments a recorder left hold media too; yt-dlp's resume state does not. - for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true }); + if (!storeHeld) for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true }); const part = partOf.get(g.stem); others.push({ group: g, why: "fragments a recorder left, not landable as they are", ...(part ? { part } : {}) }); } @@ -2519,19 +2611,28 @@ async function recordLiveRunInner( // Inside the landed file without asking how long the stream is: a shorter // part of THIS run, both from the start (both begin where the stream's // record begins). - // Not a restart's sibling nor a stalled part (REVIEW-1 1.4 of live-guard-2): - // on a DVR window that slides, a later from-start part starts later; nor - // an index-0 part unless the playlist was read to reach the start. Those - // go only by the coverage rule. - const sure = (p: LivePart) => p.restart === undefined && !p.stalled && (!p.index0 || record.reach?.fromStart === true); + // PROVEN from the start (main's rule): a part marked so when it was + // recorded. An index-0 part, the browser path, a recovery try or a + // live-edge part, and a part of a row written before the mark are not + // proven, whatever `fromStart` says. And never a restart's sibling or a + // stalled part (REVIEW-1 1.4 of live-guard-2): those go by coverage only. + const proven = (p: Pick<LivePart, "fromStart" | "provenStart"> | undefined) => p?.fromStart === true && p.provenStart === true; + const sure = (p: LivePart) => p.restart === undefined && !p.stalled; const contained = (c: Candidate) => c !== best && c.part !== undefined && best.part !== undefined && - c.part.fromStart && - best.part.fromStart && + proven(c.part) && + proven(best.part) && sure(c.part) && sure(best.part) && + // Same kind only, as per-stream lengths are not known: a picture part + // inside a picture part not merged here; an audio-only part only inside + // an audio-only one (a part with both may hold less sound than its + // container's length, which is its longer stream's). + c.video !== null && + best.video !== null && + ((c.video && best.video && !best.merged) || (!c.video && !best.video)) && c.seconds !== null && best.seconds !== null && c.seconds <= best.seconds; @@ -2557,6 +2658,7 @@ async function recordLiveRunInner( seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file], + video: c.video, }); } if (separate && !record.missingStream) { @@ -2567,11 +2669,13 @@ async function recordLiveRunInner( // also decides superseding). Its own record says whether it was from the // start: this run's part, or an earlier run's by the channel's rows (a part // no row names is not known to be). - let landedFromStart: boolean | null = best.part ? best.part.fromStart : null; + // Proven, not merely marked fromStart (REVIEW-LF-1 1): this run's part, or + // an earlier run's by its row. + let landedFromStart: boolean | null = best.part ? proven(best.part) : null; if (landedFromStart === null) { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const p = rows.filter((r) => r.id === id).flatMap((r) => r.parts).find((x) => x.stem === best.group.stem); - landedFromStart = p ? p.fromStart : null; + landedFromStart = p ? proven(p) : null; } record.coverage = streamCoverage({ capturedSeconds: best.seconds, @@ -2604,14 +2708,15 @@ async function recordLiveRunInner( const earlier = new Map(rows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); const placed = candidates.flatMap((c) => { const p = c.part ?? earlier.get(c.group.stem); - return p && c.seconds !== null ? [{ c, jp: { stem: c.group.stem, file: c.file, seconds: c.seconds, fromStart: p.fromStart, startedAt: p.startedAt ?? null } }] : []; + // "From the start" in a join only on proof (main's rule). + return p && c.seconds !== null ? [{ c, jp: { stem: c.group.stem, file: c.file, seconds: c.seconds, fromStart: proven(p), startedAt: p.startedAt ?? null } }] : []; }); if (stored) { const by = rows .filter((r) => r.id === id && r.kept === "new" && r.landedPart !== undefined && r.startedAt !== record.startedAt) .sort((a, b) => Date.parse(b.endedAt ?? b.startedAt) - Date.parse(a.endedAt ?? a.startedAt))[0]; const lp = by?.parts[by.landedPart!]; - if (lp?.fromStart && !lp.restart && !lp.stalled && !lp.index0) { + if (proven(lp) && !lp!.restart && !lp!.stalled) { placed.push({ c: null as unknown as Candidate, jp: { stem: STORED, file: stored.file, seconds: stored.seconds, fromStart: true, startedAt: lp.startedAt ?? null } }); } } @@ -2669,7 +2774,14 @@ async function recordLiveRunInner( }); } const base = r.segments[0]!; - best = { file: r.file, seconds: r.seconds, group: { stem: path.basename(joinStem), finished: [path.basename(r.file)], streams: [], scratch: [] } }; + const jp = await probe(r.file, landSignal).catch(() => null); + best = { + file: r.file, + seconds: r.seconds, + group: { stem: path.basename(joinStem), finished: [path.basename(r.file)], streams: [], scratch: [] }, + video: jp ? Boolean(jp.videoCodec) : null, + merged: false, + }; landedFromStart = base.streamFromBasis === "start"; record.joins = r.joins; joinsRecord = { seconds: r.seconds, segments: r.segments, joins: r.joins }; @@ -2695,29 +2807,28 @@ async function recordLiveRunInner( say(`The start is recovered: a from-start try beside the live edge holds the whole stream (${spanWords(cov.capturedSeconds ?? 0)}).`); } // Covered: every other part of the stream, this run's or an earlier one's, - // is inside the landed file by definition, and goes (recorded, with why). + // is inside the landed file, and goes (recorded, with why) — except a part + // that may hold the stream's END: one not from the start (a live-edge part, + // one no row describes), which goes only when the landed file is from the + // start and, on the media's own length, at least the ENDED stream's own + // duration less 60 s; never on a coverage by the clock, nor on a live or + // unknown-length stream. // Not covered — a live-edge landing, a partial, a stream whose length is // not known — every other part with bytes is kept and needs a person. - // A PART THAT MAY HOLD THE STREAM'S END (REVIEW-2 1.1, REVIEW-3 4.1): one - // not from the start (live edge, insurance, restart), this run's or an - // earlier one's (its row), or one no row describes, is never removed on a - // coverage by the clock. const placeRows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const placeOf = new Map(placeRows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); - // REVIEW-3 4.1: on the media's own length, never the stream's start - // timestamp as the media's zero: a part not from the start goes only when - // the landed file is from the start and as long as the ENDED stream's own - // duration within a minute; on a live or unknown-length stream nothing is - // assumed inside it. const endedDuration = cov.basis === "duration" ? cov.streamSeconds : null; const mayHoldEnd = (o: Other): boolean => { + // An audio-only part beside a landed file with a picture: that file's + // own sound may be shorter than its length (REVIEW-LF-2 4) — kept. + if (o.video === false && best.video !== false) return true; + if (o.video === null) return true; const p = o.part ?? placeOf.get(o.group.stem); - if (p?.fromStart && !p.index0) return false; - return !(landedFromStart && best.seconds !== null && endedDuration !== null && best.seconds >= endedDuration - 60); + if (proven(p)) return false; + return !(landedFromStart === true && best.seconds !== null && endedDuration !== null && best.seconds >= endedDuration - 60); }; for (const o of others) { - const laterEnd = mayHoldEnd(o); - if (cov.covers && !laterEnd) { + if (cov.covers && !mayHoldEnd(o)) { toRemove.push({ group: o.group, why: `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`, @@ -2749,9 +2860,9 @@ async function recordLiveRunInner( say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); throw new Error(record.error); }; - // NOTHING LANDED (REVIEW-1 1.1/1.2 of live-guard-2): the store keeps what it - // holds, and every part — the one that would have landed, every part meant - // for removal, a joined file and its parts — stays, listed, needing a person. + // NOTHING LANDED: the store keeps what it holds, and every part — the one + // that would have landed, every part meant for removal, a joined file and + // its parts — stays, listed, needing a person. Nothing is removed. const notLanded = async (why: string): Promise<RecordLiveSummary> => { await keep(best.group, `not landed: ${why}`, { seconds: best.seconds, ...(best.part ? { part: best.part } : {}), extra: [best.file] }); for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: nothing was landed`, r.o); @@ -2763,15 +2874,34 @@ async function recordLiveRunInner( delete record.joins; sayKept(); await save(); + // The operator's keep marks hold whatever landed (as main did). + if (req.doNotClean) { + await setDoNotClean(videoDir, true, { + by: "live-recording", + via: "record-live", + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(req.note ? { note: req.note } : {}), + }).catch((e: Error) => say(`"Do not clean" could not be set (${e.message}).`)); + } + await applyPendingKeep(paths, req.slug, id, onLog, opts.jobId).catch((e: Error) => say(`The pending keep could not be applied (${e.message}).`)); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); if (!cancelled) throw new Error(record.error); return summary; }; - if (stored && !cov.covers && !storedInJoin) { + // A CONTAINER ALREADY IN THE STORE (an earlier run's landing, a shutdown's + // included) is replaced only by a file that holds the whole stream from its + // start (the coverage rule), or by a proven join that includes it: "longer" + // is not containment. The store read fails closed (main's storeState). + const store = await storeState(); + if (store.kind === "unknown") { + return notLanded(`${store.why}: a container may be stored, and nothing lands over it unproven`); + } + if (store.kind === "stored" && !cov.covers && !storedInJoin) { + const storedSeconds = (await probe(store.path, landSignal).catch(() => null))?.seconds ?? null; return notLanded( - `the store already holds a recording of this stream (${spanWords(stored.seconds)}), and this one is not proven to hold it ` + - "(not the whole stream from its start, nor a join that includes it): the stored one stays", + `the store already holds a recording of this stream (${storedSeconds !== null ? spanWords(storedSeconds) : "length unknown"}), ` + + "and this one is not proven to hold it (not the whole stream from its start, nor a join that includes it): the stored one stays", ); } let landed: Awaited<ReturnType<typeof landMediaFile>>; @@ -2802,6 +2932,8 @@ async function recordLiveRunInner( ); } } + // The landing kept the store's own container: nothing of this run was + // stored, so nothing is removed. if (landed.kept !== "new") { return notLanded(`the store holds a recording as long or longer (${spanWords(landed.existingSeconds ?? 0)}); this one may hold time it does not`); } diff --git a/common/controller/xTrendingCooldown.test.ts b/common/controller/xTrendingCooldown.test.ts @@ -1,6 +1,7 @@ // X's cooldown after a trending read met a rate limit (lane x-trending, review // 1 SHOULD 5), on the real state file of a temp corpus: 15 minutes on the -// `twitter` platform entry, read back by the read's own held check. +// `twitter` platform entry — X's one stop (lane x-sittings) — read back by the +// read's own held check. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingCooldown.test.ts @@ -16,10 +17,16 @@ writeFileSync(path.join(ROOT, "settings.json"), "{}"); after(() => rmSync(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); -const { platformCooldownRemainingMs, recordPlatformClean, recordPlatformCooldown } = await import("../jobs/downloadBackoff"); +const { clearXStop, clearPlatformHold, platformCooldownRemainingMs, recordPlatformClean, recordPlatformCooldown, xStopRemainingMs } = await import( + "../jobs/downloadBackoff" +); const { X_RATE_LIMIT_HOLD_MS, xTrendingHeld } = await import("./readXTrending"); -test("no cooldown: a read may start; after a 429: refused until the minute it names; a clean answer settles it", async () => { +// THE ONE X STOP (lane x-sittings): a trending read's 429 is X's 15-minute +// stop, the same entry every X job's guard reads — not a cooldown of the +// read's own — and NOTHING ends it early but the operator's "Clear the X +// stop" (clearXStop, confirmed): not a clean answer, not Clear hold. +test("no cooldown: a read may start; after a 429: refused until the minute it names; only the operator's clear ends it early", async () => { const paths = getPaths(); assert.equal(await xTrendingHeld(paths), null); const now = Date.now(); @@ -37,8 +44,25 @@ test("no cooldown: a read may start; after a 429: refused until the minute it na assert.equal(await platformCooldownRemainingMs("bluesky", paths), 0); // A second, shorter cooldown never brings the end forward. assert.equal(await recordPlatformCooldown("twitter", 60_000, paths, now), until); + // It is the X stop itself, as the guard of every X job reads it. + const stop = await xStopRemainingMs(paths, now); + assert.equal(stop, until - now); + // A clean answer does not clear it, nor does Clear hold: the read stays refused. await recordPlatformClean("twitter", paths); - assert.equal(await xTrendingHeld(paths), null); + assert.equal(await xStopRemainingMs(paths, now), stop); + assert.ok(await xTrendingHeld(paths, now)); + await clearPlatformHold("twitter", paths); + assert.equal(await xStopRemainingMs(paths, now), stop); + assert.ok(await xTrendingHeld(paths, now)); + // The operator's clear, unconfirmed, removes nothing. + const asked = await clearXStop(paths, { confirm: false, by: "test", now }); + assert.equal(asked.ok, false); + assert.ok(await xTrendingHeld(paths, now)); + // Confirmed, it ends the stop, and a read may start again. + const cleared = await clearXStop(paths, { confirm: true, by: "test", now }); + assert.ok(cleared.ok && cleared.cleared?.until === until); + assert.equal(await xStopRemainingMs(paths, now), 0); + assert.equal(await xTrendingHeld(paths, now), null); }); // Review 2 N4: a clean trending read settles nothing on the platform. The diff --git a/common/jobs/instagramPacing.test.ts b/common/jobs/instagramPacing.test.ts @@ -180,7 +180,22 @@ async function runCount(): Promise<number> { } } +// EVERY JOB'S END ASKS FOR ITS CHANNEL'S REPORT (jobs/snapshotScheduler.ts): +// a refresh-report a second later, which writes into the channel's dir. Left +// alone it lands in the next test's reset — or the final cleanup — while that +// removes the dir: ENOTEMPTY under a loaded run. Before either, the pending +// regeneration is dropped and any one already started is waited out. +const { resetSnapshotScheduler } = await import("./snapshotScheduler"); +const { getRegistry } = await import("./registry"); +async function settleReports(): Promise<void> { + resetSnapshotScheduler(); + const busy = () => getRegistry().list().some((j) => j.kind === "refresh-report" && (j.status === "queued" || j.status === "running")); + for (let i = 0; i < 400 && busy(); i += 1) await new Promise((r) => setTimeout(r, 25)); + assert.equal(busy(), false, "a channel report still regenerating after 10 s"); +} + async function reset(cookies: string | null = "firefox:ig-profile"): Promise<void> { + await settleReports(); clearQueueGaps(); cdn.length = 0; await rm(RUNS, { force: true }); @@ -194,6 +209,7 @@ async function readLog(jobId: string): Promise<string> { } test.after(async () => { + await settleReports(); await rm(ROOT, { recursive: true, force: true }); }); diff --git a/common/lib/doNotCleanGate.test.ts b/common/lib/doNotCleanGate.test.ts @@ -17,7 +17,10 @@ import { fileURLToPath } from "node:url"; const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const ROOTS = ["common", "editor", "umtool", "mcp", "scripts", "export", "homepage", "plans"]; -const SKIP_DIRS = new Set(["node_modules", ".next", "out", "dist", "public", "e2e", ".e2e-song", "test-results", ".git", "coverage"]); +// Build and test output, never source. `out-private` is the homepage's private +// build (gitignored): it holds the published source tree — a copy of every +// file this gate reads, the one writer and its allow-list among them. +const SKIP_DIRS = new Set(["node_modules", ".next", "out", "out-private", "dist", "public", "e2e", ".e2e-song", "test-results", ".git", "coverage"]); const EXT = /\.(ts|tsx|mts|cts|js|mjs|cjs)$/; const TEST = /\.(test|spec)\.[cm]?[jt]sx?$|\.unit\.ts$/; diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -470,6 +470,16 @@ export type LivePart = { resumes?: number; // Why the last resume wrote nothing (the fallback followed). resumeError?: string; + // Proven to begin at the stream's start, by what was recorded: a YouTube + // `--live-from-start` part (not one fallen to index 0) on a stream under + // 120 h old; another platform's + // `--live-from-start` only when that run's first playlist read listed the + // start; a platform VOD whose poll began at its first segment. A part + // without it (index-0, the browser path, a later attempt, rows written + // before the mark, a recovery try, a live-edge part) is never taken as + // holding the start for a removal or a replacement. A part RESUMED in place + // keeps the mark its original run earned (the same file continues). + provenStart?: boolean; }; export type MissingStream = "video" | "audio" | "unknown"; diff --git a/common/lib/recordingClock-server.test.ts b/common/lib/recordingClock-server.test.ts @@ -60,6 +60,31 @@ async function encode(samples: Float32Array, out: string, codec: string[]) { await rm(raw); } +// WHERE THE ENCODER PUT THE START (seconds the decoded file lags its input). +// Not always zero: lame 4.0's gapless tag says an encoder delay of 47 samples +// where the stream has 576, so ffmpeg (9.1) decodes its mp3 529 samples — +// 33 ms at 16 kHz — late. The clock maps the files AS DECODED (what the +// transcriber hears), so the offsets it must find are the spliced ones plus +// the toolchain's lags: found here to the sample, independently of the code +// under test, by matching a decoded second against the input. +async function decodedLag(file: string, input: Float32Array): Promise<number> { + const r = await execa(FFMPEG, ["-v", "error", "-i", file, "-t", "3", "-ac", "1", "-ar", String(SR), "-f", "f32le", "pipe:1"], { + encoding: "buffer", + }); + const buf = Buffer.from(r.stdout as Uint8Array); + const dec = new Float32Array(Math.floor(buf.length / 4)); + for (let i = 0; i < dec.length; i += 1) dec[i] = buf.readFloatLE(i * 4); + const MAX = Math.round(0.2 * SR); + let best = 0; + let bestScore = -Infinity; + for (let lag = -MAX; lag <= MAX; lag += 1) { + let dot = 0; + for (let k = MAX; k < MAX + SR; k += 1) dot += input[k] * (dec[k + lag] ?? 0); + if (dot > bestScore) [bestScore, best] = [dot, lag]; + } + return best / SR; +} + async function fixture() { const root = await mkdtemp(path.join(os.tmpdir(), "clock-")); dirs.push(root); @@ -81,13 +106,17 @@ async function fixture() { path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-11-06T00:00:00.000Z", dir: store, file: "source-media.mp4", bytes }), ); - return { videoDir, container: path.join(store, "source-media.mp4") }; + // A span's offset is its splice offset plus (target lag - source lag). + const lag = (await decodedLag(path.join(store, "source-media.mp4"), tgt)) - (await decodedLag(path.join(videoDir, "audio.mp3"), src)); + return { videoDir, container: path.join(store, "source-media.mp4"), lag }; } const OPTS = { sampleRate: 4000, probeSeconds: 10, searchSeconds: 20, everySeconds: 60, minGapSeconds: 10 }; test("a step and an offset, measured from an mp3 against an AAC mp4, written as clock.json", async () => { - const { videoDir, container } = await fixture(); + const { videoDir, container, lag } = await fixture(); + const before = 2.5 + lag; + const afterSplice = 13.1 + lag; assert.equal((await planRecordingClock(videoDir)).kind, "measure"); const logs: string[] = []; const r = await ensureRecordingClock({ @@ -104,8 +133,9 @@ test("a step and an offset, measured from an mp3 against an AAC mp4, written as assert.equal(clock.segments.length, 2, JSON.stringify(clock.segments)); // Exact to the sample: the source decoded from its start, the target seeked // with a pre-roll (an input seek alone lands an AAC excerpt 10–55 ms off). - assert.ok(Math.abs(clock.segments[0].offset - 2.5) < 0.002, `before ${clock.segments[0].offset}`); - assert.ok(Math.abs(clock.segments[1].offset - 13.1) < 0.002, `after ${clock.segments[1].offset}`); + // The toolchain's lag is part of what the clock must find (decodedLag). + assert.ok(Math.abs(clock.segments[0].offset - before) < 0.002, `before ${clock.segments[0].offset} (expected ${before})`); + assert.ok(Math.abs(clock.segments[1].offset - afterSplice) < 0.002, `after ${clock.segments[1].offset} (expected ${afterSplice})`); assert.ok(Math.abs(clock.segments[1].offset - clock.segments[0].offset - 10.6) < 0.002); assert.ok(clock.gaps[0].from < 200 && clock.gaps[0].to > 200, JSON.stringify(clock.gaps)); assert.ok((clock.residual.rms ?? 1) < 0.005); @@ -117,8 +147,9 @@ test("a step and an offset, measured from an mp3 against an AAC mp4, written as const again = await ensureRecordingClock({ ffmpegBin: FFMPEG, ffprobeBin: FFPROBE, videoDir, options: OPTS }); assert.equal(again.measured, false); assert.equal(again.plan, "current"); - // The map: a span before the splice +2.5, after it +13.1, across it uncertain. - assert.ok(Math.abs(clockOffsetAt(clock, 100).offset - 2.5) < 0.002); + // The map: a span before the splice +2.5, after it +13.1 (each plus the + // toolchain's lag), across it uncertain. + assert.ok(Math.abs(clockOffsetAt(clock, 100).offset - before) < 0.002); assert.equal(mapSpan(clock, 300, 310).certain, true); assert.equal(mapSpan(clock, 190, 210).certain, false); }); diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts @@ -34,7 +34,11 @@ const COMMON = path.dirname(path.dirname(fileURLToPath(import.meta.url))); const REPO = path.dirname(COMMON); const ROOTS = ["common", "editor/app", "editor/lib", "mcp/src", "umtool", "export/scripts", "export/lib", "export/app", "scripts", "docker"]; -const SKIP_DIRS = new Set(["node_modules", ".next", "out", "public", "e2e", "dist", ".turbo"]); +const SKIP_DIRS = new Set(["node_modules", ".next", "out", "out-private", "public", "e2e", "dist", ".turbo"]); +// Every dot-directory under these roots is build or test output, never source +// (umtool's alternate dist dirs `.next-*`, `.e2e-song`, …, all gitignored): a +// checkout that has run a build holds its compiled chunks, which name the same +// files as the source they were built from — and the source is what is gated. // The names of the raw chat in code: the two constants, the stored one, the // literal (but not its `.part`, its `.zst` spelled out in a comment, or the @@ -102,7 +106,9 @@ async function walk(dir: string, out: string[]): Promise<void> { for (const e of entries) { if (SKIP_DIRS.has(e.name)) continue; const p = path.join(dir, e.name); - if (e.isDirectory()) await walk(p, out); + if (e.isDirectory()) { + if (!e.name.startsWith(".")) await walk(p, out); + } else if (/\.(?:ts|tsx|mjs|js)$/.test(e.name) && !/\.(?:test|spec|unit)\.|\.d\.m?ts$/.test(e.name)) out.push(p); } } @@ -224,6 +230,26 @@ const CALLERS: Record<string, Record<string, number>> = { downloadSubsForUrl: { "common/ytdlp/runYtdlp.ts": 1 }, }; +// yt-dlp's OPTION TABLES (lane network-exits): every option the installed +// yt-dlp's parser accepts, and a person's class of each — pure data, outside +// any function, read only by lib/networkExits.ts to RESOLVE a listing's argv +// as yt-dlp would (resolveLongOption, argvOptions). Nothing builds an argv +// from them, so a row naming a subtitle flag writes nothing. Only a table ROW +// outside every function passes: an argv element in these files, or a row +// moved into a function, is a site like any other. +const OPTION_TABLES: { file: string; row: RegExp; why: string }[] = [ + { + file: "common/lib/ytdlpOptions.ts", + row: /^\s*\[(?:null|"[^"]+"), "--[a-z0-9-]+", (?:true|false)\],$/, + why: "YTDLP_OPTIONS: [short, long, takes a value], generated from yt-dlp's parser", + }, + { + file: "common/lib/ytdlpOptionClasses.ts", + row: /^\s*"--[a-z0-9-]+": "(?:cookie|login|header|config|proxy|none)",$/, + why: "YTDLP_OPTION_CLASSES: the network-exit class of each long name", + }, +]; + const BUILDER_RES = Object.keys(CHAT_WRITERS).map((name) => ({ name, call: new RegExp(`\\b${name}\\s*\\(`, "g"), @@ -243,13 +269,16 @@ function enclosingFunction(lines: string[], i: number): string | null { test("every yt-dlp argv that can write the raw chat is a pinned builder, and every caller of one is pinned", async () => { const sites: string[] = []; const calls: Record<string, Record<string, number>> = {}; + const tableRows = new Set<string>(); for (const { rel, lines } of await appFiles()) { for (let i = 0; i < lines.length; i++) { const code = codeOnly(lines[i]); if (SUB_FLAGS.test(code)) { const fn = enclosingFunction(lines, i); const pinned = fn ? CHAT_WRITERS[fn] : undefined; - if (!pinned || pinned.file !== rel) sites.push(`${rel}:${i + 1} (in ${fn ?? "no function"}): ${lines[i].trim()}`); + const table = fn === null ? OPTION_TABLES.find((t) => t.file === rel && t.row.test(code)) : undefined; + if (table) tableRows.add(table.file); + else if (!pinned || pinned.file !== rel) sites.push(`${rel}:${i + 1} (in ${fn ?? "no function"}): ${lines[i].trim()}`); } for (const { name, call, def } of BUILDER_RES) { if (!code.includes(name)) continue; @@ -265,6 +294,14 @@ test("every yt-dlp argv that can write the raw chat is a pinned builder, and eve "for the stored chat first (listingHas / storedFormsIn), have a test that the fake yt-dlp is not asked for it, " + "and be listed in CHAT_WRITERS", ); + // The table exemption cannot rot, and holds only while the tables are read + // by the one argv RESOLVER: a new importer of either could build from them. + for (const t of OPTION_TABLES) assert.ok(tableRows.has(t.file), `${t.file} has no subtitle-flag row any more: drop it from OPTION_TABLES`); + const importers = new Set<string>(); + for (const { rel, lines } of await appFiles()) { + if (lines.some((l) => /\bfrom\s+["'][^"']*\/ytdlpOption(?:s|Classes)(?:\.[jt]s)?["']/.test(codeOnly(l)))) importers.add(rel); + } + assert.deepEqual([...importers], ["common/lib/networkExits.ts"], "yt-dlp's option tables are read by lib/networkExits.ts alone"); assert.deepEqual( calls, CALLERS, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -17,9 +17,14 @@ live (`liveRecording.autoRestartOnBoot`); ended, what is in staging lands; unreadable, nothing starts. - Parts that together hold more than the longest are joined `-c copy` when proven (length and sound at each join), the joins on the row and in `live-joins.json`; a gap is stated and needs a person. - - A recording already in the store is replaced only by one proven to hold it (the whole stream from its start, or a - proven join that includes it), and nothing is removed when nothing of a run was stored; the join's proof also - checks the picture. +- **A live recording's landing never deletes around, or replaces, a recording already in the store that it is not + proven to hold.** + - When the landing keeps the container already stored, nothing is removed: the part and every part meant for + removal stay, listed, and the run says "not landed" and needs a person. Before, those parts were deleted. + - A stored container is replaced only by a file that holds the whole stream from its start; a longer live-edge + part (after a restart) no longer replaces the stream's start. + - A live-edge part goes only when the landed file is as long as the ended stream's duration less a minute; an + index-0 part is never taken as inside a longer one. - **Network exits (trial): rumble and twitch listings through named proxies.** - New `settings.network`: exits `{id, label, scheme, host, port, credentials, enabled}` (`socks5h`, `socks5`, `http`, `https`), a policy per platform, cookie-jar pins, `credentialsFile` and `startupProbe`. Absent = every