Files
msd-core/scripts/gen-test-timings.cjs
Tom Boucher 953b8043ea fix(#2456): weight test chunks by measured cost and pack with LPT (#2463)
* fix(#2456): weight test chunks by measured cost and pack with LPT

scripts/run-tests.cjs guessed each test file's cost from its filename
(basename matching /^(?:install|codex-)/ scored 12, everything else 1).
Measured durations show that guess is wrong in both directions:
installer-migration-authoring.test.cjs scored 12 while running ~0.1s, and
the two most expensive files in the suite both scored 1 —
run-tests-harness.test.cjs never matched the prefix, and
release-tarball-smoke.install.test.cjs was missed because the regex is
anchored to the START of the basename.

Chunks were therefore balanced by file COUNT, not cost. On the real
shard 2/3 the two heaviest files packed into the SAME chunk, leaving the
slowest chunk 2.8x the lightest and sitting near the 600s per-chunk
timeout while other chunks idled.

Weight each file by its measured duration from a checked-in, regenerable
timings table and pack with LPT (heaviest first, into the lightest
chunk). On the same shard this drops the slowest chunk from 383s to 238s
and the imbalance from 2.79x to 1.00x, and separates the two heavy files.

Timings are advisory, never gated: an unknown file falls back to the
table's median weight, a missing or corrupt table falls back to uniform
weight, and a count-based floor guarantees the packer never produces
fewer chunks than plain count-based packing would.

Closes #2456

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2456): harden chunk packing against degenerate knobs and table keys

Follow-up hardening found while reviewing the packer, fixed inline.

The chunk knobs are read from the environment with Number(), so a typo
(RUN_TESTS_MAX_FILES_PER_CHUNK=abc) yields NaN and an explicit 0 yields
0. Both flow into the new chunk-count arithmetic: NaN made Math.ceil
return NaN, Array.from({length: NaN}) produce zero bins, and packChunks'
retry loop spin forever — a hung CI job with no output. Zero made the
count Infinity and threw RangeError: Invalid array length. The previous
count-based packer degraded to a single chunk instead, so this was a
regression introduced by the LPT rewrite.

Normalize the knobs at the environment boundary (positiveNumberEnv:
anything not a positive finite number falls back to the default) and
guard packChunks itself, since it is exported and cannot assume its
caller normalized. Non-finite weights from an arbitrary weightOf are
clamped too. RUN_TESTS_CHUNK_TIMEOUT_MS gets the same treatment.

Also resolve timing-table lookups with Object.hasOwn: the table is
JSON-parsed, so a bare index would walk the prototype chain and return a
function for a file named constructor.test.cjs or toString.test.cjs.
The typeof guard already rejected that, but the lookup now resolves
correctly rather than relying on the downstream check.

Refs #2456

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2456): correct prototype-lookup rationale and guard generator keys

Two findings from independent security review, fixed inline.

The makeFileWeigher comment claimed a bare table lookup "would return a
FUNCTION for a file named constructor.test.cjs". That premise is false:
basename('constructor.test.cjs') is 'constructor.test.cjs', which is not
an Object.prototype key, and walkTestFiles only ever collects *.test.cjs.
The prototype chain was never reachable from a real selection, and the
existing typeof guard already rejected the function it would return, so
Object.hasOwn is defense-in-depth rather than a behavior change. The
comment now says that instead of asserting something untrue.

The accompanying test inherited the same false premise: it fed
constructor.test.cjs and asserted a median fallback that would have held
with or without the guard, so it passed for a reason unrelated to what
it claimed to prove. It now uses BARE keys (constructor, toString,
valueOf, hasOwnProperty, __proto__) — the only inputs that actually
resolve on Object.prototype — and asserts the real exported contract:
any key absent from the table weighs the median, never a function.

gen-test-timings.cjs built its output object by computed-key assignment
from basenames taken out of a reporter stream it does not control — the
js/prototype-polluting-assignment shape, and this repo has a CodeQL
barrier for exactly that pattern. It was not exploitable (the value is
always a rounded number, so the __proto__ setter is a silent no-op), but
it silently DROPPED such an entry rather than reporting it. Validate every
key against a test-basename pattern and fail loudly instead, and build
the table with a null prototype.

Refs #2456

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2456): replace tautological chunking tests and clamp chunk count

Six findings from independent correctness review, all reproduced and
fixed inline.

