Archilyzer · Source

archilyzer

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

commit c064a3daeb5b3fc0daefaee993bb425b23d60fce
parent fd78d4bfadf264f5d07296262c2418c089d57659
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 23:46:28 -0500

compaction re-review fixes: every-frame tiled comparison, exact drops, robust markers

From the re-review of fd78d4bfa (F1-F5 and the lows):

- F1. The after-verify drop names exactly what it means (`expect`: kind,
  sha256, file), checked under the pointer's lock; any mismatch refuses. A
  former original needs its own confirmFormerOriginal and the same gone/review
  rule (a review of the active copy that replaced it); no automatic step
  passes that flag, and a test scans every caller for it.
- F2. The whole-file comparison scores EVERY frame at 256 px (aspect kept),
  whole and in an 8x8 grid of tiles: a hard per-frame floor, the file's own
  mean - max(8 sd, 0.03), and a tile below 0.7 for more than 2 frames in a
  row. Measured on a good SVT-AV1 crf-36 copy of a 640x360 test pattern:
  lowest frame 0.996, lowest tile 0.949. Every listed defect fails (0.47 s of
  black, 3 black frames at a join, 2.5 s of noise, a 3% region for 3 s, a 1%
  region for 3 frames, one black frame). The pointer records the mean, spread,
  lowest frame and when, and the worst tile and when.
- F3. The marker records boot id, host, pid and the pid's start time, a token
  and the job; it is live only while all hold, its job runs and it is under
  72 h. Stale ones are swept at editor boot, at every run's start and beside
  an already compacted video; `compaction-markers` lists and clears them.
- F4. The marker is held through the swap, the re-check and the drop; the
  compaction's own drop passes its token.
- F5. The prune logs and goes on past a video it may not drop.
- Lows: an interrupted drop of any alternate is recorded (pendingDrops),
  listed and finished by asking again; the swap's compare-and-swap covers
  keepReason, origin and explicit; `get kept-originals` lists every pointer an
  older editor would mistreat, with a ROLLBACK note in the changelog and
  OPERATING.md.

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

