commit 93a437b6990567d7b99774a68069b4a406219507 parent 53d75f1455f4474774ff69e0ef2d827062174975 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Tue, 17 Nov 2026 22:57:45 -0500 Merge main (ae5c3492b, which contains 7dcdc8e8e) into lane/x-trending No conflict. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
21 files changed, 427 insertions(+), 75 deletions(-)
diff --git a/plans/orpheus-retune.md b/plans/orpheus-retune.md @@ -2,7 +2,7 @@ Status: **planned 15 Nov 2026; S1 done (merged 2dff0a631, shipped 16 Nov 2026); S3 done (`lane/line-rerun`, merged 17 Nov 2026; S3b, re-read one sentence, is a follow-up after S4); S2 done (`lane/character-tuning`, -merged 17 Nov 2026); S4 built on `lane/reads-find` (17 Nov 2026), in review.** Written to be picked up cold (after a usage reset). +merged 17 Nov 2026); S4 done (`lane/reads-find`, merged and shipped 17 Nov 2026, with the shared project walk it needed). All four slices are live; S3b is the one follow-up, if wanted.** Written to be picked up cold (after a usage reset). ## The ask (operator, 15 Nov 2026) diff --git a/umtool/app/api/queue/route.ts b/umtool/app/api/queue/route.ts @@ -2,6 +2,7 @@ import { kickQueue } from "@/lib/queue/runner"; import { cancelStep, isQid, retryStep } from "@/lib/queue/store.mjs"; import { queueDir } from "@/lib/queue/runner"; import { queueView } from "@/lib/queue/view"; +import { walkStats } from "@/lib/projects/walk.mjs"; export const dynamic = "force-dynamic"; @@ -20,6 +21,9 @@ const noStore = { "cache-control": "no-store" }; export async function GET(request: Request) { const url = new URL(request.url); + // `?walks=1`: how many project walks this process has started and how many run now (lib/projects/walk.mjs) -- the + // load check's idle gauge (walk-load.spec.ts), read only. + if (url.searchParams.get("walks") === "1") return Response.json({ walks: { ...walkStats } }, { headers: noStore }); const view = await queueView({ project: url.searchParams.get("project"), all: url.searchParams.get("all") === "1" }); return Response.json(view, { headers: noStore }); } diff --git a/umtool/app/api/report/cut-points/route.ts b/umtool/app/api/report/cut-points/route.ts @@ -1,5 +1,5 @@ import { REPORTS_ROOT } from "@/lib/paths.mjs"; -import { walkProjects } from "@/lib/projects/walk.mjs"; +import { sharedWalk } from "@/lib/projects/walk.mjs"; import { cutPointsFor } from "@/lib/report/cutPoints.mjs"; export const dynamic = "force-dynamic"; @@ -19,7 +19,7 @@ export async function GET(request: Request) { const projectId = url.searchParams.get("project") ?? ""; const take = url.searchParams.get("take") || null; const clips = url.searchParams.getAll("clip").filter(Boolean); - const project = (await walkProjects(REPORTS_ROOT)).find((p: { id: string }) => p.id === projectId); + const project = (await sharedWalk(REPORTS_ROOT)).find((p: { id: string }) => p.id === projectId); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); try { const got = await cutPointsFor(project, { take, clips: clips.length ? clips : null }); diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -411,7 +411,7 @@ async function postHere(request: Request) { // finding 4); a marker whose job ended, or one never given a job within two minutes, is stale and taken over. // ITS RE-READ IN THE READS QUEUE (lane reads-find): while that step runs, a press here would make a second read // of the same post -- said, as a sentence, never asked. - const queued = await (await import("@/lib/report/readsQueue.mjs")).rereadRunningFor(r.project.id, id, { queueDir: (await import("@/lib/queue/runner")).queueDir() }).catch(() => null); + const queued = await (await import("@/lib/report/readsQueue.mjs")).rereadRunningFor(r.project, id, { queueDir: (await import("@/lib/queue/runner")).queueDir() }).catch(() => null); if (queued) return Response.json({ error: `this post is being re-read by the Reads queue (${queued.qid}): read it again when that lands`, busy: true }, { status: 409 }); const pendingFile = pendingFileOf(r.project.dir, e); await mkdir(path.dirname(pendingFile), { recursive: true }); diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -18,6 +18,7 @@ import QuickClip from "@/components/inbox/QuickClip"; import RunningList from "@/components/shell/RunningList"; import RecentCuts from "@/components/shell/RecentCuts"; import { initialRunning } from "@/lib/activity"; +import { projectRefs } from "@/lib/projects"; export const dynamic = "force-dynamic"; @@ -138,7 +139,9 @@ export default async function Inbox({ // ▶ Play beside every card of a report video (at its note, for a note card): lane/ui-simplify. const all = [...groups, ...extra]; - await Promise.all(all.flatMap((g) => g.cards.map(async (c) => (c.play = await playHrefOfPiece(c.piece, c.action.href))))); + // The projects walked ONCE for every card (never a lookup -- a walk -- per card: the regression of 17 Nov 2026). + const refs = await projectRefs(); + await Promise.all(all.flatMap((g) => g.cards.map(async (c) => (c.play = await playHrefOfPiece(c.piece, c.action.href, refs))))); return ( <div className="flex h-full flex-col"> diff --git a/umtool/components/projects/playable.ts b/umtool/components/projects/playable.ts @@ -1,4 +1,5 @@ import { resolveProjectPath } from "@/lib/projects"; +import type { ProjectRef } from "@/lib/project-types"; import { playHref } from "@/lib/hrefs"; // Which pieces have a Play view (a report video), for surfaces outside @@ -6,11 +7,15 @@ import { playHref } from "@/lib/hrefs"; // name a kind themselves (the registry rule: kind ids stay in lib/projects/ // and components/projects/). `p:<project>` → its Play address, at the note // when the card's action points at one; null for anything else. -export async function playHrefOfPiece(piece: string | null, actionHref?: string | null): Promise<string | null> { +// +// `refs` (the Inbox: every card at once): the projects, walked ONCE by the caller and handed down -- a page of +// hundreds of cards never resolves each by a walk of its own (the regression of 17 Nov 2026). +export async function playHrefOfPiece(piece: string | null, actionHref?: string | null, refs?: ProjectRef[] | null): Promise<string | null> { if (!piece || !piece.startsWith("p:")) return null; const id = piece.slice(2); - const r = await resolveProjectPath(id.split("/")).catch(() => null); - if (!r || !("project" in r) || !r.project || r.rest.length || r.project.kind !== "report-video") return null; + const project = refs ? refs.find((p) => p.id === id && p.routing === "ok") ?? null : await resolveProjectPath(id.split("/")).then((r) => (r && "project" in r && r.project && !r.rest.length ? r.project : null), () => null); + const r = project ? { project, rest: [] as string[] } : null; + if (!r || r.project.kind !== "report-video") return null; let note: string | null = null; try { note = actionHref ? new URL(actionHref, "http://umtool").searchParams.get("note") : null; diff --git a/umtool/e2e/walk-load.spec.ts b/umtool/e2e/walk-load.spec.ts @@ -0,0 +1,96 @@ +import { test, expect } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// THE BUILT SERVER UNDER A LARGE REPORTS ROOT (the regression S4 shipped with, 17 Nov 2026: the live server pegged a +// core walking the reports root over and over and never answered `/`). This suite's own fixture gains 300 project +// directories (30 folders of 10, plus loose non-project folders) and 124 OLD queue steps (done and failed take +// renders, no reads batch anywhere). Then: the server, left alone, walks nothing; `/` and a project page answer +// within seconds; and afterwards it is idle again -- the walk count flat, its CPU near nothing. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const LOAD = path.join(FIXTURE, "walk-load"); +const QUEUE = path.join(FIXTURE, ".umtool-queue", "steps"); +const OUR_STEPS = Array.from({ length: 124 }, (_, i) => `q${9001 + i}`); +const KIND = "report-video"; + +const walks = async (base: string) => ((await (await fetch(`${base}/api/queue?walks=1`)).json()) as { walks: { calls: number; inFlight: number } }).walks; +/** The server's CPU seconds so far (utime + stime), from /proc: the pid that listens on the port. */ +function cpuSeconds(port: number): number { + const out = execFileSync("ss", ["-ltnpH", `sport = :${port}`], { encoding: "utf8" }); + const pid = Number(/pid=(\d+)/.exec(out)?.[1]); + const f = readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1].split(" "); + return (Number(f[11]) + Number(f[12])) / 100; +} +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +test.beforeAll(() => { + for (let g = 0; g < 30; g++) { + for (let i = 0; i < 10; i++) { + const d = path.join(LOAD, `group-${g}`, `proj-${i}`); + mkdirSync(path.join(d, "out"), { recursive: true }); + writeFileSync(path.join(d, "project.json"), JSON.stringify({ kind: KIND, title: `Load ${g}-${i}` })); + writeFileSync(path.join(d, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: `proj-${i}`, title: `Load ${g}-${i}`, render: { width: 1920, height: 1080, fps: 30 }, timeline: [] })); + } + // Folders with no project beneath: walked, never listed. + mkdirSync(path.join(LOAD, `group-${g}`, "scratch", "a", "b"), { recursive: true }); + } + mkdirSync(QUEUE, { recursive: true }); + OUR_STEPS.forEach((qid, n) => { + const p = `walk-load/group-${n % 30}/proj-${n % 10}`; + writeFileSync(path.join(QUEUE, `${qid}.json`), JSON.stringify({ + qid, seq: 9001 + n, label: `take ${p} --id rough-1 --preview`, argv: ["take", p, "--id", "rough-1", "--preview"], cwd: null, after: null, + target: { project: p, take: "rough-1" }, state: n % 3 ? "done" : "failed", createdAt: "2026-11-01T00:00:00.000Z", by: "umtool queue add", + startedAt: "2026-11-01T00:00:01.000Z", endedAt: "2026-11-01T00:10:00.000Z", exitCode: n % 3 ? 0 : 1, signal: null, pid: 1, pidStart: null, host: os.hostname(), + runnerPid: 1, runnerStart: null, jobId: null, attempts: 1, error: n % 3 ? null : "the render failed", blockedBy: null, cancelRequested: null, timeoutMin: 720, + })); + }); +}); +test.afterAll(() => { + rmSync(LOAD, { recursive: true, force: true }); + for (const qid of OUR_STEPS) rmSync(path.join(QUEUE, `${qid}.json`), { force: true }); + void readdirSync; +}); + +test("a large reports root and 124 old queue steps: idle, then `/` and a project page within seconds, then idle again", async ({ page, baseURL }) => { + test.setTimeout(180_000); + const base = String(baseURL); + const port = Number(new URL(base).port); + // Left alone a while (the queue runner ticks every 2 s): no walk. + const w0 = await walks(base); + const c0 = cpuSeconds(port); + await sleep(6000); + const w1 = await walks(base); + const c1 = cpuSeconds(port); + expect(w1.calls - w0.calls, "walks while idle").toBe(0); + expect(c1 - c0, "CPU seconds while idle (6 s)").toBeLessThan(1.5); + // `/` and a project page. + let t = Date.now(); + const home = await page.goto("/", { timeout: 30_000 }); + expect(home?.status()).toBe(200); + const homeMs = Date.now() - t; + t = Date.now(); + const proj = await page.goto("/projects/walk-load/group-7/proj-3", { timeout: 30_000 }); + expect(proj?.status()).toBe(200); + const projMs = Date.now() - t; + expect(homeMs, "`/` answers within seconds").toBeLessThan(15_000); + expect(projMs, "a project page answers within seconds").toBeLessThan(15_000); + // Then idle again: no page polling, the walk count flat and the CPU near nothing. + await page.goto("about:blank"); + await sleep(3000); + const w2 = await walks(base); + const c2 = cpuSeconds(port); + await sleep(6000); + const w3 = await walks(base); + const c3 = cpuSeconds(port); + console.log(`walk-load: home ${homeMs} ms, project ${projMs} ms; walks idle ${w1.calls - w0.calls}, during pages ${w2.calls - w1.calls}, after ${w3.calls - w2.calls} (in flight ${w3.inFlight}); CPU idle ${(c1 - c0).toFixed(2)} s, after ${(c3 - c2).toFixed(2)} s`); + expect(w3.calls - w2.calls, "walks after the pages").toBe(0); + expect(w3.inFlight).toBe(0); + expect(c3 - c2, "CPU seconds after (6 s)").toBeLessThan(1.5); +}); diff --git a/umtool/lib/inbox/walkLoad.test.ts b/umtool/lib/inbox/walkLoad.test.ts @@ -0,0 +1,136 @@ +// A LARGE REPORTS ROOT, AND HOW MANY TIMES IT IS WALKED (the regression S4 shipped with, 17 Nov 2026: the live server +// pegged a core with hundreds of walks of the reports root in flight at once, and never answered `/`). A reports root +// of 300 projects (30 folders of 10, and folders with no project beneath) and a queue store of 124 OLD take steps +// (done and failed), no reads batch anywhere. Each surface's walks are counted (lib/projects/walk.mjs walkStats) and +// must be few and bounded, run ONE at a time, and return. Run with: pnpm --filter umtool exec tsx --test +// lib/inbox/walkLoad.test.ts +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync } from "node:fs"; +import { mkdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// The environment BEFORE any module that reads lib/paths.mjs (a static import would be hoisted and read ~/reports). +const tmp = mkdtempSync(path.join(os.tmpdir(), "umtool-walk-load-")); +const ROOT = path.join(tmp, "reports"); +process.env.REPORTS_DIR = ROOT; +process.env.CHANNELS_DIR = path.join(tmp, "channels"); +process.env.SITES_DIR = path.join(tmp, "sites"); +process.env.ARTICLES_DIR = path.join(tmp, "articles"); +process.env.UMTOOL_QUEUE_DIR = path.join(ROOT, ".umtool-queue"); +process.env.ARCHILYZER_EDITOR_URL = "http://127.0.0.1:9"; +process.env.WORKER_TOKEN = ""; +process.env.UMTOOL_URL = "http://127.0.0.1:9"; +process.env.UMTOOL_XJAR_MEMO_MS = "0"; +const QUEUE = path.join(ROOT, ".umtool-queue"); + +const { walkStats } = await import("../projects/walk.mjs"); +const { PROJECT_KINDS } = await import("../projects/kinds.mjs"); +const KIND = (PROJECT_KINDS.find((k: { makesTakes?: boolean }) => k.makesTakes) as { id: string }).id; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** The walks `fn` starts, and the most that ran at once while it did. */ +async function walksOf(fn: () => Promise<unknown>): Promise<{ walks: number; atOnce: number; ms: number }> { + const c0 = walkStats.calls; + walkStats.maxInFlight = walkStats.inFlight; + const t0 = Date.now(); + await fn(); + return { walks: walkStats.calls - c0, atOnce: walkStats.maxInFlight, ms: Date.now() - t0 }; +} +/** Every memo expired: what a server in its second second sees. */ +const expired = () => sleep(1100); + +before(async () => { + for (let g = 0; g < 30; g++) { + for (let i = 0; i < 10; i++) { + const d = path.join(ROOT, `group-${g}`, `proj-${i}`); + await mkdir(path.join(d, "out"), { recursive: true }); + await writeFile(path.join(d, "project.json"), JSON.stringify({ kind: KIND, title: `Load ${g}-${i}` })); + await writeFile(path.join(d, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: `proj-${i}`, title: `Load ${g}-${i}`, render: { width: 1920, height: 1080, fps: 30 }, timeline: [] })); + } + await mkdir(path.join(ROOT, `group-${g}`, "scratch", "a", "b"), { recursive: true }); + } + await mkdir(path.join(QUEUE, "steps"), { recursive: true }); + for (let n = 0; n < 124; n++) { + const p = `group-${n % 30}/proj-${n % 10}`; + await writeFile(path.join(QUEUE, "steps", `q${n + 1}.json`), JSON.stringify({ + qid: `q${n + 1}`, seq: n + 1, label: `take ${p} --id rough-1 --preview`, argv: ["take", p, "--id", "rough-1", "--preview"], cwd: null, after: null, + target: { project: p, take: "rough-1" }, state: n % 3 ? "done" : "failed", createdAt: "2026-11-01T00:00:00.000Z", by: "umtool queue add", + startedAt: "2026-11-01T00:00:01.000Z", endedAt: "2026-11-01T00:10:00.000Z", exitCode: n % 3 ? 0 : 1, signal: null, pid: 1, pidStart: null, host: os.hostname(), + runnerPid: 1, runnerStart: null, jobId: null, attempts: 1, error: n % 3 ? null : "the render failed", blockedBy: null, cancelRequested: null, timeoutMin: 720, + })); + } +}); +after(() => rm(tmp, { recursive: true, force: true })); + +test("THE REGRESSION: 300 inbox cards looked up at once with the memo expired -- one walk, not 300; 50 misses -- one", async () => { + const { projectRefs } = await import("../projects"); + const { playHrefOfPiece } = await import("../../components/projects/playable"); + await projectRefs(); + await expired(); + let r = await walksOf(() => Promise.all(Array.from({ length: 300 }, (_, n) => playHrefOfPiece(`p:group-${n % 30}/proj-${n % 10}`)))); + assert.deepEqual([r.walks, r.atOnce], [1, 1], JSON.stringify(r)); + await expired(); + r = await walksOf(() => Promise.all(Array.from({ length: 50 }, (_, n) => playHrefOfPiece(`p:gone-${n}`)))); + assert.ok(r.walks <= 2 && r.atOnce === 1, JSON.stringify(r)); + // The page's way: the projects walked once for every card, handed down. + await expired(); + r = await walksOf(async () => { + const refs = await projectRefs(); + await Promise.all(Array.from({ length: 300 }, (_, n) => playHrefOfPiece(`p:group-${n % 30}/proj-${n % 10}`, null, refs))); + }); + assert.deepEqual([r.walks, r.atOnce], [1, 1]); +}); + +test("the home page's data (the inbox, the rail's counts, the cards' Play): a few walks, one at a time", async () => { + const { readInbox } = await import("../inbox"); + const { railCounts } = await import("../rail"); + const { projectRefs } = await import("../projects"); + const { playHrefOfPiece } = await import("../../components/projects/playable"); + await expired(); + const r = await walksOf(async () => { + const inbox = await readInbox({}); + await railCounts(); + const refs = await projectRefs(); + const cards = inbox.groups.flatMap((g: { cards: Array<{ piece: string | null }> }) => g.cards); + await Promise.all(cards.map((c) => playHrefOfPiece(c.piece, null, refs))); + }); + console.log(`home: ${r.walks} walk(s), ${r.ms} ms`); + assert.equal(r.atOnce, 1, "never two walks at once"); + assert.ok(r.walks <= 8, `home walks ${r.walks}`); +}); + +test("a project page's data (its path resolved, its readiness): at most 2 walks", async () => { + const { resolveProjectPath } = await import("../projects"); + const { readinessOf } = await import("./readiness"); + await expired(); + const r = await walksOf(async () => { + const got = await resolveProjectPath(["group-7", "proj-3"]); + assert.ok(got && "project" in got && got.project); + await readinessOf(got.project); + }); + assert.ok(r.walks <= 2 && r.atOnce === 1, JSON.stringify(r)); +}); + +test("the reads route's GET, one queue runner tick, the bench's 409 check: no walk; the report routes: one walk shared by 20 requests", async () => { + const { projectRef } = await import("../projects"); + const { readsGet } = await import("../report/readsApi.mjs"); + const { queueTick } = await import("../queue/store.mjs"); + const { rereadRunningFor } = await import("../report/readsQueue.mjs"); + const { resolveReport } = await import("../report/serve.mjs"); + const project = await projectRef("group-3/proj-4"); + assert.ok(project); + let r = await walksOf(() => readsGet(project, new URLSearchParams(), { reportsRoot: ROOT, queueDir: QUEUE, runner: null })); + assert.equal(r.walks, 0, "reads GET"); + // The runner's tick, its executor as lib/queue/runner.ts's (its describe resolves a failed step's project). + r = await walksOf(() => queueTick(QUEUE, { busy: () => null, start: () => ({ pid: null, jobId: null, cancel: () => {} }), describe: async (s: { target?: { project?: string } }) => (await projectRef(String(s.target?.project ?? "")), null) } as never, { held: new Map() })); + assert.equal(r.walks, 0, "a runner tick"); + r = await walksOf(() => rereadRunningFor(project, "p-1", { queueDir: QUEUE })); + assert.equal(r.walks, 0, "the 409 check"); + await expired(); + r = await walksOf(() => Promise.all(Array.from({ length: 20 }, () => resolveReport("group-3/proj-4")))); + assert.deepEqual([r.walks, r.atOnce], [1, 1], "20 report requests at once: one walk"); + r = await walksOf(() => Promise.all(Array.from({ length: 20 }, (_, n) => resolveReport(`group-3/gone-${n}`)))); + assert.ok(r.walks <= 1 && r.atOnce <= 1, `20 misses: ${JSON.stringify(r)}`); +}); diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -39,7 +39,7 @@ import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promi import path from "node:path"; import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; -import { walkProjects } from "../projects/walk.mjs"; +import { sharedWalk } from "../projects/walk.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const USAGE_INDEX_FORMAT = "umtool-usage-index"; @@ -122,7 +122,7 @@ export async function manifestFilesOf(dir) { * resolveDir?: (ch: string, video: string) => Promise<string>, now?: () => Date }} o * @returns {Promise<{ index: Record<string, any>, stats: { manifests: number, parsed: number, reused: number, dropped: number, projects: number } }>} */ -export async function buildUsageIndex({ reportsRoot, channelsDir, previous = null, walk = walkProjects, resolveDir = null, now = () => new Date() }) { +export async function buildUsageIndex({ reportsRoot, channelsDir, previous = null, walk = sharedWalk, resolveDir = null, now = () => new Date() }) { const prevFiles = previous?.format === USAGE_INDEX_FORMAT && previous?.version === USAGE_INDEX_VERSION && previous.files && typeof previous.files === "object" ? previous.files : {}; const resolve = resolveDir ?? diff --git a/umtool/lib/projects.ts b/umtool/lib/projects.ts @@ -1,7 +1,7 @@ import path from "node:path"; import { REPORTS_ROOT } from "./paths"; import { KIND_META, PROJECT_KINDS, kindById } from "./projects/kinds.mjs"; -import { collapseFolders, foldersFor, walkProjects } from "./projects/walk.mjs"; +import { collapseFolders, foldersFor, forgetSharedWalks, sharedWalk } from "./projects/walk.mjs"; import { SONG_KIND } from "./projects/song.mjs"; import { openIndex, signRecord } from "./projects/index-db.mjs"; import { BROWSE_ROOT } from "./browse"; @@ -65,12 +65,12 @@ export const ALL_DECISION_KINDS: string[] = [ // renders next -- a project scaffolded a moment ago 404'd for up to a second. // --------------------------------------------------------------------------- type ProjectCaches = { - walk: { at: number; refs: ProjectRef[] } | null; + /** Retired (the walk's memo is projects/walk.mjs sharedWalk's, on globalThis too). */ + walk?: null; summary: Map<string, { sig: string; value: ProjectSummary }>; decision: Map<string, { sig: string; value: Decision[]; failed?: boolean }>; }; const CACHES = ((globalThis as { __umtoolProjectCaches?: ProjectCaches }).__umtoolProjectCaches ??= { - walk: null, summary: new Map(), decision: new Map(), }); @@ -99,17 +99,20 @@ export const indexHealth = () => ({ ...lastIndexHits }); /** Drop every cache. The CLI's `scan` and the e2e suite want this. */ export function invalidateProjects(): void { - CACHES.walk = null; + forgetSharedWalks(); summaryCache.clear(); decisionCache.clear(); } -export async function projectRefs(): Promise<ProjectRef[]> { - const hit = CACHES.walk; - if (hit && Date.now() - hit.at < 1000) return hit.refs; - const refs = (await walkProjects(REPORTS_ROOT)) as ProjectRef[]; - CACHES.walk = { at: Date.now(), refs }; - return refs; +/** + * EVERY PROJECT, from ONE walk at a time shared by every caller in this process (projects/walk.mjs sharedWalk; the + * regression of 17 Nov 2026: the live server pegged a core with hundreds of walks of the reports root in flight at + * once). A memo younger than a second answers; else the walk running now is shared, so a page that asks once per + * card, or many requests at once, cost one walk, never one each. `since` (lookUp's): only a walk that STARTED at or + * after it will do (one begun before may have passed a project made since). + */ +export async function projectRefs({ since = 0 }: { since?: number } = {}): Promise<ProjectRef[]> { + return (await sharedWalk(REPORTS_ROOT, { since })) as ProjectRef[]; } /** @@ -121,11 +124,12 @@ export async function projectRefs(): Promise<ProjectRef[]> { * a fresh walk is final, so a wrong address costs one walk, never a loop. */ async function lookUp<T>(find: (refs: ProjectRef[]) => T | null): Promise<T | null> { - const memo = !!CACHES.walk && Date.now() - CACHES.walk.at < 1000; + const asked = Date.now(); const got = find(await projectRefs()); - if (got !== null || !memo) return got; - CACHES.walk = null; - return find(await projectRefs()); + if (got !== null) return got; + // A miss: once more against a walk begun no earlier than this ask -- shared with every other miss meanwhile (one + // walk for any number of them, never one each), and final. + return find(await projectRefs({ since: asked })); } /** @@ -136,8 +140,7 @@ export async function indexPrunePlan(): Promise<{ ok: boolean; records: number; const ix = await indexHandle(); const st = ix.stats() as { ok: boolean; records: number; path: string | null; builtAt?: number }; if (!ix.ok) return { ok: false, records: 0, path: st.path ?? null, builtAt: null, stale: [] }; - CACHES.walk = null; - const live = new Set((await projectRefs()).map((p) => p.id)); + const live = new Set((await projectRefs({ since: Date.now() })).map((p) => p.id)); const stale = (ix.recent(10_000) as { id: string; title?: string }[]) .filter((r) => !live.has(r.id)) .map((r) => ({ id: r.id, title: typeof r.title === "string" ? r.title : null })); diff --git a/umtool/lib/projects/core.mjs b/umtool/lib/projects/core.mjs @@ -17,14 +17,15 @@ import path from "node:path"; import { REPORTS_ROOT } from "../paths.mjs"; import { PROJECT_KINDS, kindById } from "./kinds.mjs"; -import { collapseFolders, foldersFor, walkProjects } from "./walk.mjs"; +import { collapseFolders, foldersFor, sharedWalk } from "./walk.mjs"; export { PROJECT_KINDS, REPORTS_ROOT }; export const ROUTING_DECISION_KINDS = ["shadowed-name", "unroutable-name", "ambiguous-project"]; -export async function projectRefs(root = REPORTS_ROOT) { - return walkProjects(root); +/** Every project under `root`: the walk shared by every caller meanwhile (walk.mjs sharedWalk), never one each. */ +export async function projectRefs(root = REPORTS_ROOT, o = {}) { + return sharedWalk(root, o); } export async function summarise(p, root = REPORTS_ROOT) { @@ -117,19 +118,26 @@ export const decisionsAreComplete = (kind) => !!kindById(kind)?.decisions; * * An exact id wins; otherwise a UNIQUE basename does. Two projects answering to * one name is the reason ids are paths, so it is reported rather than resolved. + * @param {string} arg + * @param {string} [root] + * @returns {Promise<{ project?: any, ambiguous?: any[] }>} */ export async function resolveProject(arg, root = REPORTS_ROOT) { - const refs = await projectRefs(root); - const exact = refs.find((p) => p.id === arg); - if (exact) return { project: exact }; - // A path the user typed relative to the cwd, or absolute. - const abs = path.resolve(arg); - const byDir = refs.find((p) => p.dir === abs); - if (byDir) return { project: byDir }; - const named = refs.filter((p) => p.name === arg); - if (named.length === 1) return { project: named[0] }; - if (named.length > 1) return { ambiguous: named }; - return {}; + const asked = Date.now(); + const pick = (refs) => { + const exact = refs.find((p) => p.id === arg); + if (exact) return { project: exact }; + // A path the user typed relative to the cwd, or absolute. + const abs = path.resolve(arg); + const byDir = refs.find((p) => p.dir === abs); + if (byDir) return { project: byDir }; + const named = refs.filter((p) => p.name === arg); + if (named.length === 1) return { project: named[0] }; + if (named.length > 1) return { ambiguous: named }; + return null; + }; + // The shared walk; a miss asks once more of a walk begun no earlier than this ask (a project made a moment ago). + return pick(await projectRefs(root)) ?? pick(await projectRefs(root, { since: asked })) ?? {}; } export async function folders(root = REPORTS_ROOT) { diff --git a/umtool/lib/projects/sharedWalkMemo.test.mjs b/umtool/lib/projects/sharedWalkMemo.test.mjs @@ -0,0 +1,39 @@ +// The shared walk's memo is timed from when the walk FINISHED: a walk slower than the memo still answers the +// caller that asks right after it lands (timed from its start, every stage of a slow page walked again in turn). +import "../report/noLiveEditor.mjs"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { forgetSharedWalks, sharedWalk, walkStats } from "./walk.mjs"; + +test("a walk slower than the memo answers the next caller; `since` still asks for a fresh one", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "shared-walk-memo-")); + try { + for (let i = 0; i < 600; i += 1) { + const dir = path.join(root, `group-${i % 20}`, `piece-${i}`); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), "{}"); + } + forgetSharedWalks(); + // A memo shorter than the walk takes: find one by measuring. + const t0 = Date.now(); + await sharedWalk(root, { memoMs: 0 }); + const took = Date.now() - t0; + const memoMs = Math.max(5, Math.floor(took / 2)); + forgetSharedWalks(); + const before = walkStats.calls; + const a = await sharedWalk(root, { memoMs }); + const b = await sharedWalk(root, { memoMs }); + assert.equal(walkStats.calls - before, 1, `one walk for two callers in turn (walk ${took} ms, memo ${memoMs} ms)`); + assert.equal(a, b); + const asked = Date.now() + 1; + await new Promise((r) => setTimeout(r, 2)); + await sharedWalk(root, { memoMs: 60_000, since: asked }); + assert.equal(walkStats.calls - before, 2, "a caller that needs a walk begun after it asked gets a fresh one"); + } finally { + forgetSharedWalks(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/projects/song-ids.mjs b/umtool/lib/projects/song-ids.mjs @@ -10,7 +10,7 @@ // `pnpm build` does not catch it, because nothing prerenders. A page render // does. Hence a third module, which only the app's edge imports. import path from "node:path"; -import { walkProjects } from "./walk.mjs"; +import { sharedWalk } from "./walk.mjs"; import { SONG_KIND } from "./song.mjs"; /** @@ -27,7 +27,7 @@ import { SONG_KIND } from "./song.mjs"; * that is not it, which is worse than omitting it. */ export async function songIdsUnder(reportsRoot, browseRoot) { - const projects = await walkProjects(reportsRoot); + const projects = await sharedWalk(reportsRoot); return projects .filter((p) => p.kind === SONG_KIND && p.dir === path.join(browseRoot, p.name)) .map((p) => p.name) diff --git a/umtool/lib/projects/walk.mjs b/umtool/lib/projects/walk.mjs @@ -60,7 +60,21 @@ async function readDeclared(dir, names) { * reasonable thing to do -- but every real path is visited once, so a link that * points at an ancestor terminates instead of spinning. */ -export async function walkProjects(root, { maxDepth = MAX_DEPTH } = {}) { +/** How many walks were started and how many run at once now (the tests' and the load check's counter). */ +export const walkStats = { calls: 0, inFlight: 0, maxInFlight: 0 }; + +export async function walkProjects(root, o = {}) { + walkStats.calls += 1; + walkStats.inFlight += 1; + walkStats.maxInFlight = Math.max(walkStats.maxInFlight, walkStats.inFlight); + try { + return await walkOnce(root, o); + } finally { + walkStats.inFlight -= 1; + } +} + +async function walkOnce(root, { maxDepth = MAX_DEPTH } = {}) { const projects = []; const visited = new Set(); @@ -193,3 +207,38 @@ export function collapseFolders(nodes) { } return out; } + +/** + * ONE WALK AT A TIME PER ROOT, shared (the regression of 17 Nov 2026: hundreds of walks of the reports root in flight + * at once, one per request or per card). A walk that finished less than `memoMs` ago answers; else the walk running now is shared by + * every caller while it runs; else a new one is started, which every later caller shares. `since`: only a walk that + * STARTED at or after it will do (a lookup that missed asks again with the time it asked: one fresh walk for any + * number of misses, never one each). The state is on globalThis: Next bundles each route on its own, and a + * module-level memo would be one per bundle. + * + * @param {string} root + * @param {{ since?: number, memoMs?: number }} [o] + */ +export function sharedWalk(root, { since = 0, memoMs = 1000 } = {}) { + const all = (globalThis.__umtoolSharedWalks ??= new Map()); + const st = all.get(root) ?? { memo: null, inflight: null }; + all.set(root, st); + // Fresh for `memoMs` after the walk FINISHED (a walk slower than the memo is still an answer when it lands: timed + // from its start, every stage of one slow page walked again in turn); `since` compares when it STARTED. + if (st.memo && Date.now() - st.memo.done < memoMs && st.memo.at >= since) return Promise.resolve(st.memo.refs); + if (st.inflight && st.inflight.started >= since) return st.inflight.refs; + const started = Date.now(); + const refs = walkProjects(root).then((got) => { + if (!st.memo || st.memo.at <= started) st.memo = { at: started, done: Date.now(), refs: got }; + return got; + }).finally(() => { + if (st.inflight?.refs === refs) st.inflight = null; + }); + st.inflight = { started, refs }; + return refs; +} + +/** Drop the shared walks' memos (a project made or removed in this process: the next ask walks). */ +export function forgetSharedWalks() { + globalThis.__umtoolSharedWalks?.clear(); +} diff --git a/umtool/lib/report/clipsLive.mjs b/umtool/lib/report/clipsLive.mjs @@ -46,7 +46,7 @@ import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs" import { REPORTS_ROOT } from "../projects/core.mjs"; import { GLOBAL_CHANNELS_DIR, readManifest, clipsOf } from "../projects/report.mjs"; import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs"; -import { walkProjects } from "../projects/walk.mjs"; +import { sharedWalk } from "../projects/walk.mjs"; import { SHADOW_CHANNELS } from "umtool-report-to-video/sources"; import { ClipsNewError } from "./clipsNew.mjs"; import { WORDS_FILE, proposeProject } from "./reactions.mjs"; @@ -152,7 +152,7 @@ export function liveScanDoc(doc, now = new Date()) { } async function findProject(reportsRoot, slug) { - for (const p of await walkProjects(reportsRoot)) if (p.id === slug) return p; + for (const p of await sharedWalk(reportsRoot, { since: Date.now() })) if (p.id === slug) return p; return null; } diff --git a/umtool/lib/report/clipsNew.mjs b/umtool/lib/report/clipsNew.mjs @@ -31,7 +31,7 @@ import { REPORTS_ROOT } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { GLOBAL_CHANNELS_DIR } from "../projects/report.mjs"; import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs"; -import { walkProjects } from "../projects/walk.mjs"; +import { sharedWalk } from "../projects/walk.mjs"; import { ClipsError, WORDS_FILE, clipsSteps, loadRecording, recordingSegments } from "./reactions.mjs"; /** A refusal with the HTTP status the route answers. */ @@ -97,7 +97,7 @@ async function checkWords(file) { */ export async function projectsCovering({ reportsRoot, channel, video, span, duration }) { const out = []; - for (const p of await walkProjects(reportsRoot)) { + for (const p of await sharedWalk(reportsRoot, { since: Date.now() })) { if (!kindMakesTakes(p.kind)) continue; const doc = await readReactions(p.dir); if (!doc || doc.source?.channel !== channel || doc.source?.video !== video) continue; diff --git a/umtool/lib/report/readsQueue.mjs b/umtool/lib/report/readsQueue.mjs @@ -22,7 +22,7 @@ import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; import { REPORTS_ROOT } from "../projects/core.mjs"; import { withNotesLock } from "../annotations/store.mjs"; -import { addStep, cancelStep, getStep, listSteps, queueDirOf, readLease, resolveStep, retryStep, TERMINAL } from "../queue/store.mjs"; +import { addStep, cancelStep, getStep, queueDirOf, readLease, resolveStep, retryStep, TERMINAL } from "../queue/store.mjs"; import { projectReads } from "./reads.mjs"; import { itemRereadArgv } from "./readAgainArgv.mjs"; @@ -246,10 +246,10 @@ async function waitingReason(project, qdir, rows, o) { const { renderWaitSentence } = await import("./renderMode.mjs"); const render = renderWaitSentence(o.env ?? process.env); if (render) return `waiting: render mode holds the machine -- ${render}`; - const all = await listSteps(qdir); - const ours = new Set(rows.map((r) => r.qid)); - const running = all.map((s) => resolveStep(s)).find((s) => s.state === "running"); - if (running && ours.has(running.qid)) { + // ONLY this project's own steps are read (its batches'): never the whole queue store, which holds every old step + // of every project (the regression of 17 Nov 2026). What else the queue runs is the runner's to say (the route adds + // its own reason: what it waits for). + if (rows.some((x) => x.state === "running")) { const { readManifest } = await import("../projects/report.mjs"); const m = await readManifest(project.dir); for (const r of rows.filter((x) => x.state === "running")) { @@ -258,10 +258,7 @@ async function waitingReason(project, qdir, rows, o) { } return null; } - if (running) return `waiting behind ${running.qid} (${running.label}) -- the queue runs one step at a time`; - const first = all.find((s) => s.state === "queued" && !ours.has(s.qid) && s.seq < Math.min(...[...ours].map((q) => all.find((x) => x.qid === q)?.seq ?? Infinity))); - if (first) return `waiting behind ${first.qid} (${first.label}) -- the queue runs one step at a time`; - return "waiting for its turn: the app starts the next step when its own job runner is free"; + return "waiting for its turn: the queue runs one step at a time, when the app's job runner is free (umtool queue ls: what is ahead)"; } /** STOP: every step of the project's batches not started is cancelled; a running one finishes. */ @@ -358,14 +355,17 @@ export async function pickReads(project, { which = "new", only = null, token = n /** * The re-read step RUNNING now for one item of a project, or null -- the bench's single-post take op says it instead - * of asking a second read of the same post (lane reads-find): `{ qid, label }`. + * of asking a second read of the same post (lane reads-find): `{ qid, label }`. Only this project's own batches' + * steps are read, never the whole queue store. + * @param {{ id: string, dir: string }} project + * @param {string} item */ -export async function rereadRunningFor(projectId, item, o = {}) { +export async function rereadRunningFor(project, item, o = {}) { const qdir = queueDirFor(o); - for (const s of await listSteps(qdir)) { - const r = resolveStep(s); - if (r.state !== "running" || r.argv?.[0] !== "reads" || r.argv?.[1] !== projectId) continue; - if (r.argv[r.argv.indexOf("--one") + 1] === item) return { qid: r.qid, label: r.label }; + const rows = (await readBatches(project.dir)).flatMap((b) => b.rows).filter((r) => r.item === item && r.qid); + for (const qid of new Set(rows.map((r) => r.qid))) { + const s = await getStep(qdir, qid); + if (s && resolveStep(s).state === "running") return { qid, label: s.label }; } return null; } diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs @@ -13,7 +13,19 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { Readable } from "node:stream"; import { REPORTS_ROOT, inside, resolveInRoots } from "../paths.mjs"; -import { walkProjects } from "../projects/walk.mjs"; +import { sharedWalk } from "../projects/walk.mjs"; + +/** + * A project by its id, from the walk every request meanwhile shares (projects/walk.mjs sharedWalk) -- never a walk of + * its own per request (the regression of 17 Nov 2026). A miss asks once more of a walk begun no earlier than this + * ask, so a project made a moment ago is found; that answer is final. + * @param {string} projectId + */ +export async function projectOfId(projectId) { + const asked = Date.now(); + const find = (refs) => refs.find((p) => p.id === projectId) ?? null; + return find(await sharedWalk(REPORTS_ROOT)) ?? find(await sharedWalk(REPORTS_ROOT, { since: asked })); +} import { DEFAULT_VARIANT, FFMPEG_BIN, VARIANTS, WIN_EPS, probeDims, probeMedia, variantPaths } from "umtool-report-to-video/build-video"; import { rawCacheOf } from "./raw-cache.mjs"; import { isTakeId } from "./takes.mjs"; @@ -36,8 +48,7 @@ import { * @param {{ take?: string | null }} [opts] */ export async function resolveClip(projectId, clipId, { take = null } = {}) { - const projects = await walkProjects(REPORTS_ROOT); - const project = projects.find((p) => p.id === projectId); + const project = await projectOfId(projectId); if (!project) return { error: "no such project", status: 404 }; let manifest = await readManifest(project.dir); if (!manifest) return { error: "no manifest", status: 404 }; @@ -68,8 +79,7 @@ export async function resolveReport(projectId, variant = null) { if (!VARIANTS.includes(v)) { return { error: `variant must be one of ${VARIANTS.join(", ")}`, status: 400 }; } - const projects = await walkProjects(REPORTS_ROOT); - const project = projects.find((p) => p.id === projectId); + const project = await projectOfId(projectId); if (!project) return { error: "no such project", status: 404 }; const manifest = await readManifest(project.dir); if (!manifest) return { error: "no manifest", status: 404 }; @@ -676,8 +686,7 @@ export async function segmentHidesAsAsked(abs, clip, manifest) { * path either. */ export async function resolveClaim(projectId, claimId) { - const projects = await walkProjects(REPORTS_ROOT); - const project = projects.find((p) => p.id === projectId); + const project = await projectOfId(projectId); if (!project) return { error: "no such project", status: 404 }; const manifest = await readManifest(project.dir); if (!manifest) return { error: "no manifest", status: 404 }; diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs @@ -1096,8 +1096,8 @@ export async function pruneAfterBuild(projectDir, { built, log = () => {}, env = * own policy. Returns the total and each project's result. */ export async function pruneAllProjects({ reportsRoot = REPORTS_ROOT, dryRun = false, by = "cli", ...rest } = {}) { - const { walkProjects } = await import("../projects/walk.mjs"); - const refs = await walkProjects(reportsRoot); + const { sharedWalk } = await import("../projects/walk.mjs"); + const refs = await sharedWalk(reportsRoot, { since: Date.now() }); const results = []; for (const p of refs) { const has = await stat(/* turbopackIgnore: true */ takesDirOf(p.dir)).then((s) => s.isDirectory(), () => false); diff --git a/umtool/lib/report/takeVersions.mjs b/umtool/lib/report/takeVersions.mjs @@ -319,8 +319,8 @@ export async function pruneVersionsAll(opts = {}) { const reportsRoot = opts.reportsRoot ?? REPORTS_ROOT; let refs = opts.only; if (!refs) { - const { walkProjects } = await import("../projects/walk.mjs"); - refs = await walkProjects(reportsRoot); + const { sharedWalk } = await import("../projects/walk.mjs"); + refs = await sharedWalk(reportsRoot, { since: Date.now() }); } const { stat } = await import("node:fs/promises"); const results = []; diff --git a/umtool/lib/report/variantFork.mjs b/umtool/lib/report/variantFork.mjs @@ -40,7 +40,7 @@ // Plain ESM: the CLI runs it under bare node. import { copyFile, link, lstat, mkdir, readdir, readFile, rename, stat, symlink, writeFile } from "node:fs/promises"; import path from "node:path"; -import { isSegment, walkProjects } from "../projects/walk.mjs"; +import { isSegment, sharedWalk } from "../projects/walk.mjs"; import { renderHolds } from "./takeHousekeeping.mjs"; import { MANIFEST, PREVIEW, SHARED_OUT, hashText } from "./takeMaker.mjs"; import { isTakeId, listTakes, takesDirOf, TAKE_FILE } from "./takes.mjs"; @@ -220,7 +220,7 @@ export async function forkTakeAsVariant(project, takeId, { name = null, now = () export async function variantFamily(project, { root }) { const own = await readVariant(project.dir); const parentId = own?.variantOf ?? project.id; - const all = await walkProjects(root); + const all = await sharedWalk(root, { since: Date.now() }); const parent = all.find((p) => p.id === parentId) ?? null; const folder = path.posix.dirname(parentId); const beside = all.filter((p) => path.posix.dirname(p.id) === folder);