// A SERVER SET PER WORKER (plans/e2e-speed.md S5). // // The suite ran on one worker because its shared state lives in ONE Next server // (the job registry, worker pool, scheduler, auto-runner and auto-queue state // are globalThis singletons there) over one data root. A directory per worker // cannot fix the singletons; a server per worker does. So each worker slot gets // its own set — the editor test server, the export dev server it links to, and // the Ollama stub — over its own data root (testPaths.ts): // // slot 0 the config's webServer entries, on the suite's own ports (PORT, // EXPORT_PORT, OLLAMA_STUB_PORT), over the editor directory — the // one-worker suite, unchanged // slot n started by globalSetup on `slotPorts(n)`, over // `.e2e-workers/w`, stopped by globalTeardown // // The worker finds its own: Playwright evaluates the config again in every // worker with TEST_PARALLEL_INDEX already set, so `baseURL`, // PLAYWRIGHT_BASE_URL, EXPORT_PORT and testPaths() are the slot's before any // spec is loaded. Specs change nothing. // // How many workers: E2E_WORKERS — a number (1–8), or `auto` for what memory // allows at start, floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB) capped // at 3. Unset: 1, until the full runs at 1, 2 and 3 workers say the suite is // green in parallel (then the default becomes `auto`). import { spawn, execFileSync, type ChildProcess } from "node:child_process"; import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs"; import net from "node:net"; import { join } from "node:path"; import { PORT_BASES, portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { EDITOR_ROOT, slotRoot, testPathsFor } from "./testPaths"; // THE TEST-ONLY SERVER ENVIRONMENT (the config's header documents each key). export const E2E_SERVER_ENV: Record = { E2E_TEST_ROUTES: "1", E2E_AUDIO_CHECK_INTERVAL_MS: "300", E2E_AUDIO_CHECK_SIZE_GATE: "4096", E2E_AUDIO_CHECK_INTERVAL_FLOOR_MS: "50", E2E_AUDIO_CHECK_RECOVER_STEP_MS: "100", E2E_AUDIO_CHECK_RECOVER_AFTER: "2", E2E_BACKOFF_BASE_MS: "20000", E2E_CLIP_WINDOW_GAP_MS: "2000", // remote-archive.spec's stub archive is on loopback (demo epic D1): the // editor connects a local archive only when told so on its own machine. ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1", E2E_AVAILABILITY_PROBE_GAP_MS: "0", // The pacing guard's BUILT-IN defaults (plans/pacing-guard.md) are off on // the test server — a spec's two fake X fetches would otherwise sit five // minutes apart, and every fake X fetch would need a fresh jar. A spec that // sets pacing.jobGapSeconds or social.x.maxCookieAgeMinutes in settings.json // gets exactly that (pacing.spec, x-session.spec). E2E_JOB_GAP_SECONDS: "0", E2E_X_MAX_COOKIE_AGE_MINUTES: "0", // X's SITTINGS (common/lib/xSitting.ts) are off on the test server: its fake // X jobs run many to one corpus with no cookie refresh between them, and of // both kinds. X's job cap (6 an hour) is NOT off. Honoured only beside // E2E_TEST_ROUTES=1 (common/jobs/networkGuard.ts e2eSittingsOff). E2E_X_SITTINGS: "off", E2E_LIVE_CHECK: "skip", WRANGLER_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-wrangler.mjs"), ARCHILYZER_BRANCH: "main", CLOUDFLARE_API_TOKEN: "e2e-fake-token-never-sent", EXPORT_NEXT_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-next.mjs"), }; /** The file naming a slot's fake Bluesky (common/social/blueskyEndpoints.ts). */ export function blueskyOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-bluesky-origin"); } /** The file naming a slot's fake Wayback Machine (common/lib/waybackClient.ts; wayback-pages.spec). */ export function waybackOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-wayback-origin"); } /** The file naming a slot's fake archive.today (common/lib/archives/archiveTodayClient.ts; archive-today-pages.spec). */ export function archiveTodayOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-archive-today-origin"); } /** The synthetic cookies a slot's fake "Refresh cookies" browser hands back (common/social/fakeXProfileBrowser.ts; cookies-screen.spec). */ export function xProfileCookiesFixtureFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-x-profile-cookies.json"); } /** The saved thread pages a slot's forum fetcher reads (forumFixtureLoader.ts; forum-resume.spec). */ export function forumFixtureDir(transcriptsDir: string): string { return join(transcriptsDir, ".forum-fixture"); } /** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */ export function umtoolOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-umtool-origin"); } /** The slot's recorded Odysee page reads (browser-lookup.spec writes it). */ export function odyseePageFixtureFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-odysee-pages.json"); } /** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */ export const E2E_DIST_DIR = ".next/e2e"; const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites"); const DEFAULT_SETTINGS = join(EDITOR_ROOT, "e2e", "fixtures", "test-settings.default.json"); export type E2EMode = "start" | "dev"; /** An environment to read (process.env, or a test's plain object). */ export type Env = Readonly>; export function resolveE2EMode(env: Env = process.env): E2EMode { const raw = (env.E2E_MODE ?? "").trim().toLowerCase(); if (raw === "" || raw === "start") return "start"; if (raw === "dev") return "dev"; throw new Error(`E2E_MODE=${env.E2E_MODE} is not a mode: use start (the default) or dev`); } // ------------------------------------------------------------------ workers export const AUTO_WORKER_CAP = 3; export const MAX_WORKERS = 8; export const WORKER_ESTIMATE_MB = 1500; function memAvailableMb(): number | null { try { const m = /^MemAvailable:\s+(\d+)\s*kB/m.exec(readFileSync("/proc/meminfo", "utf8")); return m ? Math.floor(Number(m[1]) / 1024) : null; } catch { return null; } } /** * How many workers (= server sets) this run uses. `E2E_WORKERS`: a number, or * `auto` — floor((MemAvailable − floor) / 1.5 GB), 1 to 3. Unset: 1. */ export function resolveWorkers( env: Env = process.env, readAvailable: () => number | null = memAvailableMb, ): number { const raw = (env.E2E_WORKERS ?? "").trim().toLowerCase(); if (raw === "" || raw === "1") return 1; if (raw === "auto") { const avail = readAvailable(); const floorRaw = Number(env.HEAVY_MIN_FREE_MB); const floor = env.HEAVY_MIN_FREE_MB != null && env.HEAVY_MIN_FREE_MB !== "" && floorRaw >= 0 ? floorRaw : 6000; if (avail == null) return 1; return Math.max(1, Math.min(AUTO_WORKER_CAP, Math.floor((avail - floor) / WORKER_ESTIMATE_MB))); } const n = Number(raw); if (!Number.isInteger(n) || n < 1) throw new Error(`E2E_WORKERS=${env.E2E_WORKERS}: a number of workers, or auto`); return Math.min(MAX_WORKERS, n); } // ------------------------------------------------------- a focused run // Options of `playwright test` that take a value (1.59, `playwright test --help`). const VALUE_OPTIONS = new Set([ "--browser", "-c", "--config", "--global-timeout", "-j", "--workers", "--max-failures", "--output", "--repeat-each", "--reporter", "--retries", "--run-agents", "--timeout", "--trace", "--tsconfig", "--ui-host", "--ui-port", "--update-source-method", ]); // …that narrow WHICH tests run (with or without a value). const FILTER_OPTIONS = new Set([ "-g", "--grep", "--grep-invert", "--project", "--last-failed", "--only-changed", "--shard", "--test-list", "--test-list-invert", ]); // …whose value is optional, given only as one of these words. const OPTIONAL_VALUES: Record> = { "--debug": new Set(["inspector", "cli"]), "-u": new Set(["all", "changed", "missing", "none"]), "--update-snapshots": new Set(["all", "changed", "missing", "none"]), }; /** * Whether this `playwright test` command line narrows the run — a spec file or * a filter. Playwright applies those to TOP-LEVEL projects only: a `teardown` * project runs whole, so a focused run must not make the serial project one * (`pnpm e2e pacing.spec.ts` would run every @serial file). Unsure means * focused, which only gives up the ordering. */ export function isFocusedRun(argv: readonly string[] = process.argv): boolean { const at = argv.indexOf("test"); if (at < 0) return true; for (let i = at + 1; i < argv.length; i++) { const arg = argv[i]; const name = arg.startsWith("-") ? arg.split("=")[0] : null; if (name == null) return true; // a positional: a spec filter if (FILTER_OPTIONS.has(name)) return true; if (arg.includes("=")) continue; if (VALUE_OPTIONS.has(name)) i++; else if (OPTIONAL_VALUES[name]?.has(argv[i + 1] ?? "")) i++; } return false; } // -------------------------------------------------------------------- ports export type SlotPorts = { editor: number; export: number; ollama: number }; // The Fetch standard's "bad ports" at or above 3000: a browser refuses them, // and so does `next start` ("Bad port: "5060" is reserved for sip"). Worktree // #20's block (50xx) has two of them where slot 1 would sit. export const UNSAFE_PORTS: ReadonlySet = new Set([ 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080, ]); /** * A slot's three ports. Slot 0 is the suite's own (common/lib/ports.mjs, with * the worktree's offset). Slot n takes the next three from the unused top of * the worktree's block — from `x060` up, skipping a bad port — so no other * worktree's ports, and no other suite's, are ever touched. */ export function slotPorts(slot: number, env: Env = process.env): SlotPorts { if (slot <= 0) { return { editor: portFor("PORT", env), export: portFor("EXPORT_PORT", env), ollama: portFor("OLLAMA_STUB_PORT", env), }; } const offset = portFor("PORT", env) - PORT_BASES.PORT; const usable: number[] = []; for (let p = PORT_BASES.PORT + 49 + offset; usable.length < 3 * slot; p++) { if (!UNSAFE_PORTS.has(p)) usable.push(p); } const [editor, exportPort, ollama] = usable.slice(3 * (slot - 1)); return { editor, export: exportPort, ollama }; } // ------------------------------------------------------------------ servers export type ServerSpec = { name: "editor" | "export" | "ollama"; /** A shell command line, run in EDITOR_ROOT. */ command: string; env: Record; /** Ready once this answers. */ url: string; }; /** The three servers of a slot — the one definition the config and globalSetup share. */ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env): ServerSpec[] { const ports = slotPorts(slot, env); const paths = testPathsFor(slotRoot(slot)); const editorEnv: Record = { ...E2E_SERVER_ENV }; // Where a spec names its fake Bluesky's origin (capture-posts.spec): the // slot's own test data, so two slots never share one. editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir); // The same for the fake Wayback Machine wayback-pages.spec starts // (lib/waybackClient.ts: the process's client sends web.archive.org there). editorEnv.E2E_WAYBACK_ORIGIN_FILE = waybackOriginFile(paths.transcriptsDir); // The same for the fake archive.today archive-today-pages.spec starts // (lib/archives/archiveTodayClient.ts; no archive session browser under it). editorEnv.E2E_ARCHIVE_TODAY_ORIGIN_FILE = archiveTodayOriginFile(paths.transcriptsDir); // The forum fetcher's saved pages (forum-resume.spec): the slot's own // directory (common/social/forumFixtureLoader.ts). editorEnv.E2E_FORUM_FIXTURE_DIR = forumFixtureDir(paths.transcriptsDir); // The fake browser Refresh cookies reads the X profile through while the // file exists (common/social/fakeXProfileBrowser.ts; cookies-screen.spec). editorEnv.E2E_FAKE_X_PROFILE_COOKIES_FILE = xProfileCookiesFixtureFile(paths.transcriptsDir); // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts). editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir); // settings.privacy's opt-in rule files (demo epic D4, useSourceRules): the // slot's own, which privacy-audit.spec writes. Their default is the // operator's ~/.config/archilyzer, which a suite must never read. editorEnv.SOURCE_SCRUB_FILE = join(paths.transcriptsDir, ".privacy", "source-scrub.txt"); editorEnv.SOURCE_DENYLIST_FILE = join(paths.transcriptsDir, ".privacy", "source-denylist.txt"); // The browser lookup's recorded page reads (browser-lookup.spec): set on // every slot, so the e2e server never opens a headless browser on the // network — the player-page opener refuses under it too. editorEnv.E2E_ODYSEE_PAGE_FIXTURE = odyseePageFixtureFile(paths.transcriptsDir); // Render mode's state (common/lib/renderPriority.mjs): the slot's own, so // its heartbeat never ends — and its /jobs never shows — the machine's. editorEnv.RENDER_PRIORITY_FILE = join(paths.transcriptsDir, ".render-priority.json"); // umtool's reports as the space scan sizes them (controller/spaceScan.ts): // the slot's own, so a scan never walks the operator's ~/reports. editorEnv.SPACE_SCAN_REPORTS_DIR = join(paths.transcriptsDir, ".space-scan-reports"); // A start-mode server runs the stamped build (shared, read-only); a second // `next dev` needs a dist dir of its own (Next locks `/dev/lock`). if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR; else if (mode === "dev" && slot > 0) editorEnv.E2E_NEXT_DIST_DIR = `.next/e2e-dev-w${slot}`; if (slot > 0) { Object.assign(editorEnv, { PORT: String(ports.editor), EXPORT_PORT: String(ports.export), OLLAMA_STUB_PORT: String(ports.ollama), E2E_DATA_ROOT: paths.root, }); } return [ { name: "editor", command: mode === "start" ? "pnpm start:test" : "pnpm dev:test", env: editorEnv, url: `http://localhost:${ports.editor}`, }, { // The export server stays `next dev` in both modes (a static export // bakes test-settings.json in at build time; see the config). Its own // dist dir per slot: Next allows one `next dev` per dist dir, and the // export suite's server may be running beside this suite. name: "export", command: `pnpm --filter export run dev --port ${ports.export}`, env: { SETTINGS_FILE: paths.settingsFile, SITES_DIR: EXPORT_SITES_DIR, SITE_ID: "testsite", E2E_NEXT_DIST_DIR: slot > 0 ? `.next/e2e-editor-w${slot}` : ".next/e2e-editor", }, url: `http://localhost:${ports.export}`, }, { name: "ollama", command: `node ${join(EDITOR_ROOT, "e2e", "fixtures", "ollama-stub.mjs")}`, env: { OLLAMA_STUB_PORT: String(ports.ollama) }, // /api/tags is the endpoint digestApps.ts probes, so readiness and the // app's reachability check agree. url: `http://127.0.0.1:${ports.ollama}/api/tags`, }, ]; } // ------------------------------------------------- slot servers (globalSetup) export type SlotHandle = { slot: number; stop: () => Promise }; function portBusy(port: number): Promise { return new Promise((resolve) => { const server = net.createServer(); server.once("error", (err: NodeJS.ErrnoException) => resolve(err.code === "EADDRINUSE")); server.listen({ port, host: "0.0.0.0", exclusive: true }, () => server.close(() => resolve(false))); }); } function culprit(port: number): string { try { const out = execFileSync("ss", ["-ltnpH", `sport = :${port}`], { encoding: "utf8" }); const pid = /pid=(\d+)/.exec(out)?.[1]; return pid ? `pid ${pid} (kill ${pid})` : "owner unknown — ss -ltnp"; } catch { return "owner unknown — ss -ltnp"; } } async function waitUntilUp(url: string, child: ChildProcess, timeoutMs: number, log: string): Promise { const t0 = Date.now(); for (;;) { if (child.exitCode != null || child.signalCode != null) { throw new Error(`e2e servers: ${url} exited before it answered (${child.exitCode ?? child.signalCode}); see ${log}`); } try { const res = await fetch(url, { signal: AbortSignal.timeout(5_000) }); await res.arrayBuffer().catch(() => {}); return; } catch { /* not up yet */ } if (Date.now() - t0 > timeoutMs) throw new Error(`e2e servers: ${url} did not answer in ${timeoutMs / 1000}s; see ${log}`); await new Promise((r) => setTimeout(r, 500)); } } function stopGroup(child: ChildProcess): Promise { return new Promise((resolve) => { if (child.exitCode != null || child.signalCode != null || !child.pid) return resolve(); const kill = (sig: NodeJS.Signals) => { try { process.kill(-child.pid!, sig); // the whole group: pnpm, next, its workers } catch { /* gone */ } }; const hard = setTimeout(() => kill("SIGKILL"), 10_000); child.once("exit", () => { clearTimeout(hard); resolve(); }); kill("SIGTERM"); }); } /** * Start slot `slot`'s servers over its own data root and wait until each * answers. Refuses (naming the pid) a port that is already bound: nothing * else may answer as this slot's server. */ export async function startSlot(slot: number, mode: E2EMode, timeoutMs = 120_000): Promise { const specs = slotServers(slot, mode); const ports = slotPorts(slot); for (const p of [ports.editor, ports.export, ports.ollama]) { if (await portBusy(p)) { throw new Error(`e2e servers: slot ${slot}'s port ${p} is already in use — ${culprit(p)}; a leftover from a killed run?`); } } const paths = testPathsFor(slotRoot(slot)); mkdirSync(join(paths.transcriptsDir, "channels"), { recursive: true }); if (!existsSync(paths.settingsFile)) copyFileSync(DEFAULT_SETTINGS, paths.settingsFile); const children: ChildProcess[] = []; const stop = async () => { await Promise.all(children.map(stopGroup)); }; try { await Promise.all( specs.map(async (s) => { const log = join(paths.root, `server-${s.name}.log`); const fd = openSync(log, "w"); const child = spawn("sh", ["-c", s.command], { cwd: EDITOR_ROOT, env: { ...process.env, ...s.env }, stdio: ["ignore", fd, fd], detached: true, // its own process group, so stop() reaps the tree }); closeSync(fd); children.push(child); await waitUntilUp(s.url, child, timeoutMs, log); }), ); } catch (err) { await stop(); throw err; } armWatchdog(children.flatMap((c) => (c.pid ? [c.pid] : []))); return { slot, stop }; } // A run killed outright (SIGKILL, an OOM) never reaches globalTeardown, and a // slot's servers are process groups of their own — they would outlive it, and // the next run would find their ports bound. So each slot gets a watchdog, as // detached as its servers: it polls the runner and, once the runner is gone, // takes the groups down (TERM, then KILL) and exits. It also exits once the // groups are gone (a clean teardown). const WATCHDOG = ` const [runner, ...groups] = process.argv.slice(1).map(Number); const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } }; const kill = (sig) => { for (const g of groups) { try { process.kill(-g, sig); } catch {} } }; const tick = setInterval(() => { if (!groups.some((g) => alive(g))) process.exit(0); if (alive(runner)) return; clearInterval(tick); kill("SIGTERM"); setTimeout(() => { kill("SIGKILL"); process.exit(0); }, 5000); }, 2000); `; function armWatchdog(groups: number[]): void { if (!groups.length) return; const dog = spawn(process.execPath, ["-e", WATCHDOG, String(process.pid), ...groups.map(String)], { stdio: "ignore", detached: true, }); dog.unref(); }