Archilyzer · Source

archilyzer

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

commit 0d81c67b86da1f9351118fbbe32511ba39d49d1c
parent 6197affb74821d5581f4192b503dad163385126d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 13:56:06 -0400

e2e: S4 — the suites run side by side under a memory-weighted heavy slot; pnpm e2e:all

Each package's suite queues under its own name (`--name e2e-editor`,
`e2e-export`, `e2e-homepage`, `e2e-umtool`): the same suite never runs twice,
different suites run at once. The heavy slot admits by memory: a job that
declares an estimate (an e2e suite 1.5 GB; a build capped by systemd-run's
MemoryMax, its cap) runs while MemAvailable − Σ(running estimates) ≥
HEAVY_MIN_FREE_MB, one `next build` at a time stays hard, and a job that
declares nothing (a render, a hand `pnpm heavy`, an uncapped publish build)
runs alone, as before. Weighted jobs hold heavy-queue.lock shared, so an older
checkout's gate (exclusive) still waits for them; the line, the build slot and
the job tickets sit beside it. The legacy `e2e` name keeps the old order.

A suite builds what it serves before its own admission (`--prebuild`), so a
rebuild is admitted as a build, not inside the suite's 1.5 GB. The editor
suite's export dev server gets its own dist dir (Next allows one `next dev` per
dist dir). `pnpm e2e:all` runs one lane per package and prints one summary.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
M.gitignore | 2++
MAGENTS.md | 33+++++++++++++++++++++------------
MENVIRONMENT.md | 8++++----
MWORKTREES.md | 140++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mcommon/lib/envVars.ts | 8++++----
Meditor/package.json | 2+-
Meditor/playwright.config.ts | 4++++
Mexport/next.config.ts | 6++++++
Mexport/package.json | 8++++----
Mhomepage/package.json | 2+-
Mpackage.json | 1+
Ascripts/e2e-all.mjs | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/e2e-all.test.mjs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/e2e-stamp.mjs | 8+++++---
Mscripts/queue-lock.mjs | 646+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mscripts/queue-lock.test.mjs | 267++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/package.json | 2+-
17 files changed, 1302 insertions(+), 164 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -125,6 +125,8 @@ yarn-error.log* /editor/test-export-changelog.md /editor/playwright-report/ /editor/test-results/ +# pnpm e2e:all's per-suite logs (scripts/e2e-all.mjs) +/test-results-e2e-all/ /editor/blob-report/ # An operator's symlink out of the repo (plans/FACTS.md, "editor/content is a # symlink out of the repo"): Tailwind's source detection follows it, Turbopack diff --git a/AGENTS.md b/AGENTS.md @@ -20,12 +20,16 @@ To run more than one checkout at once, use git worktrees with per-worktree non-c ports. `pnpm wt add <branch>` creates one; `pnpm wt list` shows each worktree's port block. `pnpm dev:editor` auto-assigns ports per worktree, so dev servers run in parallel. -**e2e does not run in parallel.** Every e2e entry point takes a machine-global lock, so one -suite runs at a time and the rest wait. If `pnpm e2e` prints `waiting for the e2e queue — -held by …` and sits there, **that is working as intended, not a hung command** — the serial -suite is ~24 minutes. A run that wins the lock but finds its ports already bound aborts and -names the offending pid, instead of silently driving another session's server. Bypasses: -`E2E_QUEUE=0`, `E2E_PORT_CHECK=0`, `E2E_QUEUE_TIMEOUT=<seconds>`. +**Each e2e suite runs one at a time; different suites run side by side.** Every e2e entry +point takes a machine-global lock named for its package (`e2e-editor`, `e2e-export`, +`e2e-homepage`, `e2e-umtool`), so the same suite never runs twice at once and the second +run waits. If `pnpm e2e` prints `waiting for the e2e queue — held by …` and sits there, +**that is working as intended, not a hung command** — the editor suite is ~20 minutes. A +run that wins the lock but finds its ports already bound aborts and names the offending +pid, instead of silently driving another session's server. Bypasses: `E2E_QUEUE=0`, +`E2E_PORT_CHECK=0`, `E2E_QUEUE_TIMEOUT=<seconds>`. **`pnpm e2e:all` runs every suite at +once** (one lane per package, each through its own script and lock) and prints one summary; +per-suite logs land in `test-results-e2e-all/`. **`pnpm e2e` at the root is the EDITOR suite**, whatever spec name you append to it: the script is `pnpm --filter editor run e2e`, so `pnpm run e2e clip-bench.spec.ts` takes the @@ -51,12 +55,17 @@ specs that judge a clip read it through `e2e/capabilities.ts` and skip themselve capability is a directory that exists, decided once by the builder — not re-guessed per spec. -**Heavy work takes the heavy slot.** e2e, the publish stages' `next build` and video renders -share ONE machine-global slot and start only above a 6000 MB MemAvailable floor (two OOMs -took the desktop session down). e2e and the publish builds take it on their own; a render or -any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting for the heavy slot -— held by …` or `heavy: waiting for memory …` is the gate working, not a hang. Bypasses: -`HEAVY=0`, `HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`. +**Heavy work takes the heavy slot.** e2e, `next build`s and video renders go through ONE +machine-global slot that admits by memory (two OOMs took the desktop session down). A job +that declares an estimate — an e2e suite 1.5 GB (`--estimate`), a build capped by +`systemd-run -p MemoryMax=5G` its cap — runs beside others while MemAvailable minus the +running jobs' estimates stays ≥ 6000 MB, and **one `next build` at a time stays hard**. A +job that declares nothing (a render, a hand `pnpm heavy -- <cmd>`, an uncapped publish +build) runs ALONE above the 6000 MB floor, as before. e2e and the builds take it on their +own; a render or any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting +for the heavy slot — held by …`, `heavy: waiting for memory …` or `heavy: waiting for the +build slot …` is the gate working, not a hang. Bypasses: `HEAVY=0`, +`HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`. See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, and the shared-data caveat. diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -184,16 +184,16 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one |---|---|---|---| | `E2E_TEST_ROUTES` | off | `1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else. | editor/app/api/test/_guard.ts, editor/instrumentation.ts | | `E2E_MODE` | `start` | `start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`. | editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs | -| `E2E_NEXT_DIST_DIR` | `.next` | The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server. | editor/next.config.ts | +| `E2E_NEXT_DIST_DIR` | `.next` | The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir). | editor/next.config.ts, export/next.config.ts | | `E2E_BUILD_CHECKED` | — | Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again. | editor/playwright.config.ts, umtool/playwright.config.ts | | `E2E_QUEUE` | on | `0` skips the machine-global e2e queue (the port check still runs). | scripts/queue-lock.mjs | | `E2E_PORT_CHECK` | on | `0` skips the pre-run check that the suite's ports are free. | scripts/queue-lock.mjs | | `E2E_QUEUE_TIMEOUT` | wait forever | Seconds to wait for the queue before giving up. | scripts/queue-lock.mjs | | `E2E_PORT_GRACE_MS` | `3000` | How long the port check waits for a just-freed port. | scripts/queue-lock.mjs | -| `E2E_QUEUE_LOCK_FILE` | one per machine | The queue's lock file; the queue's own tests point it elsewhere. | scripts/queue-lock.mjs | +| `E2E_QUEUE_LOCK_FILE` | one per machine | The legacy queue's lock file (a named suite's is `<file>.<name>`); the queue's own tests point it elsewhere. | scripts/queue-lock.mjs | | `QUEUE_LOCK_HELD` | — | Set by the queue for the command it runs, so a nested wrapper passes through. | scripts/queue-lock.mjs | -| `HEAVY_HELD` | — | Set by the heavy slot for the command it runs, so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through. | scripts/queue-lock.mjs | -| `HEAVY_LOCK_FILE` | one per machine | The heavy slot's lock file; the gate's own tests point it elsewhere. | scripts/queue-lock.mjs | +| `HEAVY_HELD` | — | Set by the heavy slot for the command it runs (`build` inside a build), so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through — except a build inside a non-build, which still waits for the build slot. | scripts/queue-lock.mjs | +| `HEAVY_LOCK_FILE` | one per machine | The heavy slot's lock file (its line, build slot and job tickets sit beside it: `.admit`, `.build`, `.jobs/`); the gate's own tests point it elsewhere. | scripts/queue-lock.mjs | | `HEAVY_MEMINFO_FILE` | `/proc/meminfo` | Where the memory floor reads MemAvailable; the gate's tests hand it a fake. | scripts/queue-lock.mjs | | `HEAVY_POLL_MS` | `5000` | How often a run waiting for the memory floor re-reads it. | scripts/queue-lock.mjs | | `PLAYWRIGHT_BASE_URL` | `http://localhost:<PORT>` | The editor test server's URL; the worktree injector sets it. | editor/playwright.config.ts, editor/e2e/baseUrl.ts | diff --git a/WORKTREES.md b/WORKTREES.md @@ -4,8 +4,10 @@ Git worktrees let you check out several branches at once, each in its own direct sharing one `.git`. This repo supports running multiple worktrees **simultaneously** by giving each worktree its own non-colliding block of ports. -That applies to **dev servers**. **e2e suites are deliberately serialized**: one run at a -time across the whole machine, everyone else waits in line. See [The e2e queue](#the-e2e-queue). +That applies to **dev servers**. **e2e suites are queued per suite**: one run of each suite +(editor, export, homepage, umtool) at a time across the whole machine — a second run of the +same suite waits in line — while different suites run side by side, admitted by memory. +See [The e2e queue](#the-e2e-queue). The helper is `scripts/worktree.mjs`, exposed as `pnpm wt`. @@ -58,37 +60,70 @@ pnpm wt add feature-x # creates ../feature-x, prints its ports, seeds s # terminal B (../feature-x): pnpm dev:editor -> http://localhost:3101 # both run at once, no EADDRINUSE -# e2e is queued, not parallel — start it anywhere, it waits its turn: +# the same suite is queued — start it anywhere, it waits its turn: pnpm e2e # main: runs now cd ../feature-x && pnpm e2e # feature-x: prints "waiting …", starts when main finishes +# a different suite runs beside it (when memory allows): +pnpm --filter umtool run e2e # main: runs now, beside the editor suite ``` ## The e2e queue -Every e2e entry point takes a machine-global lock before it runs, so **exactly one suite -runs at a time**. Starting a second one is not an error — it prints who holds the queue and -blocks until its turn: +Every e2e entry point takes a machine-global lock named for its package, so **one run of +each suite at a time** — the same suite started again waits; a different suite does not. +Starting a second run of a suite is not an error — it prints who holds the queue and blocks +until its turn: ``` queue-lock: waiting for the e2e queue — held by yt-dlp-transcript-browser (main, pid 2401494) for 4m12s - (one e2e run at a time, machine-wide; E2E_QUEUE=0 to bypass) + (one run of each e2e suite at a time, machine-wide; E2E_QUEUE=0 to bypass) queue-lock: still waiting (5m00s) ``` -**A long wait here is normal, not a hang** — the serial suite is ~24 minutes. - -Queued: `pnpm e2e`, `pnpm e2e:sharded` (including its `docker build`), export's `e2e`, -`e2e:hub`, `e2e:2origin`, `e2e:report`, and homepage's and umtool's `e2e`. Wrapping is at the *package* -level, so `pnpm --filter editor run e2e` is covered too, and a nested invocation passes -through instead of deadlocking. Not queued on purpose: a raw `pnpm --filter editor exec -playwright test`, the escape hatch for debugging a single spec, and the `e2e:ui` +**A long wait here is normal, not a hang** — the editor suite is ~20 minutes. + +| Suite | Queue (`--name`) | Entry points | +|---|---|---| +| editor | `e2e-editor` | `pnpm e2e` (root), `pnpm --filter editor run e2e` | +| export | `e2e-export` | export's `e2e`, `e2e:hub`, `e2e:2origin`, `e2e:report` — one at a time among themselves | +| homepage | `e2e-homepage` | homepage's `e2e` | +| umtool | `e2e-umtool` | umtool's `e2e` | +| sharded | `e2e` | `pnpm e2e:sharded` (including its `docker build`) — the legacy one-for-all name, and it runs ALONE in the heavy slot | + +Their ports (`common/lib/ports.mjs`) and fixture files are disjoint, which is what lets two +different suites run at once. The editor suite's own export dev server builds into +`export/.next/e2e-editor` (`E2E_NEXT_DIST_DIR`), because Next allows one `next dev` per +dist dir and the export suite's server may be running beside it. Wrapping is at the +*package* level, so `pnpm --filter editor run e2e` is covered too, and a nested invocation +passes through instead of deadlocking. Not queued on purpose: a raw `pnpm --filter editor +exec playwright test`, the escape hatch for debugging a single spec, and the `e2e:ui` interactive sessions. +A suite's order of business: its queue, the port preflight, its start-mode build +(`--prebuild`: `scripts/e2e-stamp.mjs ensure <pkg>`, a 5 GB build admitted as one — editor +and umtool), then its own admission to the heavy slot (`--estimate 1500`), then the run. + +### Every suite at once: `pnpm e2e:all` + +```sh +pnpm e2e:all # editor, export (×4), homepage, umtool — side by side +pnpm e2e:all --only editor,umtool # a package, or one suite id (export-hub, …) +``` + +`scripts/e2e-all.mjs` starts one lane per package at once (export's four configs run in +order in theirs), each suite through its own package script — the queue, the preflight, the +build and every bypass behave exactly as when it runs alone. It prints a line as each suite +starts and ends, writes each suite's output to `test-results-e2e-all/<suite>.log`, and ends +with one summary: per suite passed / failed / flaky / skipped (from the suite's own json +report — only one written by this run counts), its test time, how long it waited for its +turn, and every failed test by `file:line`; then the wall time against the sum of the +suites' own. Exit 0 only when every suite passed. The release gate's e2e in one command. + ### Root `pnpm e2e` is the editor's, and only the editor's The root script is `pnpm --filter editor run e2e`, so a spec name appended to it goes to the **editor's** playwright: `pnpm run e2e clip-bench.spec.ts` matches nothing there, holds -the machine-global lock for the whole ~24-minute editor suite, and never runs the spec you +the editor suite's machine-global lock for the whole ~20-minute suite, and never runs the spec you meant. Every other package's suite goes through its own filter: | Suite | Command | @@ -104,9 +139,10 @@ data — `umtool/song/paths.mjs`'s `SONG_DATA`, which is `SONG_DIR` if set and directory — the fixture is an empty-state copy with the heavy audio symlinked in — and a machine without the data builds an empty fixture whose song-data specs skip. -The lock lives at `<git-common-dir>/e2e-queue.lock`, which resolves to the same file from -every worktree. The kernel releases it when the holding process's fd closes, so a `kill -9` -or a crashed run can never strand the queue — there is no stale-lock recovery to run. +The locks live at `<git-common-dir>/<name>-queue.lock` (`e2e-editor-queue.lock`, …), which +resolve to the same files from every worktree. The kernel releases a lock when the holding +process's fd closes, so a `kill -9` or a crashed run can never strand the queue — there is no +stale-lock recovery to run. ### Aborting on a busy port @@ -148,46 +184,68 @@ Verify the queue with `pnpm test:scripts`. ## The heavy slot (`pnpm heavy`) -An e2e suite, a `next build` and a video render each want several GB, and two of them at -once is how this machine OOMed (taking the desktop session with it). So all three go -through ONE more machine-global lock, the **heavy slot**, and start only once -`/proc/meminfo`'s MemAvailable is at least a floor (6000 MB): +An e2e suite, a `next build` and a video render each want several GB, and the wrong two at +once is how this machine OOMed (taking the desktop session with it). So all of them go +through ONE more machine-global gate, the **heavy slot**, which admits a job **by memory**: + +- A job that **declares an estimate** is admitted while + `MemAvailable − Σ(estimates of the jobs already running) ≥ HEAVY_MIN_FREE_MB` (6000 MB). + An e2e suite declares 1.5 GB (`--estimate 1500` in each package's script); a `next build` + run under `systemd-run … -p MemoryMax=5G` declares its cap (the e2e build does). +- **One `next build` at a time stays a hard rule**, whatever the memory: a build waits for + the build slot, including one started from inside an admitted run. +- A job that **declares nothing runs ALONE**, once MemAvailable is at least the floor — as + every heavy job did before release 24: a render, a hand `pnpm heavy -- <cmd>`, a publish + stage's (uncapped) build. It waits for the running jobs to finish, and none is admitted + beside it. ```sh -pnpm heavy -- <cmd…> # any heavy command, by hand -pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … # a render +pnpm heavy -- <cmd…> # alone (no estimate) +pnpm heavy -- systemd-run --user --scope -p MemoryMax=5G -p MemorySwapMax=0 \ + pnpm --filter editor exec next build # a build, 5 GB: beside suites, never beside a build +node scripts/queue-lock.mjs --heavy --estimate 2000 -- <cmd…> # declare an estimate by hand +pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … # a render (alone) ``` Who takes it, and in what order: -- **Every e2e entry point** (the same ones the e2e queue covers): the heavy slot FIRST, - then the e2e queue. One order everywhere, so nothing can deadlock — and a heavy command - that starts another (`pnpm heavy -- pnpm e2e`, a build stage run by an e2e suite's - editor) passes straight through (`HEAVY_HELD`), as a nested e2e run always has. +- **Every e2e entry point**: its suite's queue first, then its build (if any), then its own + admission. A heavy command that starts another (`pnpm heavy -- pnpm e2e`, a build stage + run by an e2e suite's editor) passes straight through (`HEAVY_HELD`) — except a build, + which still takes the build slot. The legacy `e2e` queue (the sharded runner) keeps the + old order: the slot first, then the queue. - **The publish stages' `next build`** — a site's, the hub's, the homepage's - (`common/publish/build.ts`, `heavyGated`). The wait shows in the stage's log, and a - Cancel still stops the build (the gate forwards SIGTERM). In a docker-runner container - the slot is the container's own; the floor still reads the host's memory, which - throttles a fan-out when the host runs low. + (`common/publish/build.ts`, `heavyGated`): uncapped, so alone. The wait shows in the + stage's log, and a Cancel still stops the build (the gate forwards SIGTERM). In a + docker-runner container the slot is the container's own; the floor still reads the host's + memory, which throttles a fan-out when the host runs low. - **A render**, by hand, as above. -The slot is taken before the floor is waited for, so nobody slips in while the holder -waits for memory. A waiter is told what it waits behind: +Waiting is in one line, so nobody slips in ahead: the job at the head keeps its place while +it waits for memory. A waiter is told what it waits behind: ``` -queue-lock: waiting for the heavy slot — held by feature-x (feature-x, pid 31337) for 2m10s: playwright test -heavy: waiting for memory — 4210 MB available, the floor is 6000 MB +queue-lock: waiting for the heavy slot — held by feature-x (feature-x, pid 31337, 1500 MB) for 2m10s: playwright test +heavy: waiting for memory — 7200 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB +heavy: waiting for the build slot — one next build at a time; running: main (main, pid 4242, 5120 MB, a build) … +heavy: admitted beside 1 running job (9100 MB available, 1500 MB promised to them, the floor is 6000 MB) ``` -The lock is `<git-common-dir>/heavy-queue.lock`, released by the kernel like the e2e one. -A machine whose MemTotal is under the floor is told so and runs; with no usable `flock` the -gate warns and runs on the floor alone — it is a safety net, not a correctness lock. +The pieces sit in the git common dir: `heavy-queue.lock` (the slot — held SHARED by an +admitted weighted job, EXCLUSIVELY by a job that runs alone, so an older checkout's copy of +the gate, which always takes it exclusively, still waits for every new-style job and is +never joined by one), `heavy-queue.lock.admit` (the line), `heavy-queue.lock.build` (the +build slot) and `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its +estimate and what it is; a ticket whose process is gone is dropped). The kernel releases +every lock when its holder's fd closes. A machine whose MemTotal is under the floor is told +so and runs one job at a time; with no usable `flock` the gate warns and runs on the floor +alone — it is a safety net, not a correctness lock. | Variable | Effect | |---|---| | `HEAVY=0` | Skip the heavy slot AND the memory floor | -| `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off) | -| `HEAVY_TIMEOUT=<seconds>` | Give up waiting (slot, then floor) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | +| `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off; the build rule still holds) | +| `HEAVY_TIMEOUT=<seconds>` | Give up waiting (line, slot, memory) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | ### A render and the transcription lane diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -182,16 +182,16 @@ const DECLARED: EnvVarDecl[] = [ // ── test: harnesses, fakes and test-mode branches ────────────────────── { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." }, { name: "E2E_MODE", audience: "test", default: "`start`", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs", doc: "`start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`." }, - { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server." }, + { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts, export/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir)." }, { name: "E2E_BUILD_CHECKED", audience: "test", default: "—", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts", doc: "Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again." }, { name: "E2E_QUEUE", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the machine-global e2e queue (the port check still runs)." }, { name: "E2E_PORT_CHECK", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the pre-run check that the suite's ports are free." }, { name: "E2E_QUEUE_TIMEOUT", audience: "test", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds to wait for the queue before giving up." }, { name: "E2E_PORT_GRACE_MS", audience: "test", default: "`3000`", readBy: "scripts/queue-lock.mjs", doc: "How long the port check waits for a just-freed port." }, - { name: "E2E_QUEUE_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The queue's lock file; the queue's own tests point it elsewhere." }, + { name: "E2E_QUEUE_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The legacy queue's lock file (a named suite's is `<file>.<name>`); the queue's own tests point it elsewhere." }, { name: "QUEUE_LOCK_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the queue for the command it runs, so a nested wrapper passes through." }, - { name: "HEAVY_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the heavy slot for the command it runs, so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through." }, - { name: "HEAVY_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The heavy slot's lock file; the gate's own tests point it elsewhere." }, + { name: "HEAVY_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the heavy slot for the command it runs (`build` inside a build), so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through — except a build inside a non-build, which still waits for the build slot." }, + { name: "HEAVY_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The heavy slot's lock file (its line, build slot and job tickets sit beside it: `.admit`, `.build`, `.jobs/`); the gate's own tests point it elsewhere." }, { name: "HEAVY_MEMINFO_FILE", audience: "test", default: "`/proc/meminfo`", readBy: "scripts/queue-lock.mjs", doc: "Where the memory floor reads MemAvailable; the gate's tests hand it a fake." }, { name: "HEAVY_POLL_MS", audience: "test", default: "`5000`", readBy: "scripts/queue-lock.mjs", doc: "How often a run waiting for the memory floor re-reads it." }, { name: "PLAYWRIGHT_BASE_URL", audience: "test", default: "`http://localhost:<PORT>`", readBy: "editor/playwright.config.ts, editor/e2e/baseUrl.ts", doc: "The editor test server's URL; the worktree injector sets it." }, diff --git a/editor/package.json b/editor/package.json @@ -10,7 +10,7 @@ "build": "next build", "start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", "test": "tsx --test \"app/**/*.test.ts\"", - "e2e": "node ../scripts/queue-lock.mjs --ports PORT:3011,EXPORT_PORT:3010,OLLAMA_STUB_PORT:11435 -- playwright test", + "e2e": "node ../scripts/queue-lock.mjs --name e2e-editor --estimate 1500 --prebuild editor --ports PORT:3011,EXPORT_PORT:3010,OLLAMA_STUB_PORT:11435 -- playwright test", "e2e:ui": "playwright test --ui" }, "dependencies": { diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -240,6 +240,10 @@ export default defineConfig({ SETTINGS_FILE: exportSettingsFile, SITES_DIR: exportSitesDir, SITE_ID: "testsite", + // Its own dist dir: Next allows one `next dev` per dist dir, and the + // export suite's server may be running beside this suite (release 24, + // plans/e2e-speed.md S4 — each suite queues under its own name). + E2E_NEXT_DIST_DIR: ".next/e2e-editor", }, }, { diff --git a/export/next.config.ts b/export/next.config.ts @@ -9,6 +9,12 @@ const nextConfig: NextConfig = { // resolves outside the project and `next dev` fails to boot at all. Nothing // in this repo lives above the monorepo root, so pinning it costs nothing. turbopack: { root: path.join(__dirname, "..") }, + // The editor e2e suite's export dev server builds into `.next/e2e-editor`: + // Next refuses a second `next dev` over one dist dir (`<distDir>/dev/lock`), + // and since release 24 the export suite's own server can run beside it + // (plans/e2e-speed.md S4). Inside the ignored `.next/`, so Tailwind never + // scans it. Unset everywhere else. + distDir: process.env.E2E_NEXT_DIST_DIR || ".next", output: "export", trailingSlash: true, images: { unoptimized: true }, diff --git a/export/package.json b/export/package.json @@ -17,10 +17,10 @@ "start": "node scripts/serve-out.mjs out ${EXPORT_DEV_PORT:-3000}", "lint": "eslint", "test": "tsx --test \"app/**/*.test.ts\"", - "e2e": "node ../scripts/queue-lock.mjs --ports EXPORT_E2E_PORT:3020 -- playwright test", - "e2e:hub": "node ../scripts/queue-lock.mjs --ports HUB_PORT:3041 -- playwright test --config playwright.hub.config.ts", - "e2e:2origin": "node ../scripts/queue-lock.mjs --ports ORIGIN_B_PORT:4610,HUB_A_PORT:4611 -- playwright test --config playwright.2origin.config.ts", - "e2e:report": "node ../scripts/queue-lock.mjs --ports REPORT_SITE_E2E_PORT:3042 -- playwright test --config playwright.report.config.ts", + "e2e": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports EXPORT_E2E_PORT:3020 -- playwright test", + "e2e:hub": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports HUB_PORT:3041 -- playwright test --config playwright.hub.config.ts", + "e2e:2origin": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports ORIGIN_B_PORT:4610,HUB_A_PORT:4611 -- playwright test --config playwright.2origin.config.ts", + "e2e:report": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports REPORT_SITE_E2E_PORT:3042 -- playwright test --config playwright.report.config.ts", "build:report-fixture": "tsx e2e-report/stage.ts", "e2e:ui": "playwright test --ui", "deploy": "tsx ../common/bin/archilyzer.ts deploy site" diff --git a/homepage/package.json b/homepage/package.json @@ -14,7 +14,7 @@ "start": "serve out -l ${HOMEPAGE_PORT:-3031}", "lint": "eslint", "test": "tsx --test \"app/**/*.test.ts\"", - "e2e": "node ../scripts/queue-lock.mjs --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", + "e2e": "node ../scripts/queue-lock.mjs --name e2e-homepage --estimate 1500 --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", "e2e:ui": "playwright test --ui", "deploy": "tsx ../common/bin/archilyzer.ts deploy homepage" }, diff --git a/package.json b/package.json @@ -23,6 +23,7 @@ "heavy": "node scripts/queue-lock.mjs --heavy --", "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", + "e2e:all": "node scripts/e2e-all.mjs", "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", diff --git a/scripts/e2e-all.mjs b/scripts/e2e-all.mjs @@ -0,0 +1,245 @@ +#!/usr/bin/env node +// EVERY E2E SUITE, SIDE BY SIDE, ONE SUMMARY (release 24, plans/e2e-speed.md +// S4) — the release gate's e2e in one command: +// +// pnpm e2e:all [--only editor,umtool] [--logs <dir>] +// +// Each package's suite queues under its own name (`queue-lock.mjs --name +// e2e-<pkg>`), so they no longer wait for one another — only for the heavy +// slot, which admits each by its memory estimate (an e2e suite 1.5 GB; a +// start-mode rebuild is a 5 GB build, one at a time). This starts one LANE per +// package at once; a lane runs its package's suites in order (export has four +// configs, which share one queue). Every suite still goes through its own +// package script, so the queue, the port preflight, the start-mode build and +// every bypass (E2E_QUEUE=0, HEAVY=0, E2E_MODE=dev, …) behave exactly as when +// it is run alone. The wall time becomes the longest lane, not the sum. +// +// Output: one line as each suite starts and ends; each suite's full output in +// `<logs>/<suite>.log` (default `test-results-e2e-all/`, gitignored); then one +// summary — per suite: passed / failed / flaky / skipped from its own json +// report (only a report written by THIS run counts), its wall time, how long +// it waited for the queue and the slot, and every failed test by file:line. +// Exit 0 only when every suite exited 0. +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const SELF = fileURLToPath(import.meta.url); +export const REPO_ROOT = path.resolve(path.dirname(SELF), ".."); +export const DEFAULT_LOG_DIR = "test-results-e2e-all"; + +// The suites, by lane. `report` is the json reporter's outputFile, relative +// to the repo root (each config's `["json", { outputFile }]`). +export const LANES = Object.freeze([ + { pkg: "editor", suites: [{ id: "editor", script: "e2e", report: "editor/test-results/timings.json" }] }, + { + pkg: "export", + suites: [ + { id: "export", script: "e2e", report: "export/test-results/timings.json" }, + { id: "export-hub", script: "e2e:hub", report: "export/test-results-hub/timings.json" }, + { id: "export-2origin", script: "e2e:2origin", report: "export/test-results-2origin/timings.json" }, + { id: "export-report", script: "e2e:report", report: "export/test-results-report/timings.json" }, + ], + }, + { pkg: "homepage", suites: [{ id: "homepage", script: "e2e", report: "homepage/test-results/timings.json" }] }, + { pkg: "umtool", suites: [{ id: "umtool", script: "e2e", report: "umtool/test-results/timings.json" }] }, +]); + +/** The lanes `--only` names (a package, or a suite id); all of them by default. */ +export function selectLanes(only, lanes = LANES) { + if (!only || !only.length) return lanes; + const want = new Set(only); + const out = []; + for (const lane of lanes) { + const suites = want.has(lane.pkg) ? lane.suites : lane.suites.filter((s) => want.has(s.id)); + if (suites.length) out.push({ ...lane, suites }); + } + const known = new Set(lanes.flatMap((l) => [l.pkg, ...l.suites.map((s) => s.id)])); + const unknown = only.filter((o) => !known.has(o)); + if (unknown.length) throw new Error(`e2e:all: no suite named ${unknown.join(", ")} (one of: ${[...known].join(", ")})`); + return out; +} + +/** + * A Playwright json report → counts and failures. `startedAfter` (ms) rejects + * a report left by an earlier run: a suite that died before writing its own + * would otherwise be summarised from last week's. + */ +export function readReport(report, { startedAfter = 0 } = {}) { + if (!report?.stats) return null; + const start = Date.parse(report.stats.startTime ?? ""); + if (startedAfter && !(start >= startedAfter - 1000)) return null; + const failures = []; + const walk = (suite) => { + for (const spec of suite.specs ?? []) { + for (const t of spec.tests ?? []) { + if (t.status === "unexpected") { + failures.push(`${spec.file ?? suite.file ?? "?"}:${spec.line ?? "?"} ${spec.title}`); + } + } + } + for (const child of suite.suites ?? []) walk({ ...child, file: child.file ?? suite.file }); + }; + for (const s of report.suites ?? []) walk(s); + return { + passed: Number(report.stats.expected) || 0, + failed: Number(report.stats.unexpected) || 0, + flaky: Number(report.stats.flaky) || 0, + skipped: Number(report.stats.skipped) || 0, + durationMs: Number(report.stats.duration) || 0, + startMs: Number.isFinite(start) ? start : null, + failures, + }; +} + +export function humanMs(ms) { + if (ms == null || !Number.isFinite(ms)) return "—"; + const s = Math.max(0, Math.round(ms / 1000)); + return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`; +} + +/** + * The summary, from one result per suite: + * `{id, code, launchedMs, endedMs, report: readReport(…)|null, log}`. + */ +export function renderSummary(results, { wallMs } = {}) { + const rows = [["suite", "result", "passed", "failed", "flaky", "skipped", "tests", "waited", "log"]]; + for (const r of results) { + const rep = r.report; + const result = r.code === 0 ? "ok" : rep ? `FAIL (exit ${r.code})` : `FAIL (exit ${r.code}, no report)`; + const waited = rep?.startMs != null && r.launchedMs != null ? rep.startMs - r.launchedMs : null; + rows.push([ + r.id, + result, + rep ? String(rep.passed) : "—", + rep ? String(rep.failed) : "—", + rep ? String(rep.flaky) : "—", + rep ? String(rep.skipped) : "—", + rep ? humanMs(rep.durationMs) : humanMs(r.endedMs - r.launchedMs), + humanMs(waited), + r.log ?? "", + ]); + } + const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length))); + const lines = rows.map((row) => row.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd()); + lines.splice(1, 0, widths.map((w) => "-".repeat(w)).join(" ")); + const total = (k) => results.reduce((n, r) => n + (r.report?.[k] ?? 0), 0); + const sumMs = results.reduce((n, r) => n + (r.report?.durationMs ?? r.endedMs - r.launchedMs), 0); + const ok = results.every((r) => r.code === 0); + lines.push(""); + lines.push( + `e2e:all ${ok ? "PASSED" : "FAILED"} — ${total("passed")} passed, ${total("failed")} failed, ` + + `${total("flaky")} flaky, ${total("skipped")} skipped; wall ${humanMs(wallMs)} ` + + `(the suites' own times add up to ${humanMs(sumMs)})`, + ); + const failed = results.filter((r) => r.report?.failures?.length); + for (const r of failed) { + lines.push(""); + lines.push(`${r.id} — failed:`); + for (const f of r.report.failures.slice(0, 20)) lines.push(` ${f}`); + if (r.report.failures.length > 20) lines.push(` … and ${r.report.failures.length - 20} more`); + } + return `${lines.join("\n")}\n`; +} + +// ------------------------------------------------------------------ the run + +function parseArgs(argv) { + const opts = { only: null, logs: DEFAULT_LOG_DIR }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--only") opts.only = String(argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean); + else if (a === "--logs") opts.logs = argv[++i]; + else if (a === "--help" || a === "-h") opts.help = true; + else throw new Error(`e2e:all: unknown argument '${a}'`); + } + return opts; +} + +const children = new Set(); + +function runSuite(lane, suite, logDir) { + const log = path.join(logDir, `${suite.id}.log`); + const out = fs.openSync(log, "w"); + const launchedMs = Date.now(); + process.stdout.write(`e2e:all: ${suite.id} started (pnpm --filter ${lane.pkg} run ${suite.script}) — ${path.relative(REPO_ROOT, log)}\n`); + // Through the worktree wrapper, so a worktree's suites use its own ports. + const child = spawn( + process.execPath, + [path.join(REPO_ROOT, "scripts", "worktree.mjs"), "run", "--", "pnpm", "--filter", lane.pkg, "run", suite.script], + { cwd: REPO_ROOT, stdio: ["ignore", out, out], env: process.env }, + ); + children.add(child); + return new Promise((resolve) => { + const done = (code) => { + children.delete(child); + fs.closeSync(out); + const endedMs = Date.now(); + let report = null; + try { + report = readReport(JSON.parse(fs.readFileSync(path.join(REPO_ROOT, suite.report), "utf8")), { + startedAfter: launchedMs, + }); + } catch { + /* no report: the suite died before writing one */ + } + const counts = report ? `${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped` : "no report"; + process.stdout.write( + `e2e:all: ${suite.id} ${code === 0 ? "done" : `FAILED (exit ${code})`} in ${humanMs(endedMs - launchedMs)} — ${counts}\n`, + ); + resolve({ id: suite.id, code, launchedMs, endedMs, report, log: path.relative(REPO_ROOT, log) }); + }; + child.on("error", () => done(1)); + child.on("exit", (code, signal) => done(signal ? 1 : (code ?? 1))); + }); +} + +async function runLane(lane, logDir) { + const results = []; + for (const suite of lane.suites) results.push(await runSuite(lane, suite, logDir)); + return results; +} + +async function main(argv) { + const opts = parseArgs(argv); + if (opts.help) { + process.stdout.write("usage: pnpm e2e:all [--only <pkg|suite>,…] [--logs <dir>]\n"); + return 0; + } + const lanes = selectLanes(opts.only); + const logDir = path.resolve(REPO_ROOT, opts.logs); + fs.mkdirSync(logDir, { recursive: true }); + // A terminal's Ctrl-C reaches every suite already (one process group); a + // SIGTERM sent to this process alone is passed on, so nothing is orphaned. + for (const sig of ["SIGTERM", "SIGHUP"]) { + process.on(sig, () => { + for (const c of children) { + try { + c.kill(sig); + } catch { + /* already gone */ + } + } + }); + } + process.on("SIGINT", () => process.stdout.write("\ne2e:all: SIGINT — waiting for the suites to stop\n")); + const t0 = Date.now(); + const results = (await Promise.all(lanes.map((lane) => runLane(lane, logDir)))).flat(); + process.stdout.write(`\n${renderSummary(results, { wallMs: Date.now() - t0 })}`); + for (const r of results.filter((x) => x.code !== 0 && !x.report)) { + const tail = fs.readFileSync(path.join(REPO_ROOT, r.log), "utf8").trimEnd().split("\n").slice(-12); + process.stdout.write(`\n${r.id} — last lines of ${r.log}:\n${tail.map((l) => ` ${l}`).join("\n")}\n`); + } + return results.every((r) => r.code === 0) ? 0 : 1; +} + +if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF)) { + main(process.argv.slice(2)).then( + (code) => process.exit(code), + (err) => { + process.stderr.write(`${err?.message ?? err}\n`); + process.exit(2); + }, + ); +} diff --git a/scripts/e2e-all.test.mjs b/scripts/e2e-all.test.mjs @@ -0,0 +1,84 @@ +// Tests for `pnpm e2e:all` (scripts/e2e-all.mjs): which suites, what a report +// says, and the one summary. The run itself is the suites' own scripts. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { LANES, REPO_ROOT, readReport, renderSummary, selectLanes } from "./e2e-all.mjs"; + +test("every lane names its package's real e2e scripts and their json reports", () => { + for (const lane of LANES) { + const scripts = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, lane.pkg, "package.json"), "utf8")).scripts; + for (const s of lane.suites) { + assert.ok(scripts[s.script]?.includes("queue-lock.mjs"), `${lane.pkg} run ${s.script} is not a queued suite`); + const config = /--config (\S+)/.exec(scripts[s.script])?.[1] ?? "playwright.config.ts"; + const text = fs.readFileSync(path.join(REPO_ROOT, lane.pkg, config), "utf8"); + const out = path.relative(lane.pkg, s.report); + assert.ok(text.includes(`["json", { outputFile: "${out}" }]`), `${lane.pkg}/${config} does not write ${out}`); + } + } + // Every queued e2e script of every package is in a lane. + for (const pkg of ["editor", "export", "homepage", "umtool"]) { + const scripts = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, pkg, "package.json"), "utf8")).scripts; + const queued = Object.keys(scripts).filter((k) => scripts[k].includes("queue-lock.mjs")); + const lane = LANES.find((l) => l.pkg === pkg); + assert.deepEqual(lane.suites.map((s) => s.script).sort(), queued.sort(), pkg); + } +}); + +test("--only picks packages or single suites, and refuses a name it does not know", () => { + assert.deepEqual(selectLanes(null).map((l) => l.pkg), ["editor", "export", "homepage", "umtool"]); + assert.deepEqual( + selectLanes(["umtool", "export-hub"]).map((l) => [l.pkg, l.suites.map((s) => s.id)]), + [["export", ["export-hub"]], ["umtool", ["umtool"]]], + ); + assert.throws(() => selectLanes(["editr"]), /no suite named editr/); +}); + +const report = (over = {}) => ({ + stats: { startTime: "2026-10-10T10:00:00.000Z", duration: 125_000, expected: 10, unexpected: 1, flaky: 1, skipped: 2, ...over }, + suites: [ + { + file: "a.spec.ts", + specs: [{ title: "passes", file: "a.spec.ts", line: 3, tests: [{ status: "expected" }] }], + suites: [{ specs: [{ title: "breaks", file: "a.spec.ts", line: 9, tests: [{ status: "unexpected" }] }] }], + }, + ], +}); + +test("readReport counts, lists failures by file:line, and rejects an earlier run's report", () => { + const r = readReport(report()); + assert.deepEqual( + { ...r, failures: r.failures }, + { + passed: 10, + failed: 1, + flaky: 1, + skipped: 2, + durationMs: 125_000, + startMs: Date.parse("2026-10-10T10:00:00.000Z"), + failures: ["a.spec.ts:9 breaks"], + }, + ); + assert.equal(readReport(report(), { startedAfter: Date.parse("2026-10-10T11:00:00.000Z") }), null); + assert.ok(readReport(report(), { startedAfter: Date.parse("2026-10-10T09:59:00.000Z") })); + assert.equal(readReport({}), null); +}); + +test("the summary: one row per suite, totals, the wall against the sum, and the failures", () => { + const launched = Date.parse("2026-10-10T09:58:00.000Z"); + const out = renderSummary( + [ + { id: "editor", code: 1, launchedMs: launched, endedMs: launched + 300_000, report: readReport(report()), log: "test-results-e2e-all/editor.log" }, + { id: "homepage", code: 0, launchedMs: launched, endedMs: launched + 60_000, report: readReport(report({ unexpected: 0, flaky: 0 })), log: "h.log" }, + { id: "umtool", code: 1, launchedMs: launched, endedMs: launched + 20_000, report: null, log: "u.log" }, + ], + { wallMs: 300_000 }, + ); + assert.match(out, /^suite\s+result\s+passed\s+failed\s+flaky\s+skipped\s+tests\s+waited\s+log$/m); + assert.match(out, /^editor\s+FAIL \(exit 1\)\s+10\s+1\s+1\s+2\s+2m05s\s+2m00s\s+test-results-e2e-all\/editor\.log$/m); + assert.match(out, /^homepage\s+ok\s+10\s+0\s+0\s+2\s+2m05s/m); + assert.match(out, /^umtool\s+FAIL \(exit 1, no report\)\s+—\s+—\s+—\s+—\s+20s\s+—\s+u\.log$/m); + assert.match(out, /e2e:all FAILED — 20 passed, 1 failed, 1 flaky, 4 skipped; wall 5m00s \(the suites' own times add up to 4m30s\)/); + assert.match(out, /editor — failed:\n {2}a\.spec\.ts:9 breaks/); +}); diff --git a/scripts/e2e-stamp.mjs b/scripts/e2e-stamp.mjs @@ -20,9 +20,11 @@ // // THE BUILD GOES THROUGH THE HEAVY SLOT under a 5 GB cap (AGENTS.md, "Heavy // work takes the heavy slot"): `queue-lock.mjs --heavy -- systemd-run --user -// --scope -p MemoryMax=5G -p MemorySwapMax=0 …`. Inside an e2e run the slot is -// already this run's (HEAVY_HELD), so it passes through; run by hand it waits -// for the slot and the memory floor like any build. +// --scope -p MemoryMax=5G -p MemorySwapMax=0 …`, its cap its estimate: admitted +// beside running e2e suites when memory allows, never beside another build. A +// suite's `queue-lock.mjs --prebuild` runs `ensure` before the suite's own +// admission (release 24); a rebuild from inside a running suite (the config's +// check, the tree moved since) waits only for the build slot. // // IT BUILDS INTO ITS OWN DIRECTORY, never `.next`: the primary checkout's // `.next` is what the live editor and umtool serve from, and replacing it under diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs @@ -1,38 +1,52 @@ #!/usr/bin/env node -// Global e2e queue: exactly one e2e run at a time, machine-wide — and the -// HEAVY SLOT: one heavy job (an e2e run, a `next build`, a video render) at a -// time, machine-wide, started only above a free-memory floor. +// Global e2e queue: one run of each e2e SUITE at a time, machine-wide — and +// the HEAVY SLOT: heavy jobs (an e2e run, a `next build`, a video render) +// admitted by memory, one build at a time, machine-wide. // -// Every checkout of this repo shares one lock file, so a suite started in a -// second worktree waits for the first to finish instead of racing it. That is -// both a resource decision (the serial suite is ~24 min and e2e:sharded fans -// out to 4 containers) and a correctness one: playwright.config's +// Every checkout of this repo shares one lock file per suite, so a suite +// started in a second worktree waits for the first to finish instead of racing +// it. Each package's suite queues under its own name (`--name e2e-editor`, +// `e2e-export`, `e2e-homepage`, `e2e-umtool`; release 24, plans/e2e-speed.md +// S4): their ports (common/lib/ports.mjs) and fixtures are disjoint, so two +// DIFFERENT suites run side by side, and the same suite never runs twice. The +// unnamed default (`e2e`, the sharded runner) keeps the old one-for-all queue. +// The queue is also a correctness lock: playwright.config's // `reuseExistingServer: !CI` means a second run that finds port 3011 already // bound silently drives the *other* worktree's test server, and resetData() // then wipes that session's fixtures with no error at all. // -// node scripts/queue-lock.mjs [--name e2e] [--ports PORT:3011,...] -- <cmd...> -// node scripts/queue-lock.mjs --heavy -- <cmd...> (`pnpm heavy -- <cmd>`) +// node scripts/queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] +// [--ports PORT:3011,...] -- <cmd...> +// node scripts/queue-lock.mjs --heavy [--estimate <MB>] [--build] -- <cmd...> +// (`pnpm heavy -- <cmd>`) // // THE HEAVY SLOT. Two OOMs on this machine (2026-10-08) took Xwayland and dbus // with them: two `next build`s, or a build beside an e2e suite, or a render -// beside either. So every heavy entry point goes through `withHeavy`: one -// machine-wide lock (`heavy-queue.lock`, beside the e2e one), and once it is -// held, a wait until /proc/meminfo's MemAvailable is at least -// HEAVY_MIN_FREE_MB (6000 by default). The slot is taken FIRST, then the floor -// is waited for, so a later contender cannot slip in while the holder waits -// for memory. Callers: +// beside either. So every heavy entry point goes through `withHeavy`, which +// waits in one machine-wide line and admits a job by its declared memory (see +// "the weighted admission" below): a job with an estimate runs beside others +// while MemAvailable − Σ(running estimates) ≥ HEAVY_MIN_FREE_MB (6000 by +// default) and no other build runs; a job with none runs ALONE once +// MemAvailable is at least the floor, as every heavy job did before. Callers: // - every e2e entry point (this file's CLI and run-sharded-e2e.mjs, through -// `withQueue`): the heavy slot first, then the e2e queue. One order -// everywhere, so nesting cannot deadlock: an e2e run holds both, and a -// `pnpm heavy -- pnpm e2e` passes through its own slot (HEAVY_HELD). -// - the publish stages' `next build` (common/publish/build.ts, heavyGated). -// - a render: `pnpm heavy -- node umtool/report-to-video/build-video.mjs …`. +// `withQueue`): a named suite takes its queue, builds what it serves +// (`--prebuild`), then is admitted with its `--estimate` (1500 MB in the +// package scripts). The legacy `e2e` name takes the slot first, then the +// queue. A command run inside the slot that starts another heavy one +// passes through (HEAVY_HELD) — except a build, which still takes the +// build slot. +// - the publish stages' `next build` (common/publish/build.ts, heavyGated): +// uncapped, so alone. +// - the e2e build (scripts/e2e-stamp.mjs): capped at 5 GB by systemd-run, +// and a cap is an estimate — a build beside suites, never beside a build. +// - a render: `pnpm heavy -- node umtool/report-to-video/build-video.mjs …`: +// alone. // Bypasses: HEAVY=0 (no slot, no floor), HEAVY_MIN_FREE_MB=0 (no floor), // HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue; // the floor still applies. A machine whose MemTotal is under the floor is not -// made to wait forever: it is told, and runs. The slot is a safety net, not a -// correctness lock: with no usable `flock` it warns and runs on the floor alone. +// made to wait forever: it is told, and runs one job at a time. The slot is a +// safety net, not a correctness lock: with no usable `flock` it warns and runs +// on the floor alone. // // WHY THE LOCK IS HELD BY A SEPARATE CHILD. // flock(1) deliberately keeps its lock fd open across exec — that is what the @@ -98,6 +112,12 @@ function parseArgv(argv) { portSpec: null, hold: false, heavy: false, + // The heavy slot's admission (S4): a job's memory estimate in MB, whether + // it is a `next build`, and the package whose e2e build to ensure first. + // Unset means "infer from the command" (resolveJob). + estimateMb: undefined, + build: undefined, + prebuild: null, // Unset unless --timeout: the e2e queue defaults it from E2E_QUEUE_TIMEOUT, // the heavy slot from HEAVY_TIMEOUT. timeoutMs: undefined, @@ -111,6 +131,15 @@ function parseArgv(argv) { else if (f === "--ports") opts.portSpec = flags[++i]; else if (f === "--timeout") opts.timeoutMs = Number(flags[++i]) * 1000; else if (f === "--port-grace") opts.portGraceMs = Number(flags[++i]); + else if (f === "--estimate") { + opts.estimateMb = Number(flags[++i]); + if (!(opts.estimateMb > 0)) { + process.stderr.write(`queue-lock: --estimate wants a size in MB, not '${flags[i]}'\n`); + process.exit(2); + } + } + else if (f === "--build") opts.build = true; + else if (f === "--prebuild") opts.prebuild = flags[++i]; else { process.stderr.write(`queue-lock: unknown flag '${f}'\n`); process.exit(2); @@ -172,7 +201,9 @@ function lockFileFor(name) { name === HEAVY_NAME ? process.env.HEAVY_LOCK_FILE : process.env.E2E_QUEUE_LOCK_FILE; - if (override) return override; + // The queue's override names the legacy queue's file; a named suite's sits + // beside it (`<file>.e2e-editor`), so the tests can run two suites at once. + if (override) return name === HEAVY_NAME || name === "e2e" ? override : `${override}.${name}`; const dir = gitOut(["rev-parse", "--path-format=absolute", "--git-common-dir"]) ?? os.tmpdir(); @@ -266,11 +297,17 @@ function runHolder() { // ------------------------------------------------------------ acquire/release -function flockArgs(lock, timeoutMs) { +function flockArgs(lock, timeoutMs, { shared = false, nonblock = false } = {}) { // -F/--no-fork execs directly, so the spawned process IS the holder and we // can talk to it over its own stdio. const args = ["-F"]; - if (timeoutMs > 0) { + // -s: a SHARED hold of the heavy slot, which is how a weighted job runs + // beside others while an exclusive one (an undeclared job, or a run of an + // older copy of this file, which takes it exclusively) waits for them all. + if (shared) args.push("-s"); + if (nonblock) { + args.push("-n", "-E", String(PROBE_HELD_EXIT)); + } else if (timeoutMs > 0) { args.push("-w", String(Math.ceil(timeoutMs / 1000)), "-E", String(WAIT_TIMEOUT_EXIT)); } args.push(lock, process.execPath, SELF, "--hold"); @@ -279,9 +316,10 @@ function flockArgs(lock, timeoutMs) { // Non-blocking probe, purely so the banner can name who is ahead of us. A // false "free" here is harmless: the blocking acquire below is the real gate. -function isHeld(lock) { +function isHeld(lock, { shared = false } = {}) { try { - execFileSync("flock", ["-n", "-E", String(PROBE_HELD_EXIT), lock, "true"], { + const mode = shared ? ["-s"] : []; + execFileSync("flock", [...mode, "-n", "-E", String(PROBE_HELD_EXIT), lock, "true"], { stdio: "ignore", }); return false; @@ -298,8 +336,8 @@ function missingFlock() { ); } -function acquire(lock, timeoutMs) { - const holder = spawn("flock", flockArgs(lock, timeoutMs), { +function acquire(lock, timeoutMs, mode = {}) { + const holder = spawn("flock", flockArgs(lock, timeoutMs, mode), { stdio: ["pipe", "pipe", "inherit"], }); return new Promise((resolve, reject) => { @@ -329,6 +367,8 @@ function acquire(lock, timeoutMs) { } if (code === WAIT_TIMEOUT_EXIT) { reject(Object.assign(new Error("queue-lock: timed out waiting"), { timeout: true })); + } else if (code === PROBE_HELD_EXIT && mode.nonblock) { + reject(Object.assign(new Error("queue-lock: held"), { busy: true })); } else { reject(new Error(`queue-lock: flock exited ${code} before acquiring`)); } @@ -457,20 +497,23 @@ async function preflight(ports, graceMs) { // ---------------------------------------------------------------- run + wait -function runCommand(cmd, name, { forwardTerm = false } = {}) { +function runCommand(cmd, name, { forwardTerm = false, env = null } = {}) { return new Promise((resolve) => { const child = spawn(cmd[0], cmd.slice(1), { stdio: "inherit", // A heavy-only run (name null) leaves QUEUE_LOCK_HELD alone: it holds no // e2e queue for a nested e2e run to pass through. - env: name ? { ...process.env, [HELD_ENV]: name } : { ...process.env }, + env: env ?? (name ? { ...process.env, [HELD_ENV]: name } : { ...process.env }), }); - installSignalHandlers(() => child, forwardTerm); + activeChild = child; + activeForwardTerm = forwardTerm; + installSignalHandlers(); child.on("error", (err) => { process.stderr.write(`queue-lock: ${err.message}\n`); resolve(1); }); child.on("exit", (code, signal) => { + if (activeChild === child) activeChild = null; // Never re-raise onto ourselves the way worktree.mjs's cmdRun does: we // have handlers installed, so re-raising would loop. resolve(signal ? 128 + (os.constants.signals[signal] ?? 0) : (code ?? 1)); @@ -478,19 +521,30 @@ function runCommand(cmd, name, { forwardTerm = false } = {}) { }); } +// One set of handlers per process, whatever it runs in turn (an e2e run's +// build first, then its suite): installing them per child would count one +// Ctrl-C twice, and the second count is "force". let signalHits = 0; +let activeChild = null; +let activeForwardTerm = false; +let handlersInstalled = false; // `forwardTerm`: a heavy-slot run is usually started by a PROCESS, not a // terminal — a publish stage whose Cancel SIGTERMs this wrapper alone, then // SIGKILLs it, which would orphan the `next build` under it. So a heavy run // passes SIGTERM/SIGHUP on to its command (a terminal's SIGINT already reached // the whole group, and is still never forwarded). -function installSignalHandlers(getChild, forwardTerm = false) { +function installSignalHandlers() { + if (handlersInstalled) return; + handlersInstalled = true; for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) { process.on(sig, () => { + const child = activeChild; + // Between two commands (waiting for the heavy slot after an e2e run's + // build) there is nothing to wait for: stop, as an unhandled signal would. + if (!child) process.exit(128 + (os.constants.signals[sig] ?? 0)); signalHits++; - const child = getChild(); if (signalHits === 1) { - if (forwardTerm && sig !== "SIGINT") { + if (activeForwardTerm && sig !== "SIGINT") { try { child?.kill(sig); } catch { @@ -519,9 +573,9 @@ function installSignalHandlers(getChild, forwardTerm = false) { function startWaitBanner(lock, what = E2E_LOCK) { const t0 = Date.now(); + const who = what.describe ? what.describe() : describeHolder(lock, what.showCmd); process.stderr.write( - `queue-lock: waiting for ${what.label} — held by ${describeHolder(lock, what.showCmd)}\n` + - ` ${what.hint}\n`, + `queue-lock: waiting for ${what.label} — held by ${who}\n` + ` ${what.hint}\n`, ); const timer = setInterval(() => { process.stderr.write( @@ -537,11 +591,11 @@ function startWaitBanner(lock, what = E2E_LOCK) { }; } -// ------------------------------------------------------------ the two locks +// ------------------------------------------------------------ the locks const E2E_LOCK = { label: "the e2e queue", - hint: "(one e2e run at a time, machine-wide; E2E_QUEUE=0 to bypass)", + hint: "(one run of each e2e suite at a time, machine-wide; E2E_QUEUE=0 to bypass)", timeoutHint: "Raise or unset E2E_QUEUE_TIMEOUT, or set E2E_QUEUE=0 to bypass the queue.", showCmd: false, @@ -550,21 +604,31 @@ const E2E_LOCK = { const HEAVY_LOCK = { label: "the heavy slot", hint: - "(one heavy job — an e2e run, a next build, a render — at a time, machine-wide; HEAVY=0 to bypass)", + "(heavy jobs — e2e runs, next builds, renders — are admitted by memory, one build at a time, machine-wide; HEAVY=0 to bypass)", + timeoutHint: "Raise or unset HEAVY_TIMEOUT, or set HEAVY=0 to bypass the heavy slot.", + showCmd: true, +}; + +const BUILD_LOCK = { + label: "the build slot", + hint: "(one next build at a time, machine-wide; HEAVY=0 to bypass)", timeoutHint: "Raise or unset HEAVY_TIMEOUT, or set HEAVY=0 to bypass the heavy slot.", showCmd: true, }; // Take `lock`, announcing whom we wait behind; returns the release function. // A timeout exits EXIT_TIMEOUT, as it always has for the e2e queue. -async function holdLock(lock, name, cmd, timeoutMs, what) { +// `mode.shared` takes it shared (the heavy slot, for a weighted job); +// `mode.nonblock` returns null at once when it is held. +async function holdLock(lock, name, cmd, timeoutMs, what, mode = {}) { let stopBanner = null; - if (isHeld(lock)) stopBanner = startWaitBanner(lock, what); + if (!mode.nonblock && isHeld(lock, mode)) stopBanner = startWaitBanner(lock, what); let holder; try { - holder = await acquire(lock, timeoutMs); + holder = await acquire(lock, timeoutMs, mode); } catch (err) { + if (err.busy) return null; if (err.timeout) { process.stderr.write( `\nqueue-lock: gave up after ${humanDuration(timeoutMs)} waiting for ${lock}\n` + @@ -576,13 +640,20 @@ async function holdLock(lock, name, cmd, timeoutMs, what) { } stopBanner?.(); + // A shared hold has company: the file names the newest holder (an older + // copy of this script reads it to say whom it waits behind), and only the + // run that wrote it removes it. const holderFile = writeHolderJson(lock, name, cmd); - const cleanup = () => { + const dropHolderFile = () => { try { - fs.rmSync(holderFile, { force: true }); + const info = JSON.parse(fs.readFileSync(holderFile, "utf8")); + if (info.pid === process.pid) fs.rmSync(holderFile, { force: true }); } catch { /* best effort */ } + }; + const cleanup = () => { + dropHolderFile(); try { holder.kill("SIGKILL"); } catch { @@ -592,11 +663,7 @@ async function holdLock(lock, name, cmd, timeoutMs, what) { process.on("exit", cleanup); return async () => { process.off("exit", cleanup); - try { - fs.rmSync(holderFile, { force: true }); - } catch { - /* best effort */ - } + dropHolderFile(); await release(holder); }; } @@ -714,54 +781,424 @@ async function memoryFloorOrExit(timeoutMs) { } } -// ------------------------------------------------------------ the entry points +// ------------------------------------------------- the weighted admission (S4) +// +// The heavy slot was ONE job at a time. Since release 24 it admits by memory: +// a job declares an estimate (an e2e suite ~1.5 GB, a capped `next build` its +// 5 GB cap) and is admitted while +// +// MemAvailable − Σ(estimates of the jobs already running) ≥ HEAVY_MIN_FREE_MB +// +// and, for a build, while no other build runs (one `next build` at a time stays +// a hard rule). A job that declares nothing runs ALONE, exactly as before — a +// render, a hand `pnpm heavy -- …`, an uncapped publish build. The two OOMs the +// slot exists for were builds and renders, not suites. +// +// The pieces, all beside the heavy lock (`<git-common-dir>/heavy-queue.lock`): +// heavy-queue.lock the slot itself. A weighted job holds it SHARED, an +// exclusive one EXCLUSIVELY — so an exclusive job (or +// a run of an older copy of this file, which always +// took it exclusively) waits for every weighted job, +// and none is admitted beside it. +// heavy-queue.lock.admit the line: one contender at a time decides, and keeps +// its place while it waits for memory, so a later one +// cannot slip in. Held only until admitted. +// heavy-queue.lock.build the build slot, held for a build's whole run. A +// build in line only TRIES it (never waits on it while +// holding the line); a build nested in an admitted run +// (an e2e config's stale-stamp rebuild) waits for it. +// heavy-queue.lock.jobs/ one ticket per running job, `<pid>.json`: its +// estimate, whether it builds, what it is. A ticket +// whose process is gone is stale and is dropped. +// Nothing an admitted job holds is waited on by another admitted job, and the +// line is only ever waited on by contenders holding nothing the running jobs +// need — so the order cannot deadlock. + +export const DEFAULT_BUILD_ESTIMATE_MB = 5000; +export const DEFAULT_E2E_ESTIMATE_MB = 1500; + +function admitLockFor(heavyLock) { + return `${heavyLock}.admit`; +} +function buildLockFor(heavyLock) { + return `${heavyLock}.build`; +} +function jobsDirFor(heavyLock) { + return `${heavyLock}.jobs`; +} + +// `systemd-run … -p MemoryMax=5G …` → 5120; none → null. +export function memoryCapMb(cmd = []) { + const units = { "": 1 / (1024 * 1024), K: 1 / 1024, M: 1, G: 1024, T: 1024 * 1024 }; + for (const arg of cmd) { + const m = /MemoryMax=(\d+(?:\.\d+)?)([KMGT]?)$/i.exec(String(arg)); + if (m) return Math.round(Number(m[1]) * units[m[2].toUpperCase()]); + } + return null; +} + +// `… next build …`, by the words (pnpm exec next build, node_modules/.bin/next build). +export function isNextBuild(cmd = []) { + return cmd.some( + (arg, i) => path.basename(String(arg)) === "next" && cmd[i + 1] === "build", + ); +} /** - * Run `fn` in the heavy slot: one heavy job machine-wide, started only once - * MemAvailable is at or above the floor. `opts.cmd` names the work in the - * holder file (what a waiter is told it waits behind). + * What a heavy job is, for admission: `{estimateMb, build, exclusive}`. + * An explicit estimate wins; else the command's memory cap is its estimate. + * A declared build (`--build`) with neither is 5 GB. Anything with no estimate + * is exclusive — it runs alone, as every heavy job did before release 24. */ -export async function withHeavy(opts, fn) { - if (process.env.HEAVY === "0" || process.env[HEAVY_HELD_ENV]) return fn(); - const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs("HEAVY_TIMEOUT"); - const cmd = opts.cmd ?? [HEAVY_NAME]; +export function resolveJob({ estimateMb, build } = {}, cmd = []) { + const isBuild = build ?? isNextBuild(cmd); + let est = Number(estimateMb) > 0 ? Number(estimateMb) : memoryCapMb(cmd); + if (est == null && build === true) est = DEFAULT_BUILD_ESTIMATE_MB; + if (est == null) return { estimateMb: null, build: isBuild, exclusive: true }; + return { estimateMb: est, build: isBuild, exclusive: false }; +} + +/** + * The admission rule, pure. `running` is the live tickets of the OTHER jobs; + * `mem` is `{availableMb, totalMb}` or null. Returns `{admit, reservedMb, …}` + * and, when not admitted, what it waits for: "build" (another build runs), + * "memory" (the headroom is under the floor), "serial" (a machine whose + * MemTotal is under the floor runs one job at a time, as it always did). + */ +export function admissionDecision({ mem, minMb, running = [], job }) { + const reservedMb = running.reduce((n, r) => n + (Number(r.estimateMb) || 0), 0); + const base = { reservedMb, runningCount: running.length }; + if (job.build && running.some((r) => r.build)) return { ...base, admit: false, wait: "build" }; + if (running.some((r) => r.exclusive)) return { ...base, admit: false, wait: "exclusive" }; + if (!(minMb > 0)) return { ...base, admit: true, why: "floor-off" }; + if (!mem) return { ...base, admit: true, why: "unreadable" }; + if (mem.totalMb < minMb) { + return running.length + ? { ...base, admit: false, wait: "serial" } + : { ...base, admit: true, why: "total" }; + } + const headroomMb = mem.availableMb - reservedMb; + return headroomMb >= minMb + ? { ...base, admit: true, headroomMb } + : { ...base, admit: false, wait: "memory", headroomMb }; +} - let releaseSlot = null; +// /proc/<pid>/stat's start time (field 22), so a reused pid is not mistaken +// for the job that wrote a ticket. Null off Linux. +function pidStartTime(pid) { try { - releaseSlot = await holdLock( - lockFileFor(HEAVY_NAME), - HEAVY_NAME, - cmd, - timeoutMs, - HEAVY_LOCK, + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); + return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null; + } catch { + return null; + } +} + +function ticketAlive(t) { + try { + process.kill(t.pid, 0); + } catch (err) { + if (err.code !== "EPERM") return false; + } + return t.pidStart == null || pidStartTime(t.pid) === t.pidStart; +} + +/** The live tickets in `dir` (a stale one is removed); `isAlive` is the tests' seam. */ +export function readTickets(dir, { isAlive = ticketAlive, exceptPid = null } = {}) { + let names; + try { + names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")); + } catch { + return []; + } + const live = []; + for (const n of names) { + const file = path.join(dir, n); + let t; + try { + t = JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + continue; // half-written by a peer, or not ours: never fatal + } + if (!Number.isInteger(t.pid)) continue; + if (!isAlive(t)) { + try { + fs.rmSync(file, { force: true }); + } catch { + /* best effort */ + } + continue; + } + if (t.pid !== exceptPid) live.push(t); + } + return live; +} + +function writeTicket(dir, job, cmd) { + const info = { + pid: process.pid, + pidStart: pidStartTime(process.pid), + estimateMb: job.estimateMb, + build: Boolean(job.build), + exclusive: Boolean(job.exclusive), + worktree: gitOut(["rev-parse", "--show-toplevel"]) ?? process.cwd(), + branch: gitOut(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "?", + cmd: cmd.join(" "), + startedAt: new Date().toISOString(), + }; + const file = path.join(dir, `${process.pid}.json`); + try { + fs.mkdirSync(dir, { recursive: true }); + const tmp = `${file}.tmp`; + fs.writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`); + fs.renameSync(tmp, file); + } catch { + /* informational for the arithmetic — a missing ticket undercounts, never blocks */ + } + const drop = () => { + try { + fs.rmSync(file, { force: true }); + } catch { + /* best effort */ + } + }; + process.on("exit", drop); + return () => { + process.off("exit", drop); + drop(); + }; +} + +function describeTicket(t) { + const where = t.worktree ? path.basename(t.worktree) : "?"; + const age = t.startedAt ? ` for ${humanAge(Date.parse(t.startedAt))}` : ""; + const est = `${t.estimateMb ? `, ${t.estimateMb} MB` : t.exclusive ? ", alone" : ""}${t.build ? ", a build" : ""}`; + return `${where} (${t.branch}, pid ${t.pid}${est})${age}: ${String(t.cmd ?? "").slice(0, 100)}`; +} + +// Whom the slot is held by: the running jobs' tickets, or (a run of an older +// copy of this file, which writes no ticket) the lock's holder file. +function describeSlot(heavyLock, { exceptPid = process.pid } = {}) { + const tickets = readTickets(jobsDirFor(heavyLock), { exceptPid }); + if (!tickets.length) return describeHolder(heavyLock, true); + const shown = tickets.slice(0, 3).map(describeTicket).join("; "); + return tickets.length > 3 ? `${shown}; and ${tickets.length - 3} more` : shown; +} + +function plural(n, one, many = `${one}s`) { + return `${n} ${n === 1 ? one : many}`; +} + +/** + * Wait in line until `job` is admitted (admissionDecision), then — for a + * build — take the build slot. Every input is injectable for the unit tests. + * Resolves `{decision, waitedMs, releaseBuild}`; throws `{timeout: true}` past + * `timeoutMs` (0 = never). + */ +export async function waitForAdmission({ + job, + minMb = minFreeMb(), + read = readMeminfo, + tickets = () => [], + tryBuild = async () => async () => {}, + describe = () => "", + pollMs = memPollMs(), + tickMs = TICK_MS, + timeoutMs = 0, + log = (line) => process.stderr.write(line), + now = Date.now, + sleep = (ms) => new Promise((r) => setTimeout(r, ms)), +}) { + const t0 = now(); + let lastTick = t0; + let lastWait = null; + for (;;) { + const running = tickets(); + const mem = read(); + let d = admissionDecision({ mem, minMb, running, job }); + let releaseBuild = null; + if (d.admit && job.build) { + releaseBuild = await tryBuild(); + if (!releaseBuild) d = { ...d, admit: false, wait: "build" }; + } + const waited = now() - t0; + if (d.admit) { + if (lastWait) { + log(`heavy: ${mem?.availableMb ?? "?"} MB available after ${humanDuration(waited)} — admitted\n`); + } else if (d.runningCount) { + log( + `heavy: admitted beside ${plural(d.runningCount, "running job")} ` + + `(${mem?.availableMb ?? "?"} MB available, ${d.reservedMb} MB promised to them, the floor is ${minMb} MB)\n`, + ); + } + return { decision: d, waitedMs: waited, releaseBuild }; + } + if (d.wait !== lastWait) { + lastWait = d.wait; + log(waitLine(d, mem, minMb, describe)); + } else if (now() - lastTick >= tickMs) { + lastTick = now(); + log(`heavy: still waiting (${d.wait}, ${humanDuration(waited)}; ${mem?.availableMb ?? "?"} MB available)\n`); + } + if (timeoutMs > 0 && waited >= timeoutMs) { + throw Object.assign( + new Error(`heavy: gave up after ${humanDuration(waited)} waiting to be admitted (${d.wait})`), + { timeout: true }, + ); + } + await sleep(pollMs); + } +} + +function waitLine(d, mem, minMb, describe) { + const who = describe(); + if (d.wait === "build") { + return `heavy: waiting for the build slot — one next build at a time; running: ${who}\n`; + } + if (d.wait === "exclusive") return `heavy: waiting for a job that runs alone: ${who}\n`; + if (d.wait === "serial") { + return ( + `heavy: this machine has ${mem.totalMb} MB in all, under the ${minMb} MB floor — ` + + `one heavy job at a time; waiting for: ${who}\n` ); + } + const promised = d.reservedMb + ? `, ${d.reservedMb} MB promised to ${plural(d.runningCount, "running job")}` + : ""; + return ( + `heavy: waiting for memory — ${mem.availableMb} MB available${promised}, the floor is ${minMb} MB\n` + + (d.reservedMb ? ` running: ${who}\n` : "") + + " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)\n" + ); +} + +async function admitOrExit(opts) { + try { + return await waitForAdmission(opts); } catch (err) { - // No usable flock (a container image without util-linux): the slot is a - // safety net, so run on the floor alone rather than not at all. + if (!err.timeout) throw err; process.stderr.write( - `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, + `\n${err.message}\n Raise or unset the timeout, lower HEAVY_MIN_FREE_MB, or set HEAVY=0.\n`, ); + process.exit(EXIT_TIMEOUT); } +} + +// ------------------------------------------------------------ the entry points + +/** + * Run `fn` in the heavy slot. `opts.estimateMb` / `opts.build` declare the job + * (resolveJob; inferred from `opts.cmd` when unset): a weighted job is admitted + * by memory beside others, an undeclared one runs alone once MemAvailable is at + * or above the floor. `opts.cmd` names the work (what a waiter is told). + */ +export async function withHeavy(opts, fn) { + if (process.env.HEAVY === "0") return fn(); + const cmd = opts.cmd ?? [HEAVY_NAME]; + const job = resolveJob(opts, cmd); + const heavyLock = lockFileFor(HEAVY_NAME); + const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs("HEAVY_TIMEOUT"); + + // Inside an admitted run: pass through — except a build, which still waits + // for the build slot (one build at a time is hard), and says so. + if (process.env[HEAVY_HELD_ENV]) { + // A build inside a build already holds the build slot (HEAVY_HELD=build). + if (!job.build || process.env[HEAVY_HELD_ENV] === "build") return fn(); + let releaseBuild = null; + try { + releaseBuild = await holdLock(buildLockFor(heavyLock), "heavy-build", cmd, timeoutMs, { + ...BUILD_LOCK, + describe: () => describeHolder(buildLockFor(heavyLock), true), + }); + } catch (err) { + process.stderr.write(`heavy: the build slot is not held (${err?.message ?? err})\n`); + } + const dropTicket = writeTicket(jobsDirFor(heavyLock), job, cmd); + const outer = process.env[HEAVY_HELD_ENV]; + process.env[HEAVY_HELD_ENV] = "build"; + try { + return await fn(); + } finally { + process.env[HEAVY_HELD_ENV] = outer; + dropTicket(); + await releaseBuild?.(); + } + } + + const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0; + const remaining = () => (deadline ? Math.max(1000, deadline - Date.now()) : 0); + const releases = []; try { - await memoryFloorOrExit(timeoutMs); - process.env[HEAVY_HELD_ENV] = "1"; + let releaseLine = null; + try { + releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, timeoutMs, { + ...HEAVY_LOCK, + describe: () => + `${describeSlot(heavyLock)}; next in line: ${describeHolder(admitLockFor(heavyLock), true)}`, + }); + } catch (err) { + // No usable flock (a container image without util-linux): the slot is a + // safety net, so run on the floor alone rather than not at all. + process.stderr.write( + `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, + ); + await memoryFloorOrExit(timeoutMs); + process.env[HEAVY_HELD_ENV] = "1"; + return await fn(); + } + try { + const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) }; + if (job.exclusive) { + releases.push(await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait)); + await memoryFloorOrExit(remaining()); + } else { + releases.push( + await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait, { shared: true }), + ); + const { releaseBuild } = await admitOrExit({ + job, + timeoutMs: remaining(), + tickets: () => readTickets(jobsDirFor(heavyLock), { exceptPid: process.pid }), + describe: () => describeSlot(heavyLock), + tryBuild: () => + holdLock(buildLockFor(heavyLock), "heavy-build", cmd, 0, BUILD_LOCK, { nonblock: true }), + }); + if (releaseBuild) releases.push(releaseBuild); + } + releases.push(writeTicket(jobsDirFor(heavyLock), job, cmd)); + } finally { + await releaseLine(); + } + process.env[HEAVY_HELD_ENV] = job.build ? "build" : "1"; return await fn(); } finally { delete process.env[HEAVY_HELD_ENV]; - await releaseSlot?.(); + for (const release of releases.reverse()) await release(); } } +// The default queue name, and the one older copies of this file use. A run +// under it keeps the old order — the heavy slot first, then the queue — so it +// can never wait in a cycle with an older run that holds the slot and waits +// for this queue. +export const LEGACY_QUEUE_NAME = "e2e"; + /** * Run `fn` with the global queue lock held, after checking `ports` are free. * Used both by the CLI below and directly by scripts/run-sharded-e2e.mjs. - * Unless `opts.heavySlot === false`, the run takes the heavy slot first. + * Unless `opts.heavySlot === false`, the run takes the heavy slot too. + * + * A NAMED suite (`--name e2e-<pkg>`) takes its own queue first — the same + * suite never runs twice, different suites run side by side — then builds what + * it serves (`opts.prebuild`, scripts/e2e-stamp.mjs, a build admitted as one), + * then is admitted to the heavy slot with its estimate. */ export async function withQueue(opts, fn) { - const name = opts.name ?? "e2e"; + const name = opts.name ?? LEGACY_QUEUE_NAME; const ports = parsePorts(opts.portSpec ?? null); const graceMs = opts.portGraceMs ?? Number(process.env.E2E_PORT_GRACE_MS ?? DEFAULT_PORT_GRACE_MS); const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs(); + const heavyOpts = { timeoutMs, cmd: opts.cmd ?? [name], estimateMb: opts.estimateMb }; // A nested invocation: the parent holds the queue (and the slot) already. if (process.env[HELD_ENV] === name) { @@ -779,23 +1216,48 @@ export async function withQueue(opts, fn) { return fn(); } - const queued = async () => { - const releaseQueue = await holdLock( - lockFileFor(name), - name, - opts.cmd ?? [name], - timeoutMs, - E2E_LOCK, - ); - try { - await preflight(ports, graceMs); - return await fn(); - } finally { - await releaseQueue(); + const holdQueue = () => + holdLock(lockFileFor(name), name, opts.cmd ?? [name], timeoutMs, E2E_LOCK); + + if (name === LEGACY_QUEUE_NAME) { + const queued = async () => { + const releaseQueue = await holdQueue(); + try { + await preflight(ports, graceMs); + return await fn(); + } finally { + await releaseQueue(); + } + }; + return opts.heavySlot === false ? queued() : withHeavy(heavyOpts, queued); + } + + const releaseQueue = await holdQueue(); + try { + await preflight(ports, graceMs); + if (opts.prebuild) { + const code = await prebuild(opts.prebuild); + if (code !== 0) return code; } - }; - if (opts.heavySlot === false) return queued(); - return withHeavy({ timeoutMs, cmd: opts.cmd ?? [name] }, queued); + return opts.heavySlot === false ? await fn() : await withHeavy(heavyOpts, fn); + } finally { + await releaseQueue(); + } +} + +// The suite's start-mode build, BEFORE its own admission: a rebuild is a build +// (5 GB, one at a time), not part of the suite's 1.5 GB. The playwright config +// then finds the stamp fresh and does not check again (E2E_BUILD_CHECKED). +// CI (the sharded image) builds its own `.next` and is left alone. +async function prebuild(pkg) { + if (process.env.CI) return 0; + const stamp = path.join(path.dirname(SELF), "e2e-stamp.mjs"); + const env = { ...process.env }; + delete env[HEAVY_HELD_ENV]; + const code = await runCommand([process.execPath, stamp, "ensure", pkg], null, { env }); + if (code === 0) process.env.E2E_BUILD_CHECKED = "1"; + else process.stderr.write(`queue-lock: the ${pkg} e2e build failed (exit ${code}) — not running the suite\n`); + return code; } async function main() { @@ -805,13 +1267,13 @@ async function main() { const cmd = opts.heavy && rawCmd[0] === "--" ? rawCmd.slice(1) : rawCmd; if (cmd.length === 0) { process.stderr.write( - "usage: queue-lock.mjs [--name e2e] [--ports PORT:3011,...] -- <cmd...>\n" + - " queue-lock.mjs --heavy [--timeout <s>] -- <cmd...>\n", + "usage: queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] [--ports PORT:3011,...] -- <cmd...>\n" + + " queue-lock.mjs --heavy [--estimate <MB>] [--build] [--timeout <s>] -- <cmd...>\n", ); process.exit(2); } const code = opts.heavy - ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd }, () => + ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build }, () => runCommand(cmd, null, { forwardTerm: true }), ) : await withQueue({ ...opts, cmd }, () => runCommand(cmd, opts.name)); diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -13,7 +13,16 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { parseMeminfo, waitForMemory } from "./queue-lock.mjs"; +import { + admissionDecision, + isNextBuild, + memoryCapMb, + parseMeminfo, + readTickets, + resolveJob, + waitForAdmission, + waitForMemory, +} from "./queue-lock.mjs"; const SCRIPT = fileURLToPath(new URL("./queue-lock.mjs", import.meta.url)); @@ -490,3 +499,259 @@ test("SIGTERM to a heavy wrapper alone stops its command (a stage's Cancel)", as assert.equal(res.code, 128 + os.constants.signals.SIGTERM); assert.throws(() => process.kill(cmdPid, 0), "the command survived the wrapper's SIGTERM"); }); + +// ------------------------------------------- the weighted admission (release 24) + +test("resolveJob: an estimate wins, a cap is an estimate, an undeclared job runs alone", () => { + assert.deepEqual(resolveJob({ estimateMb: 1500 }, ["playwright", "test"]), { + estimateMb: 1500, + build: false, + exclusive: false, + }); + const capped = ["systemd-run", "--user", "--scope", "-q", "-p", "MemoryMax=5G", "-p", "MemorySwapMax=0", + "pnpm", "--filter", "editor", "exec", "next", "build"]; + assert.deepEqual(resolveJob({}, capped), { estimateMb: 5120, build: true, exclusive: false }); + // A publish stage's build is uncapped: alone, as before. + assert.deepEqual(resolveJob({}, ["pnpm", "exec", "next", "build"]), { estimateMb: null, build: true, exclusive: true }); + assert.deepEqual(resolveJob({ build: true }, ["make"]), { estimateMb: 5000, build: true, exclusive: false }); + assert.deepEqual(resolveJob({}, ["node", "build-video.mjs"]), { estimateMb: null, build: false, exclusive: true }); + assert.equal(memoryCapMb(["-p", "MemoryMax=512M"]), 512); + assert.equal(memoryCapMb(["MemoryMax=2.5G"]), 2560); + assert.equal(memoryCapMb(["MemoryMax=infinity"]), null); + assert.equal(isNextBuild(["/x/node_modules/.bin/next", "build"]), true); + assert.equal(isNextBuild(["next", "start"]), false); +}); + +test("admissionDecision: MemAvailable − Σ(running estimates) ≥ floor; one build at a time", () => { + const mem = (availableMb, totalMb = 16_000) => ({ availableMb, totalMb }); + const suite = { estimateMb: 1500, build: false, exclusive: false }; + const build = { estimateMb: 5000, build: true, exclusive: false }; + assert.equal(admissionDecision({ mem: mem(9000), minMb: 6000, running: [], job: suite }).admit, true); + const two = [{ estimateMb: 1500 }, { estimateMb: 1500 }]; + assert.deepEqual(admissionDecision({ mem: mem(9000), minMb: 6000, running: two, job: suite }), { + reservedMb: 3000, + runningCount: 2, + admit: true, + headroomMb: 6000, + }); + const d = admissionDecision({ mem: mem(8999), minMb: 6000, running: two, job: suite }); + assert.equal(d.admit, false); + assert.equal(d.wait, "memory"); + // A build beside a suite is a memory question; beside a build, never. + assert.equal(admissionDecision({ mem: mem(20_000), minMb: 6000, running: [{ estimateMb: 1500 }], job: build }).admit, true); + assert.equal( + admissionDecision({ mem: mem(20_000), minMb: 6000, running: [{ estimateMb: 5000, build: true }], job: build }).wait, + "build", + ); + // A suite beside a build is fine when memory is. + assert.equal( + admissionDecision({ mem: mem(20_000), minMb: 6000, running: [{ estimateMb: 5000, build: true }], job: suite }).admit, + true, + ); + // Floor off, meminfo unreadable: admitted (the build rule still holds). + assert.equal(admissionDecision({ mem: mem(10), minMb: 0, running: two, job: suite }).admit, true); + assert.equal(admissionDecision({ mem: null, minMb: 6000, running: two, job: suite }).admit, true); + assert.equal( + admissionDecision({ mem: null, minMb: 6000, running: [{ estimateMb: 5000, build: true }], job: build }).admit, + false, + ); + // A machine under the floor in all runs one job at a time, as it always did. + assert.equal(admissionDecision({ mem: mem(3000, 4000), minMb: 6000, running: [], job: suite }).admit, true); + assert.equal(admissionDecision({ mem: mem(3000, 4000), minMb: 6000, running: two, job: suite }).wait, "serial"); +}); + +test("waitForAdmission waits while the headroom is short, then admits; a build waits for the build slot", async () => { + let clock = 0; + const lines = []; + const common = { + minMb: 6000, + pollMs: 1000, + tickMs: 60_000, + log: (l) => lines.push(l), + now: () => clock, + sleep: async (ms) => { + clock += ms; + }, + describe: () => "wt (main, pid 1, 1500 MB): playwright test", + }; + const runningSets = [[{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }]]; + const res = await waitForAdmission({ + ...common, + job: { estimateMb: 1500, build: false, exclusive: false }, + read: () => ({ availableMb: 8000, totalMb: 16_000 }), + tickets: () => runningSets.shift() ?? [], + }); + assert.equal(res.waitedMs, 2000); + assert.match(lines[0], /waiting for memory — 8000 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB/); + assert.match(lines.at(-1), /8000 MB available after 2s — admitted/); + + lines.length = 0; + clock = 0; + let tries = 0; + const built = await waitForAdmission({ + ...common, + job: { estimateMb: 5000, build: true, exclusive: false }, + read: () => ({ availableMb: 20_000, totalMb: 32_000 }), + tickets: () => [], + tryBuild: async () => (++tries < 3 ? null : async () => {}), + }); + assert.equal(tries, 3); + assert.equal(typeof built.releaseBuild, "function"); + assert.match(lines[0], /waiting for the build slot — one next build at a time/); + + clock = 0; + await assert.rejects( + waitForAdmission({ + ...common, + timeoutMs: 3000, + job: { estimateMb: 1500, build: false, exclusive: false }, + read: () => ({ availableMb: 1000, totalMb: 16_000 }), + }), + (err) => err.timeout === true, + ); +}); + +test("readTickets keeps the live and drops the stale", () => { + const dir = tmpDir(); + fs.writeFileSync(path.join(dir, "1.json"), JSON.stringify({ pid: 1, estimateMb: 1500 })); + fs.writeFileSync(path.join(dir, "2.json"), JSON.stringify({ pid: 2, estimateMb: 5000, build: true })); + fs.writeFileSync(path.join(dir, "3.json"), "{half-writ"); + const live = readTickets(dir, { isAlive: (t) => t.pid === 2 }); + assert.deepEqual(live.map((t) => t.pid), [2]); + assert.equal(fs.existsSync(path.join(dir, "1.json")), false, "a stale ticket is removed"); + assert.equal(fs.existsSync(path.join(dir, "3.json")), true, "an unreadable one is left alone"); + assert.deepEqual(readTickets(path.join(dir, "absent")), []); +}); + +// Both ran at once: the second started before the first ended. +function overlapped(order) { + return /^S\wS\w/.test(order); +} + +test("two weighted jobs run side by side; a third waits for headroom, named in the banner", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + meminfo(env.HEAVY_MEMINFO_FILE, 8000); + const jobs = path.join(dir, "heavy.lock.jobs"); + const tickets = () => (fs.existsSync(jobs) ? fs.readdirSync(jobs).filter((n) => n.endsWith(".json")).length : 0); + const a = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "a", 1500)], env); + await until(() => tickets() === 1); + const b = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "b", 1500)], env); + await until(() => tickets() === 2); + const c = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "c", 50)], env); + await c.waitFor(/waiting for memory — 8000 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB/); + const [ra, rb, rc] = await Promise.all([a.done, b.done, c.done]); + assert.equal(ra.code, 0, ra.stderr); + assert.equal(rb.code, 0, rb.stderr); + assert.equal(rc.code, 0, rc.stderr); + const order = fs.readFileSync(log, "utf8"); + assert.ok(overlapped(order), `a and b did not overlap: ${order}`); + assert.ok(order.indexOf("Sc") > Math.min(order.indexOf("Ea"), order.indexOf("Eb")), `c started too soon: ${order}`); + assert.match(rb.stderr, /admitted beside 1 running job/); + assert.match(rc.stderr, /admitted/); + assert.equal(tickets(), 0, "every ticket is removed at the end"); +}); + +test("two builds never overlap, whatever the memory; the second waits for the build slot", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const first = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "1", 600)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.build.holder.json`)); + const second = await runLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "2", 50)], env); + assert.equal((await first.done).code, 0); + assert.equal(second.code, 0, second.stderr); + assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); + assert.match(second.stderr, /waiting for the build slot — one next build at a time; running: .*pid \d+, 100 MB, a build\)/); +}); + +test("an undeclared job runs alone: it waits for the weighted ones, and none starts beside it", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const weighted = startLock(["--heavy", "--estimate", "100", "--", ...markerCmd(log, "w", 600)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.jobs`) && fs.readdirSync(`${env.HEAVY_LOCK_FILE}.jobs`).length > 0); + const alone = startLock(["--heavy", "--", ...markerCmd(log, "x", 600)], env); + await alone.waitFor(/waiting for the heavy slot — held by .*pid \d+, 100 MB/); + const later = startLock(["--heavy", "--estimate", "100", "--", ...markerCmd(log, "l", 50)], env); + for (const r of await Promise.all([weighted.done, alone.done, later.done])) assert.equal(r.code, 0, r.stderr); + assert.equal(fs.readFileSync(log, "utf8"), "SwEwSxExSlEl"); +}); + +test("a build nested in an admitted run waits for the build slot (one build at a time is hard)", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const outer = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "1", 700)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.build.holder.json`)); + // The shape of an e2e config's rebuild inside a running suite: HEAVY_HELD set. + const nested = await runLock(["--heavy", "--build", "--", ...markerCmd(log, "2", 50)], { ...env, HEAVY_HELD: "1" }); + assert.equal(nested.code, 0, nested.stderr); + await outer.done; + assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); + assert.match(nested.stderr, /waiting for the build slot/); + // A build inside a build (HEAVY_HELD=build) already holds the slot: through. + const outer2 = startLock(["--heavy", "--build", "--estimate", "100", "--", "sh", "-c", + `${JSON.stringify(process.execPath)} ${JSON.stringify(SCRIPT)} --heavy --build -- true && echo inner-ok`], env); + const r2 = await outer2.done; + assert.equal(r2.code, 0, r2.stderr); + assert.match(r2.stdout, /inner-ok/); + // A nested non-build still passes straight through. + const t0 = Date.now(); + assert.equal((await runLock(["--heavy", "--", "true"], { ...env, HEAVY_HELD: "1" })).code, 0); + assert.ok(Date.now() - t0 < 3000); +}); + +test("named suites run side by side; the same suite never runs twice", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") }); + const suite = (name, id, ms) => + startLock(["--name", name, "--estimate", "100", "--", ...markerCmd(log, id, ms)], env); + const a = suite("e2e-editor", "a", 900); + await until(() => fs.existsSync(path.join(dir, "q.lock.e2e-editor.holder.json"))); + const b = suite("e2e-umtool", "b", 900); + const order = () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8") : ""); + await until(() => order().includes("Sb") || order().includes("Ea")); + const again = suite("e2e-editor", "c", 50); + await again.waitFor(/waiting for the e2e queue — held by .*pid \d+/); + for (const r of await Promise.all([a.done, b.done, again.done])) assert.equal(r.code, 0, r.stderr); + const ran = order(); + assert.ok(overlapped(ran), `editor and umtool did not overlap: ${ran}`); + assert.ok(ran.indexOf("Sc") > ran.indexOf("Ea"), `the second editor run overlapped the first: ${ran}`); +}); + +test("every package's e2e scripts queue under the package's own name, with an estimate", () => { + const root = path.resolve(path.dirname(SCRIPT), ".."); + const seen = new Map(); + for (const pkg of ["editor", "export", "homepage", "umtool"]) { + const scripts = JSON.parse(fs.readFileSync(path.join(root, pkg, "package.json"), "utf8")).scripts; + const queued = Object.entries(scripts).filter(([, cmd]) => cmd.includes("queue-lock.mjs")); + assert.ok(queued.length > 0, `${pkg} has no queued e2e script`); + for (const [name, cmd] of queued) { + assert.match(cmd, new RegExp(`--name e2e-${pkg} `), `${pkg}'s ${name} does not queue as e2e-${pkg}`); + assert.match(cmd, /--estimate \d+ /, `${pkg}'s ${name} declares no estimate`); + seen.set(`e2e-${pkg}`, pkg); + } + // The start-mode suites build before their admission. + if (pkg === "editor" || pkg === "umtool") assert.match(scripts.e2e, new RegExp(`--prebuild ${pkg} `)); + } + assert.equal(seen.size, 4); +}); + +test("--prebuild ensures the suite's build before its admission, and the config is told", async () => { + const dir = tmpDir(); + const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock"), E2E_MODE: "dev" }); + const cmd = [process.execPath, "-e", "console.log('checked=' + process.env.E2E_BUILD_CHECKED)"]; + // E2E_MODE=dev: `ensure` builds nothing (no test may build the real editor). + const ok = await runLock(["--name", "e2e-x", "--estimate", "100", "--prebuild", "editor", "--", ...cmd], env); + assert.equal(ok.code, 0, ok.stderr); + assert.match(ok.stderr, /E2E_MODE=dev — editor runs under next dev, no build/); + assert.match(ok.stdout, /checked=1/); + // A failed build (here: no such package) stops the run before the suite. + const bad = await runLock(["--name", "e2e-x", "--estimate", "100", "--prebuild", "nope", "--", ...cmd], env); + assert.notEqual(bad.code, 0); + assert.doesNotMatch(bad.stdout, /checked=/); + assert.match(bad.stderr, /the nope e2e build failed/); +}); diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" + "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { "class-variance-authority": "^0.7.1",