Archilyzer · Source

archilyzer

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

commit 07535c36ebe5d87e1dfc443b78aec7d7bbc94d22
parent 63fbbd30f78ae26c6de2adeed90193489ad6c272
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 21:10:46 -0500

one walk of the reports root at a time, shared; the inbox resolves its cards once (the regression S4 shipped with)

The live server pegged a core with hundreds of walks of the reports root in flight at once and never
answered `/`. The cause (app/page.tsx:141, components/projects/playable.ts:12, lib/projects.ts
projectRefs/lookUp): the home page resolves EVERY inbox card's project at once
(Promise.all -> playHrefOfPiece -> resolveProjectPath -> lookUp -> projectRefs). projectRefs kept a
one-second memo and no walk in flight: once the memo had expired -- a request taking over a second,
or a cold start -- every card started its own walk, all at once (300 cards: 300 walks, measured), and a
card whose project is gone cleared the memo and walked again. On ~3,200 directories each walk costs
real CPU, so the walks outlived the memo again: the next request did the same, and requests the
client had given up on kept running. The same per-request walk, with no memo at all, was in
lib/report/serve.mjs (resolveReport, resolveClip, resolveClaim: about 80 routes).

Fixed structurally:
- lib/projects/walk.mjs sharedWalk: ONE walk per root at a time, shared by every caller while it runs,
  a one-second memo, and `since` -- a lookup that missed asks once more of a walk begun no earlier than
  its ask, which every other miss meanwhile shares (one fresh walk for any number of misses). State on
  globalThis (Next bundles each route on its own).
- Every in-app walker goes through it: lib/projects.ts projectRefs and lookUp, lib/projects/core.mjs
  projectRefs and resolveProject, lib/report/serve.mjs (projectOfId), clipsLive, clipsNew, song-ids,
  variantFork, takePrune, takeVersions, the usage index, the cut-points route. A path that makes a
  project and then looks for it asks for a fresh walk (since: now).
- The inbox walks once and hands the projects to every card (playHrefOfPiece's `refs`).
- walkStats counts walks (and how many run at once); GET /api/queue?walks=1 reads it.

Tests: lib/inbox/walkLoad.test.ts (300 projects, 124 old queue steps, no reads batch): 300 cards at
once with the memo expired -> 1 walk (300 before), 50 missing projects -> 1, the home page's data 3
walks one at a time (bound 8), a project page's data <= 2, the reads GET / a runner tick / the bench's
409 check 0, 20 report requests at once -> 1. e2e/walk-load.spec.ts: the built server, idle, then `/`
and a project page, then idle again (walks flat, CPU near nothing).

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

Diffstat:
Mumtool/app/api/queue/route.ts | 4++++
Mumtool/app/api/report/cut-points/route.ts | 4++--
Mumtool/app/page.tsx | 5++++-
Mumtool/components/projects/playable.ts | 11++++++++---
Aumtool/e2e/walk-load.spec.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/walkLoad.test.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/ingredients/usedIn.mjs | 4++--
Mumtool/lib/projects.ts | 35+++++++++++++++++++----------------
Mumtool/lib/projects/core.mjs | 36++++++++++++++++++++++--------------
Mumtool/lib/projects/song-ids.mjs | 4++--
Mumtool/lib/projects/walk.mjs | 49++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/clipsLive.mjs | 4++--
Mumtool/lib/report/clipsNew.mjs | 4++--
Mumtool/lib/report/serve.mjs | 23++++++++++++++++-------
Mumtool/lib/report/takePrune.mjs | 4++--
Mumtool/lib/report/takeVersions.mjs | 4++--
Mumtool/lib/report/variantFork.mjs | 4++--
17 files changed, 369 insertions(+), 58 deletions(-)

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/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/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,36 @@ 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 younger than `memoMs` 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); + if (st.memo && Date.now() - st.memo.at < 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, 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/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);