The two subprocess tests written to carry the #2088 guarantee forward
were tautological: every seeded file weighed exactly 1, so both passed
under the OLD prefix-heuristic packer and with the timings file deleted
entirely. Neither could fail for the reason it existed. Both are rebuilt
so the old algorithm produces a different packing and the assertion goes
red: the spread test now uses three expensive files named so the old
heuristic scored them 1 alongside three trivial `install-`-prefixed
files it scored 12 — inverted from real cost, giving {2,2,1,1} under the
old packer versus {2,2,2} under measured weights. The companion test
covers the other direction: four trivial `install-` files the old
heuristic split into four single-file chunks now stay in one.

packChunks clamped the chunk count from below but not above, so a
legitimate but tiny budget (RUN_TESTS_MAX_FILES_PER_CHUNK=1e-9, which
positiveNumberEnv accepts) asked for 637,000,000,000 bins and threw
RangeError. More chunks than files is never useful; the count now clamps
at one file per chunk.

The generator's basename-collision guard compared full dirnames, so two
OS lanes reporting the same file under different container roots
(/work/tests vs C:/work/tests) flagged every shared basename as a
collision — on the script's own documented multi-lane usage. Detection is
now scoped per stream, where the root is constant; a genuine same-lane
collision is still caught.

Also: the LPT tie-break compared raw paths, so a path separator (0x2F vs
0x5C) could order a subdir file differently per platform, contradicting
the documented byte-identical guarantee — it now normalizes separators.
loadTestTimings now honors schema_version instead of writing it and
never reading it, falling back to uniform weight on an unknown version.
A comment claiming an all-uniform suite "chunks exactly as it did
before" was false and contradicted by this PR's own test: the chunk
count is preserved, the composition is not. And the missing-table test
created a temp dir it never cleaned up, for a path that only needed to
not exist.

Refs #2456

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 16:51:35 -04:00

202 lines
8.0 KiB
JavaScript

