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.
This commit is contained in:
2026-11-21 21:40:07 +01:00
parent 30b35592c7
commit 1ac46b4969
9 changed files with 396 additions and 49 deletions
+2
View File
@@ -8,6 +8,8 @@ nimcache/
tests/t[a-z]* tests/t[a-z]*
!tests/*.nim !tests/*.nim
!tests/fixtures/ !tests/fixtures/
# tests/refold.nim is a helper module nimble test also compiles; its output binary is scratch
/tests/refold
tools/bench tools/bench
tools/mkcorpus tools/mkcorpus
run/ run/
+28 -4
View File
@@ -3,9 +3,18 @@
# browser suite against the real server through the TLS/HTTP2 test nginx. Separate from # 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 # `devbox run test` so the fast server gate stays fast (TESTING 11.1); the client's own unit tests
# are `devbox run client-test`. # 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 set -euo pipefail
cd "$(dirname "$0")/../.." || exit 1 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)}" export CHROMIUM="${CHROMIUM:-$(command -v chromium || true)}"
if [ -z "$CHROMIUM" ]; then if [ -z "$CHROMIUM" ]; then
echo "e2e: chromium not found; it is a root devbox package (devbox.json) - run inside devbox" >&2 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. # 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 && { [ -d node_modules ] || npm ci --no-audit --no-fund; } )
( cd client && npm run build ) ( cd client && npm run build )
node --test --test-concurrency=1 --test-reporter=spec client/e2e/*.test.mjs > results/e2e.log 2>&1 # Shared Nim build cache: the server binaries the stacks launch (and the leak checker) are built
rc=$? # 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 cat results/e2e.log
exit $rc [ "${rc:-0}" -eq 0 ] || exit "$rc"
+22 -3
View File
@@ -18,7 +18,18 @@ import { buildServer, gmKeyOf, makeStateDir, signIn, startServer, stopServer } f
import { openWs } from './lib.mjs' import { openWs } from './lib.mjs'
import { projectRoot } 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). // fault -> the exact set of classes the checker must report (nothing more, nothing less).
// //
@@ -60,6 +71,9 @@ function classesOf(output) {
.sort() .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', () => { test('the shipped build carries no fault hook and passes the leak test', () => {
const bin = buildServer() const bin = buildServer()
const bytes = fs.readFileSync(bin) 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)) { for (const [fault, expected] of Object.entries(FAULTS)) {
if (faultCase++ % SHARDS !== SHARD) continue
test(`fault ${fault}: caught as exactly ${expected.join(' ')}`, async () => { test(`fault ${fault}: caught as exactly ${expected.join(' ')}`, async () => {
fs.mkdirSync(results, { recursive: true }) fs.mkdirSync(logs, { recursive: true })
const stateDir = makeStateDir() const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir) const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir, defines: ['leakfault'], env: { LEAK_FAULT: fault } }) const s = await startServer({ stateDir, defines: ['leakfault'], env: { LEAK_FAULT: fault } })
@@ -77,7 +92,7 @@ for (const [fault, expected] of Object.entries(FAULTS)) {
try { try {
await runLeak({ origin: s.origin, gmKey, stateDir, transcript }) await runLeak({ origin: s.origin, gmKey, stateDir, transcript })
const check = runChecker(transcript, 'A') 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`) `== fault ${fault}\n${check.output}\n`)
assert.notEqual(check.status, 0, `the checker passed a leak (${fault}):\n${check.output}`) assert.notEqual(check.status, 0, `the checker passed a leak (${fault}):\n${check.output}`)
assert.deepEqual(classesOf(check.output), expected.sort(), 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 // #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. // 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', () => { test('the shipped build carries no dispatch fault hook', () => {
const bin = buildServer() const bin = buildServer()
const bytes = fs.readFileSync(bin) const bytes = fs.readFileSync(bin)
@@ -107,6 +123,7 @@ async function gmSession(s) {
return { ws, sceneId: hello.scene.id } return { ws, sceneId: hello.scene.id }
} }
if (SHARD === 0)
test('a CatchableError inside a locked mutation: one internal ack, then the server keeps serving', test('a CatchableError inside a locked mutation: one internal ack, then the server keeps serving',
async () => { async () => {
const stateDir = makeStateDir() 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 () => { test('a Defect inside a locked mutation: one internal ack and no open transaction', async () => {
const stateDir = makeStateDir() const stateDir = makeStateDir()
const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'txn-defect' } }) 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 () => { test('a failure after the ack was enqueued never appends a second ack', async () => {
const stateDir = makeStateDir() const stateDir = makeStateDir()
const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'after-ack' } }) const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'after-ack' } })
+46
View File
@@ -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
}
+13 -9
View File
@@ -34,7 +34,7 @@
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { spawnSync } from 'node:child_process' 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' import { signIn } from './withserver.mjs'
const QUIET_MS = 60 const QUIET_MS = 60
@@ -43,18 +43,22 @@ const QUIET_MS = 60
const FAR_WALL_X = 1400 const FAR_WALL_X = 1400
const nimblePkgs = () => path.join(process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble'), 'pkgs2') 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 let checkerBin = null
export function buildChecker() { export function buildChecker() {
if (checkerBin) return checkerBin if (checkerBin) return checkerBin
const out = path.join(projectRoot, 'run', 'test', 'leakcheck') const out = path.join(projectRoot, 'run', 'test', 'leakcheck')
fs.mkdirSync(path.dirname(out), { recursive: true }) checkerBin = cachedNimBuild({
const r = spawnSync('nim', ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`, out,
`-o:${out}`, path.join('tools', 'leakcheck.nim')], roots: [path.join('tools', 'leakcheck.nim'), 'server', 'nim.cfg'],
{ cwd: projectRoot, encoding: 'utf8' }) extra: `-d:release\n${nimblePkgs()}\n`,
if (r.status !== 0) throw new Error(`nim c tools/leakcheck.nim failed:\n${r.stdout}\n${r.stderr}`) nimArgs: tmp => ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`,
checkerBin = out `--nimcache:${path.join(projectRoot, 'run', 'nimcache', 'leakcheck')}`,
return out `-o:${tmp}`, path.join('tools', 'leakcheck.nim')],
})
return checkerBin
} }
export function runChecker(transcript, subject) { export function runChecker(transcript, subject) {
+111 -9
View File
@@ -3,6 +3,7 @@
// re-verifies on the wire that Cookie and Origin reach the server (the old "Node 22" note in // 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). // the prototype's lib.mjs was stale; here the pin is the devbox node 26).
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process'
import fs from 'node:fs' import fs from 'node:fs'
import net from 'node:net' import net from 'node:net'
import path from 'node:path' import path from 'node:path'
@@ -10,6 +11,11 @@ import { fileURLToPath } from 'node:url'
export const sleep = ms => new Promise(r => setTimeout(r, ms)) 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))) 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 // 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 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)] 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}` 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 // 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: [], messages: [],
nextReqId: 1, nextReqId: 1,
pending: new Map(), pending: new Map(),
request(payload, timeoutMs = 5000) { request(payload, timeoutMs = HARNESS_TIMEOUT_MS) {
const reqId = client.nextReqId++ const reqId = client.nextReqId++
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const timer = setTimeout(() => { const timer = setTimeout(() => {
@@ -132,7 +234,7 @@ export async function openWs(origin, cookie, opts = {}) {
ws.send(typeof objOrText === 'string' ? objOrText : JSON.stringify(objOrText)) ws.send(typeof objOrText === 'string' ? objOrText : JSON.stringify(objOrText))
}, },
// First already-received or future message matching pred (the server's frames are async). // 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 const deadline = Date.now() + timeoutMs
for (;;) { for (;;) {
const hit = client.messages.find(pred) const hit = client.messages.find(pred)
@@ -144,7 +246,7 @@ export async function openWs(origin, cookie, opts = {}) {
await sleep(10) 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) return await client.waitFor(m => m && m.t === t, timeoutMs)
}, },
} }
@@ -164,7 +266,7 @@ export async function openWs(origin, cookie, opts = {}) {
resolveClosed(closeInfo) resolveClosed(closeInfo)
} }
await new Promise((resolve, reject) => { 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) }) wireOpen(ws, () => { clearTimeout(timer); resolve() }, e => { clearTimeout(timer); reject(e) })
}) })
ws.onerror = () => {} // post-open errors surface as a close ws.onerror = () => {} // post-open errors surface as a close
@@ -200,7 +302,7 @@ export async function rawUpgrade(origin, opts = {}) {
if (err) reject(err) if (err) reject(err)
else resolve(value) 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('connect', () => sock.write(lines.join('\r\n') + '\r\n\r\n'))
sock.on('data', chunk => { sock.on('data', chunk => {
buf += chunk.toString('latin1') buf += chunk.toString('latin1')
@@ -323,7 +425,7 @@ export async function rawWs(origin, opts = {}) {
client.sendFrame(OP_CLOSE, body) client.sendFrame(OP_CLOSE, body)
}, },
// First already-received or future frame matching pred. Rejects after timeoutMs. // 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 const deadline = Date.now() + timeoutMs
for (;;) { for (;;) {
const hit = client.frames.find(pred) const hit = client.frames.find(pred)
@@ -335,7 +437,7 @@ export async function rawWs(origin, opts = {}) {
await sleep(5) 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) const frame = await client.waitFor(f => f.opcode === OP_TEXT && f.text && JSON.parse(f.text).t === t, timeoutMs)
return JSON.parse(frame.text) return JSON.parse(frame.text)
}, },
@@ -351,7 +453,7 @@ export async function rawWs(origin, opts = {}) {
}) })
await new Promise((resolve, reject) => { 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 buf = Buffer.alloc(0)
let open = false let open = false
sock.on('connect', () => sock.write(lines.join('\r\n') + '\r\n\r\n')) 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 // 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. // "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 const deadline = Date.now() + timeoutMs
for (;;) { for (;;) {
const acks = client.messages.filter(m => m && m.t === 'ack' && ids.includes(m.reqId)) const acks = client.messages.filter(m => m && m.t === 'ack' && ids.includes(m.reqId))
+16
View File
@@ -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()
+145 -10
View File
@@ -1,20 +1,155 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# devbox run test: Nim in-process tests first, then the Node black-box harnesses (DESIGN 10.4). # 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). # 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 cd "$(dirname "$0")/.." || exit 1
mkdir -p results . tools/jobs.sh
if ! nimble test -y > results/nimble-test.log 2>&1; then mkdir -p results run/logs
cat results/nimble-test.log 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/<file>_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 exit 1
fi fi
cat results/nimble-test.log
# One file at a time: every harness builds and runs the same real binary (run/test/server) and # The shared build cache must be ready before the fan-out (the prebuild itself is not a gate: a
# starts real servers; serialising removes build/write races. Ports and state dirs are isolated. # Node test file builds what it needs on its own; a prebuild failure shows up there).
node --test --test-concurrency=1 --test-reporter=spec tools/*.test.mjs > results/node-test.log 2>&1 while [ ! -f run/logs/prebuild.rc ]; do sleep 0.2; done
rc=$? 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 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 # #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. # 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 node tools/evidence.mjs results/node-test.log || exit 1
+13 -14
View File
@@ -5,7 +5,7 @@ import { spawn, spawnSync } from 'node:child_process'
import fs from 'node:fs' import fs from 'node:fs'
import os from 'node:os' import os from 'node:os'
import path from 'node:path' 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') const SERVER_BIN = path.join(projectRoot, 'run', 'test', 'server')
@@ -14,11 +14,12 @@ function nimblePkgs() {
return path.join(nimbleDir, 'pkgs2') return path.join(nimbleDir, 'pkgs2')
} }
let builtAt = null
const builtCache = new Map() const builtCache = new Map()
// Build the real binary from the working tree. `defines` adds `-d:` flags (a leak-fault build, // 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. // 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 = {}) { export function buildServer(opts = {}) {
const defines = opts.defines ?? [] const defines = opts.defines ?? []
const key = defines.join(',') const key = defines.join(',')
@@ -26,19 +27,17 @@ export function buildServer(opts = {}) {
? SERVER_BIN ? SERVER_BIN
: path.join(projectRoot, 'run', 'test', `server-${defines.join('-').replace(/[^A-Za-z0-9-]/g, '')}`)) : path.join(projectRoot, 'run', 'test', `server-${defines.join('-').replace(/[^A-Za-z0-9-]/g, '')}`))
if (builtCache.has(key)) return builtCache.get(key) if (builtCache.has(key)) return builtCache.get(key)
fs.mkdirSync(path.dirname(out), { recursive: true })
// Worktree-local nimcache: Nim's default (~/.cache/nim/<project>_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 cache = path.join(projectRoot, 'run', 'nimcache', path.basename(out))
const args = ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`, const built = cachedNimBuild({
`--nimcache:${cache}`, ...defines.map(d => `-d:${d}`), `-o:${out}`, out,
path.join('server', 'main.nim')] roots: ['server'],
const r = spawnSync('nim', args, { cwd: projectRoot, encoding: 'utf8' }) extra: `${defines.join(',')}\n${nimblePkgs()}\n`,
if (r.status !== 0) throw new Error(`nim c server/main.nim ${defines.join(' ')} failed:\n${r.stdout}\n${r.stderr}`) nimArgs: tmp => ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`,
builtAt = out `--nimcache:${cache}`, ...defines.map(d => `-d:${d}`), `-o:${tmp}`,
builtCache.set(key, out) path.join('server', 'main.nim')],
return out })
builtCache.set(key, built)
return built
} }
export function makeStateDir(prefix = 'fffvtt-') { export function makeStateDir(prefix = 'fffvtt-') {