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
+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
// 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))