Files
msd-core/tests/helpers/overlay-repo.cjs
Tom Boucher c28134ab39 fix(#3271): delete 25 duplicated folded test suites and fix three runner defects found doing it (#3285)
* test(#3271): guard against a folded suite appearing twice in one host

Adds local/no-duplicate-fold-marker, an AST rule that reports the second and
every subsequent `folded:<name>` marker in a host file, plus RuleTester cases
and a tree-wide regression assertion.

Failing-first on purpose: the rule is registered at error and the 25 duplicated
regions are still present, so eslint and the new tree-wide test are RED. The
deletions land in the next commit.

The marker key is the whitespace-delimited token after `folded:` — not the
issue's `[a-z0-9-]*` slice, which truncates at `.` and false-positives on
tests/model-resolver.test.cjs where feat-443-effort-fast-mode.integration and
feat-443-effort-fast-mode are two distinct folded suites.

Refs #3271

* fix(#3271): delete 25 duplicated folded suites from three install hosts

Three consolidated install suites each carried a verbatim second copy of a
contiguous run of #1969 B1 folded blocks. Byte-identical, constant offset, and
green — each duplicated block registered and ran twice on every lane.

  tests/install.test.cjs                   5981-9937  (3957 lines, 18 blocks)
  tests/install-minimal-hooks.test.cjs     2734-4015  (1282 lines,  5 blocks)
  tests/install-write-confinement.test.cjs 1754-2321  ( 568 lines,  2 blocks)

Introduced by 6d072435d (#1975 re-applying #1970's hunks on a tree that already
had them, 2026-07-03) — one stale-base re-application, three files, one commit.
Verified by marker-count bisect: 1 at 4f779eda4 and 0cc7a1a42, 2 from 6d072435d
onward.

The later copy is deleted in each case, so every file returns to what its
authoring batch produced and blame on the surviving lines stays accurate.
local/no-duplicate-fold-marker, red on the previous commit, is now green.

tests/model-resolver.test.cjs is untouched: the issue lists it, but its two
blocks are folded from two different files and are not identical. It is a false
positive of the issue's own grep, whose `[a-z0-9-]*` key truncates at `.`.

Fixes #3271

* test(#3271): property-test marker identity and pin the alias non-goal

Three review findings, all fixed inline:

1. foldMarkerOf is a parser and carried no fast-check property test. Raised
   independently by the /code-review standards axis and the isolated adversarial
   pass; the file already establishes the fc.property-driving-ruleTester idiom
   for a sibling rule. Added, two arms over markers generated from [a-z0-9-._]:
   the same marker twice always reports exactly once against firstLine 1, and
   two distinct markers never collide. The alphabet includes `.` on purpose —
   an implementation keyed on the issue's [a-z0-9-]* slice passes arm 1 and
   fails arm 2, which is exactly the model-resolver false positive.

2. meta.docs.category was the novel value 'Test hygiene'; all 16 sibling local
   rules use 'Best Practices', 'Portability' or 'Reliability'. Now
   'Best Practices'.

3. A call through a further alias (const d = __foldDescribe) was unreported and
   undocumented — accidental rather than deliberate. It is now the fourth entry
   in the rule's documented non-goals, with the reason, and pinned by a valid
   RuleTester case so it cannot drift silently.

Refs #3271

* test(#3271): name the step and elapsed time when a baseline build fails

buildBaselineAtRef runs four bounded steps and, when one exceeded its bound,
threw a bare "spawnSync ETIMEDOUT" naming neither the step nor how long
anything took. Diagnosing one real failure took four separate experiments to
recover information the throw already had.

Each step is now timed, and any throw carries the breakdown: which step failed,
its elapsed time, the timings of every step that completed before it, all three
bounds, and the tail of the child's captured stdout/stderr.

The failure message is deliberately the carrier. On the remote runner the
captured output field comes back empty in failures.json while error and stack
survive verbatim, so the message is the only channel that reaches a reader of a
remote verdict.

Refs #3271

* fix(#3271): size the baseline generator bound for the machine it runs on

Instrumentation from a real remote-runner failure gave the breakdown:

  git-worktree-add=15.1s  npm-run-build-lib=19.8s  gen-emitted-baseline=FAILED@300.1s

Steps 1 and 2 are comfortable. Only the generator exceeds its bound, and it is
not hung — it needs more than 300s there.

Measured ladder for that step: ~22s idle in a container, ~39s end-to-end in a
clean container, ~142s with 8 CPU burners on 8 cores, and >300s under the real
suite. Its cost is 19 sequential installer spawns, and spawn latency is exactly
where a container degrades worst (3.9x slower than host, against 1.1x for file
IO) — which is why a CPU-only load test did not reproduce it and why four
earlier hypotheses (container slowness, network, shallow clone, CPU contention)
all measured clean.

The 300s bound was sized on an idle machine for a step that never runs on one.
Under the remote runner the on-disk baseline cache is structurally absent — CI
restores it via actions/cache keyed on github.event.pull_request.base.sha, a key
that exists only inside GitHub Actions — so this slow path runs on every remote
verification. The result: this gate has passed 0 times in 754 runs, failing 80
times and never once executing successfully.

Raised to the 600000ms ceiling that local/no-unbounded-spawn treats as the
largest meaningful bound; the other two bounds are untouched. This makes the
gate RUN, which is the point: the alternative considered and rejected was
degrading the timeout to a skip, and that was measured to turn the suite green
with the gate silently not running at all.

The real remedy is making the cache reachable from the remote runner so the
in-job build returns to being the rare fallback ADR-2719 §5 describes. That is a
gsd-test-runner change, not one this repo can make.

Refs #3271

* fix(#3271): tolerate an overlay source that vanishes mid-walk

Observed on the remote runner, three runs across three different branches:

  ENOENT: no such file or directory, link '/work/hooks/dist/gsd-config-reload.js'
    -> '/tmp/gsd-2930-overlay-6nOZay/hooks/dist/gsd-config-reload.js'

buildOverlayRepo enumerates names with readdirSync and then acts on each one, so
statSync, copyFileSync and linkSync all sit in a TOCTOU window. hooks/dist is
regenerated by an ATOMIC REPLACE (scripts/build-hooks.js unlinks and renames), so
any concurrently running test that rebuilds hooks retires a just-listed name
mid-walk and the overlay dies on it. linkOrCopyFile already tolerated EXDEV and
EPERM; ENOENT went straight through.

On ENOENT the source is now re-examined ONCE rather than slept on. An atomic
rename is a single syscall, so by the time the failure surfaces the successor is
either already in place (the retry succeeds) or the path has genuinely left the
tree, in which case there is nothing to mirror and the leaf is skipped. No sleep
and no spin: a timing-based wait here would be the very flake being fixed. Every
other errno still propagates untouched, so a real permission or IO fault stays a
hard failure.

Five tests hold the boundary: gone-for-good skips without retrying, mid-replace
retries exactly once and places the file, EACCES still throws, a real linkSync
ENOENT is injected by monkeypatching fs and restoring it in a finally (never a
mode-bit trick, which root bypasses), and isMissingPath accepts only ENOENT.

Refs #3271

* fix(#3271): order the timeout ladder inward-out and lock it

Two review blockers, both real.

The generator bound had been raised to 600000ms — exactly the whole-chunk timeout
in scripts/run-tests.cjs:973. A step bound equal to the chunk ceiling loses the
race: the chunk is killed first and the failure arrives as an opaque "no failed
step" kill, so the per-step diagnostic added a commit earlier was built and then
made unreachable in the same change.

Separately the #2767 test declared a per-test timeout of 300000ms, BELOW the
inner bound it was meant to permit, so it could still die at the exact 300s
ceiling this was supposed to lift — via node:test's timeout rather than
spawnSync's. Its sibling declared 900000ms, above the chunk ceiling, which is the
same opaque-kill hazard from the other direction.

The three bounds only produce a useful failure if they fire inward-out, so they
now do: step 360s, per-test 480s, chunk 600s. 360s is ~3x the passing observation
(91.6s / 115.8s) and 20% above the censored 300.1s timeout, while leaving 240s of
chunk headroom for every other file sharing it. Four tests lock the ordering,
including a drift guard on the exported values — without it, editing a call
site's literal timeout would leave the ordering assertions passing while the real
ladder inverted.

Also from review:

- err.gsdBaselineStep and err.gsdBaselineTimings were written and never read
  anywhere in the tree; only the rewritten message is consumed. Removed rather
  than kept as speculative surface.
- buildOverlayRepo discarded placeVanishableLeaf's boolean at both call sites, so
  a vanished leaf left the overlay with no accounting at all. It now collects the
  skipped paths and warns once. Not thrown: a source that left the tree really is
  not part of the snapshot, and throwing would reintroduce the crash the
  tolerance removes — but silence would let a dropped leaf resurface later as an
  unrelated missing-file assertion.
- The instrumentation commit shipped no test. One now drives a real failure and
  asserts the message names the step, its elapsed time, and the bounds.

Refs #3271

* chore(#3271): backfill the changeset PR number

* fix(#3271): bound a hook fan-out as its own class, not as a bare probe

CI failure on PR #3285, job full test (windows-latest, 22, shard 2/3) — every
other lane green, including windows-latest node 24 across all three shards:

  not ok 1 - blocks push when any to-be-pushed commit matches local blocked regex
    error: bash .githooks\pre-push failed — outcome=timed_out exitCode=null stderr=
    duration_ms: 15040.2168

A bound, not a hang: the test supplies stdin via input:, so the hook is not
blocked reading its ref list, and the duration lands exactly on the 15000ms
bound.

The site used PROBE_TIMEOUT_MS, which tests/helpers/timeouts.cjs documents as "a
single short CLI query or node -e probe against a temp fixture". This is not
that. It spawns bash running .githooks/pre-push, and the hook then invokes a MOCK
git that is itself a bash script, so one runHook is roughly four Git Bash spawns.
On Windows each is Defender-scanned and the first hook test in a file pays cold
start on top. That module's own docstring warns against precisely this: a call
site that differs from its class must not be forced onto a shared value that does
not describe it.

HOOK_FANOUT_TIMEOUT_MS is that missing class — 60000ms, 4x the bound that failed
and half INSTALL_TIMEOUT_MS, which is the right order: a hook fan-out is much
lighter than a full installer run and far heavier than reading back a version
string. Two tests lock the ordering against both neighbours, including one
asserting real margin over the censored 15040ms observation, since a bound that
merely matched what was measured would be the same defect again.

Scoped deliberately: the other ~360 runHook sites keep their current bounds. This
adds the norm and applies it where a real failure demonstrated the need, rather
than sweeping a value across sites with no evidence for any of them.

Refs #3271

---------

Co-authored-by: sim <sim@local>
2026-08-09 23:41:44 -04:00

220 lines
9.7 KiB
JavaScript

'use strict';
/**
* overlay-repo.cjs — shared "overlay repo" builder for install-spawning test
* suites (extracted from tests/workflow-fragments-emission.install.test.cjs,
* issue #2933, so a second divergent copy is never written — see
* CONTEXT.md's Generative Fix Divergence anti-pattern).
*
* ── The overlay technique ────────────────────────────────────────────────
*
* A test that needs a spawned `bin/install.js` to read a DIFFERENT
* `gsd-core/workflows/execute-phase.md` (or any other repo file) than this
* checkout's real one, without paying to copy the ~400 MB repository (mostly
* node_modules) for every run, calls `buildOverlayRepo` with a map of
* POSIX-relative-path -> replacement content. `buildOverlayRepo` mirrors the
* repo tree with real directories (so `copyWithPathReplacement`'s own
* `entry.isDirectory()` / `entry.isFile()` Dirent checks — which do NOT
* follow symlinks — see the correct type) and HARD-LINKS every unmodified
* leaf file (not symlinks: a symlinked leaf file also fails an `isFile()`
* Dirent check elsewhere in the installer, verified empirically — "Failed
* to install agents: directory is empty" against a symlink-leaf overlay).
* Only `node_modules` and `.git` are symlinked at the top level (install.js
* never walks into either), which is what keeps the overlay build fast.
* Every overlay-spawned installer should run with `--preserve-symlinks
* --preserve-symlinks-main` as a defensive belt: with an all-hardlink leaf
* layout this checkout does not currently NEED symlink-preservation for
* correctness, but the flag is free insurance against a future install.js
* change that resolves a node_modules package by real path.
*
* `buildOverlayRepo` can only REPLACE the content of a real leaf file that
* already exists somewhere under `REPO_ROOT` — it cannot graft in a net-new
* path (a `fileOverrides` key naming a path with no existing file/directory
* ancestor in the real tree is silently never created, since `place()` only
* walks `fs.readdirSync` of the REAL source directory).
*
* ── `opts.mode`: 'link' (default) vs 'copy' ─────────────────────────────
*
* `'link'` (the default, and every pre-existing caller's behavior) hard-links
* every unmodified leaf — cheap, but a `--write` generator run inside the
* overlay does an in-place `writeFileSync` through that hard link, i.e. the
* SAME INODE as this real checkout's own tracked file, silently corrupting
* it. `'copy'` mode instead COPIES every unmodified leaf (`fs.copyFileSync`,
* a real independent inode), so a real `--write` generator — or a full `npm
* run regen:derived` chain — can safely run to completion inside the overlay
* without ever touching `REPO_ROOT`. `node_modules` and `.git` are still
* symlinked at the top level in BOTH modes (unchanged from `'link'` mode):
* `install.js`/`npm`/`tsc` never write into either through the overlay path,
* only read/resolve through them, and symlinking is what keeps even
* `'copy'` mode affordable (`node_modules` alone dwarfs the rest of the
* tree).
*/
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const REPO_ROOT = path.join(__dirname, '..', '..');
const OVERLAY_SKIP_TOP = new Set(['node_modules', '.git']);
/**
* True when `err` reports that a path was not there.
*
* @param {unknown} err
* @returns {boolean}
*/
function isMissingPath(err) {
return Boolean(err) && typeof err === 'object' && err.code === 'ENOENT';
}
/**
* Run `attempt` against a source path that another process may be replacing
* underneath the walk, and report whether the leaf was actually placed.
*
* `buildOverlayRepo` enumerates names with `readdirSync` and then acts on them,
* which is a TOCTOU window. It is not theoretical: `hooks/dist` is regenerated
* by an ATOMIC REPLACE (`scripts/build-hooks.js` unlinks and renames), so any
* concurrently running test that rebuilds hooks makes a just-listed name vanish
* mid-walk. That took down three runs on three different branches with a bare
* `ENOENT ... link '/work/hooks/dist/...'`.
*
* On ENOENT the source is re-examined ONCE rather than slept on: an atomic
* rename is a single syscall, so by the time the failure surfaces the successor
* is either already in place (retry succeeds) or the path is genuinely gone from
* the tree (nothing to mirror, so the leaf is skipped). No sleep, no spin — a
* timing-based wait here would be the flake this is fixing, not a fix for it.
*
* Returns false only when the path left the source tree entirely; the overlay
* mirrors the tree, and a file that is no longer in it is not part of the
* snapshot. Every other error propagates untouched.
*
* @param {string} srcPath
* @param {() => void} attempt
* @returns {boolean} whether the leaf was placed
*/
function placeVanishableLeaf(srcPath, attempt) {
try {
attempt();
return true;
} catch (err) {
if (!isMissingPath(err)) throw err;
if (!fs.existsSync(srcPath)) return false;
attempt();
return true;
}
}
/** Hard-link a file, falling back to a real copy only if the two paths sit on
* different filesystems/devices (EXDEV) or linking is denied (EPERM) — both
* cross-platform-legitimate, unlike a symlink's Dirent type-detection gap.
* Returns whether the leaf was placed; false means the source vanished
* mid-walk (see `placeVanishableLeaf`). */
function linkOrCopyFile(src, dest) {
return placeVanishableLeaf(src, () => {
try {
fs.linkSync(src, dest);
} catch (err) {
if (err.code === 'EXDEV' || err.code === 'EPERM') {
fs.copyFileSync(src, dest);
} else {
throw err;
}
}
});
}
/**
* Build a throwaway mirror of REPO_ROOT with real directories throughout and
* every unmodified leaf file hard-linked (or copied — see `opts.mode`
* above), except the paths named in `fileOverrides`
* (POSIX-relative-path -> content string), which are written as real files.
* Returns the mirror's absolute path; caller must
* `fs.rmSync(..., {recursive:true, force:true})` it away.
*
* @param {{[relPath: string]: string}} fileOverrides
* @param {{mode?: 'link'|'copy'}} [opts] - `mode` defaults to `'link'` so
* every pre-existing caller is unchanged. Pass `{mode: 'copy'}` when the
* overlay must survive a real `--write` generator run (see the module doc
* above) — every leaf file becomes a real independent inode, so no write
* inside the overlay can ever reach `REPO_ROOT`.
*/
function buildOverlayRepo(fileOverrides, opts = {}) {
const mode = opts.mode || 'link';
const tmpRepo = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-2930-overlay-'));
const entries = Object.entries(fileOverrides).map(([relPath, content]) => ({
parts: relPath.split('/'),
content,
}));
const skipped = [];
function place(srcDir, destDir, pending, isTop) {
fs.mkdirSync(destDir, { recursive: true });
const grouped = new Map();
for (const e of pending) {
const [head, ...rest] = e.parts;
if (!grouped.has(head)) grouped.set(head, []);
grouped.get(head).push({ parts: rest, content: e.content });
}
for (const de of fs.readdirSync(srcDir, { withFileTypes: true })) {
if (isTop && OVERLAY_SKIP_TOP.has(de.name)) {
fs.symlinkSync(path.join(srcDir, de.name), path.join(destDir, de.name));
continue;
}
const srcPath = path.join(srcDir, de.name);
const destPath = path.join(destDir, de.name);
const overridden = grouped.get(de.name);
const leaf = overridden && overridden.find((s) => s.parts.length === 0);
if (leaf) {
fs.writeFileSync(destPath, leaf.content);
continue;
}
// fs.statSync follows symlinks (unlike Dirent.isDirectory()), so a
// symlinked source directory is still recursed as a REAL directory in
// the overlay — the property copyWithPathReplacement itself needs.
//
// The stat sits in the same TOCTOU window as the copy/link below: the
// name came from readdirSync, and an atomic replace elsewhere in the tree
// can retire it before we get here.
let srcStat;
try {
srcStat = fs.statSync(srcPath);
} catch (err) {
if (isMissingPath(err)) continue;
throw err;
}
if (srcStat.isDirectory()) {
place(srcPath, destPath, overridden || [], false);
} else if (mode === 'copy') {
// Real independent inode — a write through this path in the overlay
// can never alias back to REPO_ROOT's own tracked file (see
// opts.mode doc above).
const placed = placeVanishableLeaf(srcPath, () => fs.copyFileSync(srcPath, destPath));
if (!placed) skipped.push(srcPath);
} else {
const placed = linkOrCopyFile(srcPath, destPath);
if (!placed) skipped.push(srcPath);
}
}
}
place(REPO_ROOT, tmpRepo, entries, true);
if (skipped.length > 0) {
// Not thrown: a source that left the tree mid-walk is genuinely not part of
// the snapshot, and failing here would reintroduce the crash this tolerance
// exists to remove. But it must not be SILENT either — a dropped leaf can
// surface later as a confusing "file missing" in an unrelated assertion, or
// as nothing at all for a test that never touches it.
console.warn(
`buildOverlayRepo: ${skipped.length} source file(s) vanished mid-walk and were ` +
`omitted from the overlay (likely a concurrent atomic replace, e.g. hooks/dist):\n ` +
skipped.join('\n '),
);
}
return tmpRepo;
}
module.exports = { buildOverlayRepo, linkOrCopyFile, placeVanishableLeaf, isMissingPath, REPO_ROOT, OVERLAY_SKIP_TOP };