Archilyzer · Source

archilyzer

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

commit 26561ac7f623fbbb42e7580ceb47d846c70903ca
parent d4c0f82d9c0f39acb7b4eff9c904b593e8a7f47e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 16:13:00 -0500

persist-videos below-height, review fixes: the proxy in one write, a newer record re-compares, a taller alternate is not fetched

- keptAs "proxy" is decided inside persistOverExisting (oldCopyAsProxy, set
  only by below-height through downloadOneManaged and finalizeAppExtraction)
  and written in the same pointer write as the alternate entry, when the
  download is measured taller. The second, unguarded write is gone, and with
  it markSavedAlternate.
- The same-preset rule applies only while the record's metadata.info.json is
  no newer than the copy (to the millisecond); a refresh since compares by
  height again. Every lower copy the rule leaves alone is said in the plan,
  with its heights.
- An alternate at or above the target is already here: the item is the new
  `tallerAlternate` bucket, named in the plan, never fetched and never made
  active, and out of willFetch.
- OPERATING.md says what video_720 gives (720, or the tallest listed format
  when lower); the prune's kept line names a proxy as one.

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

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 13+++++++++----
Mcommon/controller/persistVideos.test.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/controller/persistVideos.ts | 107++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mcommon/controller/pruneSavedVideos.ts | 12+++++++++++-
Mcommon/lib/savedVideo-server.ts | 30------------------------------
Mcommon/lib/savedVideoDropAlternate.test.ts | 34----------------------------------
Mcommon/ytdlp/downloadOneManaged.ts | 7+++++++
Mcommon/ytdlp/finalizeAppExtraction.ts | 4++++
Mcommon/ytdlp/savedAlternates.test.ts | 47++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/ytdlp/savedAlternates.ts | 21++++++++++++++++++++-
Meditor/CHANGELOG.md | 2+-
Meditor/app/api/ops/persist-videos/route.test.ts | 3++-
Meditor/app/api/ops/persist-videos/route.ts | 3++-
Meditor/app/saved-videos/components/PersistVideoListControl.tsx | 3++-
Mscripts/archilyzer-ops.mjs | 12+++++++-----
16 files changed, 299 insertions(+), 121 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -182,7 +182,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` | -| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality; "below-height" one whose height (recorded, else ffprobed) is below what that quality gives -- its ceiling, capped by the tallest format the record's metadata lists -- and keeps the old copy as its proxy ("keptAs": "proxy" on the alternate, once the new copy is taller); one that cannot be compared, or already downloaded at that quality, is left alone (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, lowerHeight, heightUnknown, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`) or kept as the proxy; nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | +| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality; "below-height" one whose height (recorded, else ffprobed) is below what that quality gives -- its ceiling, capped by the tallest format the record's metadata lists -- and keeps the old copy as its proxy ("keptAs": "proxy" on the alternate, once the new copy is taller); one that cannot be compared, with a taller alternate already beside it, or already downloaded at that quality (unless its metadata is newer than the copy) is left alone (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`) or kept as the proxy; nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | | `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. "archive" (items only) names the CONNECTED archive the items cite (settings.remoteArchives): a channel this editor does not hold is registered as a remote-only channel of it (config only, no listing; answered in "registered"; a dry run registers nothing), and a remote-only channel's page URL comes from the archive's record. Its window on a whole-recording platform is refused with the recording's estimated size unless "allowWholeRecording": true. Another origin registers nothing. A media URL's transient 403 (googlevideo's) is asked once more after a pause before it counts toward the two-403 stop. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (&lt;from&gt;-&lt;to&gt;.desynced.&lt;ext&gt;) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "&lt;its version, as you saw it&gt;", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -134,11 +134,16 @@ pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}] - Keep videos out of cleanup by title or description: `pnpm ops keep-videos --json '{"slug":"example","match":"interview","dryRun":true}'`. - A saved copy lower than you want (a 360p import of a VOD the source has at 1080p): `pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}],"format":"original","replace":"below-height","dryRun":true}'`. - It is in `lowerHeight` when its height (recorded, else read with ffprobe) is below what the quality gives: 720 for - `video_720`, the tallest format in its `metadata.info.json` for `original`. `heightUnknown` means it could not be - compared, and nothing is fetched for it. Run it without `dryRun`. The download becomes the active copy, and the old + It is in `lowerHeight` when its height (recorded, else read with ffprobe) is below what the quality gives. For + `original` that is the tallest format in its `metadata.info.json`. For `video_720` it is 720, or that tallest format + when it is lower (720 when the metadata lists none). `heightUnknown` means it could not be compared. + `tallerAlternate` means a copy at that height is already kept beside it; the plan names the file, and nothing makes + it active for you. Neither is fetched. Run it without `dryRun`. The download becomes the active copy, and the old one stays beside it as its proxy (`"keptAs": "proxy"` in `get saved-alternates`). Nothing is deleted. - `"above-height"` is the other way: it re-fetches a saved copy taller than `video_720`, or of unknown height. +- A lower copy already downloaded at the asked quality is left alone (the plan says so, with its heights): that is + what the quality gave. If its `metadata.info.json` is newer than the copy (`refresh-metadata` since), it is + compared again. +- `"above-height"` is the other way: it re-fetches a saved copy taller than `video_720`, or of unknown height. - A new caption download writes its `transcript.cues.json` as it lands (a umtool build reads it); `build-cues` mends an older one. diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; @@ -152,22 +152,28 @@ async function seedSaved( type Harness = { deps: Partial<PersistVideosDeps>; downloads: { slug: string; id: string; quality: string }[]; + // The ids whose download asked for the old copy to be kept as the proxy. + proxyAsked: string[]; sleeps: number[]; events: string[]; }; // The default harness: every channel exists, the gate is open, memory is // plentiful, and a download persists a 720p container named `file`. +// `oldHeights` is what finalizeAppExtraction's ffprobe reads of the copy +// already in the store (a landed one records no height of its own). function harness( paths: Paths, - over: Partial<PersistVideosDeps> & { file?: string; height?: number } = {}, + over: Partial<PersistVideosDeps> & { file?: string; height?: number; oldHeights?: Record<string, number> } = {}, ): Harness { const downloads: Harness["downloads"] = []; + const proxyAsked: string[] = []; const sleeps: number[] = []; const events: string[] = []; const download: PersistVideoDownload = async (o) => { const id = o.videoUrl.split("v=")[1]; downloads.push({ slug: o.channelSlug, id, quality: o.quality }); + if (o.oldCopyAsProxy) proxyAsked.push(id); events.push(`download ${id}`); const dir = videoDir(paths, o.channelSlug, id); const file = over.file ?? "source-media.mp4"; @@ -185,7 +191,14 @@ function harness( format: { preset: o.quality, height: over.height ?? 720 }, sourceFilename: file, explicitPersist: PERSIST_VIDEOS_DOWNLOAD.explicitPersist, - alternatesDeps: { measure: async () => null, height: async () => null }, + oldCopyAsProxy: o.oldCopyAsProxy, + alternatesDeps: { + measure: async () => null, + height: async (f) => { + const m = /^old (.+)$/.exec(await readFile(f, "utf8").catch(() => "")); + return (m && over.oldHeights?.[m[1]]) ?? null; + }, + }, onLog: () => {}, signal: o.signal, }); @@ -199,6 +212,7 @@ function harness( }; return { downloads, + proxyAsked, sleeps, events, deps: { @@ -637,13 +651,19 @@ test("below-height sorts saved copies: lower, equal, taller, probed, not compare await seedSaved(paths, S, "rec7201", { preset: "video_720", height: 720, formatHeights: tall }); // Equal: probed at the tallest the source offers. await seedSaved(paths, S, "equal11", { preset: null, requestedBy: "import-media", formatHeights: tall }); - // Downloaded at this very preset: what "original" gives, even though lower. + // Downloaded at this very preset, its metadata no newer than the copy: + // what "original" gave, even though lower (a re-run must converge). await seedSaved(paths, S, "same111", { preset: "original", height: 480, formatHeights: tall }); + // The same, but its metadata was refreshed AFTER the copy was stored: the + // source may have more now, so it is compared by height as usual. + await seedSaved(paths, S, "fresh11", { preset: "original", height: 480, formatHeights: tall }); + const later = new Date(Date.now() + 60_000); + await utimes(path.join(videoDir(paths, S, "fresh11"), "metadata.info.json"), later, later); // No formats in its metadata: what "original" gives is not known. await seedSaved(paths, S, "nofmt11", { preset: null, requestedBy: "import-media" }); // ffprobe cannot read it: not compared. await seedSaved(paths, S, "noprob1", { preset: null, requestedBy: "import-media", formatHeights: tall }); - const items = ["lower11", "rec7201", "equal11", "same111", "nofmt11", "noprob1"].map((id) => ({ slug: S, id })); + const items = ["lower11", "rec7201", "equal11", "same111", "fresh11", "nofmt11", "noprob1"].map((id) => ({ slug: S, id })); const calls: string[] = []; const h = harness(paths, { probeHeight: probeBy({ lower11: 360, equal11: 1080, nofmt11: 360 }, calls), @@ -660,15 +680,23 @@ test("below-height sorts saved copies: lower, equal, taller, probed, not compare }); assert.equal(h.downloads.length, 0); const ids = (b: { items: { id: string }[] }) => b.items.map((i) => i.id); - assert.deepEqual(ids(res.plan.lowerHeight), ["lower11", "rec7201"]); + assert.deepEqual(ids(res.plan.lowerHeight), ["lower11", "rec7201", "fresh11"]); assert.deepEqual(ids(res.plan.saved), ["equal11", "same111"]); assert.deepEqual(ids(res.plan.heightUnknown), ["nofmt11", "noprob1"]); assert.equal(res.plan.wrongHeight.count, 0); - assert.equal(res.plan.willFetch, 2); + assert.equal(res.plan.tallerAlternate.count, 0); + assert.equal(res.plan.willFetch, 3); // Only a pointer with no recorded height is probed. assert.deepEqual(calls.sort(), ["equal11", "lower11", "nofmt11", "noprob1"]); const text = lines.join(""); - assert.match(text, /2 saved below it \(to replace, the saved copy kept as a proxy\), 2 saved and not compared/); + assert.match(text, /3 saved below it \(to replace, the saved copy kept as a proxy\), 2 saved and not compared/); + // The same-preset rule says every copy it leaves alone, with its heights. + assert.match( + text, + /demo-channel\/same111: saved at 480p \(recorded\), below the 1080p its metadata lists, but it was downloaded at original and the metadata is not newer than the copy — left alone/, + ); + assert.doesNotMatch(text, /fresh11: saved at 480p \(recorded\), below the 1080p its metadata lists/); + assert.match(text, /demo-channel\/fresh11: saved at 480p \(recorded\), below the 1080p original gives\./); assert.match(text, /demo-channel\/lower11: saved at 360p \(probed\), below the 1080p original gives\./); assert.match(text, /demo-channel\/rec7201: saved at 720p \(recorded\), below the 1080p original gives\./); assert.match(text, /nofmt11: saved, not compared — its metadata\.info\.json lists no format heights/); @@ -685,7 +713,7 @@ test("below-height sorts saved copies: lower, equal, taller, probed, not compare dryRun: true, deps: { ...h.deps, probeHeight: probeBy({}, before) }, }); - assert.equal(other.plan.saved.count, 6, replace); + assert.equal(other.plan.saved.count, 7, replace); assert.equal(other.plan.lowerHeight.count, 0, replace); assert.equal(other.plan.heightUnknown.count, 0, replace); assert.equal(other.plan.willFetch, 0, replace); @@ -774,7 +802,11 @@ test("below-height makes the taller download active and keeps the lower copy bes }); const items = ["kickvod", "dl72011"].map((id) => ({ slug: S, id })); const oldKick = await loadSavedVideo(videoDir(paths, S, "kickvod")); - const h = harness(paths, { height: 1080, probeHeight: probeBy({ kickvod: 360 }) }); + const h = harness(paths, { + height: 1080, + probeHeight: probeBy({ kickvod: 360 }), + oldHeights: { kickvod: 360 }, + }); const lines: string[] = []; const res = await persistVideos({ paths, @@ -784,6 +816,8 @@ test("below-height makes the taller download active and keeps the lower copy bes onLog: (l) => lines.push(l), deps: h.deps, }); + // Only an upgrade asks the persist to keep the old copy as the proxy. + assert.deepEqual(h.proxyAsked, ["kickvod", "dl72011"]); assert.deepEqual(h.downloads, [ { slug: S, id: "kickvod", quality: "original" }, { slug: S, id: "dl72011", quality: "original" }, @@ -817,9 +851,7 @@ test("below-height makes the taller download active and keeps the lower copy bes const text = lines.join(""); assert.match(text, /kickvod: upgrading the saved 360p container \(original\)/); - // (The harness's ffprobe reads no height, so the alternate's name has none; - // in a real run finalizeAppExtraction probes the old copy and names it 360p.) - assert.match(text, /kickvod: now 1080p; the 360p copy stays beside it as source-media\.alt-\d{14}\.mp4, kept as its proxy\./); + assert.match(text, /kickvod: now 1080p; the 360p copy stays beside it as source-media\.alt-360p-\d{14}\.mp4, kept as its proxy\./); assert.match(text, /2 persisted \(2 replaced, 2 old copies kept as proxies\)/); // RE-RUNNING IS THE RESUME: both are now what "original" gives. @@ -844,7 +876,7 @@ test("below-height: a download that is not taller leaves both copies flagged for formatHeights: [360, 1080], }); // The source no longer gives more than 360p. - const h = harness(paths, { height: 360, probeHeight: probeBy({ lower11: 360 }) }); + const h = harness(paths, { height: 360, probeHeight: probeBy({ lower11: 360 }), oldHeights: { lower11: 360 } }); const lines: string[] = []; const res = await persistVideos({ paths, @@ -859,7 +891,7 @@ test("below-height: a download that is not taller leaves both copies flagged for const ptr = await loadSavedVideo(videoDir(paths, "demo-channel", "lower11")); assert.equal(ptr?.alternates?.length, 1); assert.equal(ptr?.alternates?.[0]?.keptAs, undefined); - assert.match(lines.join(""), /the download is 360p, not taller than 360p; .*flagged for a check \(not marked as a proxy\)/); + assert.match(lines.join(""), /the download is 360p, not measured taller than 360p; .*flagged for a check \(not marked as a proxy\)/); }); }); @@ -879,3 +911,61 @@ test("below-height leaves a saved copy above the ceiling alone (that is above-he assert.equal(res.plan.willFetch, 0); }); }); + +test("below-height does not fetch what is already here as a taller alternate, and does not make it active", async () => { + await withPaths(async (paths) => { + const S = "demo-channel"; + await seedSaved(paths, S, "hasalt1", { + preset: null, + requestedBy: "import-media", + formatHeights: [360, 1080], + }); + // A 1080p copy kept beside it earlier (an automatic download that was not + // longer), and a shorter 480p one. + const dir = videoDir(paths, S, "hasalt1"); + const pointerFile = path.join(dir, "saved-video.json"); + const raw = JSON.parse(await readFile(pointerFile, "utf8")); + raw.alternates = [ + { file: "source-media.alt-480p-20261101000000.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 480 }, + { file: "source-media.alt-1080p-20261102000000.mp4", bytes: 1, storedAt: "", setAsideAt: "", height: 1080 }, + ]; + await writeFile(pointerFile, JSON.stringify(raw)); + const before = await readFile(pointerFile, "utf8"); + const h = harness(paths, { probeHeight: probeBy({ hasalt1: 360 }) }); + const lines: string[] = []; + const res = await persistVideos({ + paths, + items: [{ slug: S, id: "hasalt1" }], + format: "original", + replace: "below-height", + onLog: (l) => lines.push(l), + deps: h.deps, + }); + assert.equal(h.downloads.length, 0); + assert.deepEqual(res.plan.tallerAlternate.items, [{ slug: S, id: "hasalt1" }]); + assert.equal(res.plan.lowerHeight.count, 0); + assert.equal(res.plan.willFetch, 0); + assert.deepEqual(res.replaced, []); + assert.match( + lines.join(""), + /demo-channel\/hasalt1: saved at 360p \(probed\), below the 1080p original gives, but a 1080p copy is already here as the alternate source-media\.alt-1080p-20261102000000\.mp4 \(not the active one\) — not fetched/, + ); + assert.match(lines.join(""), /1 with a taller alternate already here \(left alone\)/); + // Nothing is promoted: the pointer is byte for byte what it was. + assert.equal(await readFile(pointerFile, "utf8"), before); + + // An alternate below the target does not hold the upgrade back. + raw.alternates = raw.alternates.slice(0, 1); + await writeFile(pointerFile, JSON.stringify(raw)); + const dry = await persistVideos({ + paths, + items: [{ slug: S, id: "hasalt1" }], + format: "original", + replace: "below-height", + dryRun: true, + deps: h.deps, + }); + assert.equal(dry.plan.lowerHeight.count, 1); + assert.equal(dry.plan.willFetch, 1); + }); +}); diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts @@ -11,7 +11,6 @@ import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; import { savedVideoDir, savedVideoPath, type SavedVideoPointer } from "../lib/savedVideo"; import { loadSavedVideo, - markSavedAlternate, restoreSavedVideoProvenance, } from "../lib/savedVideo-server"; import { probeVideoHeight } from "../ytdlp/ffprobeDuration"; @@ -72,12 +71,18 @@ import { recordDownloadBackoff } from "../jobs/downloadBackoff"; // the pointer's (`format`, else `probed`), else an ffprobe of the stored file — // a landed import or attach records none. Not compared, and so not fetched // (`heightUnknown`): a height the probe could not read, or an "original" ask of -// a record whose metadata lists no format heights. A copy a download already -// made at the requested quality is what that quality gives, and is left alone -// (a re-fetch would bring the same file back on every re-run). The replace is -// the same as above-height's, and the old copy's alternate entry is then -// marked `keptAs: "proxy"` — kept on purpose, not for a check — once the new -// active copy is measured taller. Each policy re-fetches only its own bucket. +// a record whose metadata lists no format heights. Not fetched either +// (`tallerAlternate`): an alternate at or above the target is already in the +// store — it is named in the plan and NOT made active (a person's call). A +// lower copy a download already made at the requested quality is what that +// quality gave, and is left alone (a re-fetch would bring the same file back +// on every re-run) — unless the record's metadata.info.json was written after +// the copy was stored: a refresh since may list formats the source did not +// have then. Each such skip is said in the plan, with its heights. The replace +// is above-height's, asked with `oldCopyAsProxy`: persistOverExisting marks the +// old copy's alternate entry `keptAs: "proxy"` — kept on purpose, not for a +// check — in the same pointer write, when the download is measured taller. +// Each policy re-fetches only its own bucket. export type PersistVideoItem = { slug: string; id: string }; @@ -102,6 +107,9 @@ export type PersistVideosBucket = { count: number; items: PersistVideoItem[] }; // heightUnknown in the store, but whether it is below what the quality gives // could not be told (sorted only under "below-height"); never // fetched +// tallerAlternate in the store below what the quality gives, but an +// alternate copy at or above it is already there (sorted only +// under "below-height"); never fetched, never made active // toFetch not saved, with a resolvable source URL // noUrl not saved, and no source URL can be resolved // unknown no such channel, or no data/<id>/ for that video @@ -110,6 +118,7 @@ export type PersistVideosPlan = { wrongHeight: PersistVideosBucket; lowerHeight: PersistVideosBucket; heightUnknown: PersistVideosBucket; + tallerAlternate: PersistVideosBucket; toFetch: PersistVideosBucket; noUrl: PersistVideosBucket; unknown: PersistVideosBucket; @@ -153,6 +162,9 @@ export type PersistVideoDownload = (opts: { settings: SiteSettings; videoUrl: string; quality: SourceVideoQuality; + // "below-height": over the saved copy, keep it as the proxy when the + // download is taller (ManagedDownloadOpts.oldCopyAsProxy). + oldCopyAsProxy: boolean; onLog: (line: string) => void; signal: AbortSignal; }) => Promise<DownloadOutcomeRecord>; @@ -203,6 +215,7 @@ const defaultDownload: PersistVideoDownload = (o) => globalSkipLiveDownloads: o.settings.skipLiveDownloads, ...PERSIST_VIDEOS_DOWNLOAD, persistFormatPreset: o.quality, + ...(o.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), }); function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { @@ -287,13 +300,17 @@ export function tallestFormatHeight(meta: unknown): number | null { return tallest; } -async function readTallestFormatHeight(videoDir: string): Promise<number | null> { +// The record's metadata: the tallest video format it lists, and when the file +// was last written (null: no readable metadata.info.json). +async function readRecordFormats( + videoDir: string, +): Promise<{ tallest: number | null; mtimeMs: number | null }> { + const file = path.join(videoDir, "metadata.info.json"); try { - return tallestFormatHeight( - JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")), - ); + const [raw, st] = await Promise.all([readFile(file, "utf8"), stat(file)]); + return { tallest: tallestFormatHeight(JSON.parse(raw)), mtimeMs: st.mtimeMs }; } catch { - return null; + return { tallest: null, mtimeMs: null }; } } @@ -309,6 +326,10 @@ type PlannedItem = PersistVideoItem & { heightFrom?: "recorded" | "probed"; target?: number; why?: string; + // A lower copy left `saved` by the same-preset rule: the plan says so. + samePreset?: boolean; + // tallerAlternate: the alternate already here at or above the target. + alternate?: { file: string; height: number }; }; // "below-height" sorting of one saved copy. The saved copy's height is the @@ -319,7 +340,9 @@ async function classifyForUpgrade( pointer: SavedVideoPointer, quality: SourceVideoQuality, deps: PersistVideosDeps, -): Promise<Pick<PlannedItem, "bucket" | "height" | "heightFrom" | "target" | "why">> { +): Promise< + Pick<PlannedItem, "bucket" | "height" | "heightFrom" | "target" | "why" | "samePreset" | "alternate"> +> { const ceiling = sourceVideoQualityMaxHeight(quality); let height = pointer.format?.height ?? pointer.probed?.height; let heightFrom: PlannedItem["heightFrom"] = height !== undefined ? "recorded" : undefined; @@ -346,10 +369,9 @@ async function classifyForUpgrade( return { bucket: "wrongHeight", ...at }; } if (height === undefined) return { bucket: "heightUnknown", why: noHeight }; - // Already what this quality gives: a re-fetch would bring the same back. - if (pointer.format?.preset === quality) return { bucket: "saved", ...at }; - const tallest = await readTallestFormatHeight(videoDir); - const target = ceiling === null ? tallest : tallest === null ? ceiling : Math.min(ceiling, tallest); + const meta = await readRecordFormats(videoDir); + const target = + ceiling === null ? meta.tallest : meta.tallest === null ? ceiling : Math.min(ceiling, meta.tallest); if (target === null) { return { bucket: "heightUnknown", @@ -357,7 +379,28 @@ async function classifyForUpgrade( why: "its metadata.info.json lists no format heights, so what the original would give is not known", }; } - return { bucket: height < target ? "lowerHeight" : "saved", ...at, target }; + if (height >= target) return { bucket: "saved", ...at, target }; + // A TALLER COPY IS ALREADY HERE, as an alternate: not fetched again, and not + // made active either — that is a person's call. + const taller = (pointer.alternates ?? []) + .filter((a) => a.height !== undefined && a.height >= target) + .sort((a, b) => b.height! - a.height!)[0]; + if (taller) { + return { bucket: "tallerAlternate", ...at, target, alternate: { file: taller.file, height: taller.height! } }; + } + // ALREADY WHAT THIS QUALITY GAVE: a download at the requested preset brought + // this height, so a re-fetch would bring it back on every re-run — unless + // the record's metadata was written after the copy was stored (a refresh + // since may list formats the source did not have then). + const storedAtMs = Date.parse(pointer.storedAt); + if ( + pointer.format?.preset === quality && + // storedAt is to the millisecond; an mtime in that same millisecond is not newer. + !(meta.mtimeMs !== null && Number.isFinite(storedAtMs) && Math.floor(meta.mtimeMs) > storedAtMs) + ) { + return { bucket: "saved", ...at, target, samePreset: true }; + } + return { bucket: "lowerHeight", ...at, target }; } function emptyBucket(): PersistVideosBucket { @@ -441,6 +484,7 @@ function planOf( wrongHeight: emptyBucket(), lowerHeight: emptyBucket(), heightUnknown: emptyBucket(), + tallerAlternate: emptyBucket(), toFetch: emptyBucket(), noUrl: emptyBucket(), unknown: emptyBucket(), @@ -531,7 +575,8 @@ export async function persistVideos({ `requested height${replace === "above-height" ? " (to replace)" : " (left alone)"}, ` + (replace === "below-height" ? `${plan.lowerHeight.count} saved below it (to replace, the saved copy kept as a proxy), ` + - `${plan.heightUnknown.count} saved and not compared (left alone), ` + `${plan.heightUnknown.count} saved and not compared (left alone), ` + + `${plan.tallerAlternate.count} with a taller alternate already here (left alone), ` : "") + `${plan.noUrl.count} with no source URL, ${plan.unknown.count} unknown.`, ); @@ -545,6 +590,18 @@ export async function persistVideos({ ); } else if (p.bucket === "heightUnknown") { log(` ${label(p)}: saved, not compared — ${p.why}; left alone.`); + } else if (p.bucket === "tallerAlternate") { + log( + ` ${label(p)}: saved at ${p.height}p (${p.heightFrom}), below the ${p.target}p ${p.quality} gives, ` + + `but a ${p.alternate!.height}p copy is already here as the alternate ${p.alternate!.file} ` + + `(not the active one) — not fetched; making it active is a person's call.`, + ); + } else if (p.samePreset) { + log( + ` ${label(p)}: saved at ${p.height}p (${p.heightFrom}), below the ${p.target}p its metadata lists, ` + + `but it was downloaded at ${p.quality} and the metadata is not newer than the copy — left alone ` + + `(refresh its metadata to compare again).`, + ); } else if (replaces(p.bucket, replace) && !p.url) { log(` ${label(p)}: no resolvable source URL to replace it from, skipping.`); } @@ -653,6 +710,7 @@ export async function persistVideos({ settings, videoUrl: p.url!, quality, + oldCopyAsProxy: upgrading, onLog: downloadLog, signal: downloadSignal, }); @@ -689,12 +747,11 @@ export async function persistVideos({ if (p.pointer) { const kept = pointer.alternates?.find((a) => a.storedAt === p.pointer!.storedAt); if (kept && upgrading) { - // THE PROXY: the lower copy is kept on purpose — but only when the - // download really is taller. One that is not (the source no longer - // offers more) leaves both flagged for a check, as any replace does. + // THE PROXY: persistOverExisting marked the lower copy in the same + // pointer write, only when the download was measured taller. One that + // is not (the source no longer offers more) stays flagged for a check. const newHeight = pointer.format?.height ?? pointer.probed?.height; - if (newHeight !== undefined && newHeight > p.height!) { - await markSavedAlternate(videoDir, kept.file, "proxy"); + if (kept.keptAs === "proxy") { result.proxies.push({ slug: p.slug, id: p.id, file: kept.file }); log( ` ${label(p)}: now ${newHeight}p; the ${p.height}p copy stays beside it as ${kept.file}, ` + @@ -702,7 +759,7 @@ export async function persistVideos({ ); } else { log( - ` ${label(p)}: the download is ${newHeight !== undefined ? `${newHeight}p, not taller than ${p.height}p` : "of unknown height"}; ` + + ` ${label(p)}: the download is ${newHeight !== undefined ? `${newHeight}p, not measured taller than ${p.height}p` : "of unknown height"}; ` + `the old copy stays beside it as ${kept.file}, flagged for a check (not marked as a proxy).`, ); } diff --git a/common/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts @@ -65,10 +65,20 @@ export async function pruneSavedVideos({ if (await isDoNotClean(videoDir)) continue; // pinned -> keep forever // Two copies kept for a check (ytdlp/savedAlternates.ts): the prune never // removes a flagged alternate, so it leaves the whole video for the check. + // A proxy (`keptAs`) is held the same way; the line names it as one. if (pointer.alternates?.length) { + const n = pointer.alternates.length; + const proxies = pointer.alternates.filter((a) => a.keptAs === "proxy").length; + const flagged = n - proxies; + const what = proxies + ? ` (${[ + `${proxies} kept on purpose as the lower-quality proxy`, + ...(flagged ? [`${flagged} flagged for a check`] : []), + ].join(" and ")})` + : " flagged for a check"; log( `Kept saved video ${id} although it rolled out of the keep-latest window: ` + - `it holds ${pointer.alternates.length} alternate cop${pointer.alternates.length === 1 ? "y" : "ies"} flagged for a check.`, + `it holds ${n} alternate cop${n === 1 ? "y" : "ies"}${what}.`, ); continue; } diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts @@ -20,7 +20,6 @@ import { type SavedVideoFormat, type SavedVideoKeepReason, type SavedVideoAlternate, - type SavedAlternateKeptAs, type SavedVideoOrigin, type SavedVideoPointer, } from "./savedVideo"; @@ -195,35 +194,6 @@ export async function restoreSavedVideoProvenance( }); } -// SAY WHY ONE ALTERNATE IS KEPT (`keptAs`, savedVideo.ts): persist-videos' -// "below-height" marks the lower-quality copy a taller download replaced as -// its proxy. Rewritten from the pointer's RAW JSON under its file lock, as -// dropSavedAlternate does — every other key and entry stays as it was. Only the -// pointer in the data dir is written; the store is not touched. False (nothing -// written) when there is no pointer or it does not list `file`. -export async function markSavedAlternate( - videoDir: string, - file: string, - keptAs: SavedAlternateKeptAs, -): Promise<boolean> { - const pointerFile = savedVideoPointerPath(videoDir); - return withJsonFileLock(pointerFile, async () => { - const read = await readJsonFile(pointerFile); - if (!read.ok || !read.value || typeof read.value !== "object") return false; - const raw = { ...(read.value as Record<string, unknown>) }; - if (!Array.isArray(raw.alternates)) return false; - let found = false; - raw.alternates = raw.alternates.map((a: unknown) => { - if (!a || typeof a !== "object" || (a as { file?: unknown }).file !== file) return a; - found = true; - return { ...(a as Record<string, unknown>), keptAs }; - }); - if (!found) return false; - await writeJsonAtomic(pointerFile, raw); - return true; - }); -} - // Best-effort removal of a now-empty store dir (and its empty <slug> parent). async function pruneEmptyStoreDirs(storeDir: string): Promise<void> { await rm(storeDir, { recursive: false, force: true }).catch(() => {}); diff --git a/common/lib/savedVideoDropAlternate.test.ts b/common/lib/savedVideoDropAlternate.test.ts @@ -7,7 +7,6 @@ import type { Paths } from "./paths"; import { dropSavedAlternate, loadSavedVideo, - markSavedAlternate, SavedAlternateRefusal, savedVideoPointerPath, } from "./savedVideo-server"; @@ -166,36 +165,3 @@ test("the store's relocation marker holds a drop; a dry run is held too", async assert.deepEqual((await readdir(storeDir)).sort(), [ALT, ACTIVE].sort()); }); }); - -// markSavedAlternate (persist-videos "below-height"): the replaced lower copy -// is said to be kept on purpose as the proxy. One key on one entry; every -// other byte of the pointer stays; the store is not touched. -test("markSavedAlternate sets keptAs on the one listed entry and changes nothing else", async () => { - await withVideo([ALT, ALT2], async ({ videoDir, storeDir, pointer }) => { - assert.equal(await markSavedAlternate(videoDir, ALT2, "proxy"), true); - const expected = { - ...pointer, - alternates: (pointer.alternates as { file: string }[]).map((a) => - a.file === ALT2 ? { ...a, keptAs: "proxy" } : a, - ), - }; - assert.equal(await pointerText(videoDir), JSON.stringify(expected, null, 2) + "\n"); - const loaded = await loadSavedVideo(videoDir); - assert.equal(loaded?.alternates?.find((a) => a.file === ALT2)?.keptAs, "proxy"); - assert.equal(loaded?.alternates?.find((a) => a.file === ALT)?.keptAs, undefined); - assert.deepEqual((await readdir(storeDir)).sort(), [ALT, ALT2, ACTIVE].sort()); - // A name the pointer does not list, or the active copy, writes nothing. - const before = await pointerText(videoDir); - assert.equal(await markSavedAlternate(videoDir, "source-media.alt-9p-1.mp4", "proxy"), false); - assert.equal(await markSavedAlternate(videoDir, ACTIVE, "proxy"), false); - assert.equal(await pointerText(videoDir), before); - }); -}); - -test("markSavedAlternate with no pointer, or none listed, is false", async () => { - await withVideo([], async ({ videoDir }) => { - assert.equal(await markSavedAlternate(videoDir, ALT, "proxy"), false); - await rm(savedVideoPointerPath(videoDir)); - assert.equal(await markSavedAlternate(videoDir, ALT, "proxy"), false); - }); -}); diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -222,6 +222,10 @@ export type ManagedDownloadOpts = { // either way. Set by "Persist source video", persist-videos and the // whole-recording fetch; never by an automatic download. explicitPersist?: boolean; + // With explicitPersist, over a copy already in the store: mark the old copy + // `keptAs: "proxy"` when the download is taller (ytdlp/savedAlternates.ts). + // Set by persist-videos' "below-height" only. + oldCopyAsProxy?: boolean; // Per-run override of channelConfig.audioFormat for the extracted audio. audioFormatOverride?: AudioFormat; // Resolved yt-dlp `-f` download-format preset (override > channel > global), @@ -1666,6 +1670,7 @@ async function runManagedDownload( origin: opts.persistOrigin, format: persistedFormat(), explicitPersist: opts.explicitPersist, + oldCopyAsProxy: opts.oldCopyAsProxy, onLog: opts.onLog, signal: opts.signal, }); @@ -1805,6 +1810,7 @@ async function runManagedDownload( origin: opts.persistOrigin, format: persistedFormat(), explicitPersist: opts.explicitPersist, + oldCopyAsProxy: opts.oldCopyAsProxy, extractAudio: false, onLog: opts.onLog, signal: opts.signal, @@ -1827,6 +1833,7 @@ async function runManagedDownload( origin: opts.persistOrigin, format: persistedFormat(), explicitPersist: opts.explicitPersist, + oldCopyAsProxy: opts.oldCopyAsProxy, onLog: opts.onLog, signal: opts.signal, }); diff --git a/common/ytdlp/finalizeAppExtraction.ts b/common/ytdlp/finalizeAppExtraction.ts @@ -62,6 +62,9 @@ export async function finalizeAppExtraction(opts: { // A PERSON ASKED FOR THIS CONTAINER (ManagedDownloadOpts.explicitPersist): // over a copy already in the store, the download becomes the active one. explicitPersist?: boolean; + // Over a copy already in the store, keep the old one as the proxy when the + // download is taller (ManagedDownloadOpts.oldCopyAsProxy). + oldCopyAsProxy?: boolean; // Test seam: how the two copies are measured. Production passes none. alternatesDeps?: SavedAlternatesDeps; onLog: (s: string) => void; @@ -158,6 +161,7 @@ export async function finalizeAppExtraction(opts: { keepReason, origin: opts.origin, format: opts.format, + ...(opts.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), paths: opts.paths, deps: alternatesDeps, onLog: opts.onLog, diff --git a/common/ytdlp/savedAlternates.test.ts b/common/ytdlp/savedAlternates.test.ts @@ -116,7 +116,7 @@ async function seed( async function download( paths: Paths, dir: string, - opts: { explicit: boolean; seconds?: number; height?: number }, + opts: { explicit: boolean; seconds?: number; height?: number; oldCopyAsProxy?: boolean }, ): Promise<string> { await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", opts.seconds ?? 4696.479777, opts.height ?? 720)); const log: string[] = []; @@ -132,6 +132,7 @@ async function download( extractAudio: false, format: { preset: "video_720", height: opts.height ?? 720, vcodec: "avc1" }, explicitPersist: opts.explicit, + ...(opts.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), alternatesDeps: deps, onLog: (s) => void log.push(s), signal: new AbortController().signal, @@ -296,6 +297,22 @@ test("the inventory counts and lists alternates; the prune never removes one; dr }); }); +test("the prune keeps a video holding a proxy and names it as one (wording only)", async () => { + await withCorpus(async (paths) => { + const dir = await seed(paths, "vproxyp", { keepReason: "keep-latest" }); + await download(paths, dir, { explicit: true, height: 1080, oldCopyAsProxy: true }); + await writeFile(path.join(paths.channelsDir, SLUG, "config.json"), JSON.stringify(CONFIG)); + const lines: string[] = []; + const r = await pruneSavedVideos({ paths, channelSlug: SLUG, onLog: (l) => void lines.push(l) }); + assert.equal(r.pruned, 0); + assert.match( + lines.join("\n"), + /Kept saved video vproxyp .*: it holds 1 alternate copy \(1 kept on purpose as the lower-quality proxy\)\./, + ); + assert.doesNotMatch(lines.join("\n"), /flagged for a check/); + }); +}); + test("a persist that fails after the rename puts the old name back", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vfail", { landed: true }); @@ -311,6 +328,34 @@ test("a persist that fails after the rename puts the old name back", async () => }); }); +// persist-videos "below-height": the old copy is marked the proxy in the SAME +// pointer write that lists it — never by a second write that a crash or a +// throw could leave undone. +test("oldCopyAsProxy: a taller download marks the old copy keptAs proxy in the one pointer write; not taller, no mark", async () => { + await withCorpus(async (paths) => { + const dir = await seed(paths, "vprox01", { landed: true }); + const log = await download(paths, dir, { explicit: true, height: 1080, oldCopyAsProxy: true }); + assert.match(log, /stays as source-media\.alt-360p-20261023172312\.mp4\. Kept on purpose as the lower-quality proxy\.\n/); + const p = (await loadSavedVideo(dir))!; + assert.equal(p.alternates?.length, 1); + assert.equal(p.alternates![0]!.keptAs, "proxy"); + assert.equal(p.alternates![0]!.height, 360); + assert.equal(p.keepReason, "pin"); + + // The download is not taller: both kept, no mark, flagged for a check. + const dir2 = await seed(paths, "vprox02", { height: 720, requestedBy: "umtool" }); + const log2 = await download(paths, dir2, { explicit: true, height: 720, oldCopyAsProxy: true }); + assert.match(log2, /Not marked as a proxy \(the download is not measured taller\); flagged for a check\.\n/); + const p2 = (await loadSavedVideo(dir2))!; + assert.equal(p2.alternates?.[0]?.keptAs, undefined); + + // Without the option (any other explicit persist): never a proxy. + const dir3 = await seed(paths, "vprox03", { landed: true }); + await download(paths, dir3, { explicit: true, height: 1080 }); + assert.equal((await loadSavedVideo(dir3))!.alternates?.[0]?.keptAs, undefined); + }); +}); + test("alternate names: height when known, a numbered suffix on a clash", () => { assert.equal(alternateName("source-media.webm", null, NOW), "source-media.alt-20261023172312.webm"); assert.equal( diff --git a/common/ytdlp/savedAlternates.ts b/common/ytdlp/savedAlternates.ts @@ -26,6 +26,12 @@ // do-not-clean marker is not touched. Its `origin` is the // download's requester, else the old one's — never a // landed copy's, which now describes the alternate. +// a PROXY `oldCopyAsProxy` (persist-videos "below-height" only): +// when the download is measured TALLER than the copy it +// replaces, the old copy's entry carries `keptAs: "proxy"` +// — kept on purpose, not for a check — in the same pointer +// write as the rest. Not taller, or either height unknown: +// no mark, flagged for a check as any other. // // DROPPING ONE after the check (2026-10-29): `dropSavedAlternate` // (lib/savedVideo-server.ts) — `pnpm ops drop-saved-alternate`, or the video @@ -220,6 +226,8 @@ export async function persistOverExisting( keepReason?: SavedVideoKeepReason; origin?: SavedVideoOrigin; format?: SavedVideoFormat | null; + // Mark the old copy as the proxy when the download is taller (see top). + oldCopyAsProxy?: boolean; paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">; deps: SavedAlternatesDeps; onLog: (s: string) => void; @@ -250,6 +258,11 @@ export async function persistOverExisting( throw err; } const probed = probeOf(plan.newSeconds, plan.newHeight); + const proxy = + opts.oldCopyAsProxy === true && + plan.newHeight !== null && + plan.oldHeight !== null && + plan.newHeight > plan.oldHeight; pointer = { ...pointer, ...(probed ? { probed } : {}), @@ -265,6 +278,7 @@ export async function persistOverExisting( ...(old.format?.vcodec ? { vcodec: old.format.vcodec } : {}), ...(old.origin ? { origin: old.origin } : {}), ...(old.format?.preset ? { preset: old.format.preset } : {}), + ...(proxy ? { keptAs: "proxy" as const } : {}), }, ], }; @@ -273,7 +287,12 @@ export async function persistOverExisting( const why = plan.explicit ? "" : " (it is longer)"; opts.onLog( `Kept both copies: the download (${describe(plan.newHeight, plan.newSeconds)}) is now the active source${why}; ` + - `the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays as ${alt}. Flagged for a check.\n`, + `the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays as ${alt}. ` + + (proxy + ? "Kept on purpose as the lower-quality proxy.\n" + : opts.oldCopyAsProxy + ? "Not marked as a proxy (the download is not measured taller); flagged for a check.\n" + : "Flagged for a check.\n"), ); await flag(plan, alt, at); return pointer; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,7 +1,7 @@ # Changelog ## [Unreleased] -- **`persist-videos` can upgrade a saved copy that is lower than asked, and keeps the old one as its proxy.** `"replace": "below-height"` re-fetches a saved video whose height is below what the quality gives: 720 for `video_720`, or the tallest format its metadata lists for `original` (the lower of the two for `video_720`). A copy with no recorded height (an import or an attach) is measured with ffprobe first. The download becomes the active copy; the old one stays beside it, marked `"keptAs": "proxy"` once the new one is taller, and the video page, /saved-videos and `get saved-alternates` say it is the lower-quality copy kept on purpose. The dry run's new buckets are `lowerHeight` and `heightUnknown` (not compared: the height could not be read, or `original` with no format heights in the metadata). A copy already downloaded at that quality is left alone. "Save these videos" has a select for it in place of the checkbox. `"never"` stays the default, and `"above-height"` works as before. +- **`persist-videos` can upgrade a saved copy that is lower than asked, and keeps the old one as its proxy.** `"replace": "below-height"` re-fetches a saved video whose height is below what the quality gives: the tallest format its metadata lists for `original`; for `video_720`, 720 or that tallest format, whichever is lower. A copy with no recorded height (an import or an attach) is measured with ffprobe first. The download becomes the active copy; the old one stays beside it, marked `"keptAs": "proxy"` once the new one is taller, and the video page, /saved-videos and `get saved-alternates` say it is the lower-quality copy kept on purpose. The dry run's new buckets are `lowerHeight`, `heightUnknown` (not compared: the height could not be read, or `original` with no format heights in the metadata) and `tallerAlternate` (a copy at that height is already kept beside it; it is named, not fetched and not made active). A copy already downloaded at that quality is left alone, and the plan says so, unless its metadata is newer than the copy. "Save these videos" has a select for it in place of the checkbox. `"never"` stays the default, and `"above-height"` works as before. - **umtool: a picture-only post's read can become its screen, and a screen line can be read in your own voice.** `umtool posts screen <p> <item> add --from-read` (the post bench's "From its read") turns the script of a picture-only post into a screen: one line per line of the script, not checked, and with no speaker split out of a line. That screen *is* the post's read, so the thread read no longer reads the same words twice. `posts screen … record <id> <n> --recording <file>` (the bench's per-line Record / Stop / Keep) records one line as the read says it, with masked numbers and redacted words left out of what you read. It is kept as new takes: recorded, cleaned, and converted to the line's speaker's character's stock voice. None of them is picked. A line take is read only when you choose it, with the bench's per-line select or `set <id> take.<n>=<take>`. A choice follows its line when lines move, and is refused when the line's words or speaker changed. `--check-words` (CLI only) transcribes the recording first and refuses it if it says a number, a handle, an anonymous author's name or a redacted term. The lint flags every chosen take that was not heard this way. - **umtool: no preview plays a read the build refuses.** After a screen line is edited, removed, redacted or no longer read, the build refuses the old read. Play, Present (including the public payload), the card page and the post bench's player now refuse it too: they play the item silent and say why, until the read is made again. Present's public payload carries a post's screens the way the card draws them (masked, blurred speakers nameless), never the raw lines. - **umtool: no part of a read may say what the item's screens mask.** A build refuses a read in which any part says a number or e-mail one of the item's screens masks, or the words of a redacted line. That covers the post's own words, a context post and a screen line. Two recordings kept at the same moment never take the same file: a recorded take's name is now claimed with an exclusive create. diff --git a/editor/app/api/ops/persist-videos/route.test.ts b/editor/app/api/ops/persist-videos/route.test.ts @@ -22,7 +22,7 @@ const items = [ type Bucket = { count: number; items: { slug: string; id: string }[] }; type Plan = Record< - "saved" | "wrongHeight" | "lowerHeight" | "heightUnknown" | "toFetch" | "noUrl" | "unknown", + "saved" | "wrongHeight" | "lowerHeight" | "heightUnknown" | "tallerAlternate" | "toFetch" | "noUrl" | "unknown", Bucket > & { willFetch: number; @@ -45,6 +45,7 @@ test("persist-videos buckets a list in a dry run, and refuses a bad body and a l const upPlan = upgrade.body.plan as Plan; assert.deepEqual(upPlan.lowerHeight, { count: 0, items: [] }); assert.deepEqual(upPlan.heightUnknown, { count: 0, items: [] }); + assert.deepEqual(upPlan.tallerAlternate, { count: 0, items: [] }); assert.equal(upPlan.willFetch, 1); // Nothing to fetch is an answer, not a job. diff --git a/editor/app/api/ops/persist-videos/route.ts b/editor/app/api/ops/persist-videos/route.ts @@ -22,7 +22,8 @@ export const dynamic = "force-dynamic"; // // Persist specific videos, across channels, to the saved-video store: the // video page's "Persist source video" over a list. `plan` buckets every item — -// saved, wrongHeight, lowerHeight, heightUnknown, toFetch, noUrl, unknown — +// saved, wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, +// noUrl, unknown — // with counts and ids, and // `willFetch` is how many downloads a run makes. A real run starts one job per // channel with something to fetch, on that channel's download queue. diff --git a/editor/app/saved-videos/components/PersistVideoListControl.tsx b/editor/app/saved-videos/components/PersistVideoListControl.tsx @@ -94,7 +94,7 @@ export function PersistVideoListControl() { } const BUCKETS: { - key: "saved" | "toFetch" | "wrongHeight" | "lowerHeight" | "heightUnknown" | "noUrl" | "unknown"; + key: "saved" | "toFetch" | "wrongHeight" | "lowerHeight" | "heightUnknown" | "tallerAlternate" | "noUrl" | "unknown"; words: string; }[] = [ { key: "toFetch", words: "to download" }, @@ -102,6 +102,7 @@ const BUCKETS: { { key: "wrongHeight", words: "saved, but taller than asked or of unknown height" }, { key: "lowerHeight", words: "saved, but lower than that quality gives" }, { key: "heightUnknown", words: "saved, not compared (height, or the source's best, not known)" }, + { key: "tallerAlternate", words: "saved lower, but a taller copy is already kept beside it (not active; not fetched)" }, { key: "noUrl", words: "with no source address to download from" }, { key: "unknown", words: "not found (no such channel or video)" }, ]; diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1831,11 +1831,13 @@ export function usage() { ' that quality gives -- its ceiling, capped by the tallest format the', ' record\'s metadata lists -- and keeps the old copy as its proxy', ' ("keptAs": "proxy" on the alternate, once the new copy is taller); one', - ' that cannot be compared, or already downloaded at that quality, is left', - ' alone (default "never"). "gapMs" pauses between downloads (default the', - ' batch gap), "minFreeMemMb" waits for that much free memory before each.', - ' "dryRun": true answers with the buckets (saved, wrongHeight, lowerHeight,', - ' heightUnknown, toFetch, noUrl, unknown) and starts nothing. One job per', + ' that cannot be compared, with a taller alternate already beside it, or', + ' already downloaded at that quality (unless its metadata is newer than', + ' the copy) is left alone (default "never"). "gapMs" pauses between', + ' downloads (default the batch gap), "minFreeMemMb" waits for that much', + ' free memory before each. "dryRun": true answers with the buckets (saved,', + ' wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, noUrl,', + ' unknown) and starts nothing. One job per', " channel, on its download queue; a low disk or a rate limit stops it, and", " running the same body again resumes — saved videos are skipped. Over a", " copy already in the store (an import, an attach, a live recording or an",