commit 70331bdee86f349a262eafbd21ed3ea66491dd79
parent fe72e5bc909f7c495241290ce767f6d23cc6587a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 05:22:02 -0500
stored text, review-2 fixes: no capture is removed because another arrived
R1. fetch-chat `replace` over a stored chat first renames the stored capture
to chat-capture-kept.<UTC stamp>.json.zst (renameMediaFile: same bytes, a
tier link's beside themselves). The name is media and tierable, so it moves
with the video and goes with it on deletion, and no reader, lister, index,
compressor or restore treats it as the chat. Both captures are measured in
the log and the result (bytes, messages, first/last message time); a replay
with messages then becomes the chat and the earlier capture stays kept. An
empty replay is kept the same way and the stored capture goes back as the
chat; so does a failed pass, no replay or a .part. Nothing removes a kept
capture automatically; the dry run lists them. The compressor's `changed`
paths keep the stored copy of the earlier content beside the new file
(both-differ, for a person) instead of removing it.
R2. The files card's delete removes only the file named, never its other
form; the note says the other remains and whether readers still see the
chat.
R3. Compress, restore, the set-aside and the delete take a per-directory
lock file, .stored-text.lock, linked from a temp naming its owner (pid and
start token); a second process answers busy while the owner runs and takes
over a stale one. The restore looks at the plain file again (regular,
through the expected link, size and hash of a fresh decode) right before
the stored form goes; the compressor looks at the stored file again before
the original goes. Tested with a real second process.
Nits: the in-process set lives on globalThis; the lane's temp links are
`.stlink-` (never the tier hook's `.tierlink-<pid>`); a token-named temp,
set-aside or lock is classified scratch (the old patterns missed the token
form); a restore's EEXIST keeps a placed copy the name resolves to; a
restored real file is tiered like the compressor's output; OPERATING.md says
the restore needs hard links.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
19 files changed, 820 insertions(+), 245 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -160,7 +160,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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": "<file>" 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. | |
| `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | |
-| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused and both kept. A file a writer replaces during the run is kept, and the older stored copy removed. "dryRun": true answers per channel the raw chats, their bytes, the stored ones, the estimate after (about 5 %, an estimate) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "restore": true is the rollback: every stored chat put back into its plain form, verified the same way in reverse (decoded beside, fsynced, read back against a fresh decode, the same times, then the .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat (OPERATING.md). | |
+| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused and both kept. A file a writer replaces during the run is kept and read; the earlier content's stored copy is kept beside it. The dry run lists earlier chat captures a re-fetch kept (chat-capture-kept.\*.json.zst), which nothing removes automatically. "dryRun": true answers per channel the raw chats, their bytes, the stored ones, the estimate after (about 5 %, an estimate) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "restore": true is the rollback: every stored chat put back into its plain form, verified the same way in reverse (decoded beside, fsynced, read back against a fresh decode, the same times, then the .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat (OPERATING.md). | |
| `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}'` |
@@ -202,7 +202,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `rerun-service-jobs` | — | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
| `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:<slug>:<id>), 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. A raw live chat named in one form while the other is there (transcript.live\_chat.json and its .zst): both go when they hold the same content; only the named one when they differ, and "note" says the other is still there. | |
+| `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. A raw live chat named in one form while the other is there (transcript.live\_chat.json and its .zst): only the named one goes, never the other, and "note" says the other is still there. | |
| `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. 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` |
@@ -237,7 +237,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
| `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -> {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` |
-| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). "replace": true fetches the replay again over a chat stored compressed (.zst): when a whole new plain chat lands, the stored one is removed -- one form is left; a pass that lands nothing keeps the stored chat. Refused over a plain chat (delete it on the files card first) and with "renormalize". | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` |
+| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). "replace": true fetches the replay again over a chat stored compressed (.zst). The stored capture is first kept as chat-capture-kept.<UTC stamp>.json.zst (no reader sees it; never removed automatically). A replay with messages becomes the chat; an empty one is kept too and, like no replay, leaves the stored capture the chat. The log gives both captures' bytes, message counts and first/last message times. Refused over a plain chat (delete it on the files card first) and with "renormalize". | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` |
| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /cookies, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -1606,19 +1606,28 @@ pnpm ops compress-text --json '{"restore":true}' --wait # the roll
capture or a download in progress); a video whose `live-recording.json` says `recording`, or with a job running; a
drive that is not mounted or not answering; a channel whose media is moving. **Both forms present with different
content are refused, and both kept**: the plain one is what readers read; look at the pair on the video's files
- card. A file a writer replaces during the run is kept, and the older stored copy removed.
+ card. A file a writer replaces during the run is kept and read, and the stored copy of the earlier content is
+ kept beside it: two different captures are never settled by deleting one.
- **One job per channel** with work, on one machine-wide queue, so a move of that channel's media refuses while it
- runs. **Paced.** It waits while render mode holds the machine, reads at 40 MB/s (8 MB/s while a live recording runs).
+ runs, and a lock file in each video dir (`.stored-text.lock`) makes a second process (a second editor) wait its
+ turn instead of interleaving. **Paced.** It waits while render mode holds the machine, reads at 40 MB/s (8 MB/s while
+ a live recording runs).
**Started by a person only**: a restart closes a queued one and resumes no interrupted one (it removes originals);
a person re-runs it, and a re-run continues. Drain stops it between files.
- **One form of a chat, always.** No download fetches a chat that is on disk in either form: the chat-only pass is
skipped, the caption passes leave the chat out of `--sub-langs`, `fetch-chat` normalizes what is here. To fetch a
- stored chat again on purpose: `pnpm ops fetch-chat --json '{"slug":"<slug>","id":"<id>","replace":true}'` — when a
- whole new plain chat lands, the stored one is removed; a pass that lands nothing (a stream since deleted) keeps it.
- Over a plain chat `replace` is refused: delete it on the files card first, then fetch-chat.
-- **Deleting a chat**: through the video's files card (or `pnpm ops delete-file`), never with `rm`. With both forms
- there and the same content, both go (otherwise the other would come back as the file); with different content
- only the one named goes, and the card says the other is still there.
+ stored chat again on purpose: `pnpm ops fetch-chat --json '{"slug":"<slug>","id":"<id>","replace":true}'`. The
+ stored capture is first **kept** as `chat-capture-kept.<UTC stamp>.json.zst` beside it (the same bytes; no reader of
+ the chat, the index, the compressor or the restore sees it; it is media, so it moves with the video, and deleting
+ the video removes it). The job log gives both captures' bytes, message counts and first/last message times. A
+ replay with messages then becomes the chat; an empty replay is kept the same way and, like no replay at all, leaves
+ the stored capture the chat. **Nothing removes a kept capture automatically** — a platform's replay is often
+ shorter than the live capture, which cannot be fetched again. The dry run lists them ("earlier captures kept");
+ delete one on the files card when you have looked at it. Over a plain chat `replace` is refused: delete it on the
+ files card first, then fetch-chat.
+- **Deleting a chat**: through the video's files card (or `pnpm ops delete-file`), never with `rm`. Only the file you
+ name goes, never its other form; the card says when the other is still there (with the same content, readers still
+ see the chat; with different content, the other is what readers read).
- **By hand:** `zstdcat transcript.live_chat.json.zst` reads one.
#### Rollback: restore BEFORE reverting
@@ -1636,9 +1645,11 @@ pnpm ops compress-text --json '{"verify":true}' --wait # afterwards:
The restore is the compressor in reverse: each stored chat is decoded beside itself (on the same drive), fsynced,
read back and hashed against a fresh decode of the `.zst`, given the same times, put in place without replacing
-anything, and only then is the `.zst` removed through `removeMediaFile`. A kill at any step leaves a whole copy; a
-re-run finishes. The raw chats then take their plain size again (the dry run says how much): about 20 times the
-stored size.
+anything (a hard link: the drive must support them — ext4 does; on exFAT or a CIFS mount the restore refuses each
+file and leaves it stored), looked at again (size and hash), and only then is the `.zst` removed through
+`removeMediaFile`. A kill at any step leaves a whole copy; a re-run finishes. The raw chats then take their plain size
+again (the dry run says how much): about 20 times the stored size. Kept earlier captures
+(`chat-capture-kept.*.json.zst`) are not restored: an older checkout ignores them, and they stay where they are.
### Compact saved videos
diff --git a/common/controller/compressText.test.ts b/common/controller/compressText.test.ts
@@ -253,3 +253,22 @@ test("restore through the job: a dry run touches nothing; a restore with a limit
}
assert.deepEqual(await readdir(path.join(paths.channelsDir, "theta", "media", "t1")), [CHAT]);
});
+
+// REVIEW-2 R1: an earlier capture a re-fetch kept is listed by the dry run as
+// "earlier captures kept", with its bytes — and no run touches it.
+test("the dry run lists earlier captures kept; neither a compress nor a restore touches one", async () => {
+ await channel("iota", { i1: body("i1", 200) });
+ const d = path.join(paths.channelsDir, "iota", "data", "i1");
+ const keptName = "chat-capture-kept.20261121T040000Z.json.zst";
+ const { encodeStoredBytes } = await import("../lib/storedText-server");
+ const keptBytes = await encodeStoredBytes(Buffer.from(body("earlier", 300)));
+ await writeFile(path.join(d, keptName), keptBytes);
+ const lines: string[] = [];
+ const plan = await compressText({ paths, slugs: ["iota"], dryRun: true, onLog: (l) => lines.push(l) });
+ assert.equal(plan.channels[0].keptCaptures, 1);
+ assert.equal(plan.channels[0].keptCaptureBytes, keptBytes.length);
+ assert.match(lines.join(""), /earlier captures kept: 1 \(/);
+ await compressText({ paths, slugs: ["iota"], quietMs: 0, onLog: () => {} });
+ await compressText({ paths, slugs: ["iota"], restore: true, onLog: () => {} });
+ assert.deepEqual(await readFile(path.join(d, keptName)), keptBytes, "untouched");
+});
diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts
@@ -40,6 +40,7 @@ import { open, readdir, stat, statfs } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import { LIVE_CHAT_FILENAME } from "../lib/videoStatus";
import { storedFormsIn, storedNameOf } from "../lib/storedText";
+import { isKeptChatCapture } from "../lib/mediaTier";
import { frameContentSize } from "../lib/storedText-server";
import {
compressStoredText,
@@ -103,6 +104,11 @@ export type ChannelLine = {
// stopped run's leftover; a restore: the stored form or a leftover) — a
// dir with only a leftover still has work.
pending?: number;
+ // Earlier chat captures kept by a re-fetch (`chat-capture-kept.*.json.zst`,
+ // lib/mediaTier.ts): never removed automatically — counted so a person sees
+ // them.
+ keptCaptures?: number;
+ keptCaptureBytes?: number;
// Dry run only: what the plain files would take at the estimated ratio
// (a restore's dry run: the stored files' logical bytes — exact).
estimateAfterBytes?: number;
@@ -199,6 +205,7 @@ async function surveyChannel(
work: Candidate[];
// Every dir a restore visits: the stored form, or a leftover.
restoreWork: Candidate[];
+ kept: { files: number; bytes: number };
}> {
const dataDir = path.join(channelDir, "data");
const ids = (await readdir(dataDir).catch(() => [] as string[])).sort();
@@ -206,6 +213,7 @@ async function surveyChannel(
const stored: { id: string; videoDir: string; bytes: number; logical: number }[] = [];
const work: Candidate[] = [];
const restoreWork: Candidate[] = [];
+ const kept = { files: 0, bytes: 0 };
const sizeOf = (p: string) =>
(drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null);
for (const id of ids) {
@@ -214,6 +222,10 @@ async function surveyChannel(
if (!entries) continue;
const forms = storedFormsIn(entries, LIVE_CHAT_FILENAME);
const leftover = hasStoredTextLeftover(entries, LIVE_CHAT_FILENAME);
+ for (const k of entries.filter(isKeptChatCapture)) {
+ kept.files += 1;
+ kept.bytes += (await sizeOf(path.join(videoDir, k))) ?? 0;
+ }
let size: number | null = null;
if (forms === "plain" || forms === "both") {
size = await sizeOf(path.join(videoDir, LIVE_CHAT_FILENAME));
@@ -234,7 +246,7 @@ async function surveyChannel(
const bySize = (a: Candidate, b: Candidate) => a.size - b.size || (a.id < b.id ? -1 : 1);
plain.sort(bySize);
work.sort(bySize);
- return { plain, stored, work, restoreWork };
+ return { plain, stored, work, restoreWork, kept };
}
export async function compressText(opts: CompressTextOptions): Promise<CompressTextResult> {
@@ -279,7 +291,10 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
continue;
}
const drive = media.status === "ok" ? media.target : undefined;
- const { plain, stored, work, restoreWork } = await surveyChannel(channelDir, drive);
+ const { plain, stored, work, restoreWork, kept } = await surveyChannel(channelDir, drive);
+ line.keptCaptures = kept.files;
+ line.keptCaptureBytes = kept.bytes;
+ const keptText = kept.files ? `; earlier captures kept: ${kept.files} (${fmtBytes(kept.bytes)})` : "";
line.plainFiles = plain.length;
line.plainBytes = plain.reduce((a, c) => a + c.size, 0);
line.storedFiles = stored.length;
@@ -296,11 +311,11 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
corpus: await freeOf(path.join(channelDir, "data")),
...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}),
};
- if (line.storedFiles > 0) {
+ if (line.storedFiles + kept.files > 0) {
say(
`${slug}: ${line.storedFiles} stored chat(s), ${fmtBytes(line.storedBytes)} → ${fmtBytes(line.storedLogicalBytes)} ` +
`as plain files; free on ${drive ? "the media drive" : "the corpus disk"} ` +
- `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}`,
+ `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}${keptText}`,
);
}
continue;
@@ -372,13 +387,13 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
corpus: await freeOf(path.join(channelDir, "data")),
...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}),
};
- if (line.plainFiles + line.storedFiles > 0) {
+ if (line.plainFiles + line.storedFiles + kept.files > 0) {
say(
`${slug}: ${line.plainFiles} raw chat(s), ${fmtBytes(line.plainBytes)} → ~${fmtBytes(line.estimateAfterBytes)} ` +
`(estimate, ${Math.round(CHAT_RATIO_ESTIMATE * 100)} %); already stored ${line.storedFiles} ` +
`(${fmtBytes(line.storedBytes)} holding ${fmtBytes(line.storedLogicalBytes)}); ` +
`free on ${drive ? "the media drive" : "the corpus disk"} ` +
- `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}`,
+ `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}${keptText}`,
);
}
continue;
@@ -475,7 +490,12 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
} else if (dryRun) {
const tot = channels.reduce((a, c) => a + c.plainBytes, 0);
const n = channels.reduce((a, c) => a + c.plainFiles, 0);
- say(`Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate). Nothing was written.`);
+ const kf = channels.reduce((a, c) => a + (c.keptCaptures ?? 0), 0);
+ const kb = channels.reduce((a, c) => a + (c.keptCaptureBytes ?? 0), 0);
+ say(
+ `Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate)` +
+ `${kf ? `; earlier captures kept: ${kf} (${fmtBytes(kb)}), never removed automatically` : ""}. Nothing was written.`,
+ );
} else if (!verify) {
const c = channels.reduce((a, l) => a + (l.compressed ?? 0), 0);
const b = channels.reduce((a, l) => a + (l.bytesBefore ?? 0), 0);
diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts
@@ -429,67 +429,110 @@ test("renormalize: held by the media guard while the channel's media is moving",
}
});
-// THE ONE-FORM RULE FOR A DELIBERATE RE-FETCH (lane text-compress, REVIEW-1
-// F2): fetch-chat `replace` over a chat stored compressed. yt-dlp does not see
-// the `.zst` and writes the plain name; when that lands whole, the older
-// stored form goes — exactly one form is left, the new one, and readers read
-// it. A pass that lands nothing (a deleted stream), fails, or leaves a `.part`
-// keeps the stored chat as it was. Over a plain chat, `replace` is refused.
-test("replace: over a stored chat the new plain file wins and the stored one goes; nothing landed keeps it", async () => {
+// A DELIBERATE RE-FETCH OVER A STORED CAPTURE (lane text-compress, REVIEW-2
+// R1): fetch-chat `replace`. NOTHING EVER REMOVES A CAPTURE BECAUSE A
+// DIFFERENT ONE ARRIVED — a platform's replay is often shorter than the live
+// capture, and the capture cannot be fetched again. The stored capture is kept
+// as `chat-capture-kept.<stamp>.json.zst` (no reader sees it), both are
+// measured in the log and the result, and only then does the new replay
+// become the chat. An empty replay, no replay, a failed pass or a `.part`: the
+// stored capture stays THE chat. Over a plain chat, `replace` is refused.
+test("replace: a SHORTER replay over a longer stored capture — both survive, the longer one byte-identical", async () => {
const { storeFixture } = await import("../testing/storedTextFixture");
- const { readStoredText } = await import("../lib/storedText-server");
+ const { readStoredText, decodeStoredBytes, readdirLogical } = await import("../lib/storedText-server");
+ const { isKeptChatCapture } = await import("../lib/mediaTier");
+ const { readSubTracks } = await import("../lib/videoStatus");
const CHAT = "transcript.live_chat.json";
- const OLD = [chatLine(1, "a", "old whole capture"), chatLine(2, "b", "more")].join("\n") + "\n";
- const NEW = chatLine(1, "a", "re-fetched") + "\n";
- const forms = async (d: string) => (await readdir(d)).filter((e) => e.startsWith("transcript.live_chat")).sort();
-
- // Landed: one form, the new one.
- const d1 = await video("rp1", { webpage_url: "https://www.youtube.com/watch?v=rp1", was_live: true });
- await writeFile(path.join(d1, CHAT), OLD);
- await storeFixture(d1, CHAT);
- const ok = stubRunner({ writes: NEW });
- const l = log();
- const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "rp1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: ok.run, replace: true });
- assert.ok(job.ok, JSON.stringify(job));
- void job.stream.cancel();
- assert.equal((await job.done).status, "done");
- assert.equal(ok.calls.length, 1, "a deliberate re-fetch spawns");
- assert.deepEqual(await forms(d1), [CHAT], "exactly one form: the new plain file");
- assert.equal(await readStoredText(d1, CHAT, "utf8"), NEW);
- assert.equal(JSON.parse(await readFile(path.join(d1, "live_chat.cues.json"), "utf8")).cues.length, 1, "normalized from the new file");
-
- // Nothing landed (the source has no replay any more): the stored chat stays.
- for (const [id, runner] of [
- ["rp2", stubRunner({ writes: null })],
- ["rp3", stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] rp3: Video unavailable" })],
- ] as const) {
+ const LONG = [chatLine(1, "a", "live 1"), chatLine(2, "b", "live 2"), chatLine(3, "c", "live 3"), chatLine(900, "d", "live 4")].join("\n") + "\n";
+ const SHORT = chatLine(1, "a", "replay 1") + "\n";
+ for (const tiered of [false, true]) {
+ const id = tiered ? "rpt1" : "rp1";
const d = await video(id, { webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true });
- await writeFile(path.join(d, CHAT), OLD);
+ if (tiered) {
+ const media = path.join(CORPUS, "channels", SLUG, "media", id);
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), LONG);
+ const { symlink } = await import("node:fs/promises");
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(d, CHAT));
+ } else {
+ await writeFile(path.join(d, CHAT), LONG);
+ }
await storeFixture(d, CHAT);
+ const ok = stubRunner({ writes: SHORT });
+ const l = log();
const r = await fetchLiveChat({
paths, slug: SLUG, videoId: id, videoUrl: `https://www.youtube.com/watch?v=${id}`, channelConfig: CONFIG,
- cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run: runner.run, replace: true, paceSeconds: 0,
- }).catch((e: Error) => ({ status: "failed", error: e.message }));
- assert.notEqual(r.status, "fetched", id);
- assert.deepEqual(await forms(d), [`${CHAT}.zst`], `${id}: the stored chat is kept`);
- assert.equal(await readStoredText(d, CHAT, "utf8"), OLD, id);
+ cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run: ok.run, replace: true, paceSeconds: 0,
+ });
+ assert.equal(r.status, "fetched", JSON.stringify(r));
+ // The new replay is the chat…
+ assert.equal(await readStoredText(d, CHAT, "utf8"), SHORT, `${id}: the chat`);
+ // …and the earlier, longer capture is kept, byte-identical after decode.
+ const kept = (await readdir(d)).filter(isKeptChatCapture);
+ assert.equal(kept.length, 1, `${id}: ${(await readdir(d)).join(", ")}`);
+ assert.equal((await decodeStoredBytes(await readFile(path.join(d, kept[0])))).toString("utf8"), LONG, `${id}: kept whole`);
+ // No reader sees the kept capture as the chat.
+ assert.ok(!(await readdirLogical(d)).some((e) => e.startsWith("transcript.live_chat") && e !== CHAT), id);
+ const tracks = (await readSubTracks(d)).map((t) => JSON.stringify(t));
+ assert.equal(tracks.filter((t) => t.includes("live_chat")).length, 1, `${id}: one chat track (${tracks.join(" ")})`);
+ assert.ok(!tracks.some((t) => t.includes("chat-capture-kept")), `${id}: the kept capture is no track`);
+ // Both captures measured, in the result and the log.
+ assert.deepEqual(r.replace?.earlier, { bytes: LONG.length, messages: 4, firstSec: 1, lastSec: 900, keptAs: kept[0] });
+ assert.deepEqual(r.replace?.fetched, { bytes: SHORT.length, messages: 1, firstSec: 1, lastSec: 1, keptAs: null });
+ assert.match(l.lines.join(""), /Earlier capture \(chat-capture-kept\..*\): 4 message\(s\).*Replay fetched now: 1 message\(s\)/);
+ assert.match(l.lines.join(""), /3 fewer message/);
}
- // A pass that left a `.part` (a capture not finished): the stored chat stays.
- {
- const d = await video("rp4", { webpage_url: "https://www.youtube.com/watch?v=rp4", was_live: true });
+});
+
+test("replace: an EMPTY replay, no replay, a failed pass or a .part — the stored capture stays the chat", async () => {
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ const { readStoredText, decodeStoredBytes } = await import("../lib/storedText-server");
+ const { isKeptChatCapture } = await import("../lib/mediaTier");
+ const CHAT = "transcript.live_chat.json";
+ const OLD = [chatLine(1, "a", "old whole capture"), chatLine(2, "b", "more")].join("\n") + "\n";
+ const forms = async (d: string) =>
+ (await readdir(d)).filter((e) => (e.startsWith("transcript.live_chat") && !e.endsWith(".part")) || isKeptChatCapture(e)).sort();
+ const seeded = async (id: string) => {
+ const d = await video(id, { webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true });
await writeFile(path.join(d, CHAT), OLD);
await storeFixture(d, CHAT);
- const partial = async (cwd: string, args: string[]) => {
- void args;
+ return d;
+ };
+ const l = log();
+ const go = (id: string, run: Parameters<typeof fetchLiveChat>[0]["run"]) =>
+ fetchLiveChat({
+ paths, slug: SLUG, videoId: id, videoUrl: `https://www.youtube.com/watch?v=${id}`, channelConfig: CONFIG,
+ cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run, replace: true, paceSeconds: 0,
+ });
+
+ // An empty replay (a file with no message in it): the stored capture is the
+ // chat, the job says the replay was empty, and the empty replay is kept too.
+ const e = await seeded("rpe");
+ const out = await go("rpe", stubRunner({ writes: '{"replayChatItemAction":{"actions":[]}}\n' }).run);
+ assert.equal(out.status, "none");
+ assert.equal(await readStoredText(e, CHAT, "utf8"), OLD, "THE chat is the stored capture");
+ assert.match(l.lines.join(""), /The replay came back EMPTY \(0 messages\)/);
+ assert.equal(out.replace?.earlier.messages, 2);
+ assert.equal(out.replace?.fetched?.messages, 0);
+ const keptEmpty = (await forms(e)).filter(isKeptChatCapture);
+ assert.equal(keptEmpty.length, 1, (await forms(e)).join(", "));
+ assert.deepEqual((await forms(e)).filter((n) => !isKeptChatCapture(n)), [`${CHAT}.zst`]);
+ assert.equal((await decodeStoredBytes(await readFile(path.join(e, keptEmpty[0])))).toString("utf8"), '{"replayChatItemAction":{"actions":[]}}\n');
+
+ // Nothing landed; a failed pass; a .part.
+ for (const [id, run] of [
+ ["rp2", stubRunner({ writes: null }).run],
+ ["rp3", stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] rp3: Video unavailable" }).run],
+ ["rp4", async (cwd: string) => {
await writeFile(path.join(cwd, "data", "rp4", `${CHAT}.part`), "half");
return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
- };
- const r = await fetchLiveChat({
- paths, slug: SLUG, videoId: "rp4", videoUrl: "https://www.youtube.com/watch?v=rp4", channelConfig: CONFIG,
- cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run: partial, replace: true,
- });
- assert.deepEqual(r, { status: "none" });
- assert.ok((await readdir(d)).includes(`${CHAT}.zst`));
+ }],
+ ] as const) {
+ const d = await seeded(id);
+ const r = await go(id, run).catch((err: Error) => ({ status: "failed", error: err.message }));
+ assert.notEqual(r.status, "fetched", id);
+ assert.deepEqual((await forms(d)), [`${CHAT}.zst`], `${id}: the stored chat is the chat, nothing kept aside`);
+ assert.equal(await readStoredText(d, CHAT, "utf8"), OLD, id);
}
// Over a plain chat: refused before any job, nothing spawned.
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -58,7 +58,9 @@ import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys";
import { LIVE_CHAT_CUES_FILENAME, LIVE_CHAT_FILENAME, META_FILENAME } from "../lib/videoStatus";
import { listingHas, storedFormsIn } from "../lib/storedText";
import { storedTextExists } from "../lib/storedText-server";
-import { plainIdentity, settleStoredTextAfterWrite } from "../lib/storedText-write-server";
+import { keepPlainAsCapture, putBackKeptCapture, setAsideStoredText } from "../lib/storedText-write-server";
+import { decodeStoredBytes } from "../lib/storedText-server";
+import { parseLiveChat } from "../lib/liveChat";
import {
heldPlatformRefusal,
platformCooldownRemainingMs,
@@ -181,15 +183,47 @@ export type FetchLiveChatOpts = {
run?: ChatRunner;
paceSeconds?: number;
// THE DELIBERATE RE-FETCH over a chat stored compressed (fetch-chat
- // `replace`): when the pass lands a whole new plain chat, the older stored
- // form goes — one form is left (lib/storedText-write-server.ts, the one-form
- // rule). A pass that lands nothing leaves the stored chat as it was.
+ // `replace`): the stored capture is KEPT under `chat-capture-kept.<stamp>.json.zst`
+ // and never removed (lib/storedText-write-server.ts). A new replay with
+ // messages becomes the chat; an empty one, or none, leaves the stored
+ // capture the chat.
replace?: boolean;
};
+// One capture, measured: bytes, messages, and the first and last message's
+// time (seconds into the stream).
+export type CaptureMeasure = { bytes: number; messages: number; firstSec: number | null; lastSec: number | null };
+
+// What a `replace` did: the earlier capture (kept under `keptAs`, or put back
+// as the chat when `keptAs` is null) and the replay fetched (null: none).
+export type ReplaceReport = {
+ earlier: CaptureMeasure & { keptAs: string | null };
+ fetched: (CaptureMeasure & { keptAs: string | null }) | null;
+};
+
export type FetchLiveChatResult =
- | { status: "fetched"; messages: number; cuesPath: string }
- | { status: "none" };
+ | { status: "fetched"; messages: number; cuesPath: string; replace?: ReplaceReport }
+ | { status: "none"; replace?: ReplaceReport };
+
+function measureChat(bytes: Buffer): CaptureMeasure {
+ let cues: { start: number }[] = [];
+ try {
+ cues = parseLiveChat(bytes.toString("utf8"));
+ } catch {
+ cues = [];
+ }
+ return {
+ bytes: bytes.length,
+ messages: cues.length,
+ firstSec: cues.length ? cues[0].start : null,
+ lastSec: cues.length ? cues[cues.length - 1].start : null,
+ };
+}
+
+function describe(m: CaptureMeasure): string {
+ const span = m.firstSec !== null && m.lastSec !== null ? `, ${m.firstSec.toFixed(0)}–${m.lastSec.toFixed(0)} s` : "";
+ return `${m.messages} message(s), ${m.bytes} bytes${span}`;
+}
/** The pass, then the normalize. Throws on a failed pass (the job ends `failed`). */
export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveChatResult> {
@@ -212,10 +246,70 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC
if (!(await isDirectory(videoDir))) throw new Error(notFetchedRefusal(opts.videoId, opts.slug));
const pass = (cookies: string | undefined) =>
run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds));
- // The plain file before the pass: what tells a file this pass wrote from one
- // that was there (the one-form rule asks).
- const before = opts.replace ? await plainIdentity(videoDir, LIVE_CHAT_FILENAME) : null;
+ // A REPLACE keeps the stored capture first, under a name no reader sees.
+ let kept: string | null = null;
+ if (opts.replace) {
+ const set = await setAsideStoredText(videoDir, LIVE_CHAT_FILENAME);
+ if (set === "busy") throw new Error(`The chat of ${opts.videoId} is being compressed or restored right now; nothing was fetched. Try again in a moment.`);
+ kept = set.kept;
+ if (kept) opts.onLog(`The stored chat capture of ${opts.videoId} is kept as ${kept} while the replay is fetched.\n`);
+ }
+ try {
+ await passes();
+ } catch (err) {
+ if (kept) await putBack(kept);
+ throw err;
+ }
+ if (kept) return finishReplace(kept);
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (!listingHas(entries, LIVE_CHAT_FILENAME)) {
+ opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
+ return { status: "none" };
+ }
+ return normalizeChat(opts, videoDir);
+ async function putBack(k: string): Promise<void> {
+ const back = await putBackKeptCapture(videoDir, LIVE_CHAT_FILENAME, k);
+ opts.onLog(
+ back === true
+ ? `The kept capture ${k} is the chat again.\n`
+ : `The kept capture ${k} stays under that name (the chat's name is taken, or the file is busy); nothing was removed.\n`,
+ );
+ }
+
+ // After a clean pass over a kept capture: both measured, and the decision.
+ async function finishReplace(k: string): Promise<FetchLiveChatResult> {
+ const earlier = measureChat(await decodeStoredBytes(await readFile(path.join(videoDir, k)), k));
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const partial = entries.some((e) => e.startsWith(`${LIVE_CHAT_FILENAME}.part`));
+ const landed = !partial && (await stat(path.join(videoDir, LIVE_CHAT_FILENAME)).then((st) => st.isFile(), () => false));
+ if (!landed) {
+ opts.onLog(`No new chat replay for ${opts.videoId} came back${partial ? " whole (a .part is here)" : ""}. Earlier capture: ${describe(earlier)}.\n`);
+ await putBack(k);
+ return { status: "none", replace: { earlier: { ...earlier, keptAs: null }, fetched: null } };
+ }
+ const fetched = measureChat(await readFile(path.join(videoDir, LIVE_CHAT_FILENAME)));
+ opts.onLog(`Earlier capture (${k}): ${describe(earlier)}. Replay fetched now: ${describe(fetched)}.\n`);
+ if (fetched.messages === 0) {
+ const empty = await keepPlainAsCapture(videoDir, LIVE_CHAT_FILENAME);
+ const emptyAs = empty !== "busy" ? empty.kept : null;
+ opts.onLog(
+ `The replay came back EMPTY (0 messages): the earlier capture stays the chat` +
+ (emptyAs ? `; the empty replay is kept as ${emptyAs}.\n` : `.\n`),
+ );
+ await putBack(k);
+ return { status: "none", replace: { earlier: { ...earlier, keptAs: null }, fetched: { ...fetched, keptAs: emptyAs } } };
+ }
+ opts.onLog(
+ `The replay fetched now is the chat; the earlier capture is KEPT as ${k} and is never removed automatically` +
+ (fetched.messages < earlier.messages ? ` (the replay has ${earlier.messages - fetched.messages} fewer message(s))` : "") +
+ `.\n`,
+ );
+ const out = await normalizeChat(opts, videoDir);
+ return { ...out, replace: { earlier: { ...earlier, keptAs: k }, fetched: { ...fetched, keptAs: null } } };
+ }
+
+ async function passes(): Promise<void> {
opts.onLog(
opts.capturingLive
? `Capturing the live chat of ${opts.videoId} from ${opts.videoUrl} while it is live (no media); ` +
@@ -260,23 +354,7 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC
} catch {
/* shared-state write is best-effort */
}
- if (opts.replace) {
- const settled = await settleStoredTextAfterWrite(videoDir, LIVE_CHAT_FILENAME, before, (l) => opts.onLog(`${l}\n`));
- if (settled !== "one-form") {
- opts.onLog(
- settled === "busy"
- ? `The chat of ${opts.videoId} is being compressed or restored right now; nothing was replaced. Try again in a moment.\n`
- : `No new chat replay for ${opts.videoId} came back; the chat on disk is kept as it was.\n`,
- );
- return { status: "none" };
- }
- }
- const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (!listingHas(entries, LIVE_CHAT_FILENAME)) {
- opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
- return { status: "none" };
}
- return normalizeChat(opts, videoDir);
}
// Best-effort: a failed write is logged, never the job's failure.
@@ -328,10 +406,11 @@ export type FetchChatJobOpts = {
// `needsMedia`, so a raw that is a tier link onto an unreachable drive is
// refused by runManagedFunction's guard like any other media reader.
renormalize?: boolean;
- // THE DELIBERATE RE-FETCH (the one-form rule, lib/storedText-write-server.ts):
- // fetch the replay again over a chat stored compressed; the new plain file
- // replaces the stored one when it lands whole. Refused over a PLAIN chat
- // (yt-dlp would keep it and fetch nothing).
+ // THE DELIBERATE RE-FETCH (lib/storedText-write-server.ts): fetch the replay
+ // again over a chat stored compressed. The stored capture is kept as
+ // `chat-capture-kept.<stamp>.json.zst`, never removed; a replay with messages
+ // becomes the chat, an empty one (or none) leaves the stored capture the
+ // chat. Refused over a PLAIN chat (yt-dlp would keep it and fetch nothing).
replace?: boolean;
};
diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts
@@ -79,26 +79,26 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too",
assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]);
});
-// REVIEW-1 F5: THE FILES CARD'S DELETE OF ONE NAMED FORM
+// REVIEW-1 F5 / REVIEW-2 R2: THE FILES CARD'S DELETE OF ONE NAMED FORM
// (`removeStoredTextForm`, what deleteVideoFileAction and `pnpm ops
-// delete-file` run). Before: a click on the plain name removed BOTH forms
-// (`removeStoredText`), even when the stored one held different content — the
-// only whole capture, maybe. Now: the same content, both go; different content
-// (or a form that cannot be read whole), only the named one, and the answer
-// names the other.
+// delete-file` run). A person asked for ONE file: only that one goes, never the
+// other form — whether they hold the same content or not — and the answer
+// names the other and says which. (Before REVIEW-2: the same content took
+// both, so deleting a duplicate `.zst` beside its plain file left zero copies.)
const { removeStoredTextForm } = await import("../lib/storedText-write-server");
-test("delete one named form: the same content takes both; different content takes only the named one", async () => {
+test("delete one named form: only the named one goes, whatever the other holds", async () => {
const ZST = `${CHAT}.zst`;
- // Same content, either name clicked.
+ // Same content, either name clicked: the other stays, and is read.
for (const clicked of [CHAT, ZST]) {
const d = await videoDir("f5same", clicked);
await writeFile(path.join(d, CHAT), "SAME\n");
await storeFixture(d, CHAT, { keepPlain: true });
const out = await removeStoredTextForm(d, clicked);
- assert.notEqual(out, "busy");
- assert.deepEqual(out !== "busy" && out.removed.sort(), [CHAT, ZST]);
- assert.deepEqual(await readdir(d), [], `${clicked}: both gone`);
+ const other = clicked === CHAT ? ZST : CHAT;
+ assert.deepEqual(out, { removed: [clicked], kept: { name: other, same: "same" } });
+ assert.deepEqual(await readdir(d), [other], `${clicked}: only it went`);
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "SAME\n", `${clicked}: readers still see the chat`);
}
// Different content: the plain one clicked — the stored one is kept, and read.
{
@@ -107,7 +107,7 @@ test("delete one named form: the same content takes both; different content take
await storeFixture(d, CHAT);
await writeFile(path.join(d, CHAT), "NEWER, TRIMMED\n");
const out = await removeStoredTextForm(d, CHAT);
- assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, why: "differs" } });
+ assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, same: "differs" } });
assert.deepEqual(await readdir(d), [ZST]);
assert.equal(await readStoredText(d, CHAT, "utf8"), "OLD WHOLE CAPTURE\n");
}
@@ -118,7 +118,7 @@ test("delete one named form: the same content takes both; different content take
await storeFixture(d, CHAT);
await writeFile(path.join(d, CHAT), "NEW\n");
const out = await removeStoredTextForm(d, ZST);
- assert.deepEqual(out, { removed: [ZST], kept: { name: CHAT, why: "differs" } });
+ assert.deepEqual(out, { removed: [ZST], kept: { name: CHAT, same: "differs" } });
assert.deepEqual(await readdir(d), [CHAT]);
}
// One form only: it goes.
@@ -131,7 +131,7 @@ test("delete one named form: the same content takes both; different content take
}
});
-test("delete one named form through tier links: the same content takes both forms' bytes; a dangling plain link never takes the stored copy", async () => {
+test("delete one named form through tier links: the named form's bytes go, the other form's stay", async () => {
const ZST = `${CHAT}.zst`;
const d = await videoDir("f5t", "v5");
const media = path.join(ROOT, "channels", "f5t", "media", "v5");
@@ -139,14 +139,13 @@ test("delete one named form through tier links: the same content takes both form
await writeFile(path.join(media, CHAT), "TIERED\n");
await symlink(path.join("..", "..", "media", "v5", CHAT), path.join(d, CHAT));
await storeFixture(d, CHAT, { keepPlain: true });
- assert.deepEqual((await removeStoredTextForm(d, CHAT)) !== "busy" && "ok", "ok");
- assert.deepEqual(await readdir(d), []);
- assert.equal(await exists(path.join(media, CHAT)), false);
- assert.equal(await exists(path.join(media, ZST)), false);
+ assert.deepEqual(await removeStoredTextForm(d, ZST), { removed: [ZST], kept: { name: CHAT, same: "same" } });
+ assert.deepEqual(await readdir(d), [CHAT]);
+ assert.equal(await exists(path.join(media, ZST)), false, "its bytes went with it");
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "TIERED\n");
// The plain link's bytes gone (an interrupted removal): clicking the plain
- // name removes only that link — the stored copy cannot be compared, so it
- // stays, and is what readers read.
+ // name removes only that link; the stored copy stays, and is read.
const e = await videoDir("f5t", "v6");
const media6 = path.join(ROOT, "channels", "f5t", "media", "v6");
await mkdir(media6, { recursive: true });
@@ -155,6 +154,6 @@ test("delete one named form through tier links: the same content takes both form
await storeFixture(e, CHAT);
await symlink(path.join("..", "..", "media", "v6", CHAT), path.join(e, CHAT));
const out = await removeStoredTextForm(e, CHAT);
- assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, why: "unreadable" } });
+ assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, same: "unreadable" } });
assert.equal(await readStoredText(e, CHAT, "utf8"), "ONLY COPY\n");
});
diff --git a/common/lib/mediaTier.test.ts b/common/lib/mediaTier.test.ts
@@ -96,3 +96,19 @@ test("every tierable name is media (tierable is narrower)", () => {
if (isTierable(name)) assert.equal(classifyEntry(name), "media", name);
}
});
+
+// Lane text-compress, REVIEW-2 R1: a kept earlier chat capture is media and
+// tierable (it travels with the video) and is never the chat's name.
+test("chat-capture-kept.<stamp>.json.zst: media, tierable, and not a chat name", async () => {
+ const { isKeptChatCapture, keptChatCaptureName, classifyEntry, isTierable } = await import("./mediaTier");
+ const k = keptChatCaptureName(new Date(Date.UTC(2026, 10, 21, 4, 5, 6, 789)));
+ assert.equal(k, "chat-capture-kept.20261121T040506Z.json.zst");
+ assert.equal(keptChatCaptureName(new Date(Date.UTC(2026, 10, 21, 4, 5, 6)), 2), "chat-capture-kept.20261121T040506Z-2.json.zst");
+ assert.ok(isKeptChatCapture(k));
+ assert.equal(classifyEntry(k), "media");
+ assert.equal(isTierable(k), true);
+ assert.ok(!k.startsWith("transcript.") && !k.startsWith("live_chat.") && !k.endsWith(".json"));
+ for (const t of [".transcript.live_chat.json.restoring-12-abc", ".x.stlink-12-abc", ".stored-text.lock", ".transcript.live_chat.json.retire-12-abc", ".transcript.live_chat.json.zst.compressing-12-abc"]) {
+ assert.equal(classifyEntry(t), "scratch", t);
+ }
+});
diff --git a/common/lib/mediaTier.ts b/common/lib/mediaTier.ts
@@ -39,6 +39,30 @@ export const LIVE_CHAT_MEDIA_FILENAME = "transcript.live_chat.json";
// file stays" rule would not cover it.
export const LIVE_CHAT_STORED_FILENAME = `${LIVE_CHAT_MEDIA_FILENAME}.zst`;
+// AN EARLIER CHAT CAPTURE, KEPT (lane text-compress, REVIEW-2 R1): when
+// `fetch-chat {replace: true}` fetches a replay over a chat stored compressed,
+// the stored capture is first renamed `chat-capture-kept.<UTC stamp>.json.zst`
+// (the same bytes: one zstd frame). A platform's replay is often shorter than
+// the live capture, and the capture cannot be fetched again — so nothing ever
+// removes one of these automatically. The name is chosen so that NO reader of
+// the chat sees it: it does not start with `transcript.` or `live_chat.`, it
+// is not a declared stored-text name, and it does not end in `.json`. It is
+// MEDIA and TIERABLE like the chat itself, so it travels with the video: the
+// tier hook moves it, a relocation carries it, `removeVideoDirMedia` removes it
+// with the video, and the reclaim keeps it.
+export const KEPT_CHAT_CAPTURE_PREFIX = "chat-capture-kept.";
+const KEPT_CHAT_CAPTURE_RE = /^chat-capture-kept\.\d{8}T\d{6}Z(?:-\d+)?\.json\.zst$/;
+
+export function isKeptChatCapture(name: string): boolean {
+ return KEPT_CHAT_CAPTURE_RE.test(name);
+}
+
+// A kept capture's name for a moment (`n`: a second one in the same second).
+export function keptChatCaptureName(at: Date, n = 0): string {
+ const stamp = at.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
+ return `${KEPT_CHAT_CAPTURE_PREFIX}${stamp}${n ? `-${n}` : ""}.json.zst`;
+}
+
// The clip-window cache dir (`clipWindow.ts`'s `CLIPS_DIR_NAME`, pinned by the
// test for the same reason). Never tiered, never classified as media.
export const CLIPS_DIR = "clips";
@@ -91,11 +115,20 @@ const SCRATCH_PATTERNS: ReadonlyArray<RegExp> = [
// lib/storedText-write-server.ts): never a copy anyone reads — the stored
// form appears only by a rename of a verified temp — and a dead pid's is
// discarded by the next run.
- /\.compressing-\d+$/,
+ /\.compressing-\d+(?:-[0-9a-z]+)?$/,
+ // The restore's plain temp (`.transcript.live_chat.json.restoring-<pid>-<token>`)
+ // and the stored-text runs' own temp links (`.….stlink-<pid>-<token>`).
+ /\.restoring-\d+(?:-[0-9a-z]+)?$/,
+ /\.stlink-\d+(?:-[0-9a-z]+)?$/,
+ // A kept capture being written (`.chat-capture-kept.….json.zst.keeping-<pid>-<token>`).
+ /\.keeping-\d+(?:-[0-9a-z]+)?$/,
+ // The stored-text runs' per-directory lock (`.stored-text.lock`, and the
+ // temp a run links it from).
+ /^\.stored-text\.lock(?:\..+)?$/,
// The original the compressor set aside, between the stored form landing
// and the original's removal (`.transcript.live_chat.json.retire-<pid>`):
// the next run removes it, or renames it back when it is the only copy.
- /\.retire-\d+$/,
+ /\.retire-\d+(?:-[0-9a-z]+)?$/,
];
export function isScratchEntry(name: string): boolean {
@@ -114,7 +147,8 @@ export function classifyEntry(name: string): MediaTierKind {
isRealAudioFile(name) ||
isSourceMediaFile(name) ||
name === LIVE_CHAT_MEDIA_FILENAME ||
- name === LIVE_CHAT_STORED_FILENAME
+ name === LIVE_CHAT_STORED_FILENAME ||
+ isKeptChatCapture(name)
) {
return "media";
}
@@ -133,7 +167,8 @@ export function isTierable(name: string): boolean {
return (
isRealAudioFile(name) ||
name === LIVE_CHAT_MEDIA_FILENAME ||
- name === LIVE_CHAT_STORED_FILENAME
+ name === LIVE_CHAT_STORED_FILENAME ||
+ isKeptChatCapture(name)
);
}
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -31,6 +31,7 @@ import {
statfs,
symlink,
utimes,
+ writeFile,
} from "node:fs/promises";
import { Transform, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
@@ -38,8 +39,10 @@ import {
MEDIA_LINK_NAME,
TIER_RELOCATION_MARKER,
removeMediaFile,
+ renameMediaFile,
tierMediaFile,
} from "./mediaTier-server";
+import { keptChatCaptureName } from "./mediaTier";
import { onDrive, stalledLocationForPath } from "./storageHealth";
import { LIVE_RECORDING_FILENAME } from "./liveCapture";
import { isStoredTextName, plainNameOf, storedNameOf } from "./storedText";
@@ -96,8 +99,9 @@ export async function removeStoredText(videoDir: string, name: string): Promise<
// per-file lock below means no run of ours is on this file at this moment.
//
// A WRITER THAT REPLACED P DURING A RUN (`changed`): the new P is the truth
-// and is kept; the stored form beside it is OLDER content and is removed, so
-// one form is left (THE ONE-FORM RULE, `settleStoredTextAfterWrite`).
+// and is read; the stored form beside it holds the earlier content and is
+// KEPT. Two captures with different content are never settled by deleting
+// one (REVIEW-2 R1): the pair is `both-differ`, for a person.
export type CompressSkipReason =
| "not-declared"
@@ -395,18 +399,96 @@ async function storedPathOf(videoDir: string, name: string): Promise<string | nu
return null;
}
-// ONE RUN PER FILE in this process at a time — the compressor, the restore,
-// the one-form settle and the files card's delete. Two of them on one file
-// could remove each other's temp; and because of this lock, a leftover named
-// with this process's pid is never a run in progress.
-const active = new Set<string>();
+// ONE RUN PER FILE AT A TIME — the compressor, the restore, the re-fetch's
+// set-aside and the files card's delete — in two layers:
+//
+// - IN THIS PROCESS, a set kept on `globalThis` (Next loads a module once
+// per bundle layer; a route and a server action must share it — the
+// storageHealth.ts pattern). Because of it, a leftover named with this
+// process's pid is never a run in progress.
+// - ACROSS PROCESSES, a lock file in the video dir, `.stored-text.lock`
+// (REVIEW-2 R3), made by a hard link of a temp that names its owner (pid
+// and start token), so it appears whole or not at all. A second process
+// honours it: held by a run that is running now, the run answers "busy";
+// held by a process that is gone (or this pid from an earlier start), it
+// is stale and is taken over. Two editors on one corpus are an operator's
+// mistake; this makes them wait for each other instead of interleaving.
+const g = globalThis as { __archilyzerStoredTextActive?: Set<string> };
+const active: Set<string> = (g.__archilyzerStoredTextActive ??= new Set<string>());
+
+export const STORED_TEXT_DIR_LOCK = ".stored-text.lock";
+
+// Is the run that holds a dir lock running now? This process: only when the
+// token is this start's (another of its runs holds the dir).
+function lockHolderRunning(owner: Owner): boolean {
+ if (owner.pid === process.pid) return owner.token === selfToken();
+ return ownerRunning(owner, process.pid);
+}
+
+// The dir lock, or null when a live run holds it. Returns its release.
+async function takeDirLock(videoDir: string): Promise<(() => Promise<void>) | null> {
+ const lock = path.join(videoDir, STORED_TEXT_DIR_LOCK);
+ const me = { pid: process.pid, token: selfToken() };
+ const tmp = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.${me.pid}-${me.token}-${Math.random().toString(36).slice(2, 8)}`);
+ try {
+ await writeFile(tmp, JSON.stringify(me), { flag: "wx" });
+ } catch (err) {
+ // No video dir: nothing to lock and nothing to do.
+ if (errCode(err) === "ENOENT") return async () => {};
+ throw err;
+ }
+ try {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ await link(tmp, lock);
+ const ino = (await lstat(lock)).ino;
+ return async () => {
+ const l = await lstatOrNull(lock);
+ if (l && l.ino === ino) await rm(lock, { force: true });
+ };
+ } catch (err) {
+ if (errCode(err) !== "EEXIST") throw err;
+ }
+ const held = await lstatOrNull(lock);
+ if (!held) continue;
+ let owner: Owner | null = null;
+ try {
+ const o = JSON.parse(await readFile(lock, "utf8")) as { pid?: unknown; token?: unknown };
+ if (typeof o.pid === "number") owner = { pid: o.pid, ...(typeof o.token === "string" ? { token: o.token } : {}) };
+ } catch {
+ /* unreadable: no owner to honour */
+ }
+ if (owner && lockHolderRunning(owner)) return null;
+ // Stale: moved aside, and removed only if it is the very file judged —
+ // another process's fresh lock that took its place goes back.
+ const aside = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.stale-${me.pid}-${me.token}`);
+ await rename(lock, aside).catch(() => {});
+ const a = await lstatOrNull(aside);
+ if (a && a.ino !== held.ino) {
+ await link(aside, lock).catch(() => {});
+ await rm(aside, { force: true });
+ return null;
+ }
+ await rm(aside, { force: true });
+ }
+ return null;
+ } finally {
+ await rm(tmp, { force: true });
+ }
+}
async function withFileLock<T>(videoDir: string, name: string, busy: T, fn: () => Promise<T>): Promise<T> {
const key = path.resolve(videoDir, name);
if (active.has(key)) return busy;
active.add(key);
try {
- return await fn();
+ const release = await takeDirLock(videoDir);
+ if (!release) return busy;
+ try {
+ return await fn();
+ } finally {
+ await release();
+ }
} finally {
active.delete(key);
}
@@ -428,9 +510,10 @@ export async function compressStoredText(
function leftoverRes(name: string) {
const stored = storedNameOf(name);
return {
- // `.X.zst.compressing-…`, `.X.zst.tierlink-…`, `.X.restoring-…`, `.X.tierlink-…`
+ // `.X.zst.compressing-…`, `.X.zst.stlink-…`, `.X.restoring-…`, `.X.stlink-…`
+ // — never the tier hook's own `.X.tierlink-<pid>` (REVIEW-2 N2).
temp: new RegExp(
- `^\\.(?:${escapeRe(stored)}\\.(?:compressing|tierlink)|${escapeRe(name)}\\.(?:restoring|tierlink))${LEFTOVER_SUFFIX}$`,
+ `^\\.(?:${escapeRe(stored)}\\.(?:compressing|stlink)|${escapeRe(name)}\\.(?:restoring|stlink))${LEFTOVER_SUFFIX}$`,
),
retire: new RegExp(`^\\.${escapeRe(name)}\\.retire${LEFTOVER_SUFFIX}$`),
};
@@ -652,6 +735,9 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
if ((await lstatOrNull(beside))?.isFile()) zPath = beside;
}
+ // The stored file's identity once it is verified (or made): what the
+ // last look before the original goes compares with.
+ let zIdent: Ident | null = null;
if (zPath) {
let zd: Digest;
try {
@@ -665,6 +751,7 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
}
// The same content: given the plain file's times, exactly.
await utimes(zPath, s.atimeMs / 1000, s.mtimeMs / 1000);
+ zIdent = identOf(await stat(zPath));
} else {
const free = await statfs(workDir).then(
(f) => f.bavail * f.bsize,
@@ -674,12 +761,13 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
const made = await makeStored(bytesPath, workDir, stored, s, first, `${pid}-${token}`, opts);
if (made !== "ok") return made;
zPath = path.join(workDir, stored);
+ zIdent = identOf(await stat(zPath));
crash("placed");
}
// ── its tier link ─────────────────────────────────────────────────────────
if (tiered && zKind === "none") {
- const tmpLink = path.join(videoDir, `.${stored}.tierlink-${pid}-${token}`);
+ const tmpLink = path.join(videoDir, `.${stored}.stlink-${pid}-${token}`);
await rm(tmpLink, { force: true });
await symlink(path.relative(videoDir, zPath), tmpLink);
// The PLAIN LINK's times: what an `lstat` of the name answered.
@@ -725,27 +813,30 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
}
}
}
- // THE ONE-FORM RULE: the plain file now under the name is the newer
- // write; the stored form beside it holds the content it replaced, and
- // goes — one form is left, and the next run compresses the new file.
- // Not when a set-aside was kept for a person: nothing more is touched.
- if (!kept && (await wholePlainAt(videoDir, name))) {
- await removeMediaFile(videoDir, stored);
- await fsyncDir(videoDir);
- }
- log(` ${name} changed while it was being compressed: the new file is kept, the older stored copy removed; the next run compresses it`);
+ // TWO DIFFERENT CAPTURES ARE NEVER SETTLED BY DELETING ONE (REVIEW-2
+ // R1): the new file under the name is what readers read; the stored form
+ // beside it holds the content it replaced and is KEPT — the pair is
+ // `both-differ` for a person (the files card deletes one named form).
+ void kept;
+ log(` ${name} changed while it was being compressed: the new file is kept and read; the stored copy of the earlier content is kept beside it (both-differ, for a person)`);
+ return { status: "changed" };
+ }
+ // THE STORED FORM, LOOKED AT AGAIN right before the original goes (REVIEW-2
+ // R3): still a regular file, and the very one verified (another process's
+ // run could have replaced or removed it). Otherwise the original goes back.
+ const zNow = await stat(path.join(videoDir, stored)).catch(() => null);
+ if (!zNow || !zNow.isFile() || !zIdent || zNow.ino !== zIdent.ino || zNow.size !== zIdent.size || zNow.dev !== zIdent.dev) {
+ if (!(await lstatOrNull(p.path))) await rename(retiredPath, p.path);
+ log(` ${stored} is not the file that was verified any more: ${name} is left as it was`);
return { status: "changed" };
}
await removeMediaFile(videoDir, retired);
await fsyncDir(videoDir);
// A writer that landed a new file under the name after the original was
- // set aside: the one-form rule, as for `changed` above. (Only when the new
- // file opens whole — never the stored form removed beside a name whose
- // bytes are gone.)
+ // set aside: it is the truth, and the stored copy (the earlier content) is
+ // kept beside it — `changed`, both-differ for a person (REVIEW-2 R1).
if (await wholePlainAt(videoDir, name)) {
- await removeMediaFile(videoDir, stored);
- await fsyncDir(videoDir);
- log(` ${name} was written again while it was being compressed: the new file is kept, the older stored copy removed`);
+ log(` ${name} was written again while it was being compressed: the new file is kept and read; the stored copy of the earlier content is kept beside it`);
return { status: "changed" };
}
@@ -990,6 +1081,10 @@ async function restoreOne(videoDir: string, name: string, opts: CompressOptions)
return skip("both-differ", `${name} and ${stored} differ`);
}
if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ if (!(await plainStillWhole(videoDir, name, zd, null))) {
+ log(` ${name} is not a whole copy of ${stored} any more: the stored file is kept`);
+ return { status: "changed" };
+ }
await removeMediaFile(videoDir, stored);
await fsyncDir(videoDir);
return { status: "restored", before: zStat.size, after: zd.bytes, tiered: p.kind === "link" };
@@ -1020,7 +1115,7 @@ async function restoreOne(videoDir: string, name: string, opts: CompressOptions)
// ── its tier link ─────────────────────────────────────────────────────────
if (tiered) {
- const tmpLink = path.join(videoDir, `.${name}.tierlink-${pid}-${token}`);
+ const tmpLink = path.join(videoDir, `.${name}.stlink-${pid}-${token}`);
await rm(tmpLink, { force: true });
await symlink(path.relative(videoDir, placed), tmpLink);
await lutimes(tmpLink, z.l.atimeMs / 1000, z.l.mtimeMs / 1000);
@@ -1031,8 +1126,16 @@ async function restoreOne(videoDir: string, name: string, opts: CompressOptions)
await rm(tmpLink, { force: true });
if (errCode(err) !== "EEXIST") throw err;
// A writer put a plain file here meanwhile: it is the truth. The copy
- // this run placed goes; the stored form is the next run's to settle.
- await rm(placed, { force: true });
+ // this run placed goes — unless the new name resolves to it (the tier
+ // hook moved the writer's bytes over that same target, REVIEW-2 N3);
+ // the stored form is the next run's to settle.
+ const [nowName, nowPlaced] = await Promise.all([
+ stat(path.join(videoDir, name)).catch(() => null),
+ stat(placed).catch(() => null),
+ ]);
+ if (!(nowName && nowPlaced && nowName.ino === nowPlaced.ino && nowName.dev === nowPlaced.dev)) {
+ await rm(placed, { force: true });
+ }
log(` ${name} appeared while it was being restored: the new file is kept`);
return { status: "changed" };
}
@@ -1043,9 +1146,34 @@ async function restoreOne(videoDir: string, name: string, opts: CompressOptions)
// ── the stored form goes ──────────────────────────────────────────────────
if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ // THE PLAIN FILE, LOOKED AT AGAIN right before (REVIEW-2 R3): there, a
+ // regular file (through the expected link), its size and hash those of a
+ // fresh decode. Otherwise the stored form stays.
+ if (!(await plainStillWhole(videoDir, name, zd, tiered ? placed : null))) {
+ log(` ${name} is not a whole copy of ${stored} any more: the stored file is kept`);
+ return { status: "changed" };
+ }
await removeMediaFile(videoDir, stored);
await fsyncDir(videoDir);
- return { status: "restored", before: zStat.size, after: zd.bytes, tiered };
+ // A real plain file on a channel with a media tier: the hook, as the
+ // compressor does for its output (REVIEW-2 N6).
+ const nowTiered = tiered || (await tierMediaFile(videoDir, name, { onLog: log })) === "tiered";
+ return { status: "restored", before: zStat.size, after: zd.bytes, tiered: nowTiered };
+}
+
+// Is the plain file here a whole copy of the stored content `zd`? A regular
+// file (a link must resolve to `expected` when given), of its size, with its
+// hash. Read in full: this is the last look before a stored copy goes.
+async function plainStillWhole(videoDir: string, name: string, zd: Digest, expected: string | null): Promise<boolean> {
+ const file = path.join(videoDir, name);
+ const st = await stat(file).catch(() => null);
+ if (!st || !st.isFile() || st.size !== zd.bytes) return false;
+ if (expected) {
+ const ex = await stat(expected).catch(() => null);
+ if (!ex || ex.ino !== st.ino || ex.dev !== st.dev) return false;
+ }
+ const d = await digestOf(file).catch(() => null);
+ return !!d && d.sha === zd.sha && d.bytes === zd.bytes;
}
// Steps 1–3 of the restore: Z → R (verified) → P. "ok", or the outcome that
@@ -1131,71 +1259,120 @@ async function makePlain(
}
}
-// ── THE ONE-FORM RULE, AFTER A DELIBERATE RE-FETCH ──────────────────────────
+// ── A DELIBERATE RE-FETCH OVER A STORED CAPTURE: THE EARLIER ONE IS KEPT ──
//
// No pass fetches a declared file that is on disk in either form (the
// chat-only pass is skipped, the caption passes leave the chat out of
// `--sub-langs`, fetch-chat normalizes what is here). The one pass that does
-// is a DELIBERATE re-fetch — `fetch-chat {replace: true}`, over a chat stored
-// compressed (yt-dlp does not see the `.zst`, so it writes the plain name).
-// When that pass has landed a whole plain file (no `.part`; not the file that
-// was there before — `plainIdentity` taken before the pass), the stored form
-// beside it is OLDER content and goes, through `removeMediaFile`: ONE form is
-// left, the new one, and the next compress run stores it. A pass that landed
-// nothing, failed or left a `.part` changes nothing: the stored form stays.
+// is a DELIBERATE re-fetch — `fetch-chat {replace: true}` over a chat stored
+// compressed. NOTHING EVER REMOVES A CAPTURE BECAUSE A DIFFERENT ONE ARRIVED
+// (REVIEW-2 R1): a platform's replay is often shorter than the live capture,
+// and the capture cannot be fetched again. So:
//
-// Not called after any other pass: a plain file that some other path left
-// beside a stored one is `both-differ`, refused by the compressor and shown
-// on the files card, for a person — never settled by guessing which is right.
-
-export type PlainIdentity = { ino: number; size: number; mtimeMs: number } | null;
+// 1. before the pass, the stored form is RENAMED to a kept name,
+// `chat-capture-kept.<UTC stamp>.json.zst` (lib/mediaTier.ts — no reader
+// of the chat sees it; it travels with the video as media), through
+// `renameMediaFile` (a tier link's bytes are renamed beside themselves);
+// 2. the pass runs; yt-dlp writes the plain name;
+// 3. the caller measures both and decides: a new replay with messages is the
+// chat, and the earlier capture stays kept; nothing landed, a `.part`, a
+// failed pass — the kept capture goes back under the stored name
+// (`putBackKeptCapture`); an EMPTY replay is itself kept under a kept
+// name (`keepPlainAsCapture`: compressed, verified, then its plain name
+// removed) and the earlier capture goes back.
+//
+// Nothing removes a kept capture automatically. `compress-text`'s dry run
+// lists them ("earlier captures kept"); a person deletes one on the files card.
+
+export type KeepOutcome = { kept: string } | { kept: null } | "busy";
+
+// A kept name free in both places it could be (data/<id>/ and, for a tier
+// link, beside its bytes in media/<id>/).
+async function freeKeptName(videoDir: string, besideDir: string | null, at: Date): Promise<string> {
+ for (let n = 0; ; n++) {
+ const k = keptChatCaptureName(at, n);
+ const here = await lstatOrNull(path.join(videoDir, k));
+ const there = besideDir ? await lstatOrNull(path.join(besideDir, k)) : null;
+ if (!here && !there) return k;
+ }
+}
-export async function plainIdentity(videoDir: string, name: string): Promise<PlainIdentity> {
- const s = await stat(path.join(videoDir, name)).catch(() => null);
- return s && s.isFile() ? { ino: s.ino, size: s.size, mtimeMs: s.mtimeMs } : null;
+// Step 1: the stored form renamed to a kept name. `{kept: null}`: no stored
+// form here (nothing to keep).
+export async function setAsideStoredText(videoDir: string, name: string, at: Date = new Date()): Promise<KeepOutcome> {
+ if (!isStoredTextName(name)) return { kept: null };
+ return withFileLock<KeepOutcome>(videoDir, name, "busy", async () => {
+ const z = await entryAt(videoDir, storedNameOf(name));
+ if (z.kind === "none") return { kept: null };
+ const kept = await freeKeptName(videoDir, z.kind === "link" && z.inMedia ? path.dirname(z.target) : null, at);
+ await renameMediaFile(videoDir, storedNameOf(name), kept);
+ await fsyncDir(videoDir);
+ return { kept };
+ });
}
-export type SettleOutcome =
- | "one-form" // the new plain file only (the older stored form removed, or none was there)
- | "unchanged" // the pass wrote no plain file: nothing touched
- | "partial" // a `.part` beside it: nothing touched
- | "busy";
+// The kept capture back under the stored name — only when neither form of the
+// name is here (it never replaces anything). False: left where it is.
+export async function putBackKeptCapture(videoDir: string, name: string, kept: string): Promise<boolean | "busy"> {
+ return withFileLock<boolean | "busy">(videoDir, name, "busy", async () => {
+ if ((await lstatOrNull(path.join(videoDir, name))) || (await lstatOrNull(path.join(videoDir, storedNameOf(name))))) {
+ return false;
+ }
+ const k = await entryAt(videoDir, kept);
+ if (k.kind === "none") return false;
+ if (k.kind === "link" && k.inMedia && (await lstatOrNull(path.join(path.dirname(k.target), storedNameOf(name))))) {
+ return false;
+ }
+ await renameMediaFile(videoDir, kept, storedNameOf(name));
+ await fsyncDir(videoDir);
+ return true;
+ });
+}
-export async function settleStoredTextAfterWrite(
+// The plain file kept as a capture: compressed beside its bytes into a kept
+// name (written, fsynced, decoded back and hashed against it), linked when it
+// is tiered, and only then its plain name removed through removeMediaFile.
+export async function keepPlainAsCapture(
videoDir: string,
name: string,
- before: PlainIdentity,
- onLog: (line: string) => void = () => {},
-): Promise<SettleOutcome> {
- if (!isStoredTextName(name)) return "unchanged";
- return withFileLock(videoDir, name, "busy" as SettleOutcome, async () => {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (entries.some((e) => e.startsWith(`${name}.part`))) return "partial";
- const now = await plainIdentity(videoDir, name);
- if (!now) return "unchanged";
- if (before && before.ino === now.ino && before.size === now.size && before.mtimeMs === now.mtimeMs) {
- return "unchanged";
- }
- if (await lstatOrNull(path.join(videoDir, storedNameOf(name)))) {
- await removeMediaFile(videoDir, storedNameOf(name));
+ at: Date = new Date(),
+ opts: CompressOptions = {},
+): Promise<KeepOutcome> {
+ return withFileLock<KeepOutcome>(videoDir, name, "busy", async () => {
+ const p = await entryAt(videoDir, name);
+ if (p.kind !== "real" && !(p.kind === "link" && p.inMedia)) return { kept: null };
+ const tiered = p.kind === "link";
+ const bytesPath = tiered ? p.target : p.path;
+ const workDir = path.dirname(bytesPath);
+ const s = await stat(bytesPath);
+ const kept = await freeKeptName(videoDir, tiered ? workDir : null, at);
+ const ctx = runCtx(videoDir, opts);
+ const made = await makeStored(bytesPath, workDir, kept, s, identOf(s), `${ctx.pid}-${ctx.token}`, opts);
+ if (made !== "ok") return { kept: null };
+ if (tiered) {
+ const tmpLink = path.join(videoDir, `.${kept}.stlink-${ctx.pid}-${ctx.token}`);
+ await rm(tmpLink, { force: true });
+ await symlink(path.relative(videoDir, path.join(workDir, kept)), tmpLink);
+ await rename(tmpLink, path.join(videoDir, kept));
await fsyncDir(videoDir);
- onLog(`The re-fetched ${name} replaces the stored copy (${storedNameOf(name)} removed): one form is left.`);
}
- return "one-form";
+ await removeMediaFile(videoDir, name);
+ await fsyncDir(videoDir);
+ return { kept };
});
}
// ── THE FILES CARD'S DELETE OF ONE NAMED FORM ───────────────────────────────
//
-// A person deleting `X` or `X.zst` on the files card. When the other form is
-// there too: the SAME content (both decode and hash equal) — both go, or the
-// other would come back as the file; DIFFERENT content, or a form that cannot
-// be read whole — only the named one goes, and the answer says the other is
-// still there (it is then what readers read). Each through `removeMediaFile`.
+// A person deleting `X` or `X.zst` on the files card asked for ONE file: only
+// that one goes, through `removeMediaFile` — never the other form (REVIEW-2
+// R2). When the other is there too, the answer says so and whether it holds
+// the same content (readers still see the chat) or different content (it is
+// what readers read now, or still).
export type RemoveFormOutcome = {
removed: string[];
- kept?: { name: string; why: "differs" | "unreadable" };
+ kept?: { name: string; same: "same" | "differs" | "unreadable" };
};
export async function removeStoredTextForm(videoDir: string, filename: string): Promise<RemoveFormOutcome | "busy"> {
@@ -1215,11 +1392,9 @@ export async function removeStoredTextForm(videoDir: string, filename: string):
digestOf(path.join(videoDir, plain)).catch(() => null),
z ? digestOf(z, { decode: true }).catch(() => null) : Promise.resolve(null),
]);
- if (pd && zd && pd.sha === zd.sha && pd.bytes === zd.bytes) {
- await removeStoredText(videoDir, plain);
- return { removed: [storedNameOf(plain), plain] };
- }
+ const same = !pd || !zd ? "unreadable" : pd.sha === zd.sha && pd.bytes === zd.bytes ? "same" : "differs";
await removeMediaFile(videoDir, filename);
- return { removed: [filename], kept: { name: other, why: pd && zd ? "differs" : "unreadable" } };
+ await fsyncDir(videoDir);
+ return { removed: [filename], kept: { name: other, same } };
});
}
diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts
@@ -170,7 +170,7 @@ for (const tiered of [false, true]) {
assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWER\n", "the plain one is read");
});
- test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file kept, the older stored copy gone`, async () => {
+ test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file read, the earlier content's stored copy KEPT`, async () => {
// The seam is synchronous: the new file lands by rename, as yt-dlp's do,
// between the stored form landing and the original being set aside.
const g = await fixture(tiered);
@@ -186,16 +186,15 @@ for (const tiered of [false, true]) {
assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), "REWRITTEN\n");
assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n");
assert.deepEqual((await readdir(g.videoDir)).filter((e) => e.includes(".retire-")), []);
- // The one-form rule (REVIEW-1 N6): the stored copy of the replaced
- // content is not left beside the new file.
- assert.deepEqual((await readdir(g.videoDir)).sort(), ["metadata.info.json", CHAT]);
- // Its bytes in media/ too. (The replaced original's bytes stay there: a
- // writer that puts a real file over a tier link orphans them, as before
- // this lane — the tier hook's next move of the name overwrites them.)
- if (tiered) assert.deepEqual((await readdir(g.mediaDir)).filter((e) => e.endsWith(".zst")), [], "its bytes in media/ too");
- // And the next run compresses the new file.
- assert.equal((await run(g)).status, "compressed");
- assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n");
+ // REVIEW-2 R1: two captures with different content are never settled by
+ // deleting one — the stored copy of the earlier content stays, whole.
+ assert.deepEqual((await readdir(g.videoDir)).sort(), ["metadata.info.json", CHAT, ZST]);
+ const zBytes = tiered ? path.join(g.mediaDir, ZST) : path.join(g.videoDir, ZST);
+ const { decodeStoredBytes } = await import("./storedText-server");
+ assert.equal((await decodeStoredBytes(await readFile(zBytes))).toString("utf8"), ORIGINAL, "the earlier capture, byte-identical");
+ // And the next run refuses the pair, for a person.
+ const again = await run(g);
+ assert.equal(again.status === "skipped" && again.reason, "both-differ", JSON.stringify(again));
});
test(`${how}: skipped, touching nothing — a .part, a recording, a move, a job, a recent write, a full disk`, async () => {
@@ -248,11 +247,38 @@ for (const tiered of [false, true]) {
assert.equal(out.status, "changed", JSON.stringify(out));
assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n", "the newer file is the truth");
assert.deepEqual((await readdir(f.videoDir)).filter((e) => e.includes(".retire-")), []);
- // One form: the newer file; the older stored copy is gone (REVIEW-1 N6).
- assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]);
+ // Both captures kept (REVIEW-2 R1): the newer file, and the earlier
+ // content's stored copy, whole.
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT, ZST]);
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "differs");
const again = await run(f);
- assert.equal(again.status, "compressed", "the next run stores the newer file");
- assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n");
+ assert.equal(again.status === "skipped" && again.reason, "both-differ", "refused, both kept");
+ });
+
+ test(`${how}: the stored form replaced by another process before the original goes — the original stays (REVIEW-2 R3)`, async () => {
+ const f = await fixture(tiered);
+ const { writeFileSync, renameSync } = await import("node:fs");
+ const zBytes = tiered ? path.join(f.mediaDir, ZST) : path.join(f.videoDir, ZST);
+ const out = await run(f, {
+ crashAt: (p) => {
+ // After the stored form is verified and in place: someone else's run
+ // swaps a different file in under its name.
+ if (p !== (tiered ? "linked" : "placed")) return;
+ writeFileSync(zBytes + ".other", "not the verified frame");
+ renameSync(zBytes + ".other", zBytes);
+ },
+ });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, "the original is untouched");
+ });
+
+ test(`${how}: the tier hook's own temp link is not taken for a dead run's leftover (REVIEW-2 N2)`, async () => {
+ const f = await fixture(tiered);
+ const hookTemp = path.join(f.videoDir, `.${CHAT}.tierlink-${process.pid}`);
+ await writeFile(hookTemp, "the hook's");
+ assert.equal((await run(f)).status, "compressed");
+ assert.equal(await readFile(hookTemp, "utf8"), "the hook's");
+ await rm(hookTemp);
});
}
diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts
@@ -45,7 +45,7 @@ const NAMES = /\bLIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\b|transcript\.live_chat\.
// Readers and deleters only: a name helper (`storedNameOf`) or the tier hook
// (`tierMediaFile`) makes no read safe — those lines are in ALLOWED.
const SANCTIONED =
- /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|settleStoredTextAfterWrite|plainIdentity|hasStoredTextLeftover)\b/;
+ /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|setAsideStoredText|putBackKeptCapture|keepPlainAsCapture|hasStoredTextLeftover)\b/;
// Lines that name the raw chat for a reason that is neither a read nor a
// delete, each with it: `file` and a pattern of the code on the line.
@@ -66,6 +66,11 @@ const ALLOWED: { file: string; code: RegExp; why: string }[] = [
why: "the tier hook moves whichever form it is given and never reads it",
},
{
+ file: "common/controller/fetchLiveChat.ts",
+ code: /const landed = !partial && \(await stat\(path\.join\(videoDir, LIVE_CHAT_FILENAME\)\)|const fetched = measureChat\(await readFile\(path\.join\(videoDir, LIVE_CHAT_FILENAME\)\)\)/,
+ why: "the replace's look at what the pass wrote: the PLAIN file only (the stored capture was set aside first)",
+ },
+ {
file: "scripts/archilyzer-ops.mjs",
code: /^\s*['"`][^'"`]*transcript\.live_chat\.json[^'"`]*['"`],?\s*$/,
why: "a line of the ops help text (a string literal alone on its line)",
@@ -187,7 +192,7 @@ const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string }
},
liveChatOnlyArgs: {
file: "common/ytdlp/downloadOneManaged.ts",
- guard: "the chat-only pass: hasLiveChatOnDisk first; fetch-chat: liveChatPlan, or `replace` with the one-form settle",
+ guard: "the chat-only pass: hasLiveChatOnDisk first; fetch-chat: liveChatPlan, or `replace` with the stored capture kept first",
test: "ytdlp/chatOnlyStored.test.ts; controller/fetchLiveChat.test.ts (replace)",
},
downloadSubsForUrl: {
diff --git a/common/lib/storedText.lock.test.ts b/common/lib/storedText.lock.test.ts
@@ -0,0 +1,125 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { lstat, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.lock.test.ts
+//
+// TWO PROCESSES ON ONE VIDEO DIR (REVIEW-2 R3). Compress, restore and the files
+// card's delete take `.stored-text.lock` in the video dir; a second process
+// honours it ("busy", nothing touched) while its owner runs, and takes over a
+// stale one (its owner gone, or this pid from an earlier start). And the
+// restore looks at the plain file again right before the stored form goes.
+// Temp dirs only; the second process is a real child process.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-lock-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const W = await import("./storedText-write-server");
+const { readStoredText, decodeStoredBytes } = await import("./storedText-server");
+
+const CHAT = "transcript.live_chat.json";
+const ZST = `${CHAT}.zst`;
+const LOCK = ".stored-text.lock";
+const BODY = Array.from({ length: 30_000 }, (_, i) => `{"replayChatItemAction":{"n":${i},"h":"${createHash("md5").update(String(i)).digest("hex")}"}}`).join("\n") + "\n";
+
+let n = 0;
+async function videoDir(): Promise<string> {
+ const d = path.join(ROOT, "channels", `c${++n}`, "data", "v");
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, CHAT), BODY);
+ return d;
+}
+
+const exists = (p: string) => lstat(p).then(() => true, () => false);
+
+async function snapshot(d: string): Promise<string[]> {
+ const out: string[] = [];
+ for (const e of (await readdir(d)).sort()) out.push(`${e} ${createHash("sha256").update(await readFile(path.join(d, e))).digest("hex")}`);
+ return out;
+}
+
+test("a lock held by a live run of another process: compress, restore and delete answer busy, touching nothing", async () => {
+ const d = await videoDir();
+ const other = process.ppid;
+ const token = W.processStartToken(other);
+ assert.ok(token);
+ await writeFile(path.join(d, LOCK), JSON.stringify({ pid: other, token }));
+ const before = await snapshot(d);
+ const c = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(c.status === "skipped" && c.reason, "busy", JSON.stringify(c));
+ const r = await W.restoreStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(r.status === "skipped" && r.reason, "busy", JSON.stringify(r));
+ assert.equal(await W.removeStoredTextForm(d, CHAT), "busy");
+ assert.deepEqual(await snapshot(d), before, "nothing touched, the lock kept");
+});
+
+test("a stale lock (a reused pid's, a dead pid's, this pid's from an earlier start) is taken over and released", async () => {
+ for (const owner of [{ pid: process.ppid, token: "reused0" }, { pid: 999_999_995, token: "gone0" }, { pid: process.pid, token: "earlier0" }]) {
+ const d = await videoDir();
+ await writeFile(path.join(d, LOCK), JSON.stringify(owner));
+ const out = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(out.status, "compressed", `${JSON.stringify(owner)}: ${JSON.stringify(out)}`);
+ assert.equal(await exists(path.join(d, LOCK)), false, "released");
+ assert.deepEqual((await readdir(d)).sort(), [ZST]);
+ }
+});
+
+test("two processes at once: while a child process compresses, this one's restore and compress are refused; one whole copy throughout", async () => {
+ const d = await videoDir();
+ const child = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../testing/storedTextChild.ts", import.meta.url)), "compress", d, CHAT, "40"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let out = "";
+ let err = "";
+ child.stdout.on("data", (b) => (out += b));
+ child.stderr.on("data", (b) => (err += b));
+ const done = new Promise<number | null>((resolve) => child.on("exit", resolve));
+ // Wait for the child to hold the dir.
+ for (let i = 0; i < 400 && !(await exists(path.join(d, LOCK))); i++) await new Promise((r) => setTimeout(r, 25));
+ assert.ok(await exists(path.join(d, LOCK)), `the child holds the lock (${err})`);
+ const r = await W.restoreStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(r.status === "skipped" && r.reason, "busy", JSON.stringify(r));
+ const c = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(c.status === "skipped" && c.reason, "busy", JSON.stringify(c));
+ assert.equal(await readStoredText(d, CHAT, "utf8"), BODY, "one whole copy while the child runs");
+ assert.equal(await done, 0, err);
+ assert.equal(JSON.parse(out).status, "compressed", out);
+ assert.equal(await exists(path.join(d, LOCK)), false);
+ assert.deepEqual((await readdir(d)).sort(), [ZST]);
+ // And the other way round: the child restores, this process is refused.
+ const back = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../testing/storedTextChild.ts", import.meta.url)), "restore", d, CHAT, "40"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let out2 = "";
+ back.stdout.on("data", (b) => (out2 += b));
+ const done2 = new Promise<number | null>((resolve) => back.on("exit", resolve));
+ for (let i = 0; i < 400 && !(await exists(path.join(d, LOCK))); i++) await new Promise((r) => setTimeout(r, 25));
+ const c2 = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(c2.status === "skipped" && c2.reason, "busy", JSON.stringify(c2));
+ assert.equal(await done2, 0);
+ assert.equal(JSON.parse(out2).status, "restored", out2);
+ assert.equal(await readFile(path.join(d, CHAT), "utf8"), BODY);
+ assert.deepEqual((await readdir(d)).sort(), [CHAT]);
+});
+
+test("restore: the plain file is looked at again right before the stored form goes — a changed one keeps the stored form", async () => {
+ const { writeFileSync } = await import("node:fs");
+ const d = await videoDir();
+ assert.equal((await W.compressStoredText(d, CHAT, { reserveBytes: 0 })).status, "compressed");
+ const out = await W.restoreStoredText(d, CHAT, {
+ reserveBytes: 0,
+ // Another process's write lands in the placed plain file after it was verified.
+ crashAt: (p) => {
+ if (p === "restore-placed") writeFileSync(path.join(d, CHAT), BODY.replace("\"n\":7,", "\"n\":8,"));
+ },
+ });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.ok(await exists(path.join(d, ZST)), "the stored form stays");
+ assert.equal((await decodeStoredBytes(await readFile(path.join(d, ZST)))).toString("utf8"), BODY, "whole");
+});
diff --git a/common/testing/storedTextChild.ts b/common/testing/storedTextChild.ts
@@ -0,0 +1,13 @@
+// A SECOND PROCESS for the stored-text tests (lib/storedText.lock.test.ts): runs
+// one compress or restore on one file, slowly (each read chunk waits `delayMs`),
+// and prints its outcome as JSON. Temp dirs only.
+//
+// tsx testing/storedTextChild.ts <compress|restore> <videoDir> <name> <delayMs>
+
+import { compressStoredText, restoreStoredText } from "../lib/storedText-write-server";
+
+const [mode, videoDir, name, delay] = process.argv.slice(2);
+const throttle = () => new Promise<void>((resolve) => setTimeout(resolve, Number(delay)));
+const opts = { reserveBytes: 0, throttle };
+const out = mode === "restore" ? await restoreStoredText(videoDir, name, opts) : await compressStoredText(videoDir, name, opts);
+process.stdout.write(JSON.stringify(out));
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -7,15 +7,16 @@
- One file at a time, verified by reading it back before the original is removed; a crash at any step leaves a
whole copy and the next run finishes. `dryRun` reports bytes per channel and writes nothing; `verify` decodes
every stored chat; `limit` caps a run. It waits for render mode and goes slower while a live recording runs.
- - Deleting a chat (the auto-caption purge, the clear-transcript fix) removes both forms. On the video's files card,
- one form named while the other is there: both go when they hold the same content; with different content only
- the named one, and the card says the other is still there.
+ - Deleting a chat (the auto-caption purge, the clear-transcript fix) removes both forms. On the video's files card
+ only the file named goes, never its other form, and the card says when the other is still there.
- `"restore": true` is the rollback: every stored chat back to its plain form, verified the same way in reverse.
Restore before reverting or running an older checkout, which cannot read a stored chat.
- Started by a person only: a restart closes a queued compress-text job and resumes no interrupted one. A re-run
finishes whatever a stopped run left, whichever process it was.
- No download fetches a chat that is on disk in either form. `pnpm ops fetch-chat` `"replace": true` fetches a
- stored chat again on purpose; the new chat replaces the stored one only when it lands whole.
+ stored chat again on purpose: the stored capture is kept as `chat-capture-kept.<stamp>.json.zst` and never
+ removed automatically; the log compares both. An empty replay leaves the stored capture the chat.
+ - Two different captures are never settled by deleting one. A second editor process waits for a video's lock.
- **umtool: the gap mark's border is the deck's accent colour.**
- The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule
and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text
diff --git a/editor/app/api/ops/delete-file/route.ts b/editor/app/api/ops/delete-file/route.ts
@@ -14,8 +14,8 @@ export const dynamic = "force-dynamic";
// channel whose drive is not answering, something that is not a regular file.
// The channel's report is refreshed after. No undo. A stored text file
// (`transcript.live_chat.json` / `.zst`, lib/storedText.ts) named in one form
-// while the other is there: both go when they hold the same content; only the
-// named one when they differ, and `note` says the other is still there.
+// while the other is there: only the named one goes, never the other, and
+// `note` says the other is still there (same content or not).
export async function POST(request: Request) {
return ops(request, ["slug", "id", "file"], async (body) => {
const res = await deleteVideoFileAction(
diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts
@@ -22,10 +22,13 @@ export const dynamic = "force-dynamic";
// here — it never fetches.
//
// `replace: true` is the DELIBERATE RE-FETCH over a chat stored compressed
-// (`transcript.live_chat.json.zst`): the replay is fetched again, and when a
-// whole new plain chat lands the stored one is removed — one form is left. A
-// pass that lands nothing keeps the stored chat as it was. Refused over a
-// plain chat (delete it on the files card first) and with `renormalize`.
+// (`transcript.live_chat.json.zst`): the stored capture is first KEPT as
+// `chat-capture-kept.<UTC stamp>.json.zst` (no reader of the chat sees it; it
+// is never removed automatically), then the replay is fetched. A replay with
+// messages becomes the chat; an empty one is kept too and, like no replay at
+// all, leaves the stored capture the chat. The job log gives both captures'
+// bytes, message counts and first/last message times. Refused over a plain
+// chat (delete it on the files card first) and with `renormalize`.
export async function POST(request: Request) {
return ops(request, ["slug", "id", "queueKey", "renormalize", "replace"], async (body) =>
jobResponse(
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -1074,10 +1074,8 @@ export async function deleteVideoFileAction(
}
// Through its link when the file is tiered (release 17): the bytes on the
// media tier go too, never orphaned behind a removed link. A declared stored
- // name (lib/storedText.ts) is one file in two forms: either named, when the
- // other is there with the SAME content both go (the other would come back as
- // the file); with DIFFERENT content only the named one goes, and the answer
- // says the other is still there — it is what readers read now.
+ // name (lib/storedText.ts) is one file in two forms: only the one named goes,
+ // never the other; the answer says when the other is still here.
const out = await removeStoredTextForm(videoDir, path.basename(target));
if (out === "busy") {
return { ok: false, error: `${filename} not deleted: it is being compressed or restored right now. Try again in a moment.` };
@@ -1085,15 +1083,18 @@ export async function deleteVideoFileAction(
revalidatePath(`/channels/${slug}/videos/${videoId}`);
requestChannelSnapshot(getPaths(), slug);
if (out.kept) {
+ const k = out.kept;
return {
ok: true,
note:
- out.kept.why === "differs"
- ? `Deleted ${filename}. ${out.kept.name} is still here with different content, and is now the file readers read.`
- : `Deleted ${filename}. ${out.kept.name} is still here (it could not be read whole to compare).`,
+ k.same === "same"
+ ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still see the chat.`
+ : k.same === "differs"
+ ? `Deleted ${filename} only. ${k.name} is still here with different content, and is the file readers read.`
+ : `Deleted ${filename} only. ${k.name} is still here (it could not be read whole to compare).`,
};
}
- return out.removed.length > 1 ? { ok: true, note: `Deleted ${out.removed.join(" and ")} (the same content).` } : { ok: true };
+ return { ok: true };
}
// Promote a transcript.<lang>.vtt track to the canonical transcript.en.vtt so
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1596,9 +1596,8 @@ export function usage() {
' {"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. A raw live chat named in one form while the other is',
- ' there (transcript.live_chat.json and its .zst): both go when they hold the',
- ' same content; only the named one when they differ, and "note" says the',
- ' other is still there.',
+ ' there (transcript.live_chat.json and its .zst): only the named one goes,',
+ ' never the other, and "note" says the other is still there.',
"",
'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.)',
@@ -1892,8 +1891,11 @@ export function usage() {
" not, with no network — for a chat normalized before that; refused when no",
" raw is here (it never fetches).",
' "replace": true fetches the replay again over a chat stored compressed',
- " (.zst): when a whole new plain chat lands, the stored one is removed --",
- " one form is left; a pass that lands nothing keeps the stored chat. Refused",
+ " (.zst). The stored capture is first kept as chat-capture-kept.<UTC",
+ " stamp>.json.zst (no reader sees it; never removed automatically). A",
+ " replay with messages becomes the chat; an empty one is kept too and, like",
+ " no replay, leaves the stored capture the chat. The log gives both",
+ " captures' bytes, message counts and first/last message times. Refused",
' over a plain chat (delete it on the files card first) and with',
' "renormalize".',
"",
@@ -2314,7 +2316,9 @@ export function usage() {
" a .part beside it, a video recording or with a job running, a drive that",
" does not answer, a channel whose media is moving. Both forms present with",
" different content are refused and both kept. A file a writer replaces",
- " during the run is kept, and the older stored copy removed.",
+ " during the run is kept and read; the earlier content's stored copy is",
+ " kept beside it. The dry run lists earlier chat captures a re-fetch kept",
+ " (chat-capture-kept.*.json.zst), which nothing removes automatically.",
' "dryRun": true answers per channel the raw chats, their bytes, the',
" stored ones, the estimate after (about 5 %, an estimate) and the free",
' space, and writes nothing; "verify": true decodes every stored file in',