From 1ac46b4969b6d33c8d25deef9540c60d40b31ba2 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sat, 21 Nov 2026 21:01:49 +0100 Subject: [PATCH] test: fan out the gates and build shared binaries once Every Nim test file and every Node test file is already isolated (own temp state dir, free ports, own server/nginx), so run them FFF_TEST_JOBS at a time (default half the cores, capped at 8) instead of one at a time. The real server (clean, leakfault, dispfault) and the leak checker are built once per source+flags and shared across the parallel files; nimcaches are worktree-local so two checkouts cannot race on them. The 22 independent fault cases are sharded across processes. The wall-clock gate files (persistence, tiles; e2e map/fog/fogbench/ perf) still run alone first so their budgets are not measured under the suite's own load. No test or assertion changes. --- .gitignore | 2 + client/e2e/run.sh | 32 +++++++-- tools/fault.test.mjs | 25 ++++++- tools/jobs.sh | 46 +++++++++++++ tools/leak.mjs | 22 +++--- tools/lib.mjs | 120 ++++++++++++++++++++++++++++++--- tools/prebuild.mjs | 16 +++++ tools/test.sh | 155 ++++++++++++++++++++++++++++++++++++++++--- tools/withserver.mjs | 27 ++++---- 9 files changed, 396 insertions(+), 49 deletions(-) create mode 100644 tools/jobs.sh create mode 100644 tools/prebuild.mjs diff --git a/.gitignore b/.gitignore index 6dbe70c..7853548 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ nimcache/ tests/t[a-z]* !tests/*.nim !tests/fixtures/ +# tests/refold.nim is a helper module nimble test also compiles; its output binary is scratch +/tests/refold tools/bench tools/mkcorpus run/ diff --git a/client/e2e/run.sh b/client/e2e/run.sh index 8e6949f..a5cf723 100755 --- a/client/e2e/run.sh +++ b/client/e2e/run.sh @@ -3,9 +3,18 @@ # browser suite against the real server through the TLS/HTTP2 test nginx. Separate from # `devbox run test` so the fast server gate stays fast (TESTING 11.1); the client's own unit tests # are `devbox run client-test`. +# +# Parallelism: every test gets its own stack (state dir, free ports, nginx, server) and its own +# browser, so test files run FFF_E2E_JOBS at a time (default: half the cores, capped at 4; +# FFF_TEST_JOBS/FFF_E2E_JOBS=1 serialises). The files whose assertions are timing gates (the +# tile-fill budget, the fog costs, the perf overlay) run alone first, unloaded, then the rest fan +# out. The client dist and the server binaries are built once, before any worker starts. set -euo pipefail cd "$(dirname "$0")/../.." || exit 1 -mkdir -p results +. tools/jobs.sh +mkdir -p results run/logs +fff_setup_tmpdir +JOBS=$(fff_e2e_jobs) export CHROMIUM="${CHROMIUM:-$(command -v chromium || true)}" if [ -z "$CHROMIUM" ]; then echo "e2e: chromium not found; it is a root devbox package (devbox.json) - run inside devbox" >&2 @@ -14,7 +23,22 @@ fi # npm deps stay out of tools/ (TESTING 10.4) and out of git; install once per checkout. ( cd client && { [ -d node_modules ] || npm ci --no-audit --no-fund; } ) ( cd client && npm run build ) -node --test --test-concurrency=1 --test-reporter=spec client/e2e/*.test.mjs > results/e2e.log 2>&1 -rc=$? +# Shared Nim build cache: the server binaries the stacks launch (and the leak checker) are built +# once here, not once per test file. +node tools/prebuild.mjs server-only > run/logs/prebuild-e2e.log 2>&1 +E2E_SERIAL=(client/e2e/map.test.mjs client/e2e/fog.test.mjs client/e2e/fogbench.test.mjs + client/e2e/perf.test.mjs) +E2E_PARALLEL=() +for f in client/e2e/*.test.mjs; do + case " ${E2E_SERIAL[*]} " in + *" $f "*) ;; + *) E2E_PARALLEL+=("$f") ;; + esac +done +node --test --test-concurrency=1 --test-reporter=spec "${E2E_SERIAL[@]}" \ + > run/logs/e2e-serial.log 2>&1 || rc=$? +node --test --test-concurrency="$JOBS" --test-reporter=spec "${E2E_PARALLEL[@]}" \ + > run/logs/e2e-parallel.log 2>&1 || rc=$? +cat run/logs/e2e-serial.log run/logs/e2e-parallel.log > results/e2e.log cat results/e2e.log -exit $rc +[ "${rc:-0}" -eq 0 ] || exit "$rc" diff --git a/tools/fault.test.mjs b/tools/fault.test.mjs index ff88e0f..11ee7de 100644 --- a/tools/fault.test.mjs +++ b/tools/fault.test.mjs @@ -18,7 +18,18 @@ import { buildServer, gmKeyOf, makeStateDir, signIn, startServer, stopServer } f import { openWs } from './lib.mjs' import { projectRoot } from './lib.mjs' -const results = path.join(projectRoot, 'results') +// Checker output is per-process scratch; tools/test.sh concatenates the shards into the committed +// results/faults.log after the Node phase (one write per run, not an append from every process). +const logs = path.join(projectRoot, 'run', 'logs') + +// The 22 leak-fault cases are independent (own state dir, own server, own transcript) and each +// costs ~4.8 s (one leak scenario + checker). tools/test.sh therefore runs this file as several +// processes (`FFF_TEST_SHARDS`/`FFF_TEST_SHARD`) so the cases run in parallel without changing a +// single test or assertion. Unset (a direct `node --test tools/fault.test.mjs`) = all cases here, +// which is also what the shard maths below does for one shard. +const SHARDS = Math.max(1, Number(process.env.FFF_TEST_SHARDS ?? 1)) +const SHARD = Math.max(0, Number(process.env.FFF_TEST_SHARD ?? 0)) +let faultCase = 0 // fault -> the exact set of classes the checker must report (nothing more, nothing less). // @@ -60,6 +71,9 @@ function classesOf(output) { .sort() } +// The cases that do not belong to FAULTS run once, in shard 0, so a sharded run executes every test +// exactly once across the processes (and a one-shard run is still the whole file). +if (SHARD === 0) test('the shipped build carries no fault hook and passes the leak test', () => { const bin = buildServer() const bytes = fs.readFileSync(bin) @@ -68,8 +82,9 @@ test('the shipped build carries no fault hook and passes the leak test', () => { }) for (const [fault, expected] of Object.entries(FAULTS)) { + if (faultCase++ % SHARDS !== SHARD) continue test(`fault ${fault}: caught as exactly ${expected.join(' ')}`, async () => { - fs.mkdirSync(results, { recursive: true }) + fs.mkdirSync(logs, { recursive: true }) const stateDir = makeStateDir() const gmKey = gmKeyOf(stateDir) const s = await startServer({ stateDir, defines: ['leakfault'], env: { LEAK_FAULT: fault } }) @@ -77,7 +92,7 @@ for (const [fault, expected] of Object.entries(FAULTS)) { try { await runLeak({ origin: s.origin, gmKey, stateDir, transcript }) const check = runChecker(transcript, 'A') - fs.appendFileSync(path.join(results, 'faults.log'), + fs.appendFileSync(path.join(logs, `faults-${SHARD}.log`), `== fault ${fault}\n${check.output}\n`) assert.notEqual(check.status, 0, `the checker passed a leak (${fault}):\n${check.output}`) assert.deepEqual(classesOf(check.output), expected.sort(), @@ -91,6 +106,7 @@ for (const [fault, expected] of Object.entries(FAULTS)) { // #32: an escaping failure in intent handling must still answer the request. The `dispfault` build // is the only build with an injection point; the shipped binary must remain incapable of faulting. +if (SHARD === 0) test('the shipped build carries no dispatch fault hook', () => { const bin = buildServer() const bytes = fs.readFileSync(bin) @@ -107,6 +123,7 @@ async function gmSession(s) { return { ws, sceneId: hello.scene.id } } +if (SHARD === 0) test('a CatchableError inside a locked mutation: one internal ack, then the server keeps serving', async () => { const stateDir = makeStateDir() @@ -146,6 +163,7 @@ test('a CatchableError inside a locked mutation: one internal ack, then the serv } }) +if (SHARD === 0) test('a Defect inside a locked mutation: one internal ack and no open transaction', async () => { const stateDir = makeStateDir() const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'txn-defect' } }) @@ -167,6 +185,7 @@ test('a Defect inside a locked mutation: one internal ack and no open transactio } }) +if (SHARD === 0) test('a failure after the ack was enqueued never appends a second ack', async () => { const stateDir = makeStateDir() const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'after-ack' } }) diff --git a/tools/jobs.sh b/tools/jobs.sh new file mode 100644 index 0000000..10b8308 --- /dev/null +++ b/tools/jobs.sh @@ -0,0 +1,46 @@ +# Shared parallelism default for the test gates (sourced by tools/test.sh and client/e2e/run.sh). +# +# FFF_TEST_JOBS overrides it (FFF_TEST_JOBS=1 serialises). The default is half the cores, capped at +# 8: the host froze under an uncapped, memory-heavy load before, so the gate never saturates it. +# The client e2e runs whole browsers (SwiftShader is CPU-hungry per worker), so it caps its workers +# lower unless FFF_E2E_JOBS names one explicitly. +fff_half_cores() { + local n=$(( $(nproc) / 2 )) + [ "$n" -ge 1 ] || n=1 + echo "$n" +} + +fff_test_jobs() { + local n=${FFF_TEST_JOBS:-} + if [ -z "$n" ]; then + n=$(fff_half_cores) + [ "$n" -le 8 ] || n=8 + fi + echo "$n" +} + +fff_e2e_jobs() { + local n=${FFF_E2E_JOBS:-} + if [ -z "$n" ]; then + n=$(fff_test_jobs) + [ "$n" -le 4 ] || n=4 + fi + echo "$n" +} + +# Test state dirs live on tmpfs when the host has it. Every harness state dir carries a SQLite WAL +# with synchronous=FULL commits (authoring) plus transcripts and tile fixtures; on a disk-backed +# /tmp, eight suites fanning out at once can stall a first commit long enough for a harness ack to +# look lost. /dev/shm keeps the same SQLite/restart semantics (a SIGKILL restart still reads the +# same files) without the fsync storm. An explicit TMPDIR is respected; the directory is removed +# on exit. FFF_TEST_TMPDIR=dir picks another base. +fff_setup_tmpdir() { + if [ -n "${FFF_TEST_NO_TMPFS:-}" ] || { [ -n "${TMPDIR:-}" ] && [ "${TMPDIR}" != "/tmp" ]; }; then + return 0 + fi + local base=${FFF_TEST_TMPDIR:-/dev/shm} + [ -d "$base" ] && [ -w "$base" ] || return 0 + TMPDIR=$(mktemp -d "$base/fffvtt-run.XXXXXX") || return 0 + export TMPDIR + trap 'rm -rf "$TMPDIR"' EXIT +} diff --git a/tools/leak.mjs b/tools/leak.mjs index 70fe7a8..7924e39 100644 --- a/tools/leak.mjs +++ b/tools/leak.mjs @@ -34,7 +34,7 @@ import fs from 'node:fs' import path from 'node:path' import { spawnSync } from 'node:child_process' -import { createPlayer, namePlayer, openWs, sleep, projectRoot, isWindow, anchorOf } from './lib.mjs' +import { cachedNimBuild, createPlayer, namePlayer, openWs, sleep, projectRoot, isWindow, anchorOf } from './lib.mjs' import { signIn } from './withserver.mjs' const QUIET_MS = 60 @@ -43,18 +43,22 @@ const QUIET_MS = 60 const FAR_WALL_X = 1400 const nimblePkgs = () => path.join(process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble'), 'pkgs2') -// The checker is compiled once per process (it imports server/geometry.nim through --path in nim.cfg). +// The checker is compiled once per process (it imports server/geometry.nim through --path in nim.cfg), +// and once per source+flags across the concurrently-running files (cachedNimBuild). Its nimcache is +// worktree-local (run/nimcache/leakcheck) so two checkouts cannot share object files. let checkerBin = null export function buildChecker() { if (checkerBin) return checkerBin const out = path.join(projectRoot, 'run', 'test', 'leakcheck') - fs.mkdirSync(path.dirname(out), { recursive: true }) - const r = spawnSync('nim', ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`, - `-o:${out}`, path.join('tools', 'leakcheck.nim')], - { cwd: projectRoot, encoding: 'utf8' }) - if (r.status !== 0) throw new Error(`nim c tools/leakcheck.nim failed:\n${r.stdout}\n${r.stderr}`) - checkerBin = out - return out + checkerBin = cachedNimBuild({ + out, + roots: [path.join('tools', 'leakcheck.nim'), 'server', 'nim.cfg'], + extra: `-d:release\n${nimblePkgs()}\n`, + nimArgs: tmp => ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`, + `--nimcache:${path.join(projectRoot, 'run', 'nimcache', 'leakcheck')}`, + `-o:${tmp}`, path.join('tools', 'leakcheck.nim')], + }) + return checkerBin } export function runChecker(transcript, subject) { diff --git a/tools/lib.mjs b/tools/lib.mjs index 5eb2e7c..d5dca79 100644 --- a/tools/lib.mjs +++ b/tools/lib.mjs @@ -3,6 +3,7 @@ // re-verifies on the wire that Cookie and Origin reach the server (the old "Node 22" note in // the prototype's lib.mjs was stale; here the pin is the devbox node 26). import crypto from 'node:crypto' +import { spawnSync } from 'node:child_process' import fs from 'node:fs' import net from 'node:net' import path from 'node:path' @@ -10,6 +11,11 @@ import { fileURLToPath } from 'node:url' export const sleep = ms => new Promise(r => setTimeout(r, ms)) +// Harness patience, not an assertion. The Node suite runs test files in parallel, so on a busy host +// an ack can be late without being wrong; a test fails when the answer never comes, not when it +// arrives after 5 s. Tests that assert *latency* keep their own explicit budgets. +export const HARNESS_TIMEOUT_MS = 15000 + export const projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) // Wall helpers shared by the harnesses (the leak driver's scenario coverage and any test that reads @@ -18,6 +24,102 @@ export const projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.u export const isWindow = w => w.blocks_sight === false && w.blocks_movement === true export const anchorOf = w => [Math.round((w.a[0] + w.b[0]) / 2), Math.round((w.a[1] + w.b[1]) / 2)] +// --------------------------------------------------------------------------------------------- +// Shared Nim build cache for the Node harnesses and the client e2e. +// +// Every Node test *file* is its own process (node --test), and with --test-concurrency > 1 the +// files run at the same time. Each used to build its own copy of the real server binary (and the +// leak checker) into run/test/, so concurrent files raced on the output and its nimcache, and a +// serial run paid the ~1.8 s compile once per file. The cache is keyed by the source bytes plus +// the flags, guarded by an exclusive lock file, and published with rename(2), so: +// * one file builds, every other file waits for it and then reuses the same binary; +// * an unchanged tree (the next run) skips the compiler entirely; +// * a partial binary never becomes visible under the final name. +// run/ is gitignored; the per-variant nimcache under run/nimcache keeps two checkouts on one host +// from writing each other's object files. +export function sleepSync(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) +} + +function nimFiles(dir, out = []) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, entry.name) + if (entry.isDirectory()) nimFiles(p, out) + else if (entry.name.endsWith('.nim')) out.push(p) + } + return out +} + +// Hash of the inputs a build depends on: every .nim under `roots`, plus nim.cfg and the flags. +export function sourceFingerprint(roots, extra = '') { + const files = [] + for (const root of roots) { + const p = path.join(projectRoot, root) + if (fs.existsSync(p) && fs.statSync(p).isDirectory()) files.push(...nimFiles(p)) + else files.push(p) + } + files.push(path.join(projectRoot, 'nim.cfg')) + files.sort() + const h = crypto.createHash('sha256') + h.update(extra) + for (const f of files) { + h.update(path.relative(projectRoot, f)) + h.update('\0') + h.update(fs.readFileSync(f)) + h.update('\0') + } + return h.digest('hex') +} + +function acquireLock(lockPath, timeoutMs = 180000) { + const deadline = Date.now() + timeoutMs + for (;;) { + try { + const fd = fs.openSync(lockPath, 'wx') + fs.writeSync(fd, String(process.pid)) + fs.closeSync(fd) + return + } catch (e) { + if (e.code !== 'EEXIST') throw e + try { + // A crashed process leaves its lock behind: a lock older than 10 minutes is stale. + if (Date.now() - fs.statSync(lockPath).mtimeMs > 600000) { fs.rmSync(lockPath, { force: true }); continue } + } catch {} + if (Date.now() > deadline) throw new Error(`build lock ${lockPath} was not released in ${timeoutMs} ms`) + sleepSync(50) + } + } +} + +// Build `out` from `roots` once per (source, flags) pair. `nimArgs(tmpOut)` returns the compiler +// arguments with -o pointing at a temporary file. Returns `out`. +export function cachedNimBuild({ out, roots, extra = '', nimArgs }) { + fs.mkdirSync(path.dirname(out), { recursive: true }) + const stampPath = `${out}.stamp` + const stamp = `${sourceFingerprint(roots, extra)}\n${path.basename(out)}\n` + const fresh = () => { + if (!fs.existsSync(out)) return false + try { return fs.readFileSync(stampPath, 'utf8') === stamp } catch { return false } + } + if (fresh()) return out + const lockPath = `${out}.lock` + acquireLock(lockPath) + try { + if (fresh()) return out + const tmp = `${out}.tmp-${process.pid}` + const r = spawnSync('nim', nimArgs(tmp), { cwd: projectRoot, encoding: 'utf8' }) + if (r.status !== 0) { + fs.rmSync(tmp, { force: true }) + throw new Error(`nim ${nimArgs(tmp).join(' ')} failed:\n${r.stdout ?? ''}\n${r.stderr ?? ''}`) + } + fs.renameSync(tmp, out) + fs.writeFileSync(stampPath, stamp) + return out + } finally { + fs.rmSync(lockPath, { force: true }) + } +} + export const baseUrl = port => `http://127.0.0.1:${port}` // The test nginx is TLS-only (#66): its origin is https, and its generated certificate is added to @@ -116,7 +218,7 @@ export async function openWs(origin, cookie, opts = {}) { messages: [], nextReqId: 1, pending: new Map(), - request(payload, timeoutMs = 5000) { + request(payload, timeoutMs = HARNESS_TIMEOUT_MS) { const reqId = client.nextReqId++ return new Promise((resolve, reject) => { const timer = setTimeout(() => { @@ -132,7 +234,7 @@ export async function openWs(origin, cookie, opts = {}) { ws.send(typeof objOrText === 'string' ? objOrText : JSON.stringify(objOrText)) }, // First already-received or future message matching pred (the server's frames are async). - async waitFor(pred, timeoutMs = 5000) { + async waitFor(pred, timeoutMs = HARNESS_TIMEOUT_MS) { const deadline = Date.now() + timeoutMs for (;;) { const hit = client.messages.find(pred) @@ -144,7 +246,7 @@ export async function openWs(origin, cookie, opts = {}) { await sleep(10) } }, - async waitText(t, timeoutMs = 5000) { + async waitText(t, timeoutMs = HARNESS_TIMEOUT_MS) { return await client.waitFor(m => m && m.t === t, timeoutMs) }, } @@ -164,7 +266,7 @@ export async function openWs(origin, cookie, opts = {}) { resolveClosed(closeInfo) } await new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error('websocket open timeout')), 5000) + const timer = setTimeout(() => reject(new Error('websocket open timeout')), HARNESS_TIMEOUT_MS) wireOpen(ws, () => { clearTimeout(timer); resolve() }, e => { clearTimeout(timer); reject(e) }) }) ws.onerror = () => {} // post-open errors surface as a close @@ -200,7 +302,7 @@ export async function rawUpgrade(origin, opts = {}) { if (err) reject(err) else resolve(value) } - const timer = setTimeout(() => finish(new Error(`raw upgrade timeout; got: ${buf}`)), 5000) + const timer = setTimeout(() => finish(new Error(`raw upgrade timeout; got: ${buf}`)), HARNESS_TIMEOUT_MS) sock.on('connect', () => sock.write(lines.join('\r\n') + '\r\n\r\n')) sock.on('data', chunk => { buf += chunk.toString('latin1') @@ -323,7 +425,7 @@ export async function rawWs(origin, opts = {}) { client.sendFrame(OP_CLOSE, body) }, // First already-received or future frame matching pred. Rejects after timeoutMs. - async waitFor(pred, timeoutMs = 5000) { + async waitFor(pred, timeoutMs = HARNESS_TIMEOUT_MS) { const deadline = Date.now() + timeoutMs for (;;) { const hit = client.frames.find(pred) @@ -335,7 +437,7 @@ export async function rawWs(origin, opts = {}) { await sleep(5) } }, - async waitText(t, timeoutMs = 5000) { + async waitText(t, timeoutMs = HARNESS_TIMEOUT_MS) { const frame = await client.waitFor(f => f.opcode === OP_TEXT && f.text && JSON.parse(f.text).t === t, timeoutMs) return JSON.parse(frame.text) }, @@ -351,7 +453,7 @@ export async function rawWs(origin, opts = {}) { }) await new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error(`raw websocket handshake timeout; head: ${client.head}`)), 5000) + const timer = setTimeout(() => reject(new Error(`raw websocket handshake timeout; head: ${client.head}`)), HARNESS_TIMEOUT_MS) let buf = Buffer.alloc(0) let open = false sock.on('connect', () => sock.write(lines.join('\r\n') + '\r\n\r\n')) @@ -409,7 +511,7 @@ export async function createPlayer(gm) { // Wait until every reqId in `ids` has an ack; returns the ack messages. Lets a test assert // "exactly one ack" instead of trusting a promise per request. -export async function collectAcks(client, ids, timeoutMs = 5000) { +export async function collectAcks(client, ids, timeoutMs = HARNESS_TIMEOUT_MS) { const deadline = Date.now() + timeoutMs for (;;) { const acks = client.messages.filter(m => m && m.t === 'ack' && ids.includes(m.reqId)) diff --git a/tools/prebuild.mjs b/tools/prebuild.mjs new file mode 100644 index 0000000..4cf4f73 --- /dev/null +++ b/tools/prebuild.mjs @@ -0,0 +1,16 @@ +// Warm the shared Nim build cache before a test file fans out. +// +// node --test runs every test *file* in its own process; with --test-concurrency > 1 several files +// start at once. lib.mjs cachedNimBuild already makes them share one build per variant, but the +// first file to ask pays the compiler while the others wait on the lock. This script builds the +// three server variants the harnesses use plus (for the server gate) the leak checker, once, +// before the suite starts. `server-only` is for the client e2e: it launches the server but never +// builds the checker. It is a pure cache warm-up: a test file still builds anything missing when +// run on its own. +import { buildChecker } from './leak.mjs' +import { buildServer } from './withserver.mjs' + +buildServer() +buildServer({ defines: ['leakfault'] }) +buildServer({ defines: ['dispfault'] }) +if (!process.argv.includes('server-only')) buildChecker() diff --git a/tools/test.sh b/tools/test.sh index d4d0c26..9408caf 100755 --- a/tools/test.sh +++ b/tools/test.sh @@ -1,20 +1,155 @@ #!/usr/bin/env bash # devbox run test: Nim in-process tests first, then the Node black-box harnesses (DESIGN 10.4). # Nim gates Node: a red Nim suite stops the run (the Node stage takes seconds, but no point). -# Logs land in results/ like the other gates. +# Gate summaries land in results/; per-job logs are scratch under run/logs/. +# +# Parallelism: every Nim test file compiles and runs independently (own nimcache per file name, +# their own temp state dirs, no ports), and every Node test file is its own process with its own +# server/nginx/state dir. Both phases therefore run FFF_TEST_JOBS at a time (default: half the +# cores, capped at 8; FFF_TEST_JOBS=1 serialises). The two Node files whose *assertions* are +# wall-clock gates (persistence's move-ack budget, tiles' lock-free burst) stay in a serial phase +# so their numbers are not measured under the suite's own load. cd "$(dirname "$0")/.." || exit 1 -mkdir -p results -if ! nimble test -y > results/nimble-test.log 2>&1; then - cat results/nimble-test.log +. tools/jobs.sh +mkdir -p results run/logs +fff_setup_tmpdir +JOBS=$(fff_test_jobs) + +# Warm the shared Nim build cache (server, the two fault variants, the leak checker) while the Nim +# tests compile: every Node test file then starts from a cached binary instead of racing to build. +rm -f run/logs/prebuild.rc +( node tools/prebuild.mjs > run/logs/prebuild.log 2>&1; echo $? > run/logs/prebuild.rc ) & + +# --- Nim in-process tests ----------------------------------------------------------------------- +# Same files and command nimble test runs (all tests/*.nim, debug, -r), but with a bounded pool. +NIM_LOG_DIR=run/logs/nim +rm -rf "$NIM_LOG_DIR"; mkdir -p "$NIM_LOG_DIR" +PKGS=${NIMBLE_DIR:-$PWD/.devbox/nimble}/pkgs2 +nim_one() { + local f=$1 base + base=$(basename "$f" .nim) + # Worktree-local nimcache: the global ~/.cache/nim/_d is shared by every checkout on the + # host, so two worktrees testing at once would write each other's object files. run/ is + # gitignored and the cache persists across runs, so a warm run pays nothing extra. + nim c -d:NimblePkgVersion=0.1.0 --nimblePath:"$PKGS" --path:. \ + --nimcache:"$PWD/run/nimcache/test-$base" -r --hints:off \ + "$f" > "$NIM_LOG_DIR/$base.log" 2>&1 + echo $? > "$NIM_LOG_DIR/$base.log.rc" +} +nim_files=(tests/*.nim) +running=0 +for f in "${nim_files[@]}"; do + nim_one "$f" & + running=$((running + 1)) + if [ "$running" -ge "$JOBS" ]; then + wait -n + running=$((running - 1)) + fi +done +wait +nim_rc=0 +: > results/nimble-test.log +for f in "${nim_files[@]}"; do + base=$(basename "$f" .nim) + log="$NIM_LOG_DIR/$base.log" + cat "$log" >> results/nimble-test.log + rc=$(cat "$log.rc" 2>/dev/null || echo 1) + if [ "$rc" -ne 0 ]; then + nim_rc=1 + printf '\n=== FAILED: %s (exit %s) ===\n' "$f" "$rc" >> results/nimble-test.log + fi +done +cat results/nimble-test.log +if [ "$nim_rc" -ne 0 ]; then exit 1 fi -cat results/nimble-test.log -# One file at a time: every harness builds and runs the same real binary (run/test/server) and -# starts real servers; serialising removes build/write races. Ports and state dirs are isolated. -node --test --test-concurrency=1 --test-reporter=spec tools/*.test.mjs > results/node-test.log 2>&1 -rc=$? + +# The shared build cache must be ready before the fan-out (the prebuild itself is not a gate: a +# Node test file builds what it needs on its own; a prebuild failure shows up there). +while [ ! -f run/logs/prebuild.rc ]; do sleep 0.2; done +if [ "$(cat run/logs/prebuild.rc)" -ne 0 ]; then + cat run/logs/prebuild.log + exit 1 +fi + +# --- Node black-box harnesses ------------------------------------------------------------------- +# Wall-clock gate files first, alone (their ack/burst budgets are load-sensitive), then the rest at +# FFF_TEST_JOBS. Every file test still runs exactly once; tools/evidence.mjs reads the combined log. +NODE_LOG_DIR=run/logs/node +rm -rf "$NODE_LOG_DIR"; mkdir -p "$NODE_LOG_DIR" +rm -f run/logs/faults-*.log +node_task() { # $1 logbase, $2 file, $3 shard (optional), $4 shards (optional) + local base=$1 file=$2 + if [ -n "${3:-}" ]; then + FFF_TEST_SHARD="$3" FFF_TEST_SHARDS="$4" node --test --test-reporter=spec "$file" \ + > "$NODE_LOG_DIR/$base.log" 2>&1 + else + node --test --test-reporter=spec "$file" > "$NODE_LOG_DIR/$base.log" 2>&1 + fi + echo $? > "$NODE_LOG_DIR/$base.log.rc" +} +node_pool() { # $1 concurrent tasks, then "logbase|file[|shard|shards]" specs + local pool=$1; shift + local running=0 spec base file shard shards + for spec in "$@"; do + IFS='|' read -r base file shard shards <<< "$spec" + node_task "$base" "$file" "$shard" "$shards" & + running=$((running + 1)) + if [ "$running" -ge "$pool" ]; then + wait -n 2>/dev/null + running=$((running - 1)) + fi + done + wait +} +NODE_SERIAL=(tools/persistence.test.mjs tools/tiles.test.mjs) +SERIAL_SPECS=() +for f in "${NODE_SERIAL[@]}"; do + SERIAL_SPECS+=("$(basename "$f" .test.mjs)|$f") +done +node_pool 1 "${SERIAL_SPECS[@]}" +# fault.test.mjs's independent cases are sharded across processes; when the gate is serialised, +# one shard keeps the same single process (and thus the same serial run). +FAULT_SHARDS=$JOBS +[ "$JOBS" -le 4 ] || FAULT_SHARDS=4 +PARALLEL_SPECS=() +for f in tools/*.test.mjs; do + case " ${NODE_SERIAL[*]} " in + *" $f "*) continue ;; + esac + # import-scale is its own script (`devbox run import-scale`, #83): a 16384 px memory/fd soak, + # not part of the pre-push gate. + [ "$f" = tools/importscale.test.mjs ] && continue + if [ "$f" = tools/fault.test.mjs ]; then + for i in $(seq 0 $((FAULT_SHARDS - 1))); do + PARALLEL_SPECS+=("fault-$i|$f|$i|$FAULT_SHARDS") + done + else + PARALLEL_SPECS+=("$(basename "$f" .test.mjs)|$f") + fi +done +node_pool "$JOBS" "${PARALLEL_SPECS[@]}" +rc=0 +: > run/logs/node-test-serial.log +for spec in "${SERIAL_SPECS[@]}"; do + base=${spec%%|*} + cat "$NODE_LOG_DIR/$base.log" >> run/logs/node-test-serial.log + [ "$(cat "$NODE_LOG_DIR/$base.log.rc")" -eq 0 ] || rc=1 +done +: > run/logs/node-test-parallel.log +for spec in "${PARALLEL_SPECS[@]}"; do + base=${spec%%|*} + cat "$NODE_LOG_DIR/$base.log" >> run/logs/node-test-parallel.log + [ "$(cat "$NODE_LOG_DIR/$base.log.rc" 2>/dev/null || echo 1)" -eq 0 ] || rc=1 +done +cat run/logs/node-test-serial.log run/logs/node-test-parallel.log > results/node-test.log +# The fault checker's per-shard output, in shard order, is the committed evidence file. +: > results/faults.log +for i in $(seq 0 $((FAULT_SHARDS - 1))); do + [ -f "run/logs/faults-$i.log" ] && cat "run/logs/faults-$i.log" >> results/faults.log +done cat results/node-test.log -[ $rc -eq 0 ] || exit $rc +[ "$rc" -eq 0 ] || exit "$rc" # #36: the group map's evidence is only proof if the named tests actually ran and passed. This is a # separate post-run step because groups.test.mjs runs inside the suite it would have to inspect. node tools/evidence.mjs results/node-test.log || exit 1 diff --git a/tools/withserver.mjs b/tools/withserver.mjs index 0606ff5..95fef60 100644 --- a/tools/withserver.mjs +++ b/tools/withserver.mjs @@ -5,7 +5,7 @@ import { spawn, spawnSync } from 'node:child_process' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { baseUrl, freePort, join, openWs, projectRoot, refuseLivePort, sleep } from './lib.mjs' +import { baseUrl, cachedNimBuild, freePort, join, openWs, projectRoot, refuseLivePort, sleep } from './lib.mjs' const SERVER_BIN = path.join(projectRoot, 'run', 'test', 'server') @@ -14,11 +14,12 @@ function nimblePkgs() { return path.join(nimbleDir, 'pkgs2') } -let builtAt = null const builtCache = new Map() // Build the real binary from the working tree. `defines` adds `-d:` flags (a leak-fault build, // DESIGN 10.3); each variant lands in its own file so the clean build is never overwritten. +// The build is cached by source+flags and shared across the concurrently-running test files +// (lib.mjs cachedNimBuild); a serial run pays each variant once, a parallel run pays nothing extra. export function buildServer(opts = {}) { const defines = opts.defines ?? [] const key = defines.join(',') @@ -26,19 +27,17 @@ export function buildServer(opts = {}) { ? SERVER_BIN : path.join(projectRoot, 'run', 'test', `server-${defines.join('-').replace(/[^A-Za-z0-9-]/g, '')}`)) if (builtCache.has(key)) return builtCache.get(key) - fs.mkdirSync(path.dirname(out), { recursive: true }) - // Worktree-local nimcache: Nim's default (~/.cache/nim/_d) is shared by every checkout of - // the repo, so two worktrees building at once corrupt each other's object files. run/ is - // gitignored, and the variant name keeps a fault build separate from the clean build's cache. const cache = path.join(projectRoot, 'run', 'nimcache', path.basename(out)) - const args = ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`, - `--nimcache:${cache}`, ...defines.map(d => `-d:${d}`), `-o:${out}`, - path.join('server', 'main.nim')] - const r = spawnSync('nim', args, { cwd: projectRoot, encoding: 'utf8' }) - if (r.status !== 0) throw new Error(`nim c server/main.nim ${defines.join(' ')} failed:\n${r.stdout}\n${r.stderr}`) - builtAt = out - builtCache.set(key, out) - return out + const built = cachedNimBuild({ + out, + roots: ['server'], + extra: `${defines.join(',')}\n${nimblePkgs()}\n`, + nimArgs: tmp => ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`, + `--nimcache:${cache}`, ...defines.map(d => `-d:${d}`), `-o:${tmp}`, + path.join('server', 'main.nim')], + }) + builtCache.set(key, built) + return built } export function makeStateDir(prefix = 'fffvtt-') {