// THE SPACE SCAN (lane space-suggestions; the `space-scan` job, `pnpm ops // space-scan`): every disk the archive writes to, how much of each is the // archive's, and what would free space on each — through the writers that // already exist. The result is ONE file, `transcripts/.space-suggestions.json` // (lib/spaceSuggestions.ts is its shape); /cleanup/space and `pnpm ops get // space-suggestions` read it and never compute. // // IT ONLY READS. No file is removed, moved, tiered or written but the result; // no platform is asked; previewRelocation is NOT called (for a classic channel // it tiers the media in place first, which writes). // // HOW BYTES ARE COUNTED. A disk is a filesystem (`st_dev`); a file counts as // its allocated bytes (`st_blocks × 512`, what df counts), each inode once. A // file with more than one hard link frees nothing when one name goes, so a // suggestion never counts it — it is "shared" (umtool's takes, record-live's // insurance links). A tier link counts on the disk its target is on. A // channel whose media drive is not mounted or not answering has its text // walked and its media UNKNOWN, never empty; a legacy channel, one mid-move or // inconsistent is not walked for suggestions and is named. // // THE COST. A walk of every video dir (an lstat per entry), the storage // locations' trees through the drive watchdog, the store's pointers, and — // unless `compaction: false` — one ffprobe per saved container, remembered // across scans by (path, size, mtime). It runs in the editor's process and // gives the event loop back every few milliseconds. import path from "node:path"; import { lstat, readdir, realpath, stat, statfs } from "node:fs/promises"; import type { Stats } from "node:fs"; import { homedir } from "node:os"; import type { Paths } from "../lib/paths"; import type { SiteSettings } from "../lib/settings"; import type { ChannelConfig } from "../lib/channelConfig"; import type { StorageLocation, StorageSettings } from "../lib/storageLocations"; import type { SavedVideoCompactionSettings } from "../lib/savedVideoCompaction"; import { inspectChannelMedia, type ChannelMediaLocation } from "../lib/channelMedia"; import { CLIPS_DIR, isKeptChatCapture, isScratchEntry, isTierable } from "../lib/mediaTier"; import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles"; import { isStoredCaptionName, isStoredTextName } from "../lib/storedText"; import { DO_NOT_CLEAN_FILENAME } from "../lib/doNotClean"; // The raw live chat in its PLAIN form, by the stored-text rules // (lib/storedText.ts): a declared stored-text name that is not a caption // track. A listing's entry is only classified here, never opened; its stored // form (.zst) is already compressed and is not proposed. function isPlainRawChat(name: string): boolean { return isStoredTextName(name) && !isStoredCaptionName(name); } import { SAVED_VIDEO_POINTER_FILENAME, savedVideoRoot } from "../lib/savedVideo"; import { formatBytes } from "../lib/format"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { isDriveNotAnswering, onDrive, stalledLocation } from "../lib/storageHealth"; import { probeLocationMemo } from "../lib/storageVolumes"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { SPACE_CLIP_AGE_DAYS, SPACE_PARTIAL_AGE_DAYS, SPACE_SCAN_JOB_KIND, SPACE_SCAN_QUEUE, SPACE_SCAN_VERSION, SPACE_SUGGESTIONS_FILENAME, alternateDisposition, capPerKind, compressSaving, moveFit, refusalGroup, type SpaceArchiveShare, type SpaceDisk, type SpaceDiskStatus, type SpaceHeld, type SpaceProbeMemo, type SpaceRefused, type SpaceScanResult, type SpaceSuggestion, type SpaceUnmanaged, } from "../lib/spaceSuggestions"; import { listChannelBriefs, type ChannelBrief } from "./channels"; import { CAPTION_RATIO_ESTIMATE, CHAT_RATIO_ESTIMATE } from "./compressText"; import { listSavedVideos, type SavedVideoEntry } from "./savedVideoInventory"; import { listCompactionReview, listKeptFailedEncodes, planCompaction, type CompactPlan, type CompactionReviewRow, type KeptFailedEncodeRow, } from "./compactSavedVideos"; 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; // 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 & { storage: Pick; savedVideoCompaction: SavedVideoCompactionSettings; }; export type SpaceFsInfo = { dev: string; mountpoint: string; sizeBytes: number; freeBytes: number }; export type SpaceScanDeps = { now?: () => Date; // The device a path is on (default: its st_dev). Tests name two. deviceOf?: (absPath: string, st: Stats) => string; filesystemOf?: (dir: string) => Promise; briefs?: () => Promise; inspect?: (slug: string, config: ChannelConfig) => Promise; locationStatus?: (loc: StorageLocation) => Promise<{ status: SpaceDiskStatus; detail?: string }>; savedVideos?: () => Promise; compactionPlan?: (memo: SpaceProbeMemo) => Promise<{ plan: CompactPlan; probes: SpaceProbeMemo }>; compactionReview?: () => Promise; keptFailedEncodes?: () => Promise; liveRecordings?: () => Promise; // 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; // umtool's report projects (null: not measured). reportsRoot?: string | null; }; export type SpaceScanOptions = { paths: Paths; settings: SpaceScanSettings; deps?: SpaceScanDeps; // false: the ffprobe pass is not run; the last scan's compaction rows carry. compaction?: boolean; previous?: SpaceScanResult | null; jobId?: string; onLog?: (line: string) => void; onProgress?: (done: number, of: number) => void; signal?: AbortSignal; }; export function spaceSuggestionsPath(paths: Pick): string { return path.join(paths.transcriptsDir, SPACE_SUGGESTIONS_FILENAME); } // The last scan, or null (none yet, or a file of another version). export async function readSpaceSuggestions(paths: Pick): Promise { const read = await readJsonFile(spaceSuggestionsPath(paths)); if (!read.ok || !read.value || typeof read.value !== "object") return null; const v = read.value as SpaceScanResult; return v.version === SPACE_SCAN_VERSION && typeof v.computedAt === "string" ? v : null; } // The version the file on disk says, whatever it is (null: none, or no file): // the button names an older format "rescan first" (review 2, F2). export async function readSpaceSuggestionsVersion(paths: Pick): Promise { const read = await readJsonFile(spaceSuggestionsPath(paths)); const v = read.ok && read.value && typeof read.value === "object" ? (read.value as { version?: unknown }).version : null; return typeof v === "number" ? v : null; } // umtool's REPORTS_ROOT, as umtool/lib/paths.mjs resolves it. // `SPACE_SCAN_REPORTS_DIR` is the scan's own name for it (an e2e server's // fixture), so nothing else that reads REPORTS_DIR changes. export function defaultReportsRoot(env: NodeJS.ProcessEnv = process.env): string { return path.resolve(env.SPACE_SCAN_REPORTS_DIR ?? env.REPORTS_DIR ?? path.join(homedir(), "reports")); } // --- the accounting ---------------------------------------------------------------- function allocated(st: Stats): number { return typeof st.blocks === "number" && st.blocks >= 0 ? st.blocks * 512 : st.size; } function emptyShare(): SpaceArchiveShare { return { media: 0, text: 0, clips: 0, store: 0, playable: 0, builds: 0, reports: 0, other: 0 }; } type Fact = { bytes: number; size: number; nlink: number; dev: string; mtimeMs: number }; class Accounting { private seen = new Set(); readonly byDev = new Map(); readonly devDir = new Map(); constructor(private readonly deviceOf: (p: string, st: Stats) => string) {} fact(abs: string, st: Stats): Fact { 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 { const f = this.fact(abs, st); if (!this.devDir.has(f.dev)) this.devDir.set(f.dev, path.dirname(abs)); if (st.nlink > 1) { const k = `${f.dev}:${st.ino}`; if (this.seen.has(k)) return f; this.seen.add(k); } let s = this.byDev.get(f.dev); if (!s) this.byDev.set(f.dev, (s = emptyShare())); s[cat] += f.bytes; return f; } noteDir(abs: string, st: Stats): string { const dev = this.deviceOf(abs, st); if (!this.devDir.has(dev)) this.devDir.set(dev, abs); return dev; } } type Through = (call: () => Promise) => Promise; const direct: Through = (call) => call(); class Ticker { private last = Date.now(); constructor(private readonly signal?: AbortSignal) {} async tick(): Promise { if (this.signal?.aborted) throw new Error("cancelled"); if (Date.now() - this.last >= SLICE_MS) { await new Promise((r) => setImmediate(r)); this.last = Date.now(); } } } async function lstatAll(dir: string, names: string[], through: Through): Promise> { const out: Array<[string, Stats | null]> = []; for (let i = 0; i < names.length; i += LSTAT_BATCH) { const batch = names.slice(i, i + LSTAT_BATCH); const sts = await Promise.all(batch.map((n) => through(() => lstat(path.join(dir, n))).catch((e) => { if (isDriveNotAnswering(e)) throw e; return null; }))); batch.forEach((n, j) => out.push([n, sts[j]])); } return out; } async function readNames(dir: string, through: Through): Promise { return through(() => readdir(dir)).catch((e) => { if (isDriveNotAnswering(e)) throw e; return [] as string[]; }); } // Every regular file under `root` (symlinks never followed), to `onFile`. async function walkTree( root: string, onFile: (abs: string, st: Stats) => void, o: { through?: Through; skip?: (abs: string) => boolean; ticker: Ticker }, ): Promise { const through = o.through ?? direct; const stack = [root]; while (stack.length) { const dir = stack.pop()!; for (const [name, st] of await lstatAll(dir, await readNames(dir, through), through)) { await o.ticker.tick(); if (!st) continue; const abs = path.join(dir, name); if (st.isDirectory()) { if (!o.skip?.(abs)) stack.push(abs); } else if (st.isFile()) onFile(abs, st); } } } // A file's tier for the archive's share: the big files (mediaTier's media and // scratch, a source container) against the text. function mediaByName(name: string): boolean { return isTierable(name) || isSourceMediaFile(name) || isScratchEntry(name) || isKeptChatCapture(name); } function under(p: string, root: string): boolean { const rel = path.relative(root, p); return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)); } async function defaultFilesystemOf(dir: string): Promise { try { const st = await stat(dir); let mount = path.resolve(dir); for (;;) { const parent = path.dirname(mount); if (parent === mount) break; const p = await stat(parent).catch(() => null); if (!p || p.dev !== st.dev) break; mount = parent; } const fs = await statfs(dir); return { dev: String(st.dev), mountpoint: mount, sizeBytes: fs.blocks * fs.bsize, freeBytes: fs.bavail * fs.bsize }; } catch { return null; } } async function defaultLocationStatus(loc: StorageLocation, paths: Paths): Promise<{ status: SpaceDiskStatus; detail?: string }> { if (stalledLocation(loc)) return { status: "not-answering", detail: "its drive is not answering" }; const probe = await probeLocationMemo(loc, paths); if (probe.status === "available") return { status: "ok" }; if (probe.status === "stalled") return { status: "not-answering", detail: "its drive is not answering" }; const why: Record = { "mounted-elsewhere": "its disk is mounted somewhere else (re-point it on /storage)", unmounted: "its disk is attached but not mounted", absent: "its disk is not attached", missing: "its root does not exist", }; return { status: "not-mounted", detail: why[probe.status] ?? probe.status }; } // --- per channel ----------------------------------------------------------------- type PerDev = Map; function bump(m: PerDev, f: Fact, count = 1): void { let e = m.get(f.dev); if (!e) m.set(f.dev, (e = { bytes: 0, count: 0, shared: 0, sharedBytes: 0 })); if (f.nlink > 1) { e.shared += count; e.sharedBytes += f.bytes; } else { e.bytes += f.bytes; e.count += count; } } type ChannelTally = { captions: PerDev; chat: PerDev; audio: PerDev; extra: PerDev; move: { bytes: number; files: number }; // 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 }[]; // The first video of the channel the held predicate holds: a channel-wide // audio sweep is not offered while there is one (review 2, F1). firstHeld: (SpaceHold & { id: string }) | null; partials: { id: string; file: string; fact: Fact; path: string }[]; strays: { id: string; file: string; fact: Fact }[]; }; function newTally(): ChannelTally { return { captions: new Map(), chat: new Map(), audio: new Map(), extra: new Map(), move: { bytes: 0, files: 0 }, clipVideos: [], firstHeld: null, partials: [], strays: [], }; } type HeldTally = Map; function hold(h: HeldTally, key: string, base: Omit, bytes: number | null, count = 1): void { const e = h.get(key); if (e) { e.count += count; if (bytes !== null) e.bytes = (e.bytes ?? 0) + bytes; return; } h.set(key, { key, ...base, bytes, count }); } type Unmanaged = Map; function unmanaged(u: Unmanaged, key: string, base: Omit, bytes: number, count = 1): void { const e = u.get(key); if (e) { e.bytes += bytes; e.count = (e.count ?? 0) + count; return; } u.set(key, { key, ...base, bytes, count }); } // --- the scan --------------------------------------------------------------------- export async function scanSpace(opts: SpaceScanOptions): Promise { const { paths, settings } = opts; const deps = opts.deps ?? {}; const now = (deps.now ?? (() => new Date()))(); const started = Date.now(); const log = opts.onLog ?? (() => {}); const deviceOf = deps.deviceOf ?? ((_p: string, st: Stats) => String(st.dev)); const filesystemOf = deps.filesystemOf ?? defaultFilesystemOf; const acc = new Accounting(deviceOf); const ticker = new Ticker(opts.signal); const held: HeldTally = new Map(); const um: Unmanaged = new Map(); const suggestions: SpaceSuggestion[] = []; const notScanned: { slug: string; why: string }[] = []; const floorBytes = Math.max(0, settings.minFreeDiskGB) * 1024 ** 3; const locations = settings.storage.locations; 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-`. const corpusStat = await stat(paths.channelsDir); const corpusDev = acc.noteDir(paths.channelsDir, corpusStat); const locState = new Map(); for (const loc of locations) { const s = await (deps.locationStatus ? deps.locationStatus(loc) : defaultLocationStatus(loc, paths)); let dev: string | undefined; if (s.status === "ok") { try { const st = await onDrive(loc, () => stat(loc.root)); dev = acc.noteDir(loc.root, st); } catch (e) { locState.set(loc.id, { status: isDriveNotAnswering(e) ? "not-answering" : "not-mounted", detail: (e as Error).message }); continue; } } locState.set(loc.id, { ...s, ...(dev ? { dev } : {}) }); } const diskIdOf = (dev: string): string => { if (dev === corpusDev) return "corpus"; const loc = locations.find((l) => locState.get(l.id)?.dev === dev); return loc ? loc.id : `fs-${dev}`; }; // THE STORE'S REAL DIR, and the playable copies beside it. const storeReal = await realpath(paths.savedVideosDir).catch(() => paths.savedVideosDir); const playableRoot = path.join(path.dirname(storeReal), "playable"); // 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[]); // The held predicate's live rows: a test's listing when it names one, else // each channel's own file, which FAILS CLOSED when it cannot be read. const holds = new SpaceHolds(paths, { ...(deps.liveRecordings ? { liveRows: async (slug: string) => liveRows.filter((r) => r.slug === slug) } : {}), ...deps.holds, }); const heldMemo = new Map>(); const heldVideo = (slug: string, id: string, o: { noDoNotCleanFile?: boolean } = {}): Promise => { const k = `${slug}/${id}`; let p = heldMemo.get(k); if (!p) heldMemo.set(k, (p = holds.video(slug, id, o))); 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)))(); const inspect = deps.inspect ?? ((slug: string, config: ChannelConfig) => inspectChannelMedia(paths, slug, config, { fresh: true })); const moveCandidates: { slug: string; bytes: number; files: number }[] = []; const configOf = new Map(briefs.map((b) => [b.slug, b.config])); let done = 0; for (const brief of briefs) { opts.onProgress?.(done, briefs.length); done += 1; const { slug, config } = brief; const channelDir = path.join(paths.channelsDir, slug); const loc = await inspect(slug, config); if (loc.status === "legacy" || loc.status === "in-transition" || loc.status === "inconsistent") { notScanned.push({ slug, why: loc.detail ?? loc.status }); if (loc.status === "in-transition") { hold(held, `moving:${slug}`, { what: slug, disk: null, why: `a relocation is in flight: ${loc.detail ?? "its marker is present"}`, link: { href: `/channels/${slug}`, label: "Storage panel" } }, null, 1); } // Its corpus-disk bytes still count as the archive's (never following a link). if (loc.text.readable || loc.status !== "legacy") { await walkTree(channelDir, (abs, st) => acc.add(abs, st, mediaByName(path.basename(abs)) ? "media" : "text"), { ticker }).catch(() => {}); } continue; } const mediaReadable = loc.status === "ok" || loc.status === "in-place"; if (!mediaReadable) { hold(held, `media-unknown:${slug}`, { what: `${slug}: its media`, disk: null, why: `${loc.detail ?? loc.status}: its media is unknown here, not empty`, link: { href: "/storage", label: "Storage" } }, null, 1); } const through: Through = loc.relocated && loc.target ? (call) => onDrive(loc.target!, call) : direct; const tally = newTally(); const buckets = brief.snapshot?.buckets; const cleanIds = new Set(buckets?.transcribedWithAudio ?? []); const extraIds = new Set(buckets?.multipleAudioFormats ?? []); const target = config.audioFormat ? `audio.${config.audioFormat}` : null; const inPlace = loc.status === "in-place"; try { // The channel dir's own entries; `media/` a real dir is the media tier in place. for (const [name, st] of await lstatAll(channelDir, await readNames(channelDir, direct), direct)) { if (!st || name === "data") continue; const abs = path.join(channelDir, name); if (st.isDirectory()) { await walkTree(abs, (a, s) => { acc.add(a, s, name === "media" ? "media" : "text"); if (name === "media" && inPlace && isTierable(path.basename(a)) && s.nlink === 1) { tally.move.bytes += allocated(s); tally.move.files += 1; } }, { ticker }); } else if (st.isFile()) acc.add(abs, st, "text"); } const dataDir = path.join(channelDir, "data"); for (const id of await readNames(dataDir, direct)) { await ticker.tick(); const dir = path.join(dataDir, id); const dst = await lstat(dir).catch(() => null); if (!dst?.isDirectory()) continue; await scanVideo({ slug, id, dir, through, mediaReadable, inPlace, cleanIds, extraIds, target, tally }); } } catch (e) { if (!isDriveNotAnswering(e)) throw e; hold(held, `media-unknown:${slug}`, { what: `${slug}: its media`, disk: null, why: `${(e as Error).message}: the rest of its media is unknown here`, link: { href: "/storage", label: "Storage" } }, null, 1); } channelSuggestions(slug, brief, tally); if (inPlace && tally.move.bytes > 0) moveCandidates.push({ slug, bytes: tally.move.bytes, files: tally.move.files }); } opts.onProgress?.(briefs.length, briefs.length); async function scanVideo(v: { slug: string; id: string; dir: string; through: Through; mediaReadable: boolean; inPlace: boolean; cleanIds: Set; extraIds: Set; target: string | null; tally: ChannelTally; }): Promise { const { slug, id, dir, tally } = v; const names = await readNames(dir, direct); const set = new Set(names); const heldNow = () => heldVideo(slug, id, { noDoNotCleanFile: !set.has(DO_NOT_CLEAN_FILENAME) }); const hasPointer = set.has(SAVED_VIDEO_POINTER_FILENAME); const audio: { name: string; fact: Fact }[] = []; let clipDev = corpusDev; let hasClips = false; for (const [name, st] of await lstatAll(dir, names, direct)) { await ticker.tick(); if (!st) continue; const abs = path.join(dir, name); if (st.isSymbolicLink()) { if (!v.mediaReadable || !isTierable(name)) continue; const real = await v.through(() => realpath(abs)).catch((e) => { if (isDriveNotAnswering(e)) throw e; return null; }); const tst = real ? await v.through(() => stat(real)).catch(() => null) : null; if (!real || !tst?.isFile()) continue; // Counted where the target is, by the walk of its own tree (a // location's root, or `media/` in place) — here only for the row. const f = acc.fact(real, tst); if (isRealAudioFile(name)) audio.push({ name, fact: f }); else if (isPlainRawChat(name)) bump(tally.chat, f); continue; } if (st.isDirectory()) { if (name === CLIPS_DIR) { await walkTree(abs, (a, s) => { clipDev = acc.add(a, s, "clips").dev; }, { ticker }); hasClips = true; } else if (name === ARCHIVE_ORG_STAGING_DIR) { let bytes = 0; let dev = corpusDev; await walkTree(abs, (a, s) => { const f = acc.add(a, s, "media"); bytes += f.nlink > 1 ? 0 : f.bytes; dev = f.dev; }, { ticker }); unmanaged(um, `archiveorg:${slug}`, { what: `${slug}: archive.org downloads left in staging`, disk: diskIdOf(dev), owner: "the archive.org download, which resumes from it and removes it when it finishes", link: { href: `/channels/${slug}`, label: "Channel page" } }, bytes, 1); } else { await walkTree(abs, (a, s) => acc.add(a, s, isScratchEntry(name) ? "media" : "text"), { ticker }); } continue; } if (!st.isFile()) continue; const f = acc.add(abs, st, mediaByName(name) ? "media" : "text"); if (isStoredCaptionName(name)) bump(tally.captions, f); else if (isPlainRawChat(name)) bump(tally.chat, f); else if (name === "metadata.info.json") unmanaged(um, `metadata:${f.dev}`, { what: "Video metadata (metadata.info.json)", disk: diskIdOf(f.dev), owner: "no writer compresses it yet" }, f.bytes); else if (name === "transcript.json") unmanaged(um, `asr:${f.dev}`, { what: "Raw transcriber output (transcript.json)", disk: diskIdOf(f.dev), owner: "no writer compresses it yet" }, f.bytes); else if (name === "transcript.cues.json") unmanaged(um, `cues:${f.dev}`, { what: "Cue files (transcript.cues.json)", disk: diskIdOf(f.dev), owner: "derived and rebuildable (build-cues); nothing removes them" }, f.bytes); if (isRealAudioFile(name)) audio.push({ name, fact: f }); if (v.inPlace && (isTierable(name)) && f.nlink === 1) { tally.move.bytes += f.bytes; tally.move.files += 1; } if (isSourceMediaFile(name) && !hasPointer) { 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) { 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 (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, and // left out for a video the held predicate holds. const videoHeld = await heldNow(); if (videoHeld && !tally.firstHeld) tally.firstHeld = { ...videoHeld, id }; if (audio.length && !videoHeld) { 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); } } function channelSuggestions(slug: string, brief: ChannelBrief, t: ChannelTally): void { const name = brief.config.name ?? slug; for (const [dev, e] of t.captions) { if (e.bytes <= 0) continue; suggestions.push({ key: `compress-captions:${slug}:${dev}`, kind: "compress-captions", slug, title: `${name}: ${e.count.toLocaleString("en-US")} caption track(s), ${formatBytes(e.bytes)}`, frees: { disk: diskIdOf(dev), bytes: compressSaving(e.bytes, CAPTION_RATIO_ESTIMATE) }, basis: "estimate", 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 } } : {}), }); } for (const [dev, e] of t.chat) { if (e.bytes <= 0) continue; suggestions.push({ key: `compress-live-chat:${slug}:${dev}`, kind: "compress-live-chat", slug, title: `${name}: ${e.count.toLocaleString("en-US")} raw live chat(s), ${formatBytes(e.bytes)}`, frees: { disk: diskIdOf(dev), bytes: compressSaving(e.bytes, CHAT_RATIO_ESTIMATE) }, basis: "estimate", 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 } } : {}), }); } const report = brief.snapshot?.generatedAt ? ` (report of ${String(brief.snapshot.generatedAt).slice(0, 10)})` : ""; // THE AUDIO SWEEPS ARE CHANNEL-WIDE and know do-not-clean and keep-latest // by their own rules, not a must-keep or unfinished live recording: while // any video of the channel is held they are held, never offered (F1). const sweepHeld = (what: string, dev: string, bytes: number, count: number) => hold(held, `sweep:${what}:${slug}:${dev}`, { what: `${name}: the audio sweeps (${what})`, disk: diskIdOf(dev), why: `${t.firstHeld!.id}: ${t.firstHeld!.why}: a channel-wide sweep is not offered while a video of the channel is held`, link: { href: `/channels/${slug}`, label: "Channel page" }, }, bytes, count); for (const [dev, e] of t.audio) { if (e.bytes <= 0) continue; if (t.firstHeld) { sweepHeld("transcribed", dev, e.bytes, e.count); continue; } const atRisk = brief.snapshot?.reclaimableAtRiskBytes ?? 0; suggestions.push({ key: `clean-audio:${slug}:${dev}`, kind: "clean-audio", slug, title: `${name}: audio kept beside ${e.count.toLocaleString("en-US")} transcribed video(s)`, frees: { disk: diskIdOf(dev), bytes: e.bytes }, basis: "measured", basisText: `measured now: the audio files of the report's transcribed-with-audio bucket${report}`, loss: "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 } } : {}), }); } for (const [dev, e] of t.extra) { if (e.bytes <= 0) continue; if (t.firstHeld) { sweepHeld("extra formats", dev, e.bytes, e.count); continue; } suggestions.push({ key: `clean-extra-formats:${slug}:${dev}`, kind: "clean-extra-formats", slug, title: `${name}: ${e.count.toLocaleString("en-US")} audio file(s) beside the ${brief.config.audioFormat} copy`, frees: { disk: diskIdOf(dev), bytes: e.bytes }, basis: "measured", 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 (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}:*`, kind: "evict-clips", slug, 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: 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({ key: `stale-partial:${slug}:${p.id}:${p.file}`, kind: "stale-partial", slug, id: p.id, file: p.file, title: `${name} ${p.id}: ${p.file}, untouched ${Math.floor((now.getTime() - p.fact.mtimeMs) / DAY_MS)} days`, frees: { disk: diskIdOf(p.fact.dev), bytes: p.fact.bytes }, basis: "measured", 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) { suggestions.push({ key: `unstored-container:${slug}:${s.id}:${s.file}`, kind: "unstored-container", slug, id: s.id, file: s.file, title: `${name} ${s.id}: ${s.file} is not in the saved-video store`, frees: { disk: diskIdOf(s.fact.dev), bytes: s.fact.bytes }, basis: "measured", basisText: "measured now", loss: "the only copy on this machine: decide on the video page (its Files list; Persist source video)", link: { href: `/channels/${slug}/videos/${s.id}`, label: "Video page" }, }); } } // --- the rest of transcripts/, the locations, the store, builds, reports ------ const resultFile = spaceSuggestionsPath(paths); let storeWalked = false; for (const [name, st] of await lstatAll(paths.transcriptsDir, await readNames(paths.transcriptsDir, direct), direct)) { if (!st) continue; const abs = path.join(paths.transcriptsDir, name); if (abs === paths.channelsDir || abs === resultFile) continue; if (st.isDirectory()) { if (under(storeReal, abs) && abs === storeReal) continue; await walkTree(abs, (a, s) => acc.add(a, s, under(a, storeReal) ? "store" : "other"), { ticker }); if (under(storeReal, abs)) storeWalked = true; } else if (st.isFile()) { const f = acc.add(abs, st, "other"); if (name === "index.mdb") unmanaged(um, "index", { what: "The transcript index (index.mdb)", disk: diskIdOf(f.dev), owner: "rebuilt by build-index; it does not shrink on its own" }, f.bytes); } } let playableBytes = 0; let playableDev: string | null = null; const walkedRoots: string[] = []; for (const loc of [...locations].sort((a, b) => a.root.length - b.root.length)) { const s = locState.get(loc.id); if (!s?.dev) continue; if (walkedRoots.some((r) => under(loc.root, r))) continue; walkedRoots.push(loc.root); try { await walkTree(loc.root, (a, st) => { const cat = under(a, storeReal) ? "store" : under(a, playableRoot) ? "playable" : "media"; const f = acc.add(a, st, cat); if (cat === "playable") { playableBytes += f.bytes; playableDev = f.dev; } }, { ticker, through: (call) => onDrive(loc, call) }); } catch (e) { if (!isDriveNotAnswering(e)) throw e; locState.set(loc.id, { ...s, detail: `stopped answering during the scan: its figures are partial (${(e as Error).message})` }); } } if (!storeWalked && !walkedRoots.some((r) => under(storeReal, r))) { await walkTree(storeReal, (a, st) => { const f = acc.add(a, st, "store"); void f; }, { ticker }).catch(() => {}); } if (!walkedRoots.some((r) => under(playableRoot, r))) { await walkTree(playableRoot, (a, st) => { const f = acc.add(a, st, "playable"); playableBytes += f.bytes; playableDev = f.dev; }, { ticker }).catch(() => {}); } if (playableBytes > 0) { unmanaged(um, "playable", { what: "Browser-playable copies (prepare-playable)", disk: playableDev ? diskIdOf(playableDev) : null, owner: "rebuildable by prepare-playable; no remover exists" }, playableBytes); } const buildRoots = [paths.exportBuildsDir, paths.exportPublicDir, path.join(paths.monorepoRoot, "homepage", "out")].filter(Boolean); for (const root of buildRoots) { let bytes = 0; let dev: string | null = null; await walkTree(root, (a, st) => { const f = acc.add(a, st, "builds"); bytes += f.bytes; dev = f.dev; }, { ticker }).catch(() => {}); if (bytes > 0) { unmanaged(um, `builds:${root}`, { what: `Site builds (${path.relative(paths.monorepoRoot, root) || root})`, disk: dev ? diskIdOf(dev) : null, owner: "the publish stages; no pruner exists" }, bytes); } } const reportsRoot = deps.reportsRoot === undefined ? defaultReportsRoot() : deps.reportsRoot; if (reportsRoot) { let bytes = 0; let dev: string | null = null; await walkTree(reportsRoot, (a, st) => { const f = acc.add(a, st, "reports"); bytes += f.bytes; dev = f.dev; }, { ticker }).catch(() => {}); if (bytes > 0) { unmanaged(um, "reports", { what: "umtool's report projects", disk: dev ? diskIdOf(dev) : null, owner: "umtool (its takes' work files, by policy); a dry run lists what it would prune, --yes prunes", command: "umtool prune --all" }, bytes); } } // --- the disks --------------------------------------------------------------------- const disks: SpaceDisk[] = []; const devs = new Set([...acc.byDev.keys(), corpusDev, ...[...locState.values()].map((s) => s.dev).filter((d): d is string => !!d)]); const storeDev = await stat(storeReal).then((st) => deviceOf(storeReal, st), () => null); for (const dev of devs) { const dir = dev === corpusDev ? paths.channelsDir : acc.devDir.get(dev); const onLoc = locations.filter((l) => locState.get(l.id)?.dev === dev); const fs = dir ? await (onLoc.length ? onDrive(onLoc[0], () => filesystemOf(dir)).catch(() => null) : filesystemOf(dir)) : null; const share = acc.byDev.get(dev) ?? emptyShare(); const roles: string[] = []; if (dev === corpusDev) roles.push("corpus disk"); for (const l of onLoc) roles.push(`location ${l.label || l.id}`); if (storeDev === dev) roles.push("saved-video store"); if (share.builds > 0) roles.push("site builds"); if (share.reports > 0) roles.push("umtool reports"); const partial = onLoc.map((l) => locState.get(l.id)?.detail).find(Boolean); disks.push({ id: diskIdOf(dev), label: dev === corpusDev ? "Corpus disk" : onLoc.length ? onLoc.map((l) => l.label || l.id).join(" + ") : fs?.mountpoint ?? `device ${dev}`, mountpoint: fs?.mountpoint ?? null, status: "ok", ...(partial ? { detail: partial } : {}), roles, locationIds: onLoc.map((l) => l.id), sizeBytes: fs?.sizeBytes ?? null, freeBytes: fs?.freeBytes ?? null, archive: share, archiveBytes: Object.values(share).reduce((a, b) => a + b, 0), }); } for (const loc of locations) { const s = locState.get(loc.id); if (!s || s.dev) continue; disks.push({ id: loc.id, label: loc.label || loc.id, mountpoint: loc.volume?.mountpoint ?? null, status: s.status === "ok" ? "not-mounted" : s.status, detail: `${s.detail ?? s.status}: not scanned; its channels' media is unknown here, not empty`, roles: [`location ${loc.label || loc.id}`], locationIds: [loc.id], sizeBytes: null, freeBytes: null, archive: null, archiveBytes: null, }); } const diskById = new Map(disks.map((d) => [d.id, d])); // --- moves --------------------------------------------------------------------------- const targetLoc = [settings.storage.defaultLocationId, ...locations.map((l) => l.id)] .map((id) => locations.find((l) => l.id === id)) .find((l) => l && locState.get(l.id)?.dev && locState.get(l.id)!.dev !== corpusDev) ?? null; if (moveCandidates.length && !targetLoc) { hold(held, "no-target", { what: "Channels whose media is on the corpus disk", disk: "corpus", why: "no storage location on another disk is mounted to move them to", link: { href: "/storage", label: "Storage" } }, moveCandidates.reduce((n, m) => n + m.bytes, 0), moveCandidates.length); } if (targetLoc) { const tDisk = diskById.get(diskIdOf(locState.get(targetLoc.id)!.dev!)); let used = 0; for (const m of moveCandidates.sort((a, b) => b.bytes - a.bytes)) { const fit = moveFit(tDisk?.freeBytes === null || tDisk?.freeBytes === undefined ? null : tDisk.freeBytes - used, m.bytes, floorBytes); if (fit.fits) used += m.bytes; const name = configOf.get(m.slug)?.name ?? m.slug; suggestions.push({ key: `move-media:${m.slug}`, kind: "move-media", slug: m.slug, title: `${name}: ${m.files.toLocaleString("en-US")} media file(s) to ${targetLoc.label || targetLoc.id}`, frees: { disk: "corpus", bytes: m.bytes }, fills: { disk: tDisk?.id ?? targetLoc.id, bytes: m.bytes, fits: fit.fits, freeAfter: fit.freeAfter }, basis: "measured", 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` }), }); } } if (storeDev === corpusDev && targetLoc) { const share = acc.byDev.get(corpusDev)?.store ?? 0; if (share > 0) { suggestions.push({ key: "move-store", kind: "move-store", title: `The saved-video store to ${targetLoc.label || targetLoc.id}`, frees: { disk: "corpus", bytes: share }, fills: { disk: diskIdOf(locState.get(targetLoc.id)!.dev!), bytes: share, ...moveFit(diskById.get(diskIdOf(locState.get(targetLoc.id)!.dev!))?.freeBytes ?? null, share, floorBytes) }, basis: "measured", basisText: "measured now: the store's tree", loss: "nothing: the store moves whole and is verified before the swap; it can be moved back", link: { href: "/storage", label: "Storage: the store's card" }, }); } } // --- the store ------------------------------------------------------------------------ // 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 => { 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 => 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 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${former ? " (a former original)" : ""}`, frees: { disk: diskIdOf(f.dev), bytes: f.bytes }, basis: "measured", basisText: "measured now", 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" }, }); } } // Compaction (ruling 2: it follows the compaction rules, which pick the // deliberately stored — pinned — videos and keep the original). let compactionAt: string | null = null; let probes: SpaceProbeMemo = opts.previous?.probes ?? {}; let refused: SpaceRefused[] = []; if (opts.compaction === false && opts.previous) { compactionAt = opts.previous.compactionAt; refused = opts.previous.refused; 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); probes = planned.probes; compactionAt = now.toISOString(); const groups = new Map(); for (const item of planned.plan.items) { const e = entryOf.get(`${item.slug}/${item.id}`); const f = e ? await statFile(path.join(e.pointer.dir, e.pointer.file)) : null; 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" ? "when its original is dropped: after the verify if it is on its platform, else after a person's review" : "when its original is dropped (dropOriginal: keep): review it, then drop it here"; suggestions.push({ key: `compact:${item.slug}:${item.id}`, kind: "compact", slug: item.slug, id: item.id, title: `${name} ${item.id}: ${formatBytes(src)}${item.source?.height ? ` ${item.source.height}p` : ""}${item.source?.videoMbps ? ` ${item.source.videoMbps.toFixed(1)} Mbit/s` : ""} → AV1`, frees: null, later: { disk: disk ?? "corpus", low: Math.max(0, src - item.estimate.bytes[1]), high: Math.max(0, src - item.estimate.bytes[0]), when }, basis: "estimate", 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" }, }); continue; } if (item.compact) continue; const group = refusalGroup(item.reason ?? ""); if (!group) continue; let g = groups.get(group); if (!g) groups.set(group, (g = { group, count: 0, bytes: 0, disk, examples: [] })); g.count += 1; g.bytes += bytes; g.examples.push({ slug: item.slug, id: item.id, bytes, reason: item.reason ?? "" }); } refused = [...groups.values()].map((g) => ({ ...g, examples: g.examples.sort((a, b) => b.bytes - a.bytes).slice(0, EXAMPLES_PER_GROUP) })).sort((a, b) => b.bytes - a.bytes); } // Compacted originals: where the space actually comes back. const review = await (deps.compactionReview ?? (() => listCompactionReview({ paths, settings: settings.savedVideoCompaction, notAnswering: [] })))().catch(() => [] as CompactionReviewRow[]); for (const r of review) { const e = entryOf.get(`${r.slug}/${r.id}`); const dir = e?.pointer.dir; const name = configOf.get(r.slug)?.name ?? r.slug; const files: { file: string; interrupted: boolean }[] = []; 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 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}`, kind: "drop-original", slug: r.slug, 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.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")})`, ...(awaiting ? { link: { href: `/channels/${r.slug}/videos/${r.id}`, label: "Review the compacted copy first (watch it)" } } : { 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" }, }), hold: { slug: r.slug, id: r.id, store: true }, targets: [{ path: abs, size: f.size, mtimeMs: f.mtimeMs }], }); } } const failed = await (deps.keptFailedEncodes ?? (() => listKeptFailedEncodes(paths)))().catch(() => [] as KeptFailedEncodeRow[]); for (const r of failed) { const bytes = r.kept?.bytes ?? r.bytes ?? 0; if (bytes <= 0) continue; 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", slug: r.slug, id: r.id, title: `${configOf.get(r.slug)?.name ?? r.slug} ${r.id}: ${r.orphaned ? "an orphaned compaction scratch" : `a failed encode (${r.reason})`}`, frees: { disk: diskIdOf(dev), bytes }, basis: "measured", 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, so the row // frees nothing now (review 1, not blocking 3). let keptPartsBytes = 0; let keptPartsCount = 0; for (const r of liveRows) { for (const k of r.keptParts ?? []) { keptPartsBytes += k.bytes; keptPartsCount += 1; } const v = r.verification; if (r.status === "recording" || !v || v.state === "verified" || !v.against?.length) continue; 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 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: 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, 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); } // Audio the cleanup sweeps hold, from the reports: decided on /cleanup. const heldAudio = { noTranscript: 0, keepLatest: 0, doNotClean: 0, awaitingDiarization: 0 }; for (const b of briefs) { const h = b.snapshot?.heldAudioBytes; if (!h) continue; heldAudio.noTranscript += h.noTranscript; heldAudio.keepLatest += h.keepLatest; heldAudio.doNotClean += h.doNotClean; heldAudio.awaitingDiarization += h.awaitingDiarization; } const heldAudioWhy: Record = { noTranscript: "no transcript yet: transcribing releases it", keepLatest: "the channels' keep-latest window", doNotClean: "do-not-clean", awaitingDiarization: "waiting for the Speakers lane", }; for (const [k, bytes] of Object.entries(heldAudio) as [keyof typeof heldAudio, number][]) { if (bytes > 0) hold(held, `audio:${k}`, { what: "Audio the cleanup sweeps hold (from the reports)", disk: null, why: heldAudioWhy[k], link: { href: "/cleanup", label: "Audio cleanup" } }, bytes, 0); } const { kept, overflow } = capPerKind(suggestions); const overflowLink: Partial> = { compact: { href: "/saved-videos", label: "Saved videos" }, "drop-original": { href: "/saved-videos", label: "Saved videos" }, "drop-alternate": { href: "/saved-videos", label: "Saved videos" }, "evict-clips": { href: "/storage", label: "Storage: clip windows" }, "clean-audio": { href: "/cleanup", label: "Audio cleanup" }, }; const result: SpaceScanResult = { version: SPACE_SCAN_VERSION, computedAt: now.toISOString(), tookMs: Date.now() - started, ...(opts.jobId ? { jobId: opts.jobId } : {}), floorBytes, disks, suggestions: kept, overflow: overflow.map((o) => ({ ...o, ...(overflowLink[o.kind] ? { link: overflowLink[o.kind] } : {}) })), held: [...held.values()].sort((a, b) => (b.bytes ?? 0) - (a.bytes ?? 0)), refused, unmanaged: [...um.values()].sort((a, b) => b.bytes - a.bytes), notScanned, compactionAt, probes, }; await writeJsonAtomic(resultFile, result); return result; } // The selector's plan, each ffprobe remembered by (path, size, mtime). async function defaultCompactionPlan( paths: Paths, settings: SavedVideoCompactionSettings, memo: SpaceProbeMemo, ): Promise<{ plan: CompactPlan; probes: SpaceProbeMemo }> { const fresh: SpaceProbeMemo = {}; const plan = await planCompaction({ paths, settings, select: true, deps: { probe: async (file) => { const st = await stat(file).catch(() => null); const hit = memo[file]; if (st && hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) { fresh[file] = hit; return hit.probe as SourceProbe | null; } const p = await probeCompactionSource(paths.ffprobeBin, file); // 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; }, }, }); return { plan, probes: fresh }; } // --- the job --------------------------------------------------------------------- export const SPACE_SCAN_BODY_KEYS = ["compaction"] as const; export async function enqueueSpaceScan(opts: { paths: Paths; settings: () => SpaceScanSettings; compaction?: boolean; onDone?: () => void; }): Promise { return runManagedFunction({ kind: SPACE_SCAN_JOB_KIND, queueKey: SPACE_SCAN_QUEUE, paths: opts.paths, network: false, fn: async (onLog, signal, setProgress, ctx) => { onLog("Scanning the disks the archive writes to. Nothing is removed, moved or fetched; the result is .space-suggestions.json."); const previous = await readSpaceSuggestions(opts.paths); const result = await scanSpace({ paths: opts.paths, settings: opts.settings(), compaction: opts.compaction !== false, previous, jobId: ctx.jobId, onLog, signal, onProgress: (done, of) => setProgress({ metric: "channels", initial: 0, target: of, current: done }), }); for (const d of result.disks) { onLog( `${d.label} (${d.id}): ${d.status === "ok" ? `${d.freeBytes === null ? "?" : formatBytes(d.freeBytes)} free of ${d.sizeBytes === null ? "?" : formatBytes(d.sizeBytes)}, the archive's ${formatBytes(d.archiveBytes ?? 0)}` : d.detail ?? d.status}`, ); } onLog( `${result.suggestions.length} suggestion(s)${result.overflow.length ? ` (+${result.overflow.reduce((n, o) => n + o.count, 0)} more counted)` : ""}, ` + `${result.held.length} held, ${result.notScanned.length} channel(s) not scanned, in ${Math.round(result.tookMs / 1000)} s.`, ); opts.onDone?.(); }, }); }