Diffstat:
MCOMMANDS.md | 12++++++++++--
MOPERATING.md | 32+++++++++++++++++++++++++++++---
MSETTINGS.md | 12++++++++++--
Mcommon/controller/compactSavedVideos.test.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/compactSavedVideos.ts | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcommon/controller/pruneSavedVideos.test.ts | 19+++++++++++++++++++
Mcommon/controller/pruneSavedVideos.ts | 10+++++++++-
Mcommon/lib/compactMedia-server.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Acommon/lib/compactingMarker-server.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/compactingMarker.test.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideo-server.ts | 203++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Mcommon/lib/savedVideo.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/savedVideoCompaction.ts | 22++++++++++++++++++++--
Mcommon/lib/savedVideoOriginal.test.ts | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/CHANGELOG.md | 9+++++++++
Aeditor/app/api/ops/compaction-markers/route.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/api/ops/drop-saved-alternate/route.ts | 12+++++++++---
Aeditor/app/api/ops/kept-originals/route.ts | 27+++++++++++++++++++++++++++
Meditor/app/api/ops/review-compacted-original/route.ts | 6++++--
Meditor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx | 10++++++++--
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 4+++-
Meditor/app/saved-videos/compactActions.ts | 23+++++++++++++++++++++--
Meditor/instrumentation.ts | 20++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 27+++++++++++++++++++++++++--
Msettings.json.example | 4++++
25 files changed, 1272 insertions(+), 181 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -157,7 +157,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (&lt;id&gt;-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` | | `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | | | `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, every other stream and the chapters copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: a pin, an explicit persist, a requested or landed container -- never keep-latest, never persist-kept's override); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate) and is a DRY RUN unless "dryRun": false. A named video the selector would not pick is refused unless "belowThreshold": true (the refusal says how little it saves). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs, or why it is skipped. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true runs one whose last checks failed. One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | | -| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. | | +| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | +| `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | | | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | @@ -201,7 +202,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | -| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. | | +| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. A FORMER original ("former-original") needs its own "confirmFormerOriginal": true, and the same gone/review rule. | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | | `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` | | `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -&gt; {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | @@ -254,6 +255,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get storage | sites | workers | auto-queue | scheduler pnpm ops get saved-alternates [<slug>] pnpm ops get compaction-review [<slug>] + pnpm ops get kept-originals [<slug>] pnpm ops get services pnpm ops get x-session [<slug>] pnpm ops get x-run [<run id>] @@ -320,6 +322,12 @@ get compaction-review [<slug>] lists every compacted saved video and what availability and why, the original's entry, sizes, checks, the re-check, "watch" (both files and an smplayer command that plays them) and any "leftover" of an interrupted drop. +get kept-originals [<slug>] lists every saved video that keeps an original + ("keptAs": "original") or a former original ("former-original") beside + its active copy, or has a drop in flight (pendingDrops: a file the pointer + no longer lists, still on disk -- drop it again by name to finish). An + editor from before compaction would treat those as ordinary droppable + alternates: while this is not empty, do not roll the editor back past it. get sites lists every site: id, title, siteUrl, Pages project, audience, listed, search, publish policy, channels, citedChannels. (`get publish` is the status.) diff --git a/OPERATING.md b/OPERATING.md @@ -1143,8 +1143,16 @@ pnpm ops compact-saved-videos --json '{"items":[{"slug":"example","id":"<videoId pnpm ops get compaction-review # what each original waits for, and what to watch pnpm ops review-compacted-original --json '{"slug":"example","id":"<videoId>","note":"watched it"}' pnpm ops drop-saved-alternate --json '{"slug":"example","id":"<videoId>","file":"source-media.mp4","confirmOriginal":true}' +pnpm ops get kept-originals # every pointer keeping an original: read before any rollback +pnpm ops compaction-markers --json '{}' # the "being compacted" markers, live or stale +pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}}' ``` +- **ROLLBACK: do not roll the editor back past this release while any pointer keeps an original.** An editor built + from before compaction does not know `"keptAs": "original"` or `"former-original"`, and treats such a copy as an + ordinary alternate. Its prune and its drop would delete the only original. `pnpm ops get kept-originals` lists + every pointer that keeps one, and every drop in flight; when it is empty, a rollback is safe for these files. + - **What it does.** A saved container is re-encoded to AV1: SVT-AV1 preset 8, crf 36, a keyframe every 5 s, the source's height. Kick and Twitch above 30 fps go to 30. Every other stream of the source is copied bit for bit: every audio track, subtitles, data, attachments, and the chapters. The re-encode becomes the active copy under its @@ -1188,9 +1196,17 @@ pnpm ops drop-saved-alternate --json '{"slug":"example","id":"<videoId>","file": the source does not have, and the picture's start against the sound's as in the source; - the audio packets identical (bytes, and times to the millisecond); - every other stream and the chapters present (`checks.streams`); - - THE WHOLE FILE compared: both copies decoded at 2 frames a second, 64 px, grey, frames paired by time; no tick - below `wholeFileSsimMin` (0.9), the mean at least `wholeFileSsimMean` (0.97), and the comparison reaching the - end. The lowest score and where it is go in the pointer; + - THE WHOLE FILE compared, EVERY FRAME. Both copies are decoded end to end, the source taken to the copy's rate + as the encode took it, at 256 px wide, grey, paired frame for frame. The comparison must cover every frame of + the copy. Each frame is scored whole: + - no frame below `wholeFileSsimMin` (0.9); + - a mean of at least `wholeFileSsimMean` (0.97); + - no frame below the file's own mean − max(`wholeFileSigmaK` (8) × its spread, `wholeFileSigmaMargin` (0.03)). + + Each frame is also split into an 8×8 grid of tiles, each scored alone: a tile below `wholeFileTileMin` (0.7) + for more than `wholeFileTileRunFrames` (2) frames in a row fails, so a small region changed for 3 frames at 30 + fps does not average away. The pointer records the mean, the spread, the lowest frame and when, and the worst + tile and when. It costs about 1.3–1.6× a plain decode of both files; - VMAF on 2-second excerpts across every chunk join, inside every chunk, and at `qualitySamples` (12) more spread through the file: mean at least `vmafMinMean` (90), none below `vmafMinSample` (85). SSIM where this ffmpeg has no libvmaf. Frames are paired by number on one clock; @@ -1213,6 +1229,16 @@ pnpm ops drop-saved-alternate --json '{"slug":"example","id":"<videoId>","file": included, and the original waits in `get compaction-review` (and on /saved-videos) as "compacted, original awaiting review". The log says what refreshes it: Check availability on the channel page's Diagnostics. **There is no backup of the store: after a drop the compacted copy is the only copy.** +- **A former original** (`"keptAs": "former-original"`: an original whose compacted copy a later persist, attach or + import replaced) is dropped only with its own `"confirmFormerOriginal": true`. It follows the same gone/review rule + as an original: `review-compacted-original` with `"formerOriginal": "<file>"` reviews the active copy that replaced + it. No automatic step ever passes that flag, and the after-verify drop names exactly the original it means (kind, + sha256, file), so a copy re-labelled in between is not dropped. +- **The marker.** `<store dir>/.compacting.json` is held from the start of a compaction through the swap, the + re-check and the drop. It is live only on this machine's current boot and host, with the same pid and pid start + time, its job still running, and under 72 h old. Anything else is stale and ignored. Stale markers are removed at + editor boot, at the start of every compaction run, when the video is skipped as already compacted, and by + `compaction-markers {"clear": …}`. A refusal by one video never stops a batch: the prune logs it and goes on. - **A review.** `get compaction-review` gives each video's two files and an `smplayer` command that plays both. The editor has no player for the store. Watch them, then record the review (the video page's **Review the compacted copy**, or `review-compacted-original`). A review names the copy it watched (`forSha256`) and counts for that copy diff --git a/SETTINGS.md b/SETTINGS.md @@ -647,8 +647,12 @@ Compacting a saved video (`pnpm ops compact-saved-videos`, controller/compactSav | `vmafMinSample` | `85` | The VMAF no single excerpt may fall below. Default 85. | | `ssimMinMean` | `0.95` | Without libvmaf: the SSIM the excerpts' mean must reach. Default 0.95. | | `ssimMinSample` | `0.9` | Without libvmaf: the SSIM no excerpt may fall below. Default 0.9. | -| `wholeFileSsimMin` | `0.9` | THE WHOLE-FILE COMPARISON: both copies decoded at 2 frames a second, 64 px wide, grey, frames paired by their time, and compared one by one (SSIM). No frame may fall below this. Default 0.9 (a good copy scores about 0.99; a black or misplaced stretch of a test pattern 0.5–0.8). | -| `wholeFileSsimMean` | `0.97` | The whole-file comparison's mean SSIM must reach this. Default 0.97. | +| `wholeFileSsimMin` | `0.9` | THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0). | +| `wholeFileSsimMean` | `0.97` | The whole-file comparison's mean must reach this. Default 0.97. | +| `wholeFileSigmaK` | `8` | The floor relative to the file itself: no frame below its mean − max(k × the frames' standard deviation, wholeFileSigmaMargin). Default k = 8 (measured: a good crf-36 copy has a spread of 0.0006, its worst frame 3 spreads under its mean). | +| `wholeFileSigmaMargin` | `0.03` | The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03. | +| `wholeFileTileMin` | `0.7` | Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46). | +| `wholeFileTileRunFrames` | `2` | How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails. | | `availabilityMaxAgeDays` | `7` | How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7. | | `dropOriginal` | `"keep"` | "keep" (the default in this slice): every original stays until a person drops it. "after-verify": once every check passed and the pointer names the compacted copy, a separate step reads that copy back from disk (size, sha256, container, length) and then drops the original — except for a video gone from its platform (availability not public or unlisted, or unknown), whose original waits for a person's review (`get compaction-review`, `review-compacted-original`, then `drop-saved-alternate` with `confirmOriginal`); only when the verification included the whole-file comparison. There is no backup of the store: after such a drop the compacted copy is the only copy. | @@ -678,6 +682,10 @@ Default: "ssimMinSample": 0.9, "wholeFileSsimMin": 0.9, "wholeFileSsimMean": 0.97, + "wholeFileSigmaK": 8, + "wholeFileSigmaMargin": 0.03, + "wholeFileTileMin": 0.7, + "wholeFileTileRunFrames": 2, "availabilityMaxAgeDays": 7, "dropOriginal": "keep" } diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts @@ -10,6 +10,8 @@ import { compactOne, compactSavedVideos, listCompactionReview, + listKeptOriginals, + sweepCompactingMarkers, planCompaction, type CompactDeps, type Presence, @@ -23,7 +25,7 @@ import { type EncodeSettings, } from "../lib/compactMedia-server"; import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, type SavedVideoCompactionSettings } from "../lib/savedVideoCompaction"; -import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, savedVideoPointerPath } from "../lib/savedVideo-server"; +import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, restoreSavedVideoProvenance, savedVideoPointerPath } from "../lib/savedVideo-server"; import { compactedOriginalOf, savedVideoPath } from "../lib/savedVideo"; import { keepDownloadAsAlternate, planSavedContainer } from "../ytdlp/savedAlternates"; import { CLOCK_FILE, CLOCK_VERSION } from "../lib/recordingClock.mjs"; @@ -54,14 +56,14 @@ const NO_SVT = NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1"); const ORIGINAL = "source-media.mp4"; -type Gen = { gen?: string; seconds?: number; fps?: number; gop?: number; offset?: number; ext?: string; bf?: number }; +type Gen = { gen?: string; seconds?: number; fps?: number; gop?: number; offset?: number; ext?: string; bf?: number; size?: string }; async function makeSource(file: string, g: Gen = {}): Promise<void> { const seconds = g.seconds ?? 6; const fps = g.fps ?? 60; await execa("ffmpeg", [ "-nostdin", "-v", "error", "-y", - "-f", "lavfi", "-i", `${g.gen ?? "testsrc"}=size=320x180:rate=${fps}:duration=${seconds}`, + "-f", "lavfi", "-i", `${g.gen ?? "testsrc"}=size=${g.size ?? "320x180"}:rate=${fps}:duration=${seconds}`, "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, "-c:v", "libx264", "-preset", g.bf ? "veryfast" : "ultrafast", ...(g.bf ? ["-bf", String(g.bf)] : []), "-g", String(g.gop ?? fps * 2), "-keyint_min", String(g.gop ?? fps * 2), "-sc_threshold", "0", "-pix_fmt", "yuv420p", @@ -162,10 +164,15 @@ const SETTINGS: SavedVideoCompactionSettings = { }; // x264 in SVT-AV1's place: the same seek, end, frame-rate handling and clock. -async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }, crf = 18): Promise<void> { +async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }, crf = 18, defect?: string): Promise<void> { const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); const i = args.indexOf("libsvtav1"); args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", String(crf)); + if (defect) { + const v = args.indexOf("-vf"); + if (v >= 0) args[v + 1] = `${args[v + 1]},${defect}`; + else args.splice(args.indexOf("-c:v"), 0, "-vf", defect); + } await execa("ffmpeg", args); } @@ -270,7 +277,7 @@ test("probe 1: a black chunk, or a chunk of the wrong seconds, fails the whole-f }), ); assert.equal(r.status, "failed", variant); - assert.match((r as { reason: string }).reason, /whole-file comparison scores/, variant); + assert.match((r as { reason: string }).reason, /the whole-file comparison: /, variant); assert.equal(await fx.pointerText(), before); await stat(fx.source); }); @@ -813,6 +820,123 @@ test("each chunk goes through the heavy slot's gate with its estimate, niced", { assert.equal(chunks.length, 3); for (const a of chunks) assert.deepEqual(a.slice(0, 7), ["--heavy", "--estimate", "1500", "--", "nice", "-n", "10"]); assert.ok(runs.some((a) => a.includes("-xerror")), "the full decode"); - assert.ok(runs.some((a) => a.some((x) => /wholefile-ssim/.test(x))), "the whole-file comparison"); + assert.ok(runs.some((a) => a.some((x) => /wf-graph/.test(x))), "the whole-file comparison"); + }); +}); + +// --- review round 2 ------------------------------------------------------------ + +// F2: the defects the first whole-file comparison passed, on the DEFAULT +// thresholds, every check real (the reviewer's set: 0.47 s of black between +// two ticks, 3 black frames at a chunk join, 2.5 s of heavy noise, a ~3% +// region changed for 3 s), and the smaller ones the tiles now catch. +test("F2: every listed defect fails the whole-file comparison on the default thresholds", { skip: NO_TOOLS }, async () => { + const defects: [string, (c: ChunkPlan) => string | undefined][] = [ + ["0.47 s of black", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='between(t,1.1,1.57)'" : undefined)], + ["3 black frames at a join", (c) => (c.index === 0 ? `drawbox=c=black:t=fill:enable='gte(n,${c.expectedFrames - 3})'` : undefined)], + ["2.5 s of heavy noise", (c) => (c.index === 1 ? "noise=alls=60:allf=t:enable='between(t,0.5,3)'" : undefined)], + ["a 3% region for 3 s", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=110:h=63:c=red:t=fill:enable='between(t,0.5,3.5)'" : undefined)], + ["a 1% region for 3 frames", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=64:h=36:c=red:t=fill:enable='between(n,30,32)'" : undefined)], + ["one black frame", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='eq(n,40)'" : undefined)], + ]; + for (const [label, defect] of defects) { + await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => { + const before = await fx.pointerText(); + const r = await run(fx, flowDeps({ encodeChunk: (o) => x264Chunk(o, 18, defect(o.chunk)) }), { ...SETTINGS, chunkMinutes: 4 / 60 }); + assert.equal(r.status, "failed", label); + assert.match((r as { reason: string }).reason, /verification failed: the whole-file comparison: /, label); + assert.equal(await fx.pointerText(), before, label); + await stat(fx.source); + }); + } +}); + +test("F2: a GOOD SVT-AV1 crf-36 encode of a detailed 640x360 fixture passes every default threshold, with margin", { skip: NO_SVT }, async () => { + await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 6, fps: 30, gop: 60 } }, async (fx) => { + const log = logger(); + const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3 }; + const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const w = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.wholeFile!; + assert.equal(w.frames, 180); + assert.equal(w.grid, 8); + // The margins the defaults keep over a good copy (measured 0.996 / 0.949). + assert.ok(w.min >= settings.wholeFileSsimMin + 0.05, JSON.stringify(w)); + assert.ok(w.min >= w.relativeFloor! + 0.01, JSON.stringify(w)); + assert.ok(w.worstTile && w.worstTile.min >= settings.wholeFileTileMin + 0.1 && w.worstTile.longestBelow === 0, JSON.stringify(w)); + }); +}); + +test("F3: a stale marker beside an already compacted video is cleared, and every run sweeps the store", { skip: NO_TOOLS }, async () => { + await withVideo({}, async (fx) => { + const r1 = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }); + assert.equal(r1.status, "compacted"); + // The state a crash between the swap and the marker's removal leaves. + const marker = path.join(fx.storeDir, ".compacting.json"); + await writeFile(marker, JSON.stringify({ pid: 2 ** 22 + 7, host: "x", startedAt: "2026-11-01T00:00:00Z", token: "t" })); + const log = logger(); + const r2 = await run(fx, flowDeps(), SETTINGS, log.onLog); + assert.equal(r2.status, "skipped"); + await assert.rejects(stat(marker)); + assert.ok(log.lines.some((l) => /a stale compaction marker removed/.test(l)), log.lines.join("\n")); + await writeFile(marker, JSON.stringify({ pid: 2 ** 22 + 7, host: "x", startedAt: "2026-11-01T00:00:00Z", token: "t" })); + const swept = await sweepCompactingMarkers(fx.paths); + assert.deepEqual(swept.map((x) => [x.id, x.cleared]), [["v1", true]]); + await assert.rejects(stat(marker)); + }); +}); + +test("F4: the marker is held through the swap, the re-check and the drop; a persist in that window is refused", { skip: NO_TOOLS }, async () => { + await withVideo({}, async (fx) => { + let calls = 0; + let during = ""; + const r = await run( + fx, + flowDeps({ + presence: async () => { + // The second call is afterSwap's, just before the drop. + if (++calls === 2) { + const dl = path.join(fx.videoDir, "source-media.webm"); + await writeFile(dl, "a download"); + during = await persistSourceVideo({ videoDir: fx.videoDir, sourceFilename: "source-media.webm", storeDir: fx.storeDir, paths: fx.paths }).then( + () => "went through", + (e) => (e as Error).name, + ); + } + return ON; + }, + }), + ); + assert.equal(during, "CompactionInProgressError"); + assert.equal(r.status, "compacted"); + assert.equal((r as { dropped: boolean }).dropped, true, "the compaction's own drop passes its marker"); + await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json")), "released at the very end"); + }); +}); + +test("the swap's compare-and-swap covers keepReason, origin and explicit", { skip: NO_TOOLS }, async () => { + await withVideo({}, async (fx) => { + const r = await run( + fx, + flowDeps({ + encodeChunk: async (o) => { + await x264Chunk(o); + if (o.chunk.index === 1) await restoreSavedVideoProvenance(fx.videoDir, { keepReason: "keep-latest" }); + }, + }), + ); + assert.equal(r.status, "failed"); + assert.match((r as { reason: string }).reason, /the saved copy changed while it was being compacted/); + assert.equal((await loadSavedVideo(fx.videoDir))!.file, ORIGINAL); + }); +}); + +test("kept-originals lists every pointer that keeps an original (what a rollback would mistreat)", { skip: NO_TOOLS }, async () => { + await withVideo({}, async (fx) => { + assert.deepEqual(await listKeptOriginals({ paths: fx.paths }), []); + await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }); + const rows = await listKeptOriginals({ paths: fx.paths }); + assert.equal(rows.length, 1); + assert.deepEqual(rows[0].kept.map((k) => [k.file, k.keptAs, k.sha256]), [[ORIGINAL, "original", fx.sourceSha]]); }); }); diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts @@ -44,7 +44,6 @@ import path from "node:path"; import { createReadStream } from "node:fs"; import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; -import { hostname } from "node:os"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Availability } from "../lib/availability"; @@ -55,6 +54,7 @@ import { detectPlatform } from "../lib/platform"; import { compactedLine, compactedOriginalOf, + parseSavedVideoPointer, reviewIsCurrent, savedVideoPath, type SavedVideoAlternate, @@ -63,7 +63,6 @@ import { type SavedVideoPointer, } from "../lib/savedVideo"; import { - COMPACTING_MARKER_FILENAME, SavedAlternateRefusal, dropSavedAlternate, fsyncFileAndDir, @@ -96,7 +95,7 @@ import { import { CHUNK_ESTIMATE_MB, CHUNK_EXT, - WHOLE_FILE_FPS, + WHOLE_FILE_GRID, WHOLE_FILE_WIDTH, audioPacketsHash, compareCuts, @@ -123,7 +122,10 @@ import { type EncodeSettings, type PacketScan, type SourceProbe, + type WholeFileComparison, + judgeWholeFile, } from "../lib/compactMedia-server"; +import { clearCompactingMarker, readCompactingMarker, writeCompactingMarker } from "../lib/compactingMarker-server"; import { planRecordingClock, measureRecordingClock, recordingClockSidecar } from "../lib/recordingClock-server"; import { clockOffsetAt, type RecordingClock } from "../lib/recordingClock.mjs"; import "../lib/childKillGuard"; @@ -161,7 +163,7 @@ export type CompactDeps = { fullDecode?: (file: string, signal?: AbortSignal) => Promise<{ ok: boolean; why?: string }>; audioHash?: (file: string, signal?: AbortSignal) => Promise<AudioHash>; inventory?: (file: string, skipIndex: number) => Promise<string[]>; - wholeFile?: (o: { compacted: string; source: string; scratchDir: string; signal?: AbortSignal }) => Promise<number[]>; + wholeFile?: (o: Parameters<typeof compareWholeFile>[1]) => Promise<WholeFileComparison>; hasVmaf?: () => Promise<boolean>; score?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; sourceFps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>; cutCompare?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<CutComparison>; @@ -529,6 +531,8 @@ function maxGap(pts: Float64Array): number { export type CompactRunOptions = { paths: Paths; + // The job this run is (its marker names it; the registry is asked). + jobId?: string; settings: SavedVideoCompactionSettings; onLog: (line: string) => void; signal?: AbortSignal; @@ -551,19 +555,52 @@ export async function compactOne( deps, }); if (!planned.compact || !planned.pointer || !planned.probe) { + // A stale marker beside a video that is not compacted now (an already + // compacted one after a crash between the swap and the marker's + // removal) is cleared here, so it never blocks the video. + if (planned.pointer) { + const c = await clearCompactingMarker(planned.pointer.dir).catch(() => null); + if (c?.cleared) log(`${opts.item.slug}/${opts.item.id}: a stale compaction marker removed (${c.why}).`); + } log(planned.line); return { status: "skipped", reason: planned.reason ?? "not a candidate" }; } - const marker = path.join(planned.pointer.dir, COMPACTING_MARKER_FILENAME); await assertSavedVideosStoreWritable(opts.paths, planned.pointer.dir); - // THE MARKER every persist of this video reads (savedVideo-server.ts - // assertNotCompacting): written before anything else, removed at the end. - await writeJsonAtomic(marker, { pid: process.pid, host: hostname(), startedAt: deps.now().toISOString(), video: `${opts.item.slug}/${opts.item.id}` }); + const existing = await readCompactingMarker(planned.pointer.dir); + if (existing) { + const c = await clearCompactingMarker(planned.pointer.dir); + if (!c.cleared) return { status: "skipped", reason: `another compaction of this video is running (${c.why})` }; + log(`${opts.item.slug}/${opts.item.id}: a stale compaction marker removed (${c.why}).`); + } + // THE MARKER every persist, attach, import, unpersist and drop of this + // video reads (lib/compactingMarker-server.ts): written before anything + // else, HELD through the swap, the re-check and the drop (review F4), and + // removed only at the very end. The compaction's own steps pass its token. + const marker = await writeCompactingMarker(planned.pointer.dir, { + ...(opts.jobId ? { jobId: opts.jobId } : {}), + video: `${opts.item.slug}/${opts.item.id}`, + now: deps.now(), + }); try { - return await compactPlanned(opts, deps, planned, log, () => rm(marker, { force: true })); + return await compactPlanned(opts, deps, planned, log, marker.token); } finally { - await rm(marker, { force: true }).catch(() => {}); + await clearCompactingMarker(planned.pointer.dir, { token: marker.token }).catch(() => {}); + } +} + +// EVERY STALE MARKER IN THE STORE removed (lib/compactingMarker-server.ts +// says what stale is): at editor boot and at the start of every compaction +// run. Answers what it found. +export async function sweepCompactingMarkers(paths: Paths, onLog?: (l: string) => void): Promise<{ slug: string; id: string; cleared: boolean; why: string }[]> { + const out: { slug: string; id: string; cleared: boolean; why: string }[] = []; + for (const e of await listSavedVideos({ paths }).catch(() => [])) { + const m = await readCompactingMarker(e.pointer.dir).catch(() => null); + if (!m) continue; + const c = await clearCompactingMarker(e.pointer.dir).catch((err) => ({ cleared: false, why: (err as Error).message })); + out.push({ slug: e.slug, id: e.videoId, ...c }); + if (c.cleared) onLog?.(`${e.slug}/${e.videoId}: a stale compaction marker removed (${c.why}).\n`); } + return out; } async function compactPlanned( @@ -571,9 +608,8 @@ async function compactPlanned( deps: Required<CompactDeps>, planned: Awaited<ReturnType<typeof planOne>>, log: (s: string) => void, - // The compaction itself is done once the swap is written: the marker goes - // then, so the drop step (which refuses while one is there) can run. - releaseMarker: () => Promise<void>, + // The marker's token: the drop step passes it (the marker is still held). + markerToken: string, ): Promise<CompactOneResult> { const { settings: s, signal } = opts; const tag = `${opts.item.slug}/${opts.item.id}`; @@ -800,6 +836,8 @@ async function compactPlanned( raw.bytes !== pointer.bytes || raw.dir !== pointer.dir || raw.storedAt !== pointer.storedAt || + // …and is still kept for the same reason, by the same request. + !sameProvenance(raw, pointer) || (raw.sha256 !== undefined && raw.sha256 !== sourceSha) || raw.compacted !== undefined ) { @@ -855,10 +893,9 @@ async function compactPlanned( `the original is kept as ${pointer.file} until it is dropped.`, ); await rm(scratch, { recursive: true, force: true }); - await releaseMarker(); // ---- 7 and 8: the recheck, then the drop — each its own step ---- - const after = await afterSwap({ paths: opts.paths, videoDir, item: opts.item, settings: s, deps, log, tag, signal }); + const after = await afterSwap({ paths: opts.paths, videoDir, item: opts.item, settings: s, deps, log, tag, signal, markerToken }); return { status: "compacted", line: `compacted ${tag}`, pointer: (await loadSavedVideo(videoDir))!, ...after }; } catch (err) { if (swapped) { @@ -905,6 +942,16 @@ async function compactPlanned( } } +function sameProvenance(raw: Record<string, unknown>, pointer: SavedVideoPointer): boolean { + const now = parseSavedVideoPointer(raw); + return ( + !!now && + now.keepReason === pointer.keepReason && + now.explicit === pointer.explicit && + JSON.stringify(now.origin ?? null) === JSON.stringify(pointer.origin ?? null) + ); +} + // The excerpt seconds (relative to the file's start) on the copy's frame grid, // a quarter frame early: a seek lands on the same picture in both files. function onGrid(t: number, fps: number): number { @@ -1001,34 +1048,60 @@ async function verify(o: { fail(`the re-encode does not carry every stream of the source (source: ${srcInv.join(", ") || "none"}; copy: ${outInv.join(", ") || "none"})`); } - // THE WHOLE FILE, compared. - log(`${tag}: comparing the whole file at ${WHOLE_FILE_FPS} frames a second…`); - const ticks = await deps.wholeFile({ compacted: o.muxed, source: o.src, scratchDir: o.scratch, signal }); - const expectTicks = Math.floor(srcSeconds * WHOLE_FILE_FPS); - const wMean = ticks.reduce((x, y) => x + y, 0) / Math.max(1, ticks.length); - let worst = 0; - for (let i = 1; i < ticks.length; i += 1) if (ticks[i] < ticks[worst]) worst = i; + // THE WHOLE FILE, compared EVERY FRAME, whole and tile by tile. + log(`${tag}: comparing the whole file, every frame, at ${WHOLE_FILE_WIDTH} px in a ${WHOLE_FILE_GRID}×${WHOLE_FILE_GRID} grid…`); + const cmp = await deps.wholeFile({ + compacted: o.muxed, + source: o.src, + scratchDir: o.scratch, + fps: o.fps, + sourceFps: o.probe.fps, + sourceWidth: o.probe.width, + sourceHeight: o.probe.height, + tileFloor: s.wholeFileTileMin, + signal, + }); + const v = judgeWholeFile(cmp, { + minFrame: s.wholeFileSsimMin, + meanFloor: s.wholeFileSsimMean, + sigmaK: s.wholeFileSigmaK, + sigmaMinMargin: s.wholeFileSigmaMargin, + tileRunFrames: s.wholeFileTileRunFrames, + expectedFrames: n, + fps: outFps, + }); checks.wholeFile = { - fps: WHOLE_FILE_FPS, + fps: outFps, width: WHOLE_FILE_WIDTH, - frames: ticks.length, - mean: round(wMean, 4), - min: round(ticks.length ? ticks[worst] : 0, 4), - worstAt: round(worst / WHOLE_FILE_FPS, 2), + frames: cmp.frames.length, + mean: round(v.mean, 4), + min: round(v.min, 4), + worstAt: round(v.minAt / outFps, 3), minFloor: s.wholeFileSsimMin, meanFloor: s.wholeFileSsimMean, maxGapSeconds: round(gap, 4), + sd: round(v.sd, 5), + relativeFloor: round(v.relativeFloor, 4), + grid: WHOLE_FILE_GRID, + tileFloor: s.wholeFileTileMin, + tileRunFrames: s.wholeFileTileRunFrames, + ...(v.worstTile + ? { + worstTile: { + col: v.worstTile.col, + row: v.worstTile.row, + min: round(v.worstTile.min, 4), + at: round(v.worstTile.minAt / outFps, 3), + longestBelow: v.worstTile.longestBelow, + }, + } + : {}), }; - if (ticks.length < expectTicks - 1) { - fail(`the whole-file comparison reached ${ticks.length} of the ${expectTicks} ticks the source's length gives: the copy ends early or skips`); - } - if ((ticks[worst] ?? 0) < s.wholeFileSsimMin || wMean < s.wholeFileSsimMean) { - fail( - `the whole-file comparison scores ${wMean.toFixed(3)} mean, ${(ticks[worst] ?? 0).toFixed(3)} at ${(worst / WHOLE_FILE_FPS).toFixed(1)} s ` + - `(needs ${s.wholeFileSsimMean} and no tick below ${s.wholeFileSsimMin})`, - ); - } - log(`${tag}: whole file SSIM ${wMean.toFixed(3)} mean over ${ticks.length} ticks, lowest ${ticks[worst].toFixed(3)} at ${(worst / WHOLE_FILE_FPS).toFixed(1)} s.`); + if (!v.ok) fail(`the whole-file comparison: ${v.why}`); + log( + `${tag}: whole file SSIM ${v.mean.toFixed(4)} mean over ${cmp.frames.length} frames, lowest ${v.min.toFixed(4)} at ${(v.minAt / outFps).toFixed(2)} s; ` + + `worst tile ${v.worstTile ? `${v.worstTile.col},${v.worstTile.row} at ${v.worstTile.min.toFixed(3)} (${v.worstTile.longestBelow} frame(s) below ${s.wholeFileTileMin})` : "none"}.`, + ); // Quality on excerpts: spread through the file, ACROSS EVERY CHUNK JOIN and // inside every chunk (the count grows with the chunks). @@ -1170,6 +1243,7 @@ async function afterSwap(o: { log: (s: string) => void; tag: string; signal?: AbortSignal; + markerToken: string; }): Promise<{ dropped: boolean; review: CompactionReviewState }> { const { log, tag } = o; const recheck = await recheckCompactedCopy({ paths: o.paths, videoDir: o.videoDir, deps: o.deps, ...(o.signal ? { signal: o.signal } : {}) }); @@ -1199,8 +1273,14 @@ async function afterSwap(o: { return { dropped: false, review: state() }; } try { + // EXACTLY THE ORIGINAL OF THIS COMPACTED COPY, checked again under the + // pointer's lock (kind, sha256, file): a persist landing between this + // read and that lock re-labels it, and then nothing is dropped. This step + // never passes the former-original confirm (a test scans the callers). const r = await dropSavedAlternate(o.videoDir, original.file, { confirmOriginal: true, + expect: { keptAs: "original", sha256: pointer.compacted!.source.sha256, file: original.file }, + markerToken: o.markerToken, by: "compact-saved-videos (after-verify)", presence, busy: () => o.deps.busy(o.item.slug, o.item.id), @@ -1230,6 +1310,8 @@ export async function compactSavedVideos( opts: CompactRunOptions & { items: CompactItem[]; mode: "explicit" | "select"; retryFailed?: boolean; belowThreshold?: boolean }, ): Promise<CompactSavedVideosResult> { const result: CompactSavedVideosResult = { compacted: [], skipped: [], failed: [] }; + // Stale markers first: none of them may block this run (or any other). + await sweepCompactingMarkers(opts.paths, opts.onLog).catch(() => {}); for (const item of opts.items) { if (opts.signal?.aborted) { result.stopped = "cancelled"; @@ -1349,3 +1431,59 @@ export async function listCompactionReview(opts: { } return rows; } + +// --- what a rollback must know, and the markers ------------------------------------ + +// EVERY POINTER THAT KEEPS AN ORIGINAL (`keptAs: "original"`) OR A FORMER ONE +// (`"former-original"`), or has a drop in flight (`pendingDrops`). An editor +// built from before this release does not know those labels and would treat +// such a copy as an ordinary droppable alternate: while this list is not +// empty, do not roll the editor back past this release (OPERATING.md). +export type KeptOriginalRow = { + slug: string; + id: string; + active: string; + compacted: boolean; + kept: { file: string; keptAs: "original" | "former-original"; sha256?: string; bytes: number }[]; + pendingDrops: { file: string; keptAs?: string; at: string }[]; +}; + +export async function listKeptOriginals(opts: { paths: Paths; channelSlug?: string; notAnswering?: string[] }): Promise<KeptOriginalRow[]> { + const entries = await listSavedVideos({ + paths: opts.paths, + ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}), + ...(opts.notAnswering ? { notAnswering: opts.notAnswering } : {}), + }); + const rows: KeptOriginalRow[] = []; + for (const e of entries) { + const kept = (e.pointer.alternates ?? []) + .filter((a) => a.keptAs === "original" || a.keptAs === "former-original") + .map((a) => ({ file: a.file, keptAs: a.keptAs as "original" | "former-original", ...(a.sha256 ? { sha256: a.sha256 } : {}), bytes: a.bytes })); + const pending = (e.pointer.pendingDrops ?? []).map((d) => ({ file: d.file, ...(d.keptAs ? { keptAs: d.keptAs } : {}), at: d.at })); + if (!kept.length && !pending.length) continue; + rows.push({ slug: e.slug, id: e.videoId, active: e.pointer.file, compacted: !!e.pointer.compacted, kept, pendingDrops: pending }); + } + return rows; +} + +export type CompactionMarkerRow = { slug: string; id: string; dir: string; live: boolean; why: string; marker: unknown }; + +// Every `.compacting.json` in the store, live or stale, and why. +export async function listCompactionMarkers(paths: Paths): Promise<CompactionMarkerRow[]> { + const { markerLiveness } = await import("../lib/compactingMarker-server"); + const rows: CompactionMarkerRow[] = []; + for (const e of await listSavedVideos({ paths })) { + const m = await readCompactingMarker(e.pointer.dir).catch(() => null); + if (!m) continue; + const l = await markerLiveness(m); + rows.push({ slug: e.slug, id: e.videoId, dir: e.pointer.dir, live: l.live, why: l.why, marker: m }); + } + return rows; +} + +// Clear one video's marker — refused while it is live (cancel the job instead). +export async function clearCompactionMarker(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string }> { + const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id)); + if (!p) return { cleared: false, why: "no saved video" }; + return clearCompactingMarker(p.dir); +} diff --git a/common/controller/pruneSavedVideos.test.ts b/common/controller/pruneSavedVideos.test.ts @@ -105,3 +105,22 @@ test("never evicts override or pinned containers, even out of window", async () } }); }); + +// Review F5: a refusal for one video (being compacted) never stops the prune. +test("a video the prune may not drop is logged and kept; the prune goes on", async () => { + await withPaths(async (paths) => { + await writeConfig(paths, "ch", 1); + await seedSaved(paths, "ch", "newest", "20240301", "keep-latest"); + await seedSaved(paths, "ch", "a", "20240101", "keep-latest"); + await seedSaved(paths, "ch", "b", "20240102", "keep-latest"); + // a is being compacted: a live marker beside its stored copy. + const { writeCompactingMarker } = await import("../lib/compactingMarker-server"); + await writeCompactingMarker(path.join(paths.savedVideosDir, "ch", "a")); + const lines: string[] = []; + const res = await pruneSavedVideos({ channelSlug: "ch", paths, onLog: (l) => lines.push(l) }); + assert.equal(res.pruned, 1); + assert.notEqual(await loadSavedVideo(path.join(paths.channelsDir, "ch", "data", "a")), null); + assert.equal(await loadSavedVideo(path.join(paths.channelsDir, "ch", "data", "b")), null); + assert.ok(lines.some((l) => /Kept saved video a: .*being compacted/.test(l)), lines.join("\n")); + }); +}); diff --git a/common/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts @@ -84,7 +84,15 @@ export async function pruneSavedVideos({ ); continue; } - const bytes = await dropSavedVideo(videoDir); + // A REFUSAL FOR ONE VIDEO NEVER STOPS THE PRUNE (review F5): a video + // being compacted, or one that keeps an original, is logged and kept. + let bytes: number; + try { + bytes = await dropSavedVideo(videoDir); + } catch (err) { + log(`Kept saved video ${id}: ${(err as Error).message}`); + continue; + } bytesFreed += bytes; pruned++; log( diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts @@ -12,7 +12,7 @@ import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; -import { readFile, rm, stat } from "node:fs/promises"; +import { readFile, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { execa } from "execa"; import type { Paths } from "./paths"; @@ -728,49 +728,194 @@ export function cutIsOffset(c: CutComparison): boolean { return Math.max(c.earlier, c.later) > c.ssim + CUT_OFFSET_MARGIN; } -// THE WHOLE FILE, COMPARED (review H1: a bad stretch the excerpts miss). Both -// copies decoded end to end, each taken to `fps` frames a second on the same -// clock (the fps filter keeps the frame nearest each tick of the file's own -// time, so a 30 fps copy of a 60 fps source is compared at the same instants), -// scaled to `width` px, grey; the ticks paired by time and scored by SSIM one -// by one. Answers every tick's score; the caller judges the floor, the mean, -// and that the comparison reached the end. -export const WHOLE_FILE_FPS = 2; -export const WHOLE_FILE_WIDTH = 64; -export const WHOLE_FILE_ESTIMATE_MB = 1200; +// THE WHOLE FILE, COMPARED, EVERY FRAME (reviews H1 and F2). Both copies +// decoded end to end; the source taken to the copy's rate exactly as the +// encode took it (decimateTo), both on one clock and paired frame for frame +// (renumber); scaled to WHOLE_FILE_WIDTH px wide, its aspect kept, grey. Each +// frame scored by SSIM whole, AND split into a WHOLE_FILE_GRID × WHOLE_FILE_GRID +// grid of tiles, each tile scored on its own — so a change to a small region +// is not averaged away by the rest of the picture. One ffmpeg run (the tiles +// are crops of the same decoded frames: one decode, 1 + grid² SSIM filters). +// +// Answers every frame's whole score, and per tile its lowest score (and +// frame) and its longest run of frames below `tileFloor` (and where it +// starts). The caller judges the floors. +export const WHOLE_FILE_WIDTH = 256; +export const WHOLE_FILE_GRID = 8; +export const WHOLE_FILE_ESTIMATE_MB = 1500; + +export type TileSummary = { + index: number; + col: number; + row: number; + min: number; + minAt: number; // frame index + longestBelow: number; // frames + longestBelowAt: number; // frame index of the run's start +}; + +export type WholeFileComparison = { + frames: Float32Array; + tiles: TileSummary[]; + width: number; + height: number; + grid: number; +}; + +function ssimScores(text: string): number[] { + const out: number[] = []; + for (const l of text.split("\n")) { + const m = /All:([0-9.]+|inf)/.exec(l); + if (m) out.push(m[1] === "inf" ? 1 : Number(m[1])); + } + return out; +} export async function compareWholeFile( paths: GatedPaths, - opts: { compacted: string; source: string; scratchDir: string; signal?: AbortSignal }, -): Promise<number[]> { - const stats = path.join(opts.scratchDir, "wholefile-ssim.log"); - await rm(stats, { force: true }); - // The first frame in each 1/fps-second bucket of the file's own time (no - // rounding: a frame exactly on a tick opens its bucket on both sides), then - // numbered on that grid and paired by number. - const b = WHOLE_FILE_FPS; - const tick = - "setpts=PTS-STARTPTS," + - `select='isnan(prev_selected_t)+gte(floor(t*${b}+0.0001)-floor(prev_selected_t*${b}+0.0001),1)',` + - `settb=1/${b},setpts=N,scale=${WHOLE_FILE_WIDTH}:-2:flags=area,format=gray`; + opts: { + compacted: string; + source: string; + scratchDir: string; + // The copy's frame rate when it was capped, the source's rate, its size. + fps: number | null; + sourceFps: number | null; + sourceWidth: number | null; + sourceHeight: number | null; + tileFloor: number; + signal?: AbortSignal; + }, +): Promise<WholeFileComparison> { + const W = WHOLE_FILE_WIDTH; + const aspect = opts.sourceWidth && opts.sourceHeight ? opts.sourceHeight / opts.sourceWidth : 9 / 16; + const H = Math.max(2 * WHOLE_FILE_GRID, 2 * Math.round((W * aspect) / 2)); + const G = WHOLE_FILE_GRID; + const tw = Math.floor(W / G); + const th = Math.floor(H / G); + const T = G * G; + const rate = opts.fps ?? opts.sourceFps ?? null; + const n = renumber(rate); + const esc = (f: string) => f.replace(/[:\\']/g, "\\$&"); + const whole = path.join(opts.scratchDir, "wf-whole.log"); + const tileLog = (k: number) => path.join(opts.scratchDir, `wf-tile-${k}.log`); + const labels = (p: string) => Array.from({ length: T + 1 }, (_, k) => `[${p}${k}]`).join(""); + const chains = [ + `[0:v]${n},scale=${W}:${H}:flags=area,format=gray,split=${T + 1}${labels("d")}`, + `[1:v]${decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=gray,split=${T + 1}${labels("r")}`, + `[d0][r0]ssim=stats_file=${esc(whole)}:eof_action=endall[out]`, + ]; + for (let k = 0; k < T; k += 1) { + const x = (k % G) * tw; + const y = Math.floor(k / G) * th; + const crop = `crop=${tw}:${th}:${x}:${y}`; + chains.push(`[d${k + 1}]${crop}[dc${k}]`, `[r${k + 1}]${crop}[rc${k}]`, `[dc${k}][rc${k}]ssim=stats_file=${esc(tileLog(k))}:eof_action=endall,nullsink`); + } + const graphFile = path.join(opts.scratchDir, "wf-graph.txt"); + await writeFile(graphFile, chains.join(";\n")); try { await runHeavyFfmpeg( paths, [ "-nostdin", "-hide_banner", "-loglevel", "error", "-i", opts.compacted, "-i", opts.source, - "-lavfi", `[0:v]${tick}[d];[1:v]${tick}[r];[d][r]ssim=stats_file=${stats.replace(/[:\\']/g, "\\$&")}:eof_action=endall`, + // ffmpeg 7+: a "-/" option reads its value from the file. + "-/filter_complex", graphFile, "-map", "[out]", "-f", "null", "-", ], { estimateMB: WHOLE_FILE_ESTIMATE_MB, ...(opts.signal ? { signal: opts.signal } : {}) }, ); - const text = await readFile(stats, "utf8"); - return text - .split("\n") - .map((l) => /All:([0-9.]+|inf)/.exec(l)?.[1]) - .filter((x): x is string => x !== undefined) - .map((x) => (x === "inf" ? 1 : Number(x))); + const frames = Float32Array.from(ssimScores(await readFile(whole, "utf8"))); + const tiles: TileSummary[] = []; + for (let k = 0; k < T; k += 1) { + const sc = ssimScores(await readFile(tileLog(k), "utf8")); + let min = 1; + let minAt = 0; + let run = 0; + let runAt = 0; + let longest = 0; + let longestAt = 0; + for (let i = 0; i < sc.length; i += 1) { + if (sc[i] < min) { + min = sc[i]; + minAt = i; + } + if (sc[i] < opts.tileFloor) { + if (run === 0) runAt = i; + run += 1; + if (run > longest) { + longest = run; + longestAt = runAt; + } + } else run = 0; + } + tiles.push({ index: k, col: k % G, row: Math.floor(k / G), min, minAt, longestBelow: longest, longestBelowAt: longestAt }); + } + return { frames, tiles, width: W, height: H, grid: G }; } finally { - await rm(stats, { force: true }).catch(() => {}); + await rm(whole, { force: true }).catch(() => {}); + await rm(graphFile, { force: true }).catch(() => {}); + for (let k = 0; k < T; k += 1) await rm(tileLog(k), { force: true }).catch(() => {}); + } +} + +// The whole-file verdict (pure, so the thresholds are tested on their own). +export type WholeFileVerdict = { + ok: boolean; + why?: string; + mean: number; + sd: number; + min: number; + minAt: number; // frame index + relativeFloor: number; + worstTile: TileSummary | null; +}; + +export function judgeWholeFile( + c: Pick<WholeFileComparison, "frames" | "tiles">, + t: { minFrame: number; meanFloor: number; sigmaK: number; sigmaMinMargin: number; tileRunFrames: number; expectedFrames: number; fps: number }, +): WholeFileVerdict { + const f = c.frames; + let sum = 0; + let min = 1; + let minAt = 0; + for (let i = 0; i < f.length; i += 1) { + sum += f[i]; + if (f[i] < min) { + min = f[i]; + minAt = i; + } + } + const mean = f.length ? sum / f.length : 0; + let v = 0; + for (let i = 0; i < f.length; i += 1) v += (f[i] - mean) ** 2; + const sd = f.length ? Math.sqrt(v / f.length) : 0; + const relativeFloor = mean - Math.max(t.sigmaK * sd, t.sigmaMinMargin); + let worstTile: TileSummary | null = null; + for (const tile of c.tiles) { + if (!worstTile || tile.longestBelow > worstTile.longestBelow || (tile.longestBelow === worstTile.longestBelow && tile.min < worstTile.min)) worstTile = tile; + } + const at = (i: number) => `${(i / t.fps).toFixed(2)} s`; + const base = { mean, sd, min, minAt, relativeFloor, worstTile }; + if (f.length !== t.expectedFrames) { + return { ...base, ok: false, why: `the comparison saw ${f.length} of the copy's ${t.expectedFrames} frames: it ends early or skips` }; + } + if (min < t.minFrame) return { ...base, ok: false, why: `a frame at ${at(minAt)} scores ${min.toFixed(3)} (no frame may fall below ${t.minFrame})` }; + if (mean < t.meanFloor) return { ...base, ok: false, why: `the mean is ${mean.toFixed(3)} (needs ${t.meanFloor})` }; + if (min < relativeFloor) { + return { + ...base, + ok: false, + why: `a frame at ${at(minAt)} scores ${min.toFixed(4)}, below the file's own ${mean.toFixed(4)} − max(${t.sigmaK}·${sd.toFixed(4)}, ${t.sigmaMinMargin}) = ${relativeFloor.toFixed(4)}`, + }; + } + if (worstTile && worstTile.longestBelow > t.tileRunFrames) { + return { + ...base, + ok: false, + why: + `tile ${worstTile.col},${worstTile.row} of the ${Math.sqrt(c.tiles.length)}×${Math.sqrt(c.tiles.length)} grid is below its floor for ` + + `${worstTile.longestBelow} frames from ${at(worstTile.longestBelowAt)} (lowest ${worstTile.min.toFixed(3)}; more than ${t.tileRunFrames} fails)`, + }; } + return { ...base, ok: true }; } diff --git a/common/lib/compactingMarker-server.ts b/common/lib/compactingMarker-server.ts @@ -0,0 +1,165 @@ +// THE "BEING COMPACTED" MARKER, `<store dir>/.compacting.json` +// (controller/compactSavedVideos.ts writes it; every persist, attach, import, +// unpersist and drop of the video reads it). +// +// A marker is LIVE only when everything it names still holds: +// - this machine's kernel (`/proc/sys/kernel/random/boot_id`) — a reboot +// ends every compaction; +// - this host (a marker written in another container or on the host by a +// CLI cannot be checked from here, and counts as stale); +// - a running process with that pid AND that process's start time (field 22 +// of /proc/<pid>/stat), so a pid reused by another process is not it; +// - when the marker is this process's own and names a job: that job is one +// the job registry knows as queued or running (a probe the controller +// registers; lib does not import the registry); +// - younger than MARKER_MAX_AGE_HOURS. +// Anything else is stale: it is ignored by every guard and removed by the +// sweep (at editor boot and at the start of every compaction run) and by +// `pnpm ops compaction-markers {"clear": …}`. +// +// The compaction's own steps carry the marker's token, and pass where another +// writer is refused (the drop of the original under after-verify, F4). + +import { readFile, rm } from "node:fs/promises"; +import { hostname } from "node:os"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; + +export const COMPACTING_MARKER_FILENAME = ".compacting.json"; +export const MARKER_MAX_AGE_HOURS = 72; + +export type CompactingMarker = { + pid: number; + pidStart: string | null; + bootId: string | null; + host: string; + jobId?: string; + token: string; + startedAt: string; + video?: string; +}; + +export class CompactionInProgressError extends Error { + constructor(message: string) { + super(message); + this.name = "CompactionInProgressError"; + } +} + +async function bootId(): Promise<string | null> { + return readFile("/proc/sys/kernel/random/boot_id", "utf8").then((s) => s.trim(), () => null); +} + +// The process's start time in clock ticks since boot, or null (no /proc, gone). +export async function processStartTime(pid: number): Promise<string | null> { + try { + const s = await readFile(`/proc/${pid}/stat`, "utf8"); + const rest = s.slice(s.lastIndexOf(")") + 2).split(" "); + // Fields after the comm start at field 3: start time is field 22. + return rest[22 - 3] ?? null; + } catch { + return null; + } +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (e) { + // EPERM: it exists, under another user. + return (e as NodeJS.ErrnoException).code === "EPERM"; + } +} + +// The registry's word on a job of this process (registered by the controller). +type JobProbe = (jobId: string) => boolean; +let jobProbe: JobProbe | null = null; +export function registerCompactionJobProbe(probe: JobProbe | null): void { + jobProbe = probe; +} + +export function markerPath(storeDir: string): string { + return path.join(storeDir, COMPACTING_MARKER_FILENAME); +} + +export async function writeCompactingMarker(storeDir: string, opts: { jobId?: string; video?: string; now?: Date } = {}): Promise<CompactingMarker> { + const m: CompactingMarker = { + pid: process.pid, + pidStart: await processStartTime(process.pid), + bootId: await bootId(), + host: hostname(), + ...(opts.jobId ? { jobId: opts.jobId } : {}), + token: randomUUID(), + startedAt: (opts.now ?? new Date()).toISOString(), + ...(opts.video ? { video: opts.video } : {}), + }; + await writeJsonAtomic(markerPath(storeDir), m); + return m; +} + +export async function readCompactingMarker(storeDir: string): Promise<CompactingMarker | null> { + const read = await readJsonFile(markerPath(storeDir)); + if (!read.ok || !read.value || typeof read.value !== "object") return null; + const r = read.value as Record<string, unknown>; + if (typeof r.pid !== "number") return null; + return { + pid: r.pid, + pidStart: typeof r.pidStart === "string" ? r.pidStart : null, + bootId: typeof r.bootId === "string" ? r.bootId : null, + host: typeof r.host === "string" ? r.host : "", + ...(typeof r.jobId === "string" ? { jobId: r.jobId } : {}), + token: typeof r.token === "string" ? r.token : "", + startedAt: typeof r.startedAt === "string" ? r.startedAt : "", + ...(typeof r.video === "string" ? { video: r.video } : {}), + }; +} + +// Live, or why not. +export async function markerLiveness(m: CompactingMarker, now = new Date()): Promise<{ live: boolean; why: string }> { + if (m.host !== hostname()) return { live: false, why: `written on another host (${m.host || "unknown"})` }; + const boot = await bootId(); + if (!m.bootId || (boot && m.bootId !== boot)) return { live: false, why: "written before this machine last started" }; + if (!alive(m.pid)) return { live: false, why: `its process ${m.pid} is gone` }; + const start = await processStartTime(m.pid); + if (!m.pidStart || (start !== null && start !== m.pidStart)) return { live: false, why: `pid ${m.pid} is another process now` }; + if (m.pid === process.pid && m.jobId && jobProbe && !jobProbe(m.jobId)) { + return { live: false, why: `its job ${m.jobId} is not running` }; + } + const age = (now.getTime() - Date.parse(m.startedAt)) / 3_600_000; + if (!Number.isFinite(age) || age > MARKER_MAX_AGE_HOURS) return { live: false, why: `older than ${MARKER_MAX_AGE_HOURS} h` }; + return { live: true, why: `pid ${m.pid} since ${m.startedAt.slice(0, 16)}${m.jobId ? `, job ${m.jobId}` : ""}` }; +} + +export async function liveCompactingMarker(storeDir: string): Promise<CompactingMarker | null> { + const m = await readCompactingMarker(storeDir); + if (!m) return null; + return (await markerLiveness(m)).live ? m : null; +} + +// Refused while a live marker is there — unless the caller holds its token +// (the compaction's own steps). +export async function assertNotCompacting(storeDir: string, what: string, ownToken?: string): Promise<void> { + const m = await liveCompactingMarker(storeDir); + if (m && !(ownToken && m.token === ownToken)) { + throw new CompactionInProgressError( + `${what} refused: this video's saved copy is being compacted (since ${m.startedAt.slice(0, 16)}, pid ${m.pid}` + + `${m.jobId ? `, job ${m.jobId}` : ""}). Run it again once the compaction is done.`, + ); + } +} + +// Remove a marker that is not live (or, with `token`, the caller's own). +export async function clearCompactingMarker(storeDir: string, opts: { token?: string } = {}): Promise<{ cleared: boolean; why: string }> { + const m = await readCompactingMarker(storeDir); + if (!m) return { cleared: false, why: "no marker" }; + if (opts.token && m.token === opts.token) { + await rm(markerPath(storeDir), { force: true }); + return { cleared: true, why: "the compaction's own" }; + } + const l = await markerLiveness(m); + if (l.live) return { cleared: false, why: `live: ${l.why} — cancel that job instead` }; + await rm(markerPath(storeDir), { force: true }); + return { cleared: true, why: `stale: ${l.why}` }; +} diff --git a/common/lib/compactingMarker.test.ts b/common/lib/compactingMarker.test.ts @@ -0,0 +1,96 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { hostname, tmpdir } from "node:os"; +import path from "node:path"; +import { + COMPACTING_MARKER_FILENAME, + CompactionInProgressError, + MARKER_MAX_AGE_HOURS, + assertNotCompacting, + clearCompactingMarker, + liveCompactingMarker, + markerLiveness, + processStartTime, + readCompactingMarker, + registerCompactionJobProbe, + writeCompactingMarker, +} from "./compactingMarker-server"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/compactingMarker.test.ts +// +// The "being compacted" marker (review F3): live only when boot, host, pid, +// the pid's start time, the job and the age all hold; every stale case is +// ignored by the guards and cleared on request. + +async function withDir(fn: (dir: string) => Promise<void>): Promise<void> { + const dir = await mkdtemp(path.join(tmpdir(), "marker-")); + try { + await fn(dir); + } finally { + await rm(dir, { recursive: true, force: true }); + registerCompactionJobProbe(null); + } +} + +const bootId = async () => (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim(); + +async function write(dir: string, m: Record<string, unknown>): Promise<void> { + const base = { + pid: process.pid, + pidStart: await processStartTime(process.pid), + bootId: await bootId(), + host: hostname(), + token: "t", + startedAt: new Date().toISOString(), + }; + await writeFile(path.join(dir, COMPACTING_MARKER_FILENAME), JSON.stringify({ ...base, ...m })); +} + +test("a marker this process wrote is live, refuses others, and passes its own token", async () => { + await withDir(async (dir) => { + const m = await writeCompactingMarker(dir, { video: "kick/v1" }); + assert.ok(await liveCompactingMarker(dir)); + await assert.rejects(assertNotCompacting(dir, "Persisting"), (e: Error) => e instanceof CompactionInProgressError); + await assertNotCompacting(dir, "the compaction's own drop", m.token); + assert.deepEqual(await clearCompactingMarker(dir), { cleared: false, why: `live: pid ${process.pid} since ${m.startedAt.slice(0, 16)} — cancel that job instead` }); + assert.equal((await clearCompactingMarker(dir, { token: m.token })).cleared, true); + await assert.rejects(stat(path.join(dir, COMPACTING_MARKER_FILENAME))); + }); +}); + +test("every stale case is ignored by the guards and cleared", async () => { + const cases: [string, Record<string, unknown>, RegExp][] = [ + ["a dead pid", { pid: 2 ** 22 + 7 }, /process .* is gone/], + ["a pid reused by another live process", { pid: process.ppid }, /is another process now/], + ["pid 1, as a container's editor would be", { pid: 1 }, /is another process now/], + ["another host or container", { host: "another-host" }, /another host/], + ["before this machine last started", { bootId: "00000000-0000-0000-0000-000000000000" }, /before this machine last started/], + ["older than the cap", { startedAt: new Date(Date.now() - (MARKER_MAX_AGE_HOURS + 1) * 3_600_000).toISOString() }, /older than/], + ["a marker with no start time or boot (an older writer)", { pidStart: null, bootId: null }, /before this machine last started|another process/], + ]; + for (const [label, m, why] of cases) { + await withDir(async (dir) => { + await write(dir, m); + const read = (await readCompactingMarker(dir))!; + const l = await markerLiveness(read); + assert.equal(l.live, false, label); + assert.match(l.why, why, label); + await assertNotCompacting(dir, "Persisting"); + const c = await clearCompactingMarker(dir); + assert.equal(c.cleared, true, label); + }); + } +}); + +test("this process's marker for a job the registry does not run is stale", async () => { + await withDir(async (dir) => { + await writeCompactingMarker(dir, { jobId: "j-gone" }); + registerCompactionJobProbe((id) => id === "j-running"); + assert.match((await markerLiveness((await readCompactingMarker(dir))!)).why, /job j-gone is not running/); + await assertNotCompacting(dir, "Persisting"); + await writeCompactingMarker(dir, { jobId: "j-running" }); + await assert.rejects(assertNotCompacting(dir, "Persisting"), (e: Error) => e instanceof CompactionInProgressError); + }); +}); diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts @@ -5,7 +5,6 @@ import { writeJsonAtomic, } from "./jsonFile-server"; import path from "node:path"; -import { hostname } from "node:os"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { execa } from "execa"; @@ -35,6 +34,7 @@ import { } from "./savedVideo"; import { assertSavedVideosStoreWritable } from "./savedVideoStore"; import { platformPresence } from "./availability-server"; +import { assertNotCompacting } from "./compactingMarker-server"; import { probeMedia } from "./evidenceClip-server"; import type { Paths } from "./paths"; @@ -109,45 +109,15 @@ export function samePointerCopy( return a.file === b.file && a.bytes === b.bytes && a.storedAt === b.storedAt; } -// A COMPACTION IN PROGRESS (controller/compactSavedVideos.ts) for one video: -// `<store dir>/.compacting.json`, `{pid, host, startedAt}`, written when a -// compaction starts and removed when it ends. A persist, attach, import or -// re-download of that video refuses while it is there (its container stays in -// the data dir or its staging, and the next run picks it up). A marker whose -// process is gone (this host, a dead pid) is stale and ignored. -export const COMPACTING_MARKER_FILENAME = ".compacting.json"; - -export class CompactionInProgressError extends Error { - constructor(message: string) { - super(message); - this.name = "CompactionInProgressError"; - } -} - -export async function liveCompactingMarker(storeDir: string): Promise<{ pid: number; startedAt: string } | null> { - const read = await readJsonFile(path.join(storeDir, COMPACTING_MARKER_FILENAME)); - if (!read.ok || !read.value || typeof read.value !== "object") return null; - const m = read.value as { pid?: unknown; host?: unknown; startedAt?: unknown }; - if (typeof m.pid !== "number") return null; - if (m.host === hostname()) { - try { - process.kill(m.pid, 0); - } catch { - return null; - } - } - return { pid: m.pid, startedAt: String(m.startedAt ?? "") }; -} - -export async function assertNotCompacting(storeDir: string, what: string): Promise<void> { - const m = await liveCompactingMarker(storeDir); - if (m) { - throw new CompactionInProgressError( - `${what} refused: this video's saved copy is being compacted (since ${m.startedAt.slice(0, 16)}, pid ${m.pid}). ` + - "Run it again once the compaction is done.", - ); - } -} +// A COMPACTION IN PROGRESS for one video: lib/compactingMarker-server.ts +// (`<store dir>/.compacting.json`). Every persist, attach, import, unpersist +// and drop of the video refuses while a LIVE one is there. +export { + COMPACTING_MARKER_FILENAME, + CompactionInProgressError, + assertNotCompacting, + liveCompactingMarker, +} from "./compactingMarker-server"; // Repoint a video's saved-video.json at a new absolute store dir. Used when a // channel is renamed: the pointer's `dir` is stored absolutely and includes the @@ -331,12 +301,29 @@ export async function updateSavedVideoChecksum( export async function recordOriginalReview( videoDir: string, review: Omit<SavedAlternateReview, "forSha256">, + // A FORMER original (`keptAs: "former-original"`) by its file name: the + // review is then of the active copy that replaced it (its sha256). + opts: { formerOriginal?: string } = {}, ): Promise<SavedVideoAlternate> { const pointerFile = savedVideoPointerPath(videoDir); return withJsonFileLock(pointerFile, async () => { const read = await readJsonFile(pointerFile); const pointer = read.ok ? parseSavedVideoPointer(read.value) : null; if (!read.ok || !pointer) throw new SavedAlternateRefusal("This video has no saved-video pointer."); + if (opts.formerOriginal) { + const former = pointer.alternates?.find((a) => a.file === opts.formerOriginal && a.keptAs === "former-original"); + if (!former) throw new SavedAlternateRefusal(`${opts.formerOriginal} is not a former original of this video.`); + if (!pointer.sha256) { + throw new SavedAlternateRefusal("The active copy has no recorded sha256 yet (the backup step or a prepare-playable records it): it cannot be reviewed."); + } + const full: SavedAlternateReview = { ...review, forSha256: pointer.sha256 }; + const raw = { ...(read.value as Record<string, unknown>) }; + raw.alternates = (Array.isArray(raw.alternates) ? raw.alternates : []).map((a) => + a && typeof a === "object" && (a as { file?: unknown }).file === former.file ? { ...(a as object), review: full } : a, + ); + await writeJsonAtomic(pointerFile, raw); + return { ...former, review: full }; + } if (!pointer.compacted) { throw new SavedAlternateRefusal("This video's active copy is not a compacted re-encode: there is nothing to review."); } @@ -622,13 +609,24 @@ export async function readBackCompactedCopy( return { ok: true, sha256: sha }; } +export type DropExpectation = { keptAs: "original"; sha256: string; file?: string }; + export async function dropSavedAlternate( videoDir: string, file: string, opts: { dryRun?: boolean; paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">; + // A person's word for an ORIGINAL ("keptAs": "original"). confirmOriginal?: boolean; + // A person's word for a FORMER ORIGINAL ("keptAs": "former-original"). + // Its own flag: no automatic step passes it (a test scans the callers). + confirmFormerOriginal?: boolean; + // WHAT THE CALLER MEANS TO DROP, checked under the lock: the entry must be + // exactly this (kind, sha256, file) or nothing is dropped. The automatic + // after-verify drop always passes it — a persist landing between its read + // and this lock may have re-labelled the entry. + expect?: DropExpectation; // Who drops it, for `originalDropped.by` (default "drop-saved-alternate"). by?: string; // The gone rule's answer (default: platformPresence of the video dir, @@ -638,6 +636,9 @@ export async function dropSavedAlternate( // A download or persist of this video queued or running: the reason, or // null. An original is never dropped while one is. busy?: () => string | null | Promise<string | null>; + // The compaction's own marker token: its after-verify drop passes the + // marker it still holds (F4); anyone else is refused while it is live. + markerToken?: string; // The read-back's hasher and prober (tests name their own). readBack?: ReadBackDeps; } = {}, @@ -659,21 +660,28 @@ export async function dropSavedAlternate( } const alternate = pointer.alternates?.find((a) => a.file === file); if (!alternate) { - // AN INTERRUPTED DROP OF AN ORIGINAL: the pointer was written, the file - // was not removed. Asked again by name, with the confirm, it is finished. - const d = pointer.compacted?.originalDropped; - if (d && d.file === file && d.fileRemoved === false && opts.confirmOriginal === true) { + // AN INTERRUPTED DROP: the pointer was written, the file was not removed + // (`pendingDrops`). Asked again by name — with the same confirm an + // original or a former original needed — it is finished. + const pending = pointer.pendingDrops?.find((d) => d.file === file); + if (pending && !opts.expect) { + if (pending.keptAs === "original" && opts.confirmOriginal !== true) { + throw new SavedAlternateRefusal(`${file} is an original whose drop was interrupted: finish it with "confirmOriginal": true.`); + } + if (pending.keptAs === "former-original" && opts.confirmFormerOriginal !== true) { + throw new SavedAlternateRefusal(`${file} is a former original whose drop was interrupted: finish it with "confirmFormerOriginal": true.`); + } const target = path.join(pointer.dir, file); const st = await stat(target).catch(() => null); if (!opts.dryRun) { if (st) await rm(target, { force: true }); const raw = { ...(read.value as Record<string, unknown>) }; - raw.compacted = { ...(raw.compacted as Record<string, unknown>), originalDropped: { ...d, fileRemoved: true } }; + finishPending(raw, file); await writeJsonAtomic(pointerFile, raw); } return { dryRun: opts.dryRun === true, - alternate: { file, bytes: d.bytes, storedAt: "", setAsideAt: "", keptAs: "original", sha256: d.sha256 }, + alternate: { file, bytes: st?.size ?? 0, storedAt: "", setAsideAt: "", ...(pending.keptAs ? { keptAs: pending.keptAs } : {}), ...(pending.sha256 ? { sha256: pending.sha256 } : {}) }, path: target, existed: st !== null, bytes: st?.size ?? 0, @@ -687,17 +695,45 @@ export async function dropSavedAlternate( ".", ); } - const isOriginal = alternate.keptAs === "original"; - if (isOriginal || alternate.keptAs === "former-original") { - if (opts.confirmOriginal !== true) { + // THE CALLER'S EXPECTATION, under the lock: any mismatch refuses. + if (opts.expect) { + const e = opts.expect; + if (alternate.keptAs !== e.keptAs || alternate.sha256 !== e.sha256 || (e.file !== undefined && alternate.file !== e.file)) { throw new SavedAlternateRefusal( - `${file} is ${isOriginal ? "the ORIGINAL the active copy was re-encoded from" : "the ORIGINAL of an earlier compacted copy"} ` + - `(sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}…): it is dropped only when the drop names it — pass "confirmOriginal": true.`, + `${file} is not what this drop expected (${e.keptAs}, sha256 ${e.sha256.slice(0, 12)}…): it is ` + + `${alternate.keptAs ?? "an ordinary alternate"}, sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}… now — nothing dropped.`, ); } + } + const isOriginal = alternate.keptAs === "original"; + const isFormer = alternate.keptAs === "former-original"; + if (isOriginal && opts.confirmOriginal !== true) { + throw new SavedAlternateRefusal( + `${file} is the ORIGINAL the active copy was re-encoded from (sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}…): ` + + 'it is dropped only when the drop names it — pass "confirmOriginal": true.', + ); + } + if (isFormer && opts.confirmFormerOriginal !== true) { + throw new SavedAlternateRefusal( + `${file} is the ORIGINAL of an earlier compacted copy (the active copy has since been replaced; sha256 ` + + `${alternate.sha256?.slice(0, 12) ?? "unknown"}…): it is dropped only by a person who names it — pass "confirmFormerOriginal": true.`, + ); + } + if (isOriginal || isFormer) { const busy = opts.busy ? await opts.busy() : null; if (busy) throw new SavedAlternateRefusal(`${file} is kept: ${busy}.`); - await assertNotCompacting(pointer.dir, `Dropping ${file}`); + await assertNotCompacting(pointer.dir, `Dropping ${file}`, opts.markerToken); + // THE GONE RULE, for both: still on its platform, freshly and + // first-hand — or a person's review of the copy that stays. + const presence = + opts.presence ?? (await platformPresence(videoDir, { maxAgeDays: opts.maxAgeDays ?? 7 }).catch(() => ({ onPlatform: false, why: "its availability could not be read" }))); + if (!presence.onPlatform && !reviewIsCurrent(pointer, alternate)) { + throw new SavedAlternateRefusal( + `This video is not known to be on its platform (${presence.why}): the stored ${file} may be the only original there is. ` + + "Review the copy that stays first (review-compacted-original), then drop it." + + (alternate.review ? " (Its review is for another copy than the one active now.)" : ""), + ); + } } if (isOriginal) { // The original of THIS compacted copy, by its bytes — never by position. @@ -714,15 +750,6 @@ export async function dropSavedAlternate( if (!c.checks.passed) { throw new SavedAlternateRefusal(`The compacted copy's checks did not pass: ${file}, its original, is kept.`); } - const presence = - opts.presence ?? (await platformPresence(videoDir, { maxAgeDays: opts.maxAgeDays ?? 7 }).catch(() => ({ onPlatform: false, why: "its availability could not be read" }))); - if (!presence.onPlatform && !reviewIsCurrent(pointer, alternate)) { - throw new SavedAlternateRefusal( - `This video is not known to be on its platform (${presence.why}): the stored ${file} may be the only original there is. ` + - "Review the compacted copy first (review-compacted-original), then drop it." + - (alternate.review ? " (Its review is for another copy than the one active now.)" : ""), - ); - } if (!opts.dryRun) { const back = await readBackCompactedCopy(pointer, opts.readBack); if (!back.ok) { @@ -744,32 +771,50 @@ export async function dropSavedAlternate( remaining, }; if (opts.dryRun) return result; - // THE POINTER FIRST, THEN THE FILE: a crash between leaves a file the - // pointer says is going (`fileRemoved: false`), never a pointer naming a - // file that is gone. Asking again finishes it (above). + // THE POINTER FIRST, THEN THE FILE: a crash between leaves the file listed + // in `pendingDrops` (any alternate, not only an original), never a pointer + // naming a file that is gone nor a file nothing names. Asking again + // finishes it (above); `get kept-originals` and the review list show it. const raw = { ...(read.value as Record<string, unknown>) }; const kept = (Array.isArray(raw.alternates) ? raw.alternates : []).filter( (a) => !(a && typeof a === "object" && (a as { file?: unknown }).file === file), ); if (kept.length) raw.alternates = kept; else delete raw.alternates; - const dropped = - isOriginal && raw.compacted && typeof raw.compacted === "object" - ? { - at: new Date().toISOString(), - by: opts.by ?? "drop-saved-alternate", - file, - bytes: st?.size ?? alternate.bytes, - sha256: alternate.sha256 ?? "", - } - : null; - if (dropped) raw.compacted = { ...(raw.compacted as Record<string, unknown>), originalDropped: { ...dropped, fileRemoved: false } }; + const at = new Date().toISOString(); + raw.pendingDrops = [ + ...(Array.isArray(raw.pendingDrops) ? raw.pendingDrops : []), + { file, at, ...(alternate.keptAs ? { keptAs: alternate.keptAs } : {}), ...(alternate.sha256 ? { sha256: alternate.sha256 } : {}) }, + ]; + if (isOriginal && raw.compacted && typeof raw.compacted === "object") { + raw.compacted = { + ...(raw.compacted as Record<string, unknown>), + originalDropped: { + at, + by: opts.by ?? "drop-saved-alternate", + file, + bytes: st?.size ?? alternate.bytes, + sha256: alternate.sha256 ?? "", + fileRemoved: false, + }, + }; + } await writeJsonAtomic(pointerFile, raw); if (existed) await rm(target, { force: true }); - if (dropped) { - raw.compacted = { ...(raw.compacted as Record<string, unknown>), originalDropped: { ...dropped, fileRemoved: true } }; - await writeJsonAtomic(pointerFile, raw); - } + finishPending(raw, file); + await writeJsonAtomic(pointerFile, raw); return result; }); } + +// The drop of `file` done: off `pendingDrops`, and an original's record says so. +function finishPending(raw: Record<string, unknown>, file: string): void { + const left = (Array.isArray(raw.pendingDrops) ? raw.pendingDrops : []).filter( + (d) => !(d && typeof d === "object" && (d as { file?: unknown }).file === file), + ); + if (left.length) raw.pendingDrops = left; + else delete raw.pendingDrops; + const c = raw.compacted as Record<string, unknown> | undefined; + const d = c?.originalDropped as Record<string, unknown> | undefined; + if (c && d && d.file === file) raw.compacted = { ...c, originalDropped: { ...d, fileRemoved: true } }; +} diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts @@ -87,8 +87,15 @@ export type SavedVideoPointer = { // dropped (then `compacted.originalDropped` says when, and its hash). Absent // on every pointer that was never compacted, which parses as before. compacted?: SavedVideoCompacted; + // DROPS IN FLIGHT: an alternate whose pointer entry is gone and whose file + // is being removed (dropSavedAlternate writes this first). One left here + // after a crash is a file on disk no other key names: it is listed (`get + // kept-originals`) and dropping it again by name finishes it. + pendingDrops?: SavedPendingDrop[]; }; +export type SavedPendingDrop = { file: string; at: string; keptAs?: SavedAlternateKeptAs; sha256?: string }; + export type SavedVideoProbe = { seconds?: number; height?: number }; // What compaction asked the encoder for. The result's own measurements are in @@ -149,6 +156,15 @@ export type SavedVideoCompactedChecks = { minFloor: number; meanFloor: number; maxGapSeconds: number; + // Every frame since review F2: the frames' spread, the floor relative to + // it, the tile grid and its floor, the worst tile (lowest score, when, + // its longest run below the floor). + sd?: number; + relativeFloor?: number; + grid?: number; + tileFloor?: number; + tileRunFrames?: number; + worstTile?: { col: number; row: number; min: number; at: number; longestBelow: number }; }; // Every stream but the video, and the chapters: what the source holds and // the copy holds ("audio:aac", "subtitle:mov_text", "chapters:3", …). @@ -468,6 +484,17 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { wholeFile: { fps: num(w.fps), width: num(w.width), frames: num(w.frames), mean: num(w.mean), min: num(w.min), worstAt: num(w.worstAt), minFloor: num(w.minFloor), meanFloor: num(w.meanFloor), maxGapSeconds: num(w.maxGapSeconds), + ...(typeof w.sd === "number" ? { sd: w.sd } : {}), + ...(typeof w.relativeFloor === "number" ? { relativeFloor: w.relativeFloor } : {}), + ...(typeof w.grid === "number" ? { grid: w.grid } : {}), + ...(typeof w.tileFloor === "number" ? { tileFloor: w.tileFloor } : {}), + ...(typeof w.tileRunFrames === "number" ? { tileRunFrames: w.tileRunFrames } : {}), + ...(w.worstTile && typeof w.worstTile === "object" + ? (() => { + const t = obj(w.worstTile); + return { worstTile: { col: num(t.col), row: num(t.row), min: num(t.min), at: num(t.at), longestBelow: num(t.longestBelow) } }; + })() + : {}), }, }; })() @@ -512,9 +539,14 @@ export function keepsAnyOriginal(pointer: SavedVideoPointer): boolean { return (pointer.alternates ?? []).some((a) => a.keptAs === "original" || a.keptAs === "former-original"); } -// Is a review valid for the compacted copy this pointer names now? +// Is a review valid for the copy that stays? An original's: for the compacted +// copy this pointer names now (its result sha256). A former original's: for +// the active copy that replaced it (the pointer's sha256). export function reviewIsCurrent(pointer: SavedVideoPointer, alternate: SavedVideoAlternate): boolean { - return !!alternate.review && !!pointer.compacted && alternate.review.forSha256 !== "" && alternate.review.forSha256 === pointer.compacted.result.sha256; + const r = alternate.review; + if (!r || r.forSha256 === "") return false; + if (alternate.keptAs === "former-original") return !!pointer.sha256 && r.forSha256 === pointer.sha256; + return !!pointer.compacted && r.forSha256 === pointer.compacted.result.sha256; } function codecName(vcodec: string | undefined): string { @@ -659,6 +691,21 @@ export function parseSavedVideoPointer(raw: unknown): SavedVideoPointer | null { if (alternates.length) pointer.alternates = alternates; const probed = parseProbe(r.probed); if (probed) pointer.probed = probed; + const pending = Array.isArray(r.pendingDrops) + ? r.pendingDrops + .map((d): SavedPendingDrop | null => { + const o = obj(d); + if (typeof o.file !== "string" || o.file === "") return null; + return { + file: o.file, + at: strOr(o.at), + ...((SAVED_ALTERNATE_KEPT_AS as readonly unknown[]).includes(o.keptAs) ? { keptAs: o.keptAs as SavedAlternateKeptAs } : {}), + ...(typeof o.sha256 === "string" && o.sha256 ? { sha256: o.sha256 } : {}), + }; + }) + .filter((d): d is SavedPendingDrop => d !== null) + : []; + if (pending.length) pointer.pendingDrops = pending; // And again: no `compacted`, the pointer parses as before. const compacted = parseCompacted(r.compacted); if (compacted) pointer.compacted = compacted; diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts @@ -49,6 +49,10 @@ export type SavedVideoCompactionSettings = { ssimMinSample: number; wholeFileSsimMin: number; wholeFileSsimMean: number; + wholeFileSigmaK: number; + wholeFileSigmaMargin: number; + wholeFileTileMin: number; + wholeFileTileRunFrames: number; availabilityMaxAgeDays: number; dropOriginal: CompactionDropOriginal; }; @@ -74,6 +78,10 @@ export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettin // the file): no frame below the floor, the mean at least the mean floor. wholeFileSsimMin: 0.9, wholeFileSsimMean: 0.97, + wholeFileSigmaK: 8, + wholeFileSigmaMargin: 0.03, + wholeFileTileMin: 0.7, + wholeFileTileRunFrames: 2, availabilityMaxAgeDays: 7, dropOriginal: "keep", }; @@ -98,8 +106,14 @@ export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCom ssimMinMean: "Without libvmaf: the SSIM the excerpts' mean must reach. Default 0.95.", ssimMinSample: "Without libvmaf: the SSIM no excerpt may fall below. Default 0.9.", wholeFileSsimMin: - "THE WHOLE-FILE COMPARISON: both copies decoded at 2 frames a second, 64 px wide, grey, frames paired by their time, and compared one by one (SSIM). No frame may fall below this. Default 0.9 (a good copy scores about 0.99; a black or misplaced stretch of a test pattern 0.5–0.8).", - wholeFileSsimMean: "The whole-file comparison's mean SSIM must reach this. Default 0.97.", + "THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0).", + wholeFileSsimMean: "The whole-file comparison's mean must reach this. Default 0.97.", + wholeFileSigmaK: + "The floor relative to the file itself: no frame below its mean − max(k × the frames' standard deviation, wholeFileSigmaMargin). Default k = 8 (measured: a good crf-36 copy has a spread of 0.0006, its worst frame 3 spreads under its mean).", + wholeFileSigmaMargin: "The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03.", + wholeFileTileMin: + "Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46).", + wholeFileTileRunFrames: "How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails.", availabilityMaxAgeDays: "How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7.", dropOriginal: @@ -140,6 +154,10 @@ export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompacti ssimMinSample: clampNum(r.ssimMinSample, d.ssimMinSample, 0, 1), wholeFileSsimMin: clampNum(r.wholeFileSsimMin, d.wholeFileSsimMin, 0, 1), wholeFileSsimMean: clampNum(r.wholeFileSsimMean, d.wholeFileSsimMean, 0, 1), + wholeFileSigmaK: clampNum(r.wholeFileSigmaK, d.wholeFileSigmaK, 1, 100), + wholeFileSigmaMargin: clampNum(r.wholeFileSigmaMargin, d.wholeFileSigmaMargin, 0, 1), + wholeFileTileMin: clampNum(r.wholeFileTileMin, d.wholeFileTileMin, 0, 1), + wholeFileTileRunFrames: Math.round(clampNum(r.wholeFileTileRunFrames, d.wholeFileTileRunFrames, 0, 300)), availabilityMaxAgeDays: clampNum(r.availabilityMaxAgeDays, d.availabilityMaxAgeDays, 0, 365), dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal) ? (r.dropOriginal as CompactionDropOriginal) diff --git a/common/lib/savedVideoOriginal.test.ts b/common/lib/savedVideoOriginal.test.ts @@ -11,6 +11,7 @@ import { parseSavedVideoPointer, savedAlternatesLine, } from "./savedVideo"; +import { writeCompactingMarker } from "./compactingMarker-server"; import { COMPACTING_MARKER_FILENAME, CompactionInProgressError, @@ -121,8 +122,7 @@ async function withCompacted(fn: (f: Fixture) => Promise<void>): Promise<void> { const readRaw = async (videoDir: string) => JSON.parse(await readFile(savedVideoPointerPath(videoDir), "utf8")); const writeRaw = (videoDir: string, raw: unknown) => writeFile(savedVideoPointerPath(videoDir), JSON.stringify(raw)); const CONFIRM = { confirmOriginal: true, readBack: READ_BACK } as const; -const liveMarker = (storeDir: string) => - writeFile(path.join(storeDir, COMPACTING_MARKER_FILENAME), JSON.stringify({ pid: process.pid, host: hostname(), startedAt: "2026-11-14T00:00" })); +const liveMarker = (storeDir: string) => writeCompactingMarker(storeDir); test("a pointer without `compacted` parses exactly as before", () => { const raw = { storedAt: "x", dir: "/s", file: "source-media.mp4", bytes: 3, keepReason: "pin" }; @@ -226,7 +226,7 @@ test("a video not known to be on its platform keeps its original until a review await withCompacted(async ({ videoDir, storeDir }) => { await assert.rejects( dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: GONE }), - /not known to be on its platform \(no availability record\).*Review the compacted copy first/, + /not known to be on its platform \(no availability record\).*Review the copy that stays first/, ); // With no availability record on disk at all, the default reads it as gone. await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, CONFIRM), /not known to be on its platform \(no availability record/); @@ -308,8 +308,9 @@ test("the drop writes the pointer first; an interrupted drop is seen and finishe const raw = await readRaw(videoDir); delete raw.alternates; raw.compacted.originalDropped = { at: "2026-11-20T00:00:00.000Z", by: "x", file: ORIGINAL, bytes: 1200, sha256: SHA_ORIGINAL, fileRemoved: false }; + raw.pendingDrops = [{ file: ORIGINAL, at: "2026-11-20T00:00:00.000Z", keptAs: "original", sha256: SHA_ORIGINAL }]; await writeRaw(videoDir, raw); - await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { presence: ON }), /not one of this video's listed alternates/); + await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { presence: ON }), /drop was interrupted: finish it with "confirmOriginal": true/); const r = await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true }); assert.equal(r.existed, true); await assert.rejects(stat(path.join(storeDir, ORIGINAL))); @@ -399,3 +400,97 @@ test("a checksum is written only while the pointer names the file that was hashe assert.ok(raw.compacted, "the rest of the pointer is kept"); }); }); + +// --- review round 2 ------------------------------------------------------------ + +async function makeFormer(videoDir: string, storeDir: string): Promise<string> { + // A download of another container extension lands: no rename, the original relabelled. + await writeFile(path.join(videoDir, "source-media.mkv"), "a new download"); + const p = await persistSourceVideo({ videoDir, sourceFilename: "source-media.mkv", storeDir, keepReason: "pin" }); + const former = p.alternates!.find((a) => a.sha256 === SHA_ORIGINAL)!; + assert.equal(former.keptAs, "former-original"); + assert.equal(former.file, ORIGINAL); + return former.file; +} + +test("F1: the after-verify drop names exactly what it means; a re-labelled original is not dropped", async () => { + await withCompacted(async ({ videoDir, storeDir }) => { + const captured = compactedOriginalOf((await loadSavedVideo(videoDir))!)!; + await makeFormer(videoDir, storeDir); + await assert.rejects( + dropSavedAlternate(videoDir, captured.file, { + confirmOriginal: true, + expect: { keptAs: "original", sha256: SHA_ORIGINAL, file: captured.file }, + presence: ON, + busy: () => null, + readBack: READ_BACK, + }), + /not what this drop expected \(original, .*it is former-original, .*nothing dropped/, + ); + await stat(path.join(storeDir, ORIGINAL)); + // Even without `expect`, confirmOriginal alone never drops a former original. + await assert.rejects(dropSavedAlternate(videoDir, captured.file, { ...CONFIRM, presence: ON }), /pass "confirmFormerOriginal": true/); + await stat(path.join(storeDir, ORIGINAL)); + }); +}); + +test("F1: a former original is dropped only with confirmFormerOriginal and the same gone/review rule", async () => { + await withCompacted(async ({ videoDir, storeDir }) => { + const file = await makeFormer(videoDir, storeDir); + await assert.rejects( + dropSavedAlternate(videoDir, file, { confirmFormerOriginal: true, presence: GONE }), + /not known to be on its platform .*Review the copy that stays first/, + ); + // The review is of the active copy that replaced it: it needs that copy's sha256. + await assert.rejects(recordOriginalReview(videoDir, { at: "x", by: "editor" }, { formerOriginal: file }), /no recorded sha256/); + await updateSavedVideoChecksum(videoDir, sha("a new download"), "source-media.mkv"); + const r = await recordOriginalReview(videoDir, { at: "2026-11-20T00:00:00.000Z", by: "editor" }, { formerOriginal: file }); + assert.equal(r.review?.forSha256, sha("a new download")); + await dropSavedAlternate(videoDir, file, { confirmFormerOriginal: true, presence: GONE }); + await assert.rejects(stat(path.join(storeDir, ORIGINAL))); + }); +}); + +test("F1: no automatic step passes confirmFormerOriginal (a scan of every caller)", async () => { + const roots = ["controller", "lib", "jobs", "ytdlp", "bin"].map((d) => path.join(import.meta.dirname, "..", d)); + const editorApp = path.join(import.meta.dirname, "..", "..", "editor", "app"); + // The flag's definition, and the person-driven ways in: the drop button, the + // ops route, the server action that both call. + const allowed = new Set([ + path.join(import.meta.dirname, "savedVideo-server.ts"), + path.join(editorApp, "api", "ops", "drop-saved-alternate", "route.ts"), + path.join(editorApp, "channels", "[slug]", "videos", "[id]", "videoActions.ts"), + path.join(editorApp, "channels", "[slug]", "videos", "[id]", "components", "cards", "SourceVideoSection.tsx"), + ]); + const found: string[] = []; + const walk = async (d: string): Promise<void> => { + for (const e of await readdir(d, { withFileTypes: true }).catch(() => [])) { + const p = path.join(d, e.name); + if (e.isDirectory()) { + if (e.name !== "node_modules" && !e.name.startsWith(".")) await walk(p); + } else if (/\.(ts|tsx|mjs)$/.test(e.name) && !/\.test\./.test(e.name)) { + if ((await readFile(p, "utf8")).includes("confirmFormerOriginal")) found.push(p); + } + } + }; + for (const r of [...roots, editorApp]) await walk(r); + assert.deepEqual(found.filter((f) => !allowed.has(f)), [], "an unexpected caller names confirmFormerOriginal"); + const compactor = await readFile(path.join(import.meta.dirname, "..", "controller", "compactSavedVideos.ts"), "utf8"); + assert.ok(!compactor.includes("confirmFormerOriginal")); + assert.match(compactor, /expect: \{ keptAs: "original", sha256: pointer\.compacted!\.source\.sha256, file: original\.file \}/); +}); + +test("an interrupted drop of an ordinary alternate is listed and finished by asking again", async () => { + await withCompacted(async ({ videoDir, storeDir }) => { + await writeFile(path.join(storeDir, "source-media.alt-360p-1.mp4"), "alt"); + const raw = await readRaw(videoDir); + // The state a crash between the pointer write and the rm leaves. + raw.pendingDrops = [{ file: "source-media.alt-360p-1.mp4", at: "2026-11-20T00:00:00.000Z" }]; + await writeRaw(videoDir, raw); + assert.equal((await loadSavedVideo(videoDir))!.pendingDrops?.[0].file, "source-media.alt-360p-1.mp4"); + const r = await dropSavedAlternate(videoDir, "source-media.alt-360p-1.mp4"); + assert.equal(r.existed, true); + await assert.rejects(stat(path.join(storeDir, "source-media.alt-360p-1.mp4"))); + assert.equal((await readRaw(videoDir)).pendingDrops, undefined); + }); +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -26,6 +26,15 @@ - Saved-video pointer writes now go under the pointer's lock and re-read it there. A download planned before a compaction refuses to write over it, and a persist of a video being compacted waits for a re-run. - A channel opts out with `excludeFromCompaction`. There is no lane: it runs only when asked. + - The whole-file comparison scores EVERY frame, whole and in an 8×8 grid of tiles, against a hard floor, the + file's own spread and a tile floor held for more than 2 frames. The after-verify drop names exactly the original + it means. A former original needs its own `"confirmFormerOriginal": true`. The `.compacting.json` marker is held + through the drop and checked against boot, host, pid start time and job. Stale ones are swept, and listed or + cleared with `compaction-markers`. The prune goes on past a video it may not drop. An interrupted drop of any + alternate is listed (`pendingDrops`) and finished by asking again. + - **ROLLBACK: do not roll the editor back past this release while `pnpm ops get kept-originals` lists anything.** + An older editor does not know `"keptAs": "original"` / `"former-original"`, would treat them as ordinary + alternates, and could prune or drop the only original. - **Clip windows can be asked for taller than 720, and the 720 window stays.** A `maxHeight` above 720 on fetch-windows, fetch-window or `fetch_clip` asks for a taller window, up to the new setting `clips.windowMaxHeight` (default 1080; a taller ask is held to it and the answer says so). With no `maxHeight` a diff --git a/editor/app/api/ops/compaction-markers/route.ts b/editor/app/api/ops/compaction-markers/route.ts @@ -0,0 +1,31 @@ +import { NextResponse } from "next/server"; +import { compactionMarkersAction } from "../../../saved-videos/compactActions"; +import { ops, reqSlug, reqVideoId, type OpsBody, OpsInputError } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST {} | { clear: { slug, id } } +// -> { ok, markers: [{ slug, id, dir, live, why, marker }], cleared? } +// +// The "being compacted" markers (`<store dir>/.compacting.json`, +// lib/compactingMarker-server.ts): each one, LIVE (its compaction runs: same +// kernel boot, host, pid and pid start time, its job running, younger than +// 72 h) or STALE, and why. `clear` removes one video's marker when it is +// stale; a live one is refused — cancel its job instead. Stale markers are +// also swept at editor boot and at the start of every compaction run. +function optClear(body: OpsBody): { slug: string; id: string } | undefined { + if (body.clear === undefined) return undefined; + if (!body.clear || typeof body.clear !== "object" || Array.isArray(body.clear)) { + throw new OpsInputError('"clear" must be { "slug", "id" }'); + } + const c = body.clear as OpsBody; + return { slug: reqSlug(c, "slug"), id: reqVideoId(c, "id") }; +} + +export async function POST(request: Request) { + return ops(request, ["clear"], async (body) => { + const clear = optClear(body); + const res = await compactionMarkersAction(clear ? { clear } : {}); + return NextResponse.json({ ok: true, ...res }); + }); +} diff --git a/editor/app/api/ops/drop-saved-alternate/route.ts b/editor/app/api/ops/drop-saved-alternate/route.ts @@ -4,7 +4,7 @@ import { ops, opsFail, optBool, reqSlug, reqString, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, file, dryRun?, confirmOriginal? } +// POST { slug, id, file, dryRun?, confirmOriginal?, confirmFormerOriginal? } // -> { ok, dryRun, file, path, existed, bytes, remaining, alternate } // // Drop ONE saved alternate of one video — a copy kept beside a newer download @@ -23,13 +23,19 @@ export const dynamic = "force-dynamic"; // compacted copy is read back from disk and must match its recorded sha256; // and a video not known to be on its platform needs its review recorded first // (review-compacted-original). `get compaction-review` lists each one's state. +// A FORMER original (`keptAs: "former-original"`) needs its own +// "confirmFormerOriginal": true — a person's word, never an automatic step's. export async function POST(request: Request) { - return ops(request, ["slug", "id", "file", "dryRun", "confirmOriginal"], async (body) => { + return ops(request, ["slug", "id", "file", "dryRun", "confirmOriginal", "confirmFormerOriginal"], async (body) => { const res = await dropSavedAlternateAction( reqSlug(body, "slug"), reqVideoId(body, "id"), reqString(body, "file"), - { dryRun: optBool(body, "dryRun") ?? false, confirmOriginal: optBool(body, "confirmOriginal") ?? false }, + { + dryRun: optBool(body, "dryRun") ?? false, + confirmOriginal: optBool(body, "confirmOriginal") ?? false, + confirmFormerOriginal: optBool(body, "confirmFormerOriginal") ?? false, + }, ); if (!res.ok) return opsFail(res.error); const r = res.result; diff --git a/editor/app/api/ops/kept-originals/route.ts b/editor/app/api/ops/kept-originals/route.ts @@ -0,0 +1,27 @@ +import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import { keptOriginalsList } from "../../../saved-videos/compactActions"; +import { readRoute } from "../_read"; +import { opsFail } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// GET [?slug=<channel>] +// -> { ok, count, videos: [{ slug, id, active, compacted, kept: [{ file, +// keptAs: "original" | "former-original", sha256?, bytes }], +// pendingDrops: [{ file, keptAs?, at }] }], notAnswering } +// +// Every saved video that keeps an ORIGINAL or a FORMER ORIGINAL beside its +// active copy, or has a drop in flight (a file the pointer no longer lists, +// still on disk: drop it again by name to finish). An editor built from +// before compaction does not know those labels and would treat such a copy +// as an ordinary droppable alternate: while this list is not empty, do not +// roll the editor back past that release (OPERATING.md, "Compact saved +// videos"). Pointers only — no container is opened. +export async function GET(request: Request) { + return readRoute(request, ["slug"], async (q) => { + const slug = q.get("slug")?.trim() || undefined; + if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); + const { rows, notAnswering } = await keptOriginalsList(slug ? { slug } : {}); + return { count: rows.length, videos: rows, notAnswering }; + }); +} diff --git a/editor/app/api/ops/review-compacted-original/route.ts b/editor/app/api/ops/review-compacted-original/route.ts @@ -4,7 +4,7 @@ import { ops, opsFail, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, note? } +// POST { slug, id, note?, formerOriginal? } // -> { ok, original, watched } // // A person's review of a compacted copy: "the compacted copy is proven good" — @@ -17,9 +17,11 @@ export const dynamic = "force-dynamic"; // "confirmOriginal": true, drops its original. Refused when the video keeps no // original beside a compacted copy, or the copy's checks did not pass. export async function POST(request: Request) { - return ops(request, ["slug", "id", "note"], async (body) => { + return ops(request, ["slug", "id", "note", "formerOriginal"], async (body) => { const res = await reviewCompactedOriginalAction(reqSlug(body, "slug"), reqVideoId(body, "id"), { by: "ops", + // A FORMER original by its file name: the review is of the active copy that replaced it. + ...(optString(body, "formerOriginal") ? { formerOriginal: optString(body, "formerOriginal") } : {}), ...(optString(body, "note") ? { note: optString(body, "note") } : {}), }); if (!res.ok) return opsFail(res.error); diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx @@ -355,7 +355,9 @@ function SavedAlternateRow({ {armed ? ( <> <span> - {original + {alternate.keptAs === "former-original" + ? "This is the ORIGINAL of an earlier compacted copy; the active copy has replaced it since. A video not known to be on its platform needs a review of the active copy first. Delete it? No undo." + : original ? "This is the ORIGINAL the active copy was re-encoded from. The compacted copy is read back from disk first; a video not known to be on its platform needs its review recorded. Delete the original? No undo." : alternate.keptAs === "proxy" ? "This is the lower-quality copy kept on purpose as a proxy. Delete it from the store? No undo." @@ -372,7 +374,11 @@ function SavedAlternateRow({ slug, videoId, alternate.file, - original ? { confirmOriginal: true } : {}, + original + ? { confirmOriginal: true } + : alternate.keptAs === "former-original" + ? { confirmFormerOriginal: true } + : {}, ); if (!res.ok) setError(res.error); setArmed(false); diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -1474,7 +1474,7 @@ export async function dropSavedAlternateAction( slug: string, videoId: string, file: string, - opts: { dryRun?: boolean; confirmOriginal?: boolean } = {}, + opts: { dryRun?: boolean; confirmOriginal?: boolean; confirmFormerOriginal?: boolean } = {}, ): Promise<{ ok: true; result: DropSavedAlternateResult } | { ok: false; error: string }> { const paths = getPaths(); const config = await readChannelConfig(paths, slug); @@ -1489,6 +1489,8 @@ export async function dropSavedAlternateAction( dryRun: opts.dryRun, paths, ...(opts.confirmOriginal ? { confirmOriginal: true } : {}), + // A person's word only (this action is the button and the ops route). + ...(opts.confirmFormerOriginal ? { confirmFormerOriginal: true } : {}), // The gone rule's freshness, and no drop while a download or persist // of this video is queued or running. maxAgeDays: getSettings().savedVideoCompaction.availabilityMaxAgeDays, diff --git a/editor/app/saved-videos/compactActions.ts b/editor/app/saved-videos/compactActions.ts @@ -6,8 +6,11 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { + clearCompactionMarker, compactSavedVideos, effectiveCompactionSettings, + listCompactionMarkers, + listKeptOriginals, listCompactionReview, planCompaction, type CompactItem, @@ -87,6 +90,7 @@ export async function compactChannelVideosAction( // The settings as they are when the job STARTS (it may have queued). const result = await compactSavedVideos({ paths, + jobId: ctx.jobId, settings: settingsFor(overrides), items: wanted.map((id) => ({ slug, id })), mode: opts.mode, @@ -199,7 +203,7 @@ export async function compactionReviewList(opts: { slug?: string } = {}): Promis export async function reviewCompactedOriginalAction( slug: string, videoId: string, - opts: { note?: string; by?: string } = {}, + opts: { note?: string; by?: string; formerOriginal?: string } = {}, ): Promise<{ ok: true; original: SavedVideoAlternate; watched: string } | { ok: false; error: string }> { const paths = getPaths(); const config = await readChannelConfig(paths, slug); @@ -212,7 +216,7 @@ export async function reviewCompactedOriginalAction( at: new Date().toISOString(), by: opts.by ?? "editor", ...(opts.note?.trim() ? { note: opts.note.trim() } : {}), - }); + }, opts.formerOriginal ? { formerOriginal: opts.formerOriginal } : {}); safeRevalidate([`/channels/${slug}/videos/${videoId}`, "/saved-videos"]); return { ok: true, original, watched: original.review?.forSha256 ?? "" }; } catch (e) { @@ -220,3 +224,18 @@ export async function reviewCompactedOriginalAction( throw e; } } + +// Every pointer that keeps an original or a former one, or has a drop in +// flight: what a rollback past this release would mistreat (OPERATING.md). +export async function keptOriginalsList(opts: { slug?: string } = {}) { + const notAnswering: string[] = []; + const rows = await listKeptOriginals({ paths: getPaths(), ...(opts.slug ? { channelSlug: opts.slug } : {}), notAnswering }); + return { rows, notAnswering: notAnswering.sort() }; +} + +// The `.compacting.json` markers, and clearing a stale one. +export async function compactionMarkersAction(opts: { clear?: CompactItem } = {}) { + const paths = getPaths(); + const cleared = opts.clear ? { ...opts.clear, ...(await clearCompactionMarker(paths, opts.clear)) } : null; + return { markers: await listCompactionMarkers(paths), ...(cleared ? { cleared } : {}) }; +} diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -103,6 +103,26 @@ export async function register() { /* a health pass that fails to arm must not block server readiness */ } + // STALE "BEING COMPACTED" MARKERS (common/lib/compactingMarker-server.ts): + // none survives a restart — every compaction of the last process is over — + // so each is removed, on an idle boot too (it starts no work). The job + // registry probe a live marker is checked against is registered here. + void (async () => { + try { + const { registerCompactionJobProbe } = await import("yt-dlp-transcript-common/lib/compactingMarker-server"); + const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); + registerCompactionJobProbe((id) => { + const j = getRegistry().get(id); + return !!j && (j.status === "running" || j.status === "queued"); + }); + const { sweepCompactingMarkers } = await import("yt-dlp-transcript-common/controller/compactSavedVideos"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + await sweepCompactingMarkers(getPaths(), (line) => console.log(line.trimEnd())); + } catch { + /* a sweep that fails must not block server readiness */ + } + })(); + // ONE PASS OVER THE STORAGE LOCATIONS, and it runs on an IDLE BOOT TOO: it // only reads, like the health pass above. // diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -297,6 +297,10 @@ const GETTERS = { // drop, nothing): the compaction review list. "compaction-review": (slug) => slug ? `/api/ops/compaction-review?slug=${encodeURIComponent(slug)}` : "/api/ops/compaction-review", + // Every pointer that keeps an original or a former original (what an editor + // rolled back past compaction would mistreat), and drops in flight. + "kept-originals": (slug) => + slug ? `/api/ops/kept-originals?slug=${encodeURIComponent(slug)}` : "/api/ops/kept-originals", // Every site: id, title, siteUrl, Pages project, audience, policy, channels. sites: () => "/api/ops/sites", // The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's, @@ -382,6 +386,7 @@ const GET_ARG_OPTIONAL = new Set([ "storage", "saved-alternates", "compaction-review", + "kept-originals", "sites", "archives", "workers", @@ -510,6 +515,9 @@ const ACTIONS = [ // ({slug, id, note?}). "compact-saved-videos", "review-compacted-original", + // The "being compacted" markers, live or stale, and clearing a stale one + // ({} | {clear: {slug, id}}). + "compaction-markers", // Write transcript.cues.json from each video's raw transcript ({slug, ids?, // force?}) — what a reader with no index build wants. "build-cues", @@ -1132,6 +1140,7 @@ export function usage() { " pnpm ops get storage | sites | workers | auto-queue | scheduler", " pnpm ops get saved-alternates [<slug>]", " pnpm ops get compaction-review [<slug>]", + " pnpm ops get kept-originals [<slug>]", " pnpm ops get services", " pnpm ops get x-session [<slug>]", " pnpm ops get x-run [<run id>]", @@ -1200,6 +1209,12 @@ export function usage() { " availability and why, the original's entry, sizes, checks, the re-check,", ' "watch" (both files and an smplayer command that plays them) and any', ' "leftover" of an interrupted drop.', + "get kept-originals [<slug>] lists every saved video that keeps an original", + ' ("keptAs": "original") or a former original ("former-original") beside', + " its active copy, or has a drop in flight (pendingDrops: a file the pointer", + " no longer lists, still on disk -- drop it again by name to finish). An", + " editor from before compaction would treat those as ordinary droppable", + " alternates: while this is not empty, do not roll the editor back past it.", "get sites lists every site: id, title, siteUrl, Pages project, audience,", " listed, search, publish policy, channels, citedChannels. (`get publish`", " is the status.)", @@ -1462,7 +1477,9 @@ export function usage() { " (size, sha256, container, length) before it goes; a video not freshly", " checked on its platform needs a review of this copy recorded first; and", " nothing goes while a download or persist of the video is queued or", - " running, or while it is being compacted.", + " running, or while it is being compacted. A FORMER original", + ' ("former-original") needs its own "confirmFormerOriginal": true, and', + " the same gone/review rule.", "", 'diarize runs a channel\'s "Diarize speakers" as a job: {"slug"}. Every video', ' still holding audio with no current diarization.json is diarized, and a', @@ -1898,12 +1915,18 @@ export function usage() { " checked on its platform (get compaction-review). There is no backup of", " the store: after a drop the compacted copy is the only copy.", "", + 'compaction-markers lists the "being compacted" markers (.compacting.json),', + ' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale', + " one; a live one is refused (cancel its job). Stale ones are also swept at", + " editor boot and at the start of every compaction run.", + "", 'review-compacted-original records a person\'s review of one compacted copy', ' (watch it first: get compaction-review\'s "watch"): {"slug", "id",', ' "note"?}. It names the copy it is for ("watched", its sha256) and counts', " for that copy only; it changes nothing on disk. It is what lets", ' drop-saved-alternate ("confirmOriginal": true) drop the original of a', - " video not freshly checked on its platform.", + " video not freshly checked on its platform. \"formerOriginal\": \"<file>\"", + " reviews the active copy that replaced a former original instead.", "", 'import-archive-org imports archive.org media into a channel, as one job on', ' archive.org\'s queue: {"slug", "item", "files": [...] | "match": "<regex>"}', diff --git a/settings.json.example b/settings.json.example @@ -169,6 +169,10 @@ "ssimMinSample": 0.9, "wholeFileSsimMin": 0.9, "wholeFileSsimMean": 0.97, + "wholeFileSigmaK": 8, + "wholeFileSigmaMargin": 0.03, + "wholeFileTileMin": 0.7, + "wholeFileTileRunFrames": 2, "availabilityMaxAgeDays": 7, "dropOriginal": "keep" },