Archilyzer · Source

archilyzer

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

commit e81a64843ce898b203e5f912dac24b120278799e
parent 140858670b352c375e79da46d65015bcf8eaa2e9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 24 Nov 2026 18:58:56 -0500

space-suggestions REVIEW-1 B1-B3: one held predicate, asked of every row

controller/spaceHold.ts: do-not-clean, a must-keep or unfinished live
recording (anything but landed, failed, cancelled or superseded; interrupted
and awaiting a resume hold), a job for the video, the channel's and the
store's relocation markers. The scan asks it of every video a row touches,
the store rows (alternates, originals, compaction, failed encodes, landings)
included. A channel-wide clip eviction only when no video holding a window is
held and no old window is shared, its old windows digested; otherwise one per
unheld video naming its windows. Rows carry what the click re-checks (hold,
targets, digest). A former original is a row with a link to the video page,
no button; the scan never writes the former-original confirm. A partial of a
video not known to be on its platform is held (it may be the only copy); a
landing to verify frees nothing now; store files are statted through the drive
watchdog and a drive not answering is "unknown"; a failed ffprobe is not
remembered.

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

Diffstat:
Acommon/controller/spaceHold.test.ts | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/spaceHold.ts | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/spaceScan.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/controller/spaceScan.ts | 337++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Mcommon/lib/spaceSuggestions.test.ts | 2+-
Mcommon/lib/spaceSuggestions.ts | 18++++++++++++------
6 files changed, 743 insertions(+), 121 deletions(-)