#!/usr/bin/env node
// Regenerate the per-file test timing table used to weight chunk packing in
// scripts/run-tests.cjs (issue #2456).
//
// The chunk packer needs to know what each test file actually COSTS. Before
// #2456 it guessed from the filename (`^(?:install|codex-)` scored 12x,
// everything else 1) and was wrong in both directions — installer-migration-
// authoring.test.cjs scored 12x but runs ~0.1s, while the two heaviest files in
// the suite (run-tests-harness.test.cjs and release-tarball-smoke.install
// .test.cjs) both scored 1. This script replaces the guess with measurement.
//
// Input is one or more node:test reporter event streams as emitted by
// `gsd-test` (`~/.local/state/gsd-test/runs/<run-id>/test-events-<os>-node<v>
// .jsonl`). Each stream carries one `test:summary` event per test FILE, whose
// `data.duration_ms` is that file's total wall-clock and whose `data.file` is
// its absolute in-container path.
//
// Usage:
// node scripts/gen-test-timings.cjs <events.jsonl> [<events.jsonl> ...]
// node scripts/gen-test-timings.cjs ~/.local/state/gsd-test/runs/*/test-events-*.jsonl
// node scripts/gen-test-timings.cjs events.jsonl --out tests/test-timings.json
//
// When several streams are supplied (multiple lanes, e.g. node22 + node24), a
// file's recorded time is the MAX across them, not the mean: the packer exists
// to keep the SLOWEST lane's slowest chunk away from the per-chunk timeout, so
// the conservative bound is the right one to balance against.
//
// The table is ADVISORY and deliberately un-gated — there is no `--check` mode
// and no CI lint that fails on staleness, because timing data legitimately
// varies run to run. A file missing from the table falls back to the table's
// median weight, so a stale table degrades chunk BALANCE gracefully instead of
// failing the build. Regenerate it when the suite's cost profile has visibly
// drifted, not on a schedule.
'use strict';
const fs = require('fs');
const { basename, dirname, join } = require('path');
const { ExitError, runMain } = require('./lib/cli-exit.cjs');
const DEFAULT_OUT = join(__dirname, '..', 'tests', 'test-timings.json');
const SCHEMA_VERSION = 1;
function parseArgs(argv) {
const inputs = [];
let out = DEFAULT_OUT;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out') {
const value = argv[++i];
if (!value) return { error: '--out requires a path' };
out = value;
} else if (arg.startsWith('--out=')) {
const value = arg.slice('--out='.length);
if (!value) return { error: '--out requires a path' };
out = value;
} else if (arg.startsWith('-')) {
return { error: `unknown flag "${arg}"` };
} else {
inputs.push(arg);
}
}
if (inputs.length === 0) {
return { error: 'usage: gen-test-timings.cjs <reporter-events.jsonl> [...] [--out <path>]' };
}
return { inputs, out };
}
// Fold one reporter event stream into `acc`, keeping the MAX duration seen for
// each test file. Returns per-stream counters plus any basename collisions
// found WITHIN this stream.
//
// Keying is by BASENAME, matching how run-tests.cjs weights a selected file:
// the reporter reports absolute in-container paths (/work/tests/foo.test.cjs)
// while the harness carries paths relative to its test dir, so the basename is
// the only stable join key between the two. A basename seen in two different
// directories would make the table ambiguous, so it must fail loudly.
//
// Collision detection is scoped to a SINGLE stream deliberately. Every lane
// writes its own stream under its own container root (`/work/tests` on Linux,
// `C:/work/tests` on Windows), so comparing directories ACROSS streams reports
// every shared basename as a collision — which is the script's own documented
// usage (globbing `test-events-*.jsonl` across lanes). Within one stream the
// root is constant, so a differing directory is a real collision.
function foldStream(text, acc) {
const dirsByBase = new Map();
let files = 0;
let malformed = 0;
for (const line of text.split('\n')) {
if (line.trim() === '') continue;
let event;
try {
event = JSON.parse(line);
} catch {
malformed++;
continue;
}
if (!event || event.type !== 'test:summary') continue;
const data = event.data;
if (!data || typeof data.file !== 'string') continue;
const ms = data.duration_ms;
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) continue;
const path = data.file.replace(/\\/g, '/');
const base = basename(path);
if (!dirsByBase.has(base)) dirsByBase.set(base, new Set());
dirsByBase.get(base).add(dirname(path));
const prev = acc.get(base);
if (prev === undefined || ms > prev) acc.set(base, ms);
files++;
}
const collisions = [...dirsByBase.entries()]
.filter(([, dirs]) => dirs.size > 1)
.map(([base, dirs]) => `${base} (${[...dirs].sort().join(', ')})`);
return { files, malformed, collisions };
}
function main() {
const parsed = parseArgs(process.argv.slice(2));
if (parsed.error) throw new ExitError(2, `gen-test-timings: ${parsed.error}`);
const acc = new Map();
const allCollisions = new Set();
const sources = [];
for (const input of parsed.inputs) {
let text;
try {
text = fs.readFileSync(input, 'utf8');
} catch (err) {
throw new ExitError(2, `gen-test-timings: cannot read "${input}": ${err.message}`);
}
const { files, malformed, collisions } = foldStream(text, acc);
for (const c of collisions) allCollisions.add(c);
sources.push(basename(input));
console.error(
`gen-test-timings: ${basename(input)} — ${files} file summaries` +
(malformed > 0 ? `, ${malformed} unparseable lines skipped` : ''),
);
}
if (acc.size === 0) {
throw new ExitError(
2,
'gen-test-timings: no `test:summary` events with a file and duration_ms were found. ' +
'Check that the input is a node:test reporter event stream (test-events-<os>-node<v>.jsonl).',
);
}
// A basename that resolves to two different directories within one lane makes
// the table ambiguous: run-tests.cjs joins on basename alone, so one file's
// measured cost would silently be applied to the other. Fail rather than emit
// a table that lies.
if (allCollisions.size > 0) {
throw new ExitError(
2,
`gen-test-timings: basename collision — the table cannot key on basename alone:\n ${[...allCollisions].sort().join('\n ')}`,
);
}
// Every key must be a plain test-file basename. This is a data-integrity
// check on a stream we do not control (the reporter emits whatever path the
// runner saw), and it structurally excludes a computed key like `__proto__`
// or `constructor` from being written into the table object below — the
// `js/prototype-polluting-assignment` shape, even though the value here is
// always a number and could not actually pollute.
const SAFE_BASENAME_RE = /^[A-Za-z0-9._-]+\.test\.cjs$/;
const rejected = [...acc.keys()].filter((base) => !SAFE_BASENAME_RE.test(base));
if (rejected.length > 0) {
throw new ExitError(
2,
`gen-test-timings: refusing to emit non-test-file keys: ${rejected.sort().join(', ')}`,
);
}
// Sorted keys keep the checked-in diff reviewable: a regeneration shows only
// the files whose cost actually moved, not a reshuffled object.
const timings = Object.create(null);
for (const base of [...acc.keys()].sort()) {
timings[base] = Math.round(acc.get(base));
}
const payload = {
schema_version: SCHEMA_VERSION,
generated_by: 'scripts/gen-test-timings.cjs',
unit: 'ms',
sources: sources.sort(),
file_count: acc.size,
timings,
};
fs.writeFileSync(parsed.out, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
const totalMs = [...acc.values()].reduce((sum, ms) => sum + ms, 0);
console.error(
`gen-test-timings: wrote ${parsed.out} — ${acc.size} files, ${(totalMs / 1000).toFixed(1)}s total`,
);
return 0;
}
if (require.main === module) {
runMain(main);
}
module.exports = { parseArgs, foldStream };