diff --git a/common/controller/spaceHold.test.ts b/common/controller/spaceHold.test.ts @@ -0,0 +1,150 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { link, mkdir, mkdtemp, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { SpaceScanResult, SpaceSuggestion } from "../lib/spaceSuggestions"; +import { + SPACE_MAX_SCAN_AGE_MS, + SpaceHolds, + clipWindowsDigest, + liveRowHold, + recheckSpaceRow, + type SpaceHoldDeps, +} from "./spaceHold"; + +// THE ONE HELD PREDICATE (review 1, B2) and THE CLICK-TIME RE-CHECK (B4): what +// the scan holds back, asked again when the button is pressed, against the +// disk as it is then. + +const NOW = new Date("2026-11-24T12:00:00.000Z"); +const DAY = 86_400_000; + +async function put(file: string, bytes: number, ageDays = 0): Promise<void> { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, Buffer.alloc(bytes, 7)); + if (ageDays) { + const t = new Date(NOW.getTime() - ageDays * DAY); + await utimes(file, t, t); + } +} + +async function world() { + const tmp = await mkdtemp(path.join(tmpdir(), "space-hold-")); + const transcriptsDir = path.join(tmp, "transcripts"); + const paths = { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels"), savedVideosDir: path.join(transcriptsDir, "saved-videos") } as Paths; + await mkdir(paths.channelsDir, { recursive: true }); + return { tmp, paths, data: (slug: string, id: string) => path.join(paths.channelsDir, slug, "data", id) }; +} + +const noLive: SpaceHoldDeps = { liveRows: async () => [], jobs: () => [] }; + +test("live rows: anything not landed, failed, cancelled or superseded holds; must-keep and awaiting resume hold whatever the status", () => { + const row = (r: Record<string, unknown>) => liveRowHold({ id: "v", mustKeep: false, status: "landed", ...r } as never); + assert.equal(row({}), null); + assert.equal(row({ status: "failed" }), null); + assert.equal(row({ status: "cancelled" }), null); + assert.equal(row({ status: "recording", supersededBy: "x" }), null); + assert.equal(row({ status: "recording" })?.kind, "live"); + assert.equal(row({ status: "interrupted" })?.kind, "live"); + assert.equal(row({ awaitingResume: ["p1"] })?.kind, "live"); + assert.equal(row({ mustKeep: true })?.kind, "must-keep"); +}); + +test("a video is held by do-not-clean, a live row, a job for it, or its channel's relocation marker; the store by its own marker", async () => { + const w = await world(); + try { + await mkdir(w.data("c", "dnc"), { recursive: true }); + await writeFile(path.join(w.data("c", "dnc"), "do-not-clean.json"), JSON.stringify({ setAt: "x" })); + const holds = new SpaceHolds(w.paths, { + liveRows: async (slug) => (slug === "c" ? [{ id: "rec", status: "interrupted", mustKeep: false }, { id: "keep", status: "landed", mustKeep: true }] : []), + jobs: () => [ + { id: "j1", kind: "download-one-pipeline", status: "running", channelSlug: "c", videoId: "busy" }, + { id: "j2", kind: "compact-saved-videos", status: "queued", channelSlug: "c", spec: { kind: "compact-saved-videos", slug: "c", params: { ids: ["queued"] } } }, + { id: "j3", kind: "sync", status: "running", channelSlug: "d" }, + { id: "j4", kind: "transcribe-one", status: "done", channelSlug: "c", videoId: "free" }, + ], + }); + assert.equal((await holds.video("c", "dnc"))?.kind, "do-not-clean"); + assert.equal((await holds.video("c", "rec"))?.kind, "live"); + assert.equal((await holds.video("c", "keep"))?.kind, "must-keep"); + assert.equal((await holds.video("c", "busy"))?.kind, "job"); + assert.equal((await holds.video("c", "queued"))?.kind, "job"); + // A channel-wide writer (sync) holds every video of its channel. + assert.equal((await holds.video("d", "any"))?.kind, "job"); + assert.equal(await holds.video("c", "free"), null); + await mkdir(path.join(w.paths.channelsDir, "m"), { recursive: true }); + await writeFile(path.join(w.paths.channelsDir, "m", ".relocating.json"), JSON.stringify({ target: "/x/m/media", direction: "out", startedAt: "", phase: "copy", scope: "media" })); + assert.equal((await new SpaceHolds(w.paths, noLive).video("m", "v"))?.kind, "moving"); + assert.equal(await new SpaceHolds(w.paths, noLive).store(), null); + await writeFile(path.join(w.paths.transcriptsDir, ".relocating-saved-videos.json"), JSON.stringify({ target: "/x/saved-videos", direction: "out", startedAt: "", phase: "copy" })); + assert.equal((await new SpaceHolds(w.paths, noLive).store())?.kind, "store-moving"); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +function row(extra: Partial<SpaceSuggestion>): SpaceSuggestion { + return { key: "k", kind: "stale-partial", title: "", frees: { disk: "corpus", bytes: 1 }, basis: "measured", basisText: "", loss: "", ...extra }; +} + +test("the re-check: a scan older than a day, a target changed, grown, gone or shared, a hold that appeared since — each refused and named", async () => { + const w = await world(); + try { + const dir = w.data("c", "v1"); + const part = path.join(dir, "audio.mp3.part"); + await put(part, 1000, 30); + await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" })); + const st = await stat(part); + const result = { computedAt: NOW.toISOString() } as SpaceScanResult; + const good = row({ slug: "c", id: "v1", file: "audio.mp3.part", hold: { slug: "c", id: "v1" }, targets: [{ path: part, size: st.size, mtimeMs: st.mtimeMs }] }); + const ask = (r: SpaceSuggestion, deps: SpaceHoldDeps = noLive, at = NOW) => recheckSpaceRow({ paths: w.paths, result, row: r, now: at, holds: new SpaceHolds(w.paths, deps) }); + assert.equal(await ask(good), null); + assert.match((await ask(good, noLive, new Date(NOW.getTime() + SPACE_MAX_SCAN_AGE_MS + 60_000)))!, /rescan first/); + assert.match((await ask(good, { ...noLive, jobs: () => [{ id: "j", kind: "download-one-pipeline", status: "running", channelSlug: "c", videoId: "v1" }] }))!, /a job/); + // Gone from its platform since: the partial may be the only copy. + await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "deleted", checkedAt: NOW.toISOString(), checkedBy: "check" })); + assert.match((await ask(good))!, /only copy/); + await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" })); + // Resumed since (it grew): changed. + await writeFile(part, Buffer.alloc(2000, 1)); + assert.match((await ask(good))!, /changed since the scan/); + await rm(part); + assert.match((await ask(good))!, /no longer there/); + // Shared. + const alt = path.join(dir, "alt.mp4"); + await put(alt, 500); + await link(alt, path.join(w.tmp, "other-link")); + const ast = await stat(alt); + assert.match((await ask(row({ kind: "drop-alternate", hold: { slug: "c", id: "v1", store: true }, targets: [{ path: alt, size: ast.size, mtimeMs: ast.mtimeMs }] })))!, /hard link/); + // Marked do-not-clean since. + await writeFile(path.join(dir, "do-not-clean.json"), JSON.stringify({ setAt: "x" })); + assert.match((await ask(row({ kind: "drop-original", hold: { slug: "c", id: "v1", store: true } })))!, /do-not-clean/); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("a channel-wide eviction: refused when the set of old windows changed or a video holding windows is held now", async () => { + const w = await world(); + try { + await put(path.join(w.data("c", "a"), "clips", "10.00-20.00.mp4"), 300, 60); + await put(path.join(w.data("c", "a"), "clips", "10.00-20.00.json"), 10, 60); + await put(path.join(w.data("c", "b"), "clips", "1.00-2.00.mp4"), 300, 2); + const digest = await clipWindowsDigest(w.paths, "c", 30, NOW); + assert.equal(digest.count, 1); + const result = { computedAt: NOW.toISOString() } as SpaceScanResult; + const r = row({ kind: "evict-clips", slug: "c", hold: { slug: "c" }, digest: { olderThanDays: 30, count: digest.count, sha1: digest.sha1 } }); + const ask = (deps: SpaceHoldDeps = noLive, at = NOW) => recheckSpaceRow({ paths: w.paths, result, row: r, now: at, holds: new SpaceHolds(w.paths, deps) }); + assert.equal(await ask(), null); + // b's window turns 30 days old (a scan an hour old then): the set grew. + const later = new Date(NOW.getTime() + 29 * DAY); + const fresh = await recheckSpaceRow({ paths: w.paths, result: { computedAt: new Date(later.getTime() - 3_600_000).toISOString() } as SpaceScanResult, row: r, now: later, holds: new SpaceHolds(w.paths, noLive) }); + assert.match(fresh!, /changed since the scan/); + // b (holding a young window) is recording now. + assert.match((await ask({ ...noLive, liveRows: async () => [{ id: "b", status: "recording", mustKeep: false }] }))!, /live recording/); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); diff --git a/common/controller/spaceHold.ts b/common/controller/spaceHold.ts @@ -0,0 +1,282 @@ +// WHAT FREE UP SPACE NEVER OFFERS, AND THE CHECK AT THE CLICK (lane +// space-suggestions, review 1 B2 and B4). +// +// ONE HELD PREDICATE. The scan (controller/spaceScan.ts) asks it of every +// video a row would touch, the store rows included, and the page's button asks +// it again before anything runs (editor/app/cleanup/space/lib/runSpaceAction.ts). +// A video is held by: +// - do-not-clean; +// - a live recording of it that is must-keep, or whose run is not over +// (anything but landed, failed, cancelled or superseded; interrupted and +// awaiting a resume hold); +// - a job queued or running for it (or a channel-wide writer on its channel); +// - its channel's relocation marker. +// The store's rows are held, too, by the store's own relocation marker. A pin +// keeps every copy of its video (ruling 2): that rule is alternateDisposition's +// (lib/spaceSuggestions.ts), for the one kind that removes a copy of it. +// +// THE RE-CHECK (rulings for B4, orchestrator's, 24 Nov). A scan older than a +// day is refused ("rescan first"). Then, for the row's own subject: the held +// predicate, as it is now; every target file still there with the size and +// mtime the scan saw, and one link; a channel-wide clip eviction's whole set +// of old windows the same as at the scan, and no video holding a window held. +// A partial is also refused when its video is not known to be on its platform +// (it may be the only copy of those bytes). Any mismatch refuses the row and +// says why. Reads only. + +import path from "node:path"; +import { createHash } from "node:crypto"; +import { lstat, readdir } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { getRegistry, type JobRecord } from "../jobs/registry"; +import type { SpaceScanResult, SpaceSuggestion } from "../lib/spaceSuggestions"; +import { readRelocationMarker } from "../lib/channelMedia"; +import { readSavedVideosMarker } from "../lib/savedVideoStore"; +import { isDoNotClean } from "../lib/doNotClean-server"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; +import { CLIPS_DIR_NAME, parseAnyClipWindowName, parseDesyncedClipWindowName, clipWindowStem } from "../lib/clipWindow"; +import { loadLiveRecordingRows, type LiveRecordingRow } from "../lib/liveRecordings-server"; +import { VIDEO_WRITING_KINDS } from "./videoBusy"; + +export const SPACE_MAX_SCAN_AGE_MS = 24 * 60 * 60 * 1000; + +// A downloader's partial: what `delete-file` may be asked to remove once it is +// abandoned. NARROWER than mediaTier's scratch on purpose — a stored-text +// run's `.retire-<pid>` (possibly the only copy), a `.landed-kept` or +// `.corrupt-kept` container, a tier hook's temp are somebody's kept bytes. +const PARTIAL_RES: readonly RegExp[] = [ + /\.part$/, + /\.ytdl$/, + /\.part-Frag\d+$/, + /\.part\.(good|testing)$/, + /\.stored\.part\.json$/, + /^\.syncthing\..*\.tmp$/, + /^audio\.tmp-\d+\./, + /\.temp\./, +]; + +export function isAbandonablePartial(name: string): boolean { + return PARTIAL_RES.some((re) => re.test(name)); +} + +// On its platform by the record's word (public or unlisted). Anything else — +// gone, private, unknown — and a partial may be the only copy. +export function partialMayBeOnlyCopy(availability: string | null): boolean { + return availability !== "public" && availability !== "unlisted"; +} + +export type SpaceHoldKind = "do-not-clean" | "must-keep" | "live" | "job" | "moving" | "store-moving"; +export type SpaceHold = { kind: SpaceHoldKind; why: string }; + +export const SPACE_HOLD_LABELS: Record<SpaceHoldKind, string> = { + "do-not-clean": "Videos marked do-not-clean", + "must-keep": "Must-keep live recordings", + live: "Videos with a live recording not over", + job: "Videos a job is working on", + moving: "Channels mid-relocation", + "store-moving": "The saved-video store, mid-move", +}; + +type LiveRowLike = Pick<LiveRecordingRow, "id" | "mustKeep"> & { + status: string; + supersededBy?: string; + awaitingResume?: string[]; +}; + +const TERMINAL = new Set(["landed", "failed", "cancelled"]); + +export function liveRowHold(r: LiveRowLike): SpaceHold | null { + if (r.mustKeep) return { kind: "must-keep", why: "a must-keep live recording" }; + if (r.awaitingResume?.length) return { kind: "live", why: "a live recording awaiting a resume" }; + if (r.supersededBy) return null; + if (!TERMINAL.has(r.status)) return { kind: "live", why: `a live recording (${r.status})` }; + return null; +} + +type JobLike = Pick<JobRecord, "id" | "kind" | "status"> & Partial<Pick<JobRecord, "channelSlug" | "videoId" | "spec">>; + +export type SpaceHoldDeps = { + isDoNotClean?: (videoDir: string) => Promise<boolean>; + liveRows?: (slug: string) => Promise<LiveRowLike[]>; + jobs?: () => readonly JobLike[]; +}; + +function jobIds(j: JobLike): string[] | null { + const ids = (j.spec?.params as { ids?: unknown } | undefined)?.ids; + return Array.isArray(ids) ? ids.filter((x): x is string => typeof x === "string") : null; +} + +export class SpaceHolds { + private readonly live = new Map<string, Promise<LiveRowLike[]>>(); + private readonly markers = new Map<string, Promise<SpaceHold | null>>(); + private storeMemo: Promise<SpaceHold | null> | null = null; + private jobList: readonly JobLike[] | null = null; + constructor( + private readonly paths: Pick<Paths, "channelsDir" | "transcriptsDir">, + private readonly deps: SpaceHoldDeps = {}, + ) {} + + private jobs(): readonly JobLike[] { + if (!this.jobList) { + this.jobList = (this.deps.jobs ?? defaultJobs)().filter((j) => j.status === "queued" || j.status === "running"); + } + return this.jobList; + } + + channel(slug: string): Promise<SpaceHold | null> { + let m = this.markers.get(slug); + if (!m) { + m = readRelocationMarker(this.paths, slug).then((marker) => + marker ? { kind: "moving" as const, why: `a relocation is in flight (${marker.direction}, phase ${marker.phase})` } : null, + ); + this.markers.set(slug, m); + } + return m; + } + + store(): Promise<SpaceHold | null> { + this.storeMemo ??= readSavedVideosMarker(this.paths).then((marker) => + marker ? { kind: "store-moving" as const, why: `the saved-video store is being moved (${marker.direction}, phase ${marker.phase})` } : null, + ); + return this.storeMemo; + } + + private liveRows(slug: string): Promise<LiveRowLike[]> { + let p = this.live.get(slug); + if (!p) { + p = (this.deps.liveRows ?? ((s: string) => loadLiveRecordingRows(this.paths, s)))(slug).catch(() => []); + this.live.set(slug, p); + } + return p; + } + + job(slug: string, id: string): SpaceHold | null { + for (const j of this.jobs()) { + if (j.kind === "space-scan") continue; + if (j.channelSlug && j.channelSlug !== slug) continue; + const ids = jobIds(j); + const forIt = j.videoId ? j.videoId === id : ids ? ids.includes(id) : !!j.channelSlug && VIDEO_WRITING_KINDS.has(j.kind); + if (forIt) return { kind: "job", why: `a job is working on it (${j.kind}, ${j.status})` }; + } + return null; + } + + async video(slug: string, id: string): Promise<SpaceHold | null> { + const moving = await this.channel(slug); + if (moving) return moving; + const dir = path.join(this.paths.channelsDir, slug, "data", id); + if (await (this.deps.isDoNotClean ?? isDoNotClean)(dir).catch(() => false)) { + return { kind: "do-not-clean", why: "do-not-clean" }; + } + for (const r of await this.liveRows(slug)) { + if (r.id !== id) continue; + const h = liveRowHold(r); + if (h) return h; + } + return this.job(slug, id); + } +} + +function defaultJobs(): readonly JobLike[] { + return getRegistry().list(); +} + +// --- clip windows --------------------------------------------------------------------- + +export type ClipWindowFile = { id: string; name: string; stem: string; path: string; size: number; mtimeMs: number; nlink: number; blocks: number }; + +// One video dir's clip windows (the media, never the sidecars), as the +// evictor reads them. +export async function clipWindowsOf(videoDir: string, id: string): Promise<ClipWindowFile[]> { + const dir = path.join(videoDir, CLIPS_DIR_NAME); + const out: ClipWindowFile[] = []; + for (const name of await readdir(dir).catch(() => [] as string[])) { + const span = parseAnyClipWindowName(name) ?? parseDesyncedClipWindowName(name); + if (!span) continue; + const p = path.join(dir, name); + const st = await lstat(p).catch(() => null); + if (!st?.isFile()) continue; + out.push({ id, name, stem: clipWindowStem(span.from, span.to, span.tier), path: p, size: st.size, mtimeMs: st.mtimeMs, nlink: st.nlink, blocks: st.blocks * 512 }); + } + return out; +} + +export function digestOf(files: readonly Pick<ClipWindowFile, "id" | "name" | "size" | "mtimeMs">[]): string { + const h = createHash("sha1"); + for (const line of files.map((f) => `${f.id}/${f.name}\u0000${f.size}\u0000${f.mtimeMs}`).sort()) h.update(line + "\n"); + return h.digest("hex"); +} + +// A channel's windows not touched for `olderThanDays` at `now`, digested, and +// every video that holds any window (old or not). +export async function clipWindowsDigest( + paths: Pick<Paths, "channelsDir">, + slug: string, + olderThanDays: number, + now: Date, +): Promise<{ count: number; sha1: string; videosWithWindows: string[]; shared: number }> { + const data = path.join(paths.channelsDir, slug, "data"); + const cutoff = now.getTime() - olderThanDays * 86_400_000; + const old: ClipWindowFile[] = []; + const videos: string[] = []; + let shared = 0; + for (const id of await readdir(data).catch(() => [] as string[])) { + const w = await clipWindowsOf(path.join(data, id), id); + if (!w.length) continue; + videos.push(id); + for (const f of w) { + if (f.mtimeMs > cutoff) continue; + old.push(f); + if (f.nlink > 1) shared += 1; + } + } + return { count: old.length, sha1: digestOf(old), videosWithWindows: videos, shared }; +} + +// --- the re-check ---------------------------------------------------------------------- + +export async function recheckSpaceRow(opts: { + paths: Pick<Paths, "channelsDir" | "transcriptsDir">; + result: Pick<SpaceScanResult, "computedAt">; + row: SpaceSuggestion; + now?: Date; + holds: SpaceHolds; + availability?: (videoDir: string) => Promise<string | null>; +}): Promise<string | null> { + const now = opts.now ?? new Date(); + const age = now.getTime() - Date.parse(opts.result.computedAt); + if (!(age <= SPACE_MAX_SCAN_AGE_MS)) { + return `the last scan is ${Number.isFinite(age) ? `${Math.round(age / 3_600_000)} h` : "of an unknown"} old: rescan first`; + } + const { row, holds } = opts; + const h = row.hold; + if (h?.store) { + const s = await holds.store(); + if (s) return `held: ${s.why}`; + } + if (h?.slug) { + const held = h.id ? await holds.video(h.slug, h.id) : await holds.channel(h.slug); + if (held) return `held: ${held.why}`; + } + for (const t of row.targets ?? []) { + const st = await lstat(t.path).catch(() => null); + if (!st?.isFile()) return `${path.basename(t.path)} is no longer there: rescan`; + if (st.size !== t.size || st.mtimeMs !== t.mtimeMs) return `${path.basename(t.path)} changed since the scan: rescan`; + if (st.nlink !== 1) return `${path.basename(t.path)} has another hard link now: removing it would free nothing`; + } + if (row.kind === "stale-partial" && h?.slug && h.id) { + if (!row.file || !isAbandonablePartial(row.file)) return `${row.file ?? "?"} is not a partial download`; + const a = await (opts.availability ?? resolveEffectiveAvailability)(path.join(opts.paths.channelsDir, h.slug, "data", h.id)).catch(() => null); + if (partialMayBeOnlyCopy(a)) return `held: the video is not known to be on its platform (${a ?? "unknown"}): the partial may be the only copy`; + } + if (row.digest && h?.slug) { + const d = await clipWindowsDigest(opts.paths, h.slug, row.digest.olderThanDays, now); + if (d.count !== row.digest.count || d.sha1 !== row.digest.sha1) return "the channel's old clip windows changed since the scan: rescan"; + if (d.shared) return "a window has another hard link now: rescan"; + for (const id of d.videosWithWindows) { + const held = await holds.video(h.slug, id); + if (held) return `held: ${id}: ${held.why}`; + } + } + return null; +} diff --git a/common/controller/spaceScan.test.ts b/common/controller/spaceScan.test.ts @@ -90,6 +90,10 @@ async function world(): Promise<World> { await put(path.join(v3, "audio.mp3.part-recent"), 1); // not a partial name await put(path.join(v3, "source-media.mp4"), 500_000); await put(path.join(v3, ".transcript.live_chat.json.retire-123"), 5_000, 30); // the stored-text run's: never proposed + await json(path.join(v3, "availability.json"), { availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" }); + await put(path.join(v3, "clips", "50.00-60.00.mp4"), 40_000, 60); + // A partial of a video not known to be on its platform: it may be the only copy. + await put(path.join(classic, "data", "v9", "audio.mp3.part"), 70_000, 30); // A clip window hard-linked into a take: shared, frees nothing. const v4 = path.join(classic, "data", "v4"); await put(path.join(v4, "clips", "5.00-9.00.mp4"), 90_000, 60); @@ -123,6 +127,27 @@ async function world(): Promise<World> { storedAt: "", dir: s6, file: "source-media.mkv", bytes: 600_000, keepReason: "pin", alternates: [{ file: "source-media.alt-720p-20261001000000.mkv", bytes: 500_000, storedAt: "", setAsideAt: "" }], }); + // Saved alternates of a do-not-clean video, a must-keep recording's and an + // interrupted recording's: held (review 1, B2). A former original: a row + // with a link to the video page only (ruling B1). + for (const id of ["v10", "v11", "v12", "v13"]) { + const sd = path.join(storeDir, "classic", id); + await put(path.join(sd, "source-media.mp4"), 100_000); + await put(path.join(sd, "source-media.alt-480p-20261001000000.mp4"), 200_000); + await json(path.join(classic, "data", id, "saved-video.json"), { + storedAt: "", dir: sd, file: "source-media.mp4", bytes: 100_000, keepReason: "override", + alternates: [{ file: "source-media.alt-480p-20261001000000.mp4", bytes: 200_000, storedAt: "", setAsideAt: "", ...(id === "v13" ? { keptAs: "former-original" } : {}) }], + }); + } + await json(path.join(classic, "data", "v10", "do-not-clean.json"), { setAt: NOW.toISOString() }); + // Two channels of clip windows: one with nothing held (one eviction for the + // channel), one whose other video is recording (per video). + await json(path.join(channelsDir, "clipsy", "config.json"), { name: "Clipsy" }); + await put(path.join(channelsDir, "clipsy", "data", "c1", "clips", "1.00-2.00.mp4"), 10_000, 60); + await put(path.join(channelsDir, "clipsy", "data", "c2", "clips", "3.00-4.00.h1080.mp4"), 10_000, 45); + await json(path.join(channelsDir, "clipsrec", "config.json"), { name: "Clipsrec" }); + await put(path.join(channelsDir, "clipsrec", "data", "k1", "clips", "1.00-2.00.mp4"), 10_000, 60); + await put(path.join(channelsDir, "clipsrec", "data", "k2", "clips", "1.00-2.00.mp4"), 10_000, 2); // A live landing whose check failed, its stream file in the store's staging. await put(path.join(storeDir, "classic", "live.part1.mp4"), 250_000); @@ -194,6 +219,8 @@ async function world(): Promise<World> { briefOf("moving", null), briefOf("legacy", null), briefOf("offline", null), + briefOf("clipsy", null), + briefOf("clipsrec", null), ]), compactionPlan: async () => ({ plan: { @@ -221,8 +248,11 @@ async function world(): Promise<World> { liveRecordings: async () => [ { slug: "classic", id: "v7", status: "landed", verification: { state: "failed", at: "", against: ["live.part1.mp4"] }, startedAt: "2026-11-20T00:00:00Z", mustKeep: false, parts: [], keptParts: [{ stem: "k", files: [], bytes: 33_000, seconds: null, fromStart: null, run: "earlier", why: "" }] } as unknown as LiveRecordingView, { slug: "classic", id: "v3", status: "recording", startedAt: "2026-11-24T11:00:00Z", mustKeep: true, parts: [] } as unknown as LiveRecordingView, + { slug: "classic", id: "v11", status: "landed", startedAt: "2026-11-01T00:00:00Z", mustKeep: true, parts: [] } as unknown as LiveRecordingView, + { slug: "classic", id: "v12", status: "interrupted", startedAt: "2026-11-23T00:00:00Z", mustKeep: false, parts: [] } as unknown as LiveRecordingView, + { slug: "clipsrec", id: "k2", status: "interrupted", startedAt: "2026-11-23T00:00:00Z", mustKeep: false, parts: [] } as unknown as LiveRecordingView, ], - busy: () => null, + holds: { jobs: () => [] }, reportsRoot: reports, }; return { tmp, paths, settings, deps, platter, storeDir }; @@ -352,12 +382,22 @@ test("clip windows: older than the cutoff, a shared window frees nothing, a do-n const { w, r } = await scanned(); try { const rows = kinds(r, "evict-clips").filter((s) => s.slug === "classic"); - // v2 is do-not-clean, so the channel's eviction is per video: v1's (v4's is shared). + // v2 is do-not-clean and v3 recording, so the channel's eviction is per + // video: v1's, naming its old window (v4's is shared). assert.equal(rows.length, 1); assert.equal(rows[0].id, "v1"); - assert.deepEqual(rows[0].actions, [{ op: "evict-clips", body: { slug: "classic", id: "v1", olderThanDays: 30 } }]); + assert.deepEqual(rows[0].actions, [{ op: "evict-clips", body: { slug: "classic", id: "v1", windows: ["10.00-20.00"], olderThanDays: 30 } }]); + assert.deepEqual(rows[0].hold, { slug: "classic", id: "v1" }); + assert.equal(rows[0].targets?.length, 1); assert.ok(rows[0].frees!.bytes >= 60_000 && rows[0].frees!.bytes < 70_000); assert.ok(r.held.some((h) => /shared|hard link/i.test(h.why) && (h.bytes ?? 0) >= 90_000)); + // Nothing held in clipsy: one eviction for the channel, its windows digested. + const clipsy = kinds(r, "evict-clips").filter((s) => s.slug === "clipsy"); + assert.equal(clipsy.length, 1); + assert.deepEqual(clipsy[0].actions, [{ op: "evict-clips", body: { olderThanDays: 30, slug: "clipsy" } }]); + assert.equal(clipsy[0].digest?.count, 2); + // clipsrec's k2 (a young window) is recording: k1 alone, never the channel. + assert.deepEqual(kinds(r, "evict-clips").filter((s) => s.slug === "clipsrec").map((s) => s.id), ["k1"]); } finally { await rm(w.tmp, { recursive: true, force: true }); } @@ -386,6 +426,11 @@ test("partials and unstored containers once nothing holds them", async () => { const partials = kinds(r, "stale-partial").filter((s) => s.id === "v3"); assert.deepEqual(partials.map((s) => s.file).sort(), ["audio.mp3.part", "audio.mp3.ytdl"]); assert.deepEqual(partials[0].actions![0].op, "delete-file"); + assert.deepEqual(partials[0].hold, { slug: "classic", id: "v3" }); + assert.equal(partials[0].targets?.length, 1); + // v9 is not known to be on its platform: held, the partial may be the only copy. + assert.equal(kinds(r, "stale-partial").filter((s) => s.id === "v9").length, 0); + assert.ok(r.held.some((h) => /only copy/.test(h.why) && (h.bytes ?? 0) >= 70_000)); const stray = kinds(r, "unstored-container"); assert.deepEqual(stray.map((s) => s.id), ["v3"]); assert.equal(stray[0].actions, undefined); @@ -410,14 +455,27 @@ test("the store: compaction frees the platter later, a reviewed original now; re assert.ok(drop.frees!.bytes >= 1_200_000); assert.deepEqual(drop.actions, [{ op: "drop-saved-alternate", body: { slug: "classic", id: "v5", file: "source-media.mp4", confirmOriginal: true } }]); const alts = kinds(r, "drop-alternate"); - assert.deepEqual(alts.map((s) => `${s.id}/${s.file}`), ["v5/source-media.alt-480p-20261001000000.mp4"]); + // v10 (do-not-clean), v11 (must-keep) and v12 (interrupted recording) are held; + // v13's former original is a row with a link only. + assert.deepEqual(alts.map((s) => `${s.id}/${s.file}`).sort(), ["v13/source-media.alt-480p-20261001000000.mp4", "v5/source-media.alt-480p-20261001000000.mp4"]); + const former = alts.find((s) => s.id === "v13")!; + assert.equal(former.actions, undefined); + assert.equal(former.link?.href, "/channels/classic/videos/v13"); + const v5alt = alts.find((s) => s.id === "v5")!; + assert.deepEqual(v5alt.hold, { slug: "classic", id: "v5", store: true }); + assert.equal(v5alt.targets?.length, 1); assert.ok(r.held.some((h) => /pinned/.test(h.why) && (h.bytes ?? 0) >= 500_000)); + assert.ok(r.held.some((h) => /do-not-clean/.test(h.why) && (h.bytes ?? 0) >= 200_000)); + assert.ok(r.held.some((h) => /must-keep/.test(h.why))); + assert.ok(r.held.some((h) => /interrupted/.test(h.why))); assert.deepEqual(r.refused.map((g) => g.group), ["keep-latest (not deliberately stored)"]); const failed = kinds(r, "failed-encode")[0]; assert.deepEqual(failed.actions, [{ op: "kept-failed-encodes", body: { clear: { slug: "classic", id: "v6" } } }]); const landing = kinds(r, "reverify-landing")[0]; - assert.equal(landing.frees!.disk, "platter"); - assert.ok(landing.frees!.bytes >= 250_000); + // It frees nothing unless it verifies. + assert.equal(landing.frees, null); + assert.equal(landing.later!.disk, "platter"); + assert.ok(landing.later!.low >= 250_000); assert.deepEqual(landing.actions, [{ op: "live-recording-verify", body: { slug: "classic", id: "v7", startedAt: "2026-11-20T00:00:00Z" } }]); assert.ok(r.unmanaged.some((u) => /kept parts/i.test(u.what) && u.bytes === 33_000)); assert.ok(r.unmanaged.some((u) => /umtool/i.test(u.what) && u.command === "umtool prune --all")); @@ -454,10 +512,11 @@ test("the result stays small: thousands of clip windows are counted, fifty liste const base = path.join(w.paths.channelsDir, "classic", "data"); for (let i = 0; i < 300; i++) await put(path.join(base, `x${i}`, "clips", "1.00-2.00.mp4"), 1_000 + i, 60); const r = await scanSpace({ paths: w.paths, settings: w.settings, deps: w.deps }); - const clipRows = kinds(r, "evict-clips").filter((s) => s.slug === "classic"); + // classic's 301 per-video rows, clipsy's one and clipsrec's one: 50 kept. + const clipRows = kinds(r, "evict-clips"); assert.equal(clipRows.length, 50); const over = r.overflow.find((o) => o.kind === "evict-clips")!; - assert.equal(over.count, 301 - 50); + assert.equal(over.count, 303 - 50); const file = await stat(path.join(w.paths.transcriptsDir, SPACE_SUGGESTIONS_FILENAME)); assert.ok(file.size < 200_000, `${file.size} bytes`); } finally { diff --git a/common/controller/spaceScan.ts b/common/controller/spaceScan.ts @@ -37,8 +37,6 @@ import { inspectChannelMedia, type ChannelMediaLocation } from "../lib/channelMe import { CLIPS_DIR, LIVE_CHAT_MEDIA_FILENAME, isKeptChatCapture, isScratchEntry, isTierable } from "../lib/mediaTier"; import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles"; import { isStoredCaptionName } from "../lib/storedText"; -import { DO_NOT_CLEAN_FILENAME } from "../lib/doNotClean"; -import { isDoNotClean } from "../lib/doNotClean-server"; import { SAVED_VIDEO_POINTER_FILENAME, savedVideoRoot } from "../lib/savedVideo"; import { formatBytes } from "../lib/format"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; @@ -81,30 +79,27 @@ import { import { listLiveRecordings, type LiveRecordingView } from "./liveRecordings"; import { ARCHIVE_ORG_STAGING_DIR } from "./archiveOrgDownload"; import { probeCompactionSource, type SourceProbe } from "../lib/compactMedia-server"; +import { + SPACE_HOLD_LABELS, + SpaceHolds, + clipWindowsOf, + digestOf, + isAbandonablePartial, + partialMayBeOnlyCopy, + type ClipWindowFile, + type SpaceHold, + type SpaceHoldDeps, +} from "./spaceHold"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; const DAY_MS = 86_400_000; const SLICE_MS = 15; const LSTAT_BATCH = 32; const EXAMPLES_PER_GROUP = 5; -// A downloader's partial: what `delete-file` may be asked to remove once it is -// abandoned. NARROWER than mediaTier's scratch on purpose — a stored-text -// run's `.retire-<pid>` (possibly the only copy), a `.landed-kept` or -// `.corrupt-kept` container, a tier hook's temp are somebody's kept bytes. -const PARTIAL_RES: readonly RegExp[] = [ - /\.part$/, - /\.ytdl$/, - /\.part-Frag\d+$/, - /\.part\.(good|testing)$/, - /\.stored\.part\.json$/, - /^\.syncthing\..*\.tmp$/, - /^audio\.tmp-\d+\./, - /\.temp\./, -]; - -export function isAbandonablePartial(name: string): boolean { - return PARTIAL_RES.some((re) => re.test(name)); -} +// The partial-name rule lives with the held predicate (controller/spaceHold.ts), +// which the click asks again. +export { isAbandonablePartial } from "./spaceHold"; export type SpaceScanSettings = Pick<SiteSettings, "minFreeDiskGB"> & { storage: Pick<StorageSettings, "locations" | "defaultLocationId" | "savedVideosLocationId">; @@ -126,8 +121,11 @@ export type SpaceScanDeps = { compactionReview?: () => Promise<CompactionReviewRow[]>; keptFailedEncodes?: () => Promise<KeptFailedEncodeRow[]>; liveRecordings?: () => Promise<LiveRecordingView[]>; - busy?: (slug: string, id: string) => string | null; - isDoNotClean?: (videoDir: string) => Promise<boolean>; + // The held predicate's sources (controller/spaceHold.ts). Its live rows + // default to `liveRecordings` below, by channel. + holds?: SpaceHoldDeps; + // A video's availability, for a partial (default: the record's). + availability?: (videoDir: string) => Promise<string | null>; // umtool's report projects (null: not measured). reportsRoot?: string | null; }; @@ -174,7 +172,7 @@ function emptyShare(): SpaceArchiveShare { return { media: 0, text: 0, clips: 0, store: 0, playable: 0, builds: 0, reports: 0, other: 0 }; } -type Fact = { bytes: number; nlink: number; dev: string; mtimeMs: number }; +type Fact = { bytes: number; size: number; nlink: number; dev: string; mtimeMs: number }; class Accounting { private seen = new Set<string>(); @@ -182,7 +180,7 @@ class Accounting { readonly devDir = new Map<string, string>(); constructor(private readonly deviceOf: (p: string, st: Stats) => string) {} fact(abs: string, st: Stats): Fact { - return { bytes: allocated(st), nlink: st.nlink, dev: this.deviceOf(abs, st), mtimeMs: st.mtimeMs }; + return { bytes: allocated(st), size: st.size, nlink: st.nlink, dev: this.deviceOf(abs, st), mtimeMs: st.mtimeMs }; } // Counted once per inode; returns the fact either way. add(abs: string, st: Stats, cat: keyof SpaceArchiveShare): Fact { @@ -325,9 +323,10 @@ type ChannelTally = { audio: PerDev; extra: PerDev; move: { bytes: number; files: number }; - clips: { id: string; bytes: number; count: number; dev: string }[]; - clipsDncVideos: number; - partials: { id: string; file: string; fact: Fact }[]; + // Every video holding a clip window: its old (unshared) windows, whether + // it is held, and whether one of its old windows has another link. + clipVideos: { id: string; old: ClipWindowFile[]; held: SpaceHold | null; shared: number; dev: string }[]; + partials: { id: string; file: string; fact: Fact; path: string }[]; strays: { id: string; file: string; fact: Fact }[]; }; @@ -338,8 +337,7 @@ function newTally(): ChannelTally { audio: new Map(), extra: new Map(), move: { bytes: 0, files: 0 }, - clips: [], - clipsDncVideos: 0, + clipVideos: [], partials: [], strays: [], }; @@ -385,13 +383,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult const notScanned: { slug: string; why: string }[] = []; const floorBytes = Math.max(0, settings.minFreeDiskGB) * 1024 ** 3; const locations = settings.storage.locations; - const busy = deps.busy ?? ((s: string, i: string) => { - // Lazily: the registry is the editor's, and a test names its own. - return busyReason?.(s, i) ?? null; - }); - let busyReason: ((s: string, i: string) => string | null) | null = null; - if (!deps.busy) busyReason = (await import("./videoBusy")).videoPersistBusyReason; - const dnc = deps.isDoNotClean ?? isDoNotClean; + const availabilityOf = deps.availability ?? ((dir: string) => resolveEffectiveAvailability(dir)); // THE DEVICES' IDS. The corpus disk is `corpus`; a location's disk takes the // first location on it; anything else `fs-<dev>`. @@ -422,14 +414,25 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult const storeReal = await realpath(paths.savedVideosDir).catch(() => paths.savedVideosDir); const playableRoot = path.join(path.dirname(storeReal), "playable"); - // LIVE RECORDINGS FIRST: what is recording is never proposed. + // LIVE RECORDINGS FIRST, and THE ONE HELD PREDICATE (controller/spaceHold.ts): + // do-not-clean, a must-keep or unfinished live recording, a job for the + // video, a relocation marker — asked of every video a row would touch, the + // store's rows included, and asked again at the click. const liveRows = await (deps.liveRecordings ?? (async () => (await listLiveRecordings(paths, { all: true })).rows))().catch(() => [] as LiveRecordingView[]); - const recording = new Set(liveRows.filter((r) => r.status === "recording").map((r) => `${r.slug}/${r.id}`)); - for (const r of liveRows) { - if (r.status === "recording") { - hold(held, `recording:${r.slug}/${r.id}`, { what: `${r.slug}/${r.id}`, disk: null, why: "a live recording is running: nothing of it is proposed", link: { href: `/channels/${r.slug}/videos/${r.id}`, label: "Video page" } }, null, 1); - } - } + const holds = new SpaceHolds(paths, { + liveRows: async (slug) => liveRows.filter((r) => r.slug === slug), + ...deps.holds, + }); + const heldMemo = new Map<string, Promise<SpaceHold | null>>(); + const heldVideo = (slug: string, id: string): Promise<SpaceHold | null> => { + const k = `${slug}/${id}`; + let p = heldMemo.get(k); + if (!p) heldMemo.set(k, (p = holds.video(slug, id))); + return p; + }; + // A held file's bytes, under its hold's kind. + const holdBytes = (h: SpaceHold, disk: string | null, bytes: number, count = 1) => + hold(held, `video:${h.kind}:${h.kind === "live" || h.kind === "job" ? h.why : ""}`, { what: SPACE_HOLD_LABELS[h.kind], disk, why: `${h.why}: nothing of it is proposed` }, bytes, count); // --- the channels ------------------------------------------------------------- const briefs = await (deps.briefs ?? (() => listChannelBriefs(paths)))(); @@ -512,14 +515,11 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult const { slug, id, dir, tally } = v; const names = await readNames(dir, direct); const set = new Set(names); - const isRecording = recording.has(`${slug}/${id}`); - let dncMemo: boolean | null = null; - const isDnc = async () => (dncMemo ??= set.has(DO_NOT_CLEAN_FILENAME) ? await dnc(dir) : false); + const heldNow = () => heldVideo(slug, id); const hasPointer = set.has(SAVED_VIDEO_POINTER_FILENAME); const audio: { name: string; fact: Fact }[] = []; - let clipOld = 0; - let clipOldCount = 0; let clipDev = corpusDev; + let hasClips = false; for (const [name, st] of await lstatAll(dir, names, direct)) { await ticker.tick(); if (!st) continue; @@ -542,16 +542,9 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult if (st.isDirectory()) { if (name === CLIPS_DIR) { await walkTree(abs, (a, s) => { - const f = acc.add(a, s, "clips"); - clipDev = f.dev; - if (now.getTime() - f.mtimeMs < SPACE_CLIP_AGE_DAYS * DAY_MS) return; - if (f.nlink > 1) { - hold(held, "clips-shared", { what: "Clip windows linked into a umtool take", disk: diskIdOf(f.dev), why: "shared (another hard link holds the same bytes): evicting one frees nothing" }, f.bytes, 1); - return; - } - clipOld += f.bytes; - clipOldCount += 1; + clipDev = acc.add(a, s, "clips").dev; }, { ticker }); + hasClips = true; } else if (name === ARCHIVE_ORG_STAGING_DIR) { let bytes = 0; let dev = corpusDev; @@ -579,26 +572,44 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult tally.move.files += 1; } if (isSourceMediaFile(name) && !hasPointer) { - if (isRecording) hold(held, "recording-files", { what: "Files of a live recording", disk: diskIdOf(f.dev), why: "a live recording is running" }, f.bytes, 1); - else if (await isDnc()) hold(held, "dnc-files", { what: "Files of do-not-clean videos", disk: diskIdOf(f.dev), why: "do-not-clean: nothing of it is proposed" }, f.bytes, 1); - else if (!busy(slug, id)) tally.strays.push({ id, file: name, fact: f }); + const h = await heldNow(); + if (h) holdBytes(h, diskIdOf(f.dev), f.bytes); + else tally.strays.push({ id, file: name, fact: f }); } else if (isAbandonablePartial(name) && now.getTime() - f.mtimeMs >= SPACE_PARTIAL_AGE_DAYS * DAY_MS) { - if (isRecording) hold(held, "recording-files", { what: "Files of a live recording", disk: diskIdOf(f.dev), why: "a live recording is running" }, f.bytes, 1); - else if (await isDnc()) hold(held, "dnc-files", { what: "Files of do-not-clean videos", disk: diskIdOf(f.dev), why: "do-not-clean: nothing of it is proposed" }, f.bytes, 1); - else if (f.nlink === 1 && !busy(slug, id)) tally.partials.push({ id, file: name, fact: f }); + const h = await heldNow(); + if (h) holdBytes(h, diskIdOf(f.dev), f.bytes); + else if (f.nlink > 1) hold(held, "partial-shared", { what: "Partial downloads with another hard link", disk: diskIdOf(f.dev), why: "shared: removing one name frees nothing" }, f.bytes, 1); + else { + // A video not known to be on its platform: the partial may be the + // only copy of those bytes (ruling, review 1). + const a = await availabilityOf(dir).catch(() => null); + if (partialMayBeOnlyCopy(a)) { + hold(held, "partial-only-copy", { what: "Partial downloads of videos not known to be on their platform", disk: diskIdOf(f.dev), why: "gone from its platform or its availability unknown: the partial may be the only copy" }, f.bytes, 1); + } else tally.partials.push({ id, file: name, fact: f, path: abs }); + } } } - if (clipOld > 0) { - if (await isDnc()) { - tally.clipsDncVideos += 1; - hold(held, "dnc-files", { what: "Files of do-not-clean videos", disk: diskIdOf(clipDev), why: "do-not-clean: nothing of it is proposed" }, clipOld, clipOldCount); - } else if (isRecording) { - hold(held, "recording-files", { what: "Files of a live recording", disk: diskIdOf(clipDev), why: "a live recording is running" }, clipOld, clipOldCount); - } else tally.clips.push({ id, bytes: clipOld, count: clipOldCount, dev: clipDev }); + if (hasClips) { + const windows = await clipWindowsOf(dir, id); + if (windows.length) { + const cutoff = now.getTime() - SPACE_CLIP_AGE_DAYS * DAY_MS; + const old = windows.filter((w) => w.mtimeMs <= cutoff); + const h = await heldNow(); + let shared = 0; + for (const w of old) { + if (w.nlink > 1) { + shared += 1; + hold(held, "clips-shared", { what: "Clip windows linked into a umtool take", disk: diskIdOf(clipDev), why: "shared (another hard link holds the same bytes): evicting one frees nothing" }, w.blocks, 1); + } + } + if (h && old.length) holdBytes(h, diskIdOf(clipDev), old.reduce((n, w) => n + w.blocks, 0), old.length); + tally.clipVideos.push({ id, old, held: h, shared, dev: clipDev }); + } } // The cleanup sweeps' targets: the report's buckets (already net of - // do-not-clean, keep-latest and the diarization hold), measured now. - if (audio.length && !isRecording && !(await isDnc())) { + // do-not-clean, keep-latest and the diarization hold), measured now, and + // left out for a video the held predicate holds. + if (audio.length && !(await heldNow())) { if (v.cleanIds.has(id)) for (const a of audio) bump(v.tally.audio, a.fact); if (v.extraIds.has(id) && v.target) for (const a of audio) if (a.name !== v.target) bump(v.tally.extra, a.fact); } @@ -618,6 +629,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: `estimate: ${formatBytes(e.bytes)} of plain caption tracks × (1 − ${CAPTION_RATIO_ESTIMATE}), compress-text's own ratio; the job measures each file`, loss: "nothing: each track is written compressed, read back and hashed before the plain one goes; compress-text restore puts them back", actions: [{ op: "compress-text", body: { slugs: [slug], kinds: ["captions"] } }], + hold: { slug }, ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}), }); } @@ -633,6 +645,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: `estimate: ${formatBytes(e.bytes)} of raw live chats × (1 − ${CHAT_RATIO_ESTIMATE}), compress-text's own ratio`, loss: "nothing: each chat is written compressed and verified before the plain one goes; compress-text restore puts them back", actions: [{ op: "compress-text", body: { slugs: [slug] } }], + hold: { slug }, ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}), }); } @@ -652,6 +665,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult "the audio; every transcript stays; re-fetchable while each video is on its platform" + (atRisk > 0 ? ` (~${formatBytes(atRisk)} of it the pre-clean check may refuse: gone or needs sign-in)` : ""), actions: [{ op: "cleanup", body: { slug, sweep: "transcribed" } }], + hold: { slug }, ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}), }); } @@ -667,26 +681,52 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: `measured now: the report's extra-formats bucket${report}`, loss: `the extra formats; the ${brief.config.audioFormat} copy stays (overlaps the clean-audio row of this channel)`, actions: [{ op: "cleanup", body: { slug, sweep: "extra-formats" } }], + hold: { slug }, }); } - // Clip windows: one eviction for the channel, or — when a do-not-clean - // video holds old windows — one per video, so its windows are not touched. - const clipRows = t.clips.length && t.clipsDncVideos === 0 - ? [{ id: undefined as string | undefined, bytes: t.clips.reduce((n, c) => n + c.bytes, 0), count: t.clips.reduce((n, c) => n + c.count, 0), dev: t.clips[0].dev }] - : t.clips.map((c) => ({ ...c, id: c.id as string | undefined })); - for (const c of clipRows) { + // Clip windows (review 1, B3): ONE eviction for the channel only when no + // video holding a window is held and no old window has another link — + // its whole set of old windows digested, so the click can tell it is the + // same set. Otherwise one per unheld video, naming its old windows. + const clipLoss = "re-fetchable: an evicted window costs a fetch, not data. By age only: nothing here knows whether a umtool report still cites one"; + const withOld = t.clipVideos.filter((c) => c.old.some((w) => w.nlink === 1)); + const channelWide = withOld.length > 0 && t.clipVideos.every((c) => !c.held && c.shared === 0); + if (channelWide) { + const old = t.clipVideos.flatMap((c) => c.old); suggestions.push({ - key: `evict-clips:${slug}:${c.id ?? "*"}`, + key: `evict-clips:${slug}:*`, kind: "evict-clips", slug, - ...(c.id ? { id: c.id } : {}), - title: `${name}${c.id ? ` ${c.id}` : ""}: ${c.count.toLocaleString("en-US")} clip window(s) untouched ${SPACE_CLIP_AGE_DAYS}+ days`, - frees: { disk: diskIdOf(c.dev), bytes: c.bytes }, + title: `${name}: ${old.length.toLocaleString("en-US")} clip window(s) untouched ${SPACE_CLIP_AGE_DAYS}+ days`, + frees: { disk: diskIdOf(withOld[0].dev), bytes: old.reduce((n, w) => n + w.blocks, 0) }, basis: "measured", basisText: "measured now: windows not modified for the cutoff", - loss: "re-fetchable: an evicted window costs a fetch, not data. By age only: nothing here knows whether a umtool report still cites one", - actions: [{ op: "evict-clips", body: c.id ? { slug, id: c.id, olderThanDays: SPACE_CLIP_AGE_DAYS } : { olderThanDays: SPACE_CLIP_AGE_DAYS, slug } }], + loss: clipLoss, + actions: [{ op: "evict-clips", body: { olderThanDays: SPACE_CLIP_AGE_DAYS, slug } }], + hold: { slug }, + digest: { olderThanDays: SPACE_CLIP_AGE_DAYS, count: old.length, sha1: digestOf(old) }, }); + } else { + for (const c of withOld) { + if (c.held) continue; + const sharedStems = new Set(c.old.filter((w) => w.nlink > 1).map((w) => w.stem)); + const own = c.old.filter((w) => w.nlink === 1 && !sharedStems.has(w.stem)); + if (!own.length) continue; + suggestions.push({ + key: `evict-clips:${slug}:${c.id}`, + kind: "evict-clips", + slug, + id: c.id, + title: `${name} ${c.id}: ${own.length.toLocaleString("en-US")} clip window(s) untouched ${SPACE_CLIP_AGE_DAYS}+ days`, + frees: { disk: diskIdOf(c.dev), bytes: own.reduce((n, w) => n + w.blocks, 0) }, + basis: "measured", + basisText: "measured now: windows not modified for the cutoff", + loss: clipLoss, + actions: [{ op: "evict-clips", body: { slug, id: c.id, windows: [...new Set(own.map((w) => w.stem))], olderThanDays: SPACE_CLIP_AGE_DAYS } }], + hold: { slug, id: c.id }, + targets: own.map((w) => ({ path: w.path, size: w.size, mtimeMs: w.mtimeMs })), + }); + } } for (const p of t.partials) { suggestions.push({ @@ -701,6 +741,8 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: "measured now", loss: "an abandoned partial download; running the download again starts over", actions: [{ op: "delete-file", body: { slug, id: p.id, file: p.file } }], + hold: { slug, id: p.id }, + targets: [{ path: p.path, size: p.fact.size, mtimeMs: p.fact.mtimeMs }], }); } for (const s of t.strays) { @@ -876,6 +918,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: "measured now: the media tier's files on the corpus disk (audio, raw live chat, kept chat captures)", loss: "nothing: the media moves and the text stays on the corpus disk; relocate-back brings it back. A classic channel is first tiered in place (same-disk renames)", actions: [{ op: "relocate", body: { slugs: [m.slug], locationId: targetLoc.id } }], + hold: { slug: m.slug }, ...(fit.fits ? {} : { disabled: `does not fit on ${targetLoc.label || targetLoc.id} with its floor kept (after the bigger moves above): free space there first` }), }); } @@ -898,38 +941,71 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult } // --- the store ------------------------------------------------------------------------ - const entries = await (deps.savedVideos ?? (() => listSavedVideos({ paths, notAnswering: [] })))().catch(() => [] as SavedVideoEntry[]); + // Every store row asks the held predicate of its video and the store's own + // relocation marker (review 1, B2). A store file is statted through the + // drive watchdog; a channel or a store not answering is "unknown", not missing. + const notAnswering: string[] = []; + const entries = await (deps.savedVideos ?? (() => listSavedVideos({ paths, notAnswering })))().catch(() => [] as SavedVideoEntry[]); + for (const slug of new Set(notAnswering)) { + hold(held, `store-unknown:${slug}`, { what: `${slug}: its saved videos`, disk: null, why: "its drive is not answering: unknown here, not missing", link: { href: "/storage", label: "Storage" } }, null, 1); + } const entryOf = new Map(entries.map((e) => [`${e.slug}/${e.videoId}`, e])); + let storeUnknown = false; const statFile = async (file: string): Promise<Fact | null> => { - const st = await stat(file).catch(() => null); - return st?.isFile() ? acc.fact(file, st) : null; + try { + const st = await onDrive(file, () => stat(file)); + return st.isFile() ? acc.fact(file, st) : null; + } catch (e) { + if (isDriveNotAnswering(e)) storeUnknown = true; + return null; + } }; + const storeHold = await holds.store(); + // The held predicate for a store row: the store's marker, then the video's. + const storeRowHold = async (slug: string, id: string): Promise<SpaceHold | null> => storeHold ?? (await heldVideo(slug, id)); + const sharedHold = (disk: string, bytes: number) => + hold(held, "store-shared", { what: "Saved-video files with another hard link", disk, why: "shared: removing one name frees nothing" }, bytes, 1); for (const e of entries) { const name = configOf.get(e.slug)?.name ?? e.slug; for (const alt of e.pointer.alternates ?? []) { const disp = alternateDisposition(e.pointer, alt); if (alt.keptAs === "original") continue; - const f = await statFile(path.join(e.pointer.dir, alt.file)); + const file = path.join(e.pointer.dir, alt.file); + const f = await statFile(file); if (!f) continue; if (!disp.offer) { hold(held, `alt:${disp.why}`, { what: "Saved alternates", disk: diskIdOf(f.dev), why: disp.why, link: { href: "/saved-videos", label: "Saved videos" } }, f.bytes, 1); continue; } + const h = await storeRowHold(e.slug, e.videoId); + if (h) { + holdBytes(h, diskIdOf(f.dev), f.bytes); + continue; + } + if (f.nlink > 1) { + sharedHold(diskIdOf(f.dev), f.bytes); + continue; + } + // A FORMER ORIGINAL is the person's to drop, on the video page (ruling + // B1): a row with its bytes and a link, no button here. + const former = disp.formerOriginal === true; suggestions.push({ key: `drop-alternate:${e.slug}:${e.videoId}:${alt.file}`, kind: "drop-alternate", slug: e.slug, id: e.videoId, file: alt.file, - title: `${name} ${e.videoId}: ${alt.file}${alt.height ? ` (${alt.height}p)` : ""} beside the active copy`, - frees: { disk: diskIdOf(f.dev), bytes: f.nlink > 1 ? 0 : f.bytes }, + title: `${name} ${e.videoId}: ${alt.file}${alt.height ? ` (${alt.height}p)` : ""} beside the active copy${former ? " (a former original)" : ""}`, + frees: { disk: diskIdOf(f.dev), bytes: f.bytes }, basis: "measured", basisText: "measured now", - loss: alt.keptAs === "former-original" ? "a former original: a copy of the source bytes no longer active" : "the alternate copy; the active copy stays", - actions: [{ op: "drop-saved-alternate", body: { slug: e.slug, id: e.videoId, file: alt.file, ...(disp.confirmFormerOriginal ? { confirmFormerOriginal: true } : {}) } }], - ...(disp.confirmFormerOriginal ? { tick: "I mean the former original" } : {}), - ...(f.nlink > 1 ? { shared: { files: 1, bytes: f.bytes } } : {}), - link: { href: `/channels/${e.slug}/videos/${e.videoId}`, label: "Video page" }, + loss: former + ? "a former original: a copy of the source bytes no longer active. Its review and drop are on the video page" + : "the alternate copy; the active copy stays", + ...(former ? {} : { actions: [{ op: "drop-saved-alternate", body: { slug: e.slug, id: e.videoId, file: alt.file } }] }), + hold: { slug: e.slug, id: e.videoId, store: true }, + targets: [{ path: file, size: f.size, mtimeMs: f.mtimeMs }], + link: { href: `/channels/${e.slug}/videos/${e.videoId}`, label: former ? "Video page: review and drop it there" : "Video page" }, }); } } @@ -942,7 +1018,10 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult if (opts.compaction === false && opts.previous) { compactionAt = opts.previous.compactionAt; refused = opts.previous.refused; - suggestions.push(...opts.previous.suggestions.filter((s) => s.kind === "compact")); + for (const row of opts.previous.suggestions.filter((x) => x.kind === "compact")) { + const h = row.slug && row.id ? await storeRowHold(row.slug, row.id) : null; + if (!h) suggestions.push(row); + } } else if (opts.compaction !== false) { log("Planning compaction (one ffprobe per saved container not seen unchanged before) …"); const planned = await (deps.compactionPlan ?? ((memo: SpaceProbeMemo) => defaultCompactionPlan(paths, settings.savedVideoCompaction, memo)))(probes); @@ -955,6 +1034,11 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult const bytes = f?.bytes ?? item.source?.bytes ?? e?.pointer.bytes ?? 0; const disk = f ? diskIdOf(f.dev) : e ? diskIdOf(storeDev ?? corpusDev) : null; if (item.compact && item.estimate) { + const h = await storeRowHold(item.slug, item.id); + if (h) { + holdBytes(h, disk, bytes); + continue; + } const src = item.source?.bytes ?? bytes; const name = configOf.get(item.slug)?.name ?? item.slug; const when = settings.savedVideoCompaction.dropOriginal === "after-verify" @@ -972,6 +1056,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: `estimate: the measured crf share for its bitrate (${item.estimate.share.toFixed(2)}) ± 20 %; ${item.estimate.hours[0].toFixed(1)}–${item.estimate.hours[1].toFixed(1)} h of encoding`, loss: "nothing at this step: the original is kept beside the verified copy", actions: [{ op: "compact-saved-videos", body: { items: [{ slug: item.slug, id: item.id }] } }], + hold: { slug: item.slug, id: item.id, store: true }, detail: item.line, link: { href: `/channels/${item.slug}/videos/${item.id}`, label: "Video page" }, }); @@ -999,8 +1084,18 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult if (r.original && r.state !== "dropped") files.push({ file: r.original.file, interrupted: false }); if (r.leftover) files.push({ file: path.basename(r.leftover), interrupted: true }); for (const { file, interrupted } of files) { - const f = dir ? await statFile(path.join(dir, file)) : r.leftover ? await statFile(r.leftover) : null; - if (!f) continue; + const abs = dir ? path.join(dir, file) : r.leftover ?? null; + const f = abs ? await statFile(abs) : null; + if (!f || !abs) continue; + const h = await storeRowHold(r.slug, r.id); + if (h) { + holdBytes(h, diskIdOf(f.dev), f.bytes); + continue; + } + if (f.nlink > 1) { + sharedHold(diskIdOf(f.dev), f.bytes); + continue; + } const awaiting = r.state === "awaiting-review" && !interrupted; suggestions.push({ key: `drop-original:${r.slug}:${r.id}:${file}`, @@ -1009,7 +1104,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult id: r.id, file, title: `${name} ${r.id}: ${interrupted ? "an interrupted drop of " : ""}the original (${r.state.replace("-", " ")})`, - frees: { disk: diskIdOf(f.dev), bytes: f.nlink > 1 ? 0 : f.bytes }, + frees: { disk: diskIdOf(f.dev), bytes: f.bytes }, basis: "measured", basisText: "measured now", loss: `the original source bytes; the compacted copy (its checks passed) stays active; re-fetchable only while the video is on its platform (${r.presence || (r.onPlatform ? "on its platform" : "not known to be")})`, @@ -1019,7 +1114,8 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult actions: [{ op: "drop-saved-alternate", body: { slug: r.slug, id: r.id, file, confirmOriginal: true } }], link: { href: `/channels/${r.slug}/videos/${r.id}`, label: "Video page" }, }), - ...(f.nlink > 1 ? { shared: { files: 1, bytes: f.bytes } } : {}), + hold: { slug: r.slug, id: r.id, store: true }, + targets: [{ path: abs, size: f.size, mtimeMs: f.mtimeMs }], }); } } @@ -1027,8 +1123,16 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult for (const r of failed) { const bytes = r.kept?.bytes ?? r.bytes ?? 0; if (bytes <= 0) continue; - const dst = await stat(r.dir).catch(() => null); + const dst = await onDrive(r.dir, () => stat(r.dir)).catch((e) => { + if (isDriveNotAnswering(e)) storeUnknown = true; + return null; + }); const dev = dst ? deviceOf(r.dir, dst) : storeDev ?? corpusDev; + const h = await storeRowHold(r.slug, r.id); + if (h) { + holdBytes(h, diskIdOf(dev), bytes); + continue; + } suggestions.push({ key: `failed-encode:${r.slug}:${r.id}`, kind: "failed-encode", @@ -1040,10 +1144,12 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult basisText: r.kept ? "as the compaction recorded it" : "measured now", loss: "a re-verify's head start: compacting it again encodes it again", actions: [{ op: "kept-failed-encodes", body: { clear: { slug: r.slug, id: r.id } } }], + hold: { slug: r.slug, id: r.id, store: true }, }); } // Live landings whose check failed or never ran: Verify again removes the - // stream files only if the landed file checks out against them. + // stream files only if the landed file checks out against them, so the row + // frees nothing now (review 1, not blocking 3). let keptPartsBytes = 0; let keptPartsCount = 0; for (const r of liveRows) { @@ -1056,26 +1162,43 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult const staging = path.join(await realpath(savedVideoRoot(paths, configOf.get(r.slug) ?? null)).catch(() => savedVideoRoot(paths, configOf.get(r.slug) ?? null)), r.slug); let bytes = 0; let dev: string | null = null; + const targets: { path: string; size: number; mtimeMs: number }[] = []; for (const n of v.against) { - const f = await statFile(path.join(staging, n)); + const file = path.join(staging, n); + const f = await statFile(file); if (!f) continue; if (f.nlink === 1) bytes += f.bytes; dev = f.dev; + targets.push({ path: file, size: f.size, mtimeMs: f.mtimeMs }); } if (!dev) continue; + const h = await storeRowHold(r.slug, r.id); + if (h) { + holdBytes(h, diskIdOf(dev), bytes); + continue; + } suggestions.push({ key: `reverify-landing:${r.slug}:${r.id}:${r.startedAt}`, kind: "reverify-landing", slug: r.slug, id: r.id, title: `${configOf.get(r.slug)?.name ?? r.slug} ${r.id}: a landing whose check ${v.state === "failed" ? "failed" : "never ran"} (${v.against.length} stream file(s))`, - frees: { disk: diskIdOf(dev), bytes }, + frees: null, + later: { disk: diskIdOf(dev), low: bytes, high: bytes, when: "only if it verifies against them" }, basis: "measured", - basisText: "measured now: the stream files the landing is checked against", + basisText: "measured now: the stream files the landing is checked against, freed only if it verifies", loss: "nothing unless it verifies: the stream files go only when the landed file checks out against them and the stream is done", actions: [{ op: "live-recording-verify", body: { slug: r.slug, id: r.id, startedAt: r.startedAt } }], + hold: { slug: r.slug, id: r.id, store: true }, + targets, }); } + if (storeHold) { + hold(held, "store-moving", { what: "The saved-video store", disk: storeDev ? diskIdOf(storeDev) : null, why: `${storeHold.why}: none of its rows is proposed`, link: { href: "/storage", label: "Storage" } }, null, 1); + } + if (storeUnknown) { + hold(held, "store-not-answering", { what: "Saved-video files", disk: storeDev ? diskIdOf(storeDev) : null, why: "a drive did not answer: those files are unknown here, not missing", link: { href: "/storage", label: "Storage" } }, null, 1); + } if (keptPartsBytes > 0) { unmanaged(um, "kept-parts", { what: "Live recordings' kept parts", disk: storeDev ? diskIdOf(storeDev) : null, owner: "a person decides; nothing removes them (pnpm ops get live-recordings)" }, keptPartsBytes, keptPartsCount); } @@ -1147,7 +1270,9 @@ async function defaultCompactionPlan( return hit.probe as SourceProbe | null; } const p = await probeCompactionSource(paths.ffprobeBin, file); - if (st) fresh[file] = { size: st.size, mtimeMs: st.mtimeMs, probe: p }; + // A FAILED PROBE IS NOT REMEMBERED (review 1, 12): one transient + // failure must not make a container "unreadable" on every later scan. + if (st && p) fresh[file] = { size: st.size, mtimeMs: st.mtimeMs, probe: p }; return p; }, }, diff --git a/common/lib/spaceSuggestions.test.ts b/common/lib/spaceSuggestions.test.ts @@ -147,7 +147,7 @@ test("alternates: a pin keeps every copy; a proxy is kept on purpose; an origina assert.equal(alternateDisposition(base, { ...alt, keptAs: "original" }).offer, false); const former = alternateDisposition(base, { ...alt, keptAs: "former-original" }); assert.equal(former.offer, true); - assert.ok(former.offer && former.confirmFormerOriginal); + assert.ok(former.offer && former.formerOriginal); }); test("summary line: the fullest disk, its free space and what the scan suggests there", () => { diff --git a/common/lib/spaceSuggestions.ts b/common/lib/spaceSuggestions.ts @@ -125,8 +125,14 @@ export type SpaceSuggestion = { loss: string; actions?: SpaceAction[]; link?: SpaceLink; - // The confirm needs this ticked (a person's word the writer asks for). - tick?: string; + // WHAT THE CLICK RE-CHECKS (controller/spaceHold.ts recheckSpaceRow): the + // subject the held predicate is asked of again (a channel, a video of it, + // and the store for a store row), each target file as the scan saw it + // (still there, same size and mtime, one link), and for a channel-wide clip + // eviction the digest of its whole set of old windows. + hold?: { slug?: string; id?: string; store?: true }; + targets?: { path: string; size: number; mtimeMs: number }[]; + digest?: { olderThanDays: number; count: number; sha1: string }; // Files with other hard links: removing this name frees nothing of them. shared?: { files: number; bytes: number }; detail?: string; @@ -333,16 +339,16 @@ export function refusalGroup(reason: string): string | null { // May a non-original alternate be proposed for a drop? A pin keeps every copy // of its video (ruling 2, orchestrator's default 24 Nov: a pin bars removing // the pinned copy); a proxy is kept on purpose; an original belongs to the -// compaction rules (drop-original rows); a former original needs the person's -// own word (`confirmFormerOriginal`). +// compaction rules (drop-original rows); a former original is the person's +// to drop on the video page (ruling B1): offered as a row with a link only. export function alternateDisposition( pointer: SavedVideoPointer, alt: SavedVideoAlternate, -): { offer: true; confirmFormerOriginal?: true } | { offer: false; why: string } { +): { offer: true; formerOriginal?: true } | { offer: false; why: string } { if (alt.keptAs === "original") return { offer: false, why: "an original a compacted copy was made from (see Drop compacted originals)" }; if (alt.keptAs === "proxy") return { offer: false, why: "kept on purpose as the lower-quality proxy" }; if (pointer.keepReason === "pin") return { offer: false, why: "the video is pinned: its copies are kept" }; - if (alt.keptAs === "former-original") return { offer: true, confirmFormerOriginal: true }; + if (alt.keptAs === "former-original") return { offer: true, formerOriginal: true }; return { offer: true }; }