From 21a11bc48ee638c444cd14c6a5ebad20613dba6a Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Sat, 14 Nov 2026 00:43:03 -0800 Subject: [PATCH] test: the Node legs cost each swizzle-proof slice by the targets it holds that the change can affect --- .github/scripts/ci-node-leg-bounds.test.mjs | 2 +- .github/scripts/node-time-drift.mjs | 50 ++- .github/scripts/node-time-drift.test.mjs | 44 ++ .github/workflows/ci.yml | 4 +- .../cli/test/swizzle-proof/bound-worker.mjs | 38 ++ .../cli/test/swizzle-proof/bound.test.mjs | 110 +++++ packages/cli/test/swizzle-proof/proof.mjs | 376 +++++++++++++++--- packages/cli/test/swizzle-proof/slice.mjs | 24 +- scripts/lib/swizzle-cost.mjs | 131 ++++++ scripts/lib/swizzle-cost.test.mjs | 104 +++++ scripts/vitest-node-durations.json | 6 + scripts/vitest-shard-sequencer.mjs | 121 +++++- scripts/vitest-shard-sequencer.test.mjs | 80 ++++ 13 files changed, 1008 insertions(+), 82 deletions(-) create mode 100644 packages/cli/test/swizzle-proof/bound-worker.mjs create mode 100644 packages/cli/test/swizzle-proof/bound.test.mjs create mode 100644 scripts/lib/swizzle-cost.mjs create mode 100644 scripts/lib/swizzle-cost.test.mjs diff --git a/.github/scripts/ci-node-leg-bounds.test.mjs b/.github/scripts/ci-node-leg-bounds.test.mjs index f9ec91f779769..5b6a63965e9d5 100644 --- a/.github/scripts/ci-node-leg-bounds.test.mjs +++ b/.github/scripts/ci-node-leg-bounds.test.mjs @@ -50,7 +50,7 @@ describe('the Node legs inside their job limit', () => { "always() && github.event_name == 'pull_request' && steps.node-tests.outcome != 'skipped'", ); expect(check.run).toBe( - 'node .github/scripts/node-time-drift.mjs --times "$RUNNER_TEMP/node-file-times.json" --changed HEAD^1', + 'node .github/scripts/node-time-drift.mjs --times "$RUNNER_TEMP/node-file-times.json" --swizzle "$RUNNER_TEMP/swizzle-proof.jsonl" --changed HEAD^1', ); }); diff --git a/.github/scripts/node-time-drift.mjs b/.github/scripts/node-time-drift.mjs index 0d2326b95c866..c048c3b89bab3 100644 --- a/.github/scripts/node-time-drift.mjs +++ b/.github/scripts/node-time-drift.mjs @@ -17,7 +17,8 @@ * seconds over that. A file with no recorded time counts as the median and is * not checked. The failure names the one entry to update and its value. * - * @input --times (the shard watchdog's per-file seconds), + * @input --times (the shard watchdog's per-file seconds), --swizzle + * (optional: each swizzle-proof slice's summary, one JSON a line), * --changed (the merge commit's first parent) * @output exit 1 and one error line per drifted file; exit 0 otherwise * @position .github/scripts — run by ci.yml's Node legs after their tests @@ -28,6 +29,8 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import {fileURLToPath, pathToFileURL} from 'node:url'; +import {slowSlices} from '../../scripts/lib/swizzle-cost.mjs'; + export const RATIO = 1.5; export const MARGIN_S = 60; export const MIN_PEERS = 5; @@ -94,6 +97,28 @@ export function drifted(measured, recorded, changed) { .sort((a, b) => b.measured - b.recorded - (a.measured - a.recorded)); } +/** Paths whose change can make the swizzle-proof model wrong. */ +const MODEL_INPUTS = + /^(?:packages\/cli\/test\/swizzle-proof\/|scripts\/vitest-shard-sequencer\.mjs$|scripts\/lib\/swizzle-cost\.mjs$|scripts\/vitest-node-durations\.json$)/; + +/** + * The swizzle-proof slices that ran past the record's model, and whether + * that fails the leg: only when the change touches what the model depends on + * (the proof, the split, the model's code or the record). Elsewhere a slow + * slice is a warning, so a slow runner never fails an unrelated change. + * @param {import('../../scripts/lib/swizzle-cost.mjs').SliceSample[]} samples + * @param {import('../../scripts/lib/swizzle-cost.mjs').SliceModel | undefined} model + * @param {string[]} changed + * @param {number} factor the leg's slowdown + */ +export function slowSwizzleSlices(samples, model, changed, factor) { + if (!model) return {fails: false, slow: []}; + return { + fails: changed.some(file => MODEL_INPUTS.test(file)), + slow: slowSlices(samples, model, {factor, ratio: RATIO, margin: MARGIN_S}), + }; +} + /** @param {string[]} args */ function main(args) { const option = (/** @type {string} */ name) => args[args.indexOf(name) + 1]; @@ -110,9 +135,8 @@ function main(args) { return 0; } const measured = JSON.parse(fs.readFileSync(timesFile, 'utf8')); - const recorded = JSON.parse( - fs.readFileSync(path.join(ROOT, RECORD), 'utf8'), - ).seconds; + const record = JSON.parse(fs.readFileSync(path.join(ROOT, RECORD), 'utf8')); + const recorded = record.seconds; const changed = execFileSync( 'git', ['-C', ROOT, 'diff', '--name-only', base, 'HEAD'], @@ -144,7 +168,23 @@ function main(args) { } if (late.length === 0) console.log('The changed Node test files run within their recorded times.'); - return late.length ? 1 : 0; + const swizzleFile = args.includes('--swizzle') ? option('--swizzle') : ''; + const samples = + swizzleFile && fs.existsSync(swizzleFile) + ? fs + .readFileSync(swizzleFile, 'utf8') + .split('\n') + .filter(Boolean) + .map(line => JSON.parse(line)) + : []; + const model = record.swizzleProof; + const swizzle = slowSwizzleSlices(samples, model, changed, leg.factor); + for (const {slice, affected, measured: now, expected} of swizzle.slow) { + console.log( + `::${swizzle.fails ? 'error' : 'warning'} title=Recorded swizzle-proof model is stale::Swizzle-proof slice ${slice} proved ${affected} target(s) in ${now} s; the model in ${RECORD} (setup ${model.setupSeconds} s, proof setup ${model.proveBaseSeconds} s, ${model.perTargetSeconds} s per target) gives ${expected} s, and ${legSays}. Run \`node scripts/vitest-shard-sequencer.mjs record\` on this run's Node leg logs to refit it.`, + ); + } + return late.length || (swizzle.fails && swizzle.slow.length) ? 1 : 0; } if ( diff --git a/.github/scripts/node-time-drift.test.mjs b/.github/scripts/node-time-drift.test.mjs index 220364e5506b1..9bf5757390084 100644 --- a/.github/scripts/node-time-drift.test.mjs +++ b/.github/scripts/node-time-drift.test.mjs @@ -7,6 +7,7 @@ import { RATIO, drifted, legFactor, + slowSwizzleSlices, } from './node-time-drift.mjs'; const CHANGES = 'packages/cli/test/packed-gather-cache.changes.test.mjs'; @@ -130,3 +131,46 @@ describe('the recorded-time check for the test files a change touches', () => { expect(drifted({'new.test.mjs': 400}, {}, ['new.test.mjs'])).toEqual([]); }); }); + +describe('the swizzle-proof slices against the recorded model', () => { + const model = {setupSeconds: 28, proveBaseSeconds: 97, perTargetSeconds: 4}; + const slow = { + slice: '2/8', + affected: 1, + timings: {list: 1000, eject: 25_000, affected: 2000}, + totalMs: 310_000, + }; + const quick = {...slow, slice: '1/8', totalMs: 130_000}; + + it('fails the leg only when the change touches what the model depends on', () => { + for (const file of [ + 'packages/cli/test/swizzle-proof/proof.mjs', + 'scripts/vitest-shard-sequencer.mjs', + 'scripts/lib/swizzle-cost.mjs', + 'scripts/vitest-node-durations.json', + ]) { + const result = slowSwizzleSlices([slow, quick], model, [file], 1); + expect(result.fails).toBe(true); + expect(result.slow.map(each => each.slice)).toEqual(['2/8']); + } + }); + + it('only warns on any other change, so a slow runner never fails it', () => { + const result = slowSwizzleSlices( + [slow, quick], + model, + ['packages/core/src/Button/Button.tsx'], + 1, + ); + expect(result).toEqual({ + fails: false, + slow: [{slice: '2/8', affected: 1, measured: 310, expected: 129}], + }); + }); + + it('judges nothing without a recorded model', () => { + expect( + slowSwizzleSlices([slow], undefined, ['scripts/lib/swizzle-cost.mjs'], 1), + ).toEqual({fails: false, slow: []}); + }); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84f824c87fe80..103ffe10e777f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1200,6 +1200,8 @@ jobs: env: SCOPED: ${{ github.event_name == 'pull_request' && steps.scope.outputs.vitest_full_suite == 'false' }} VITEST_SHARD_TIMES_FILE: ${{ runner.temp }}/node-file-times.json + # Each swizzle-proof slice adds its summary here, for the drift check. + SWIZZLE_PROOF_SUMMARY: ${{ runner.temp }}/swizzle-proof.jsonl # The split gives the first leg its own later steps' time # (scripts/vitest-node-durations.json legOneSteps), under those # steps' scope condition. Every leg sets the same value, so every @@ -1237,7 +1239,7 @@ jobs: # job limit. Files the change does not touch are not checked. - name: Check the recorded times of the test files this change touches if: always() && github.event_name == 'pull_request' && steps.node-tests.outcome != 'skipped' - run: node .github/scripts/node-time-drift.mjs --times "$RUNNER_TEMP/node-file-times.json" --changed HEAD^1 + run: node .github/scripts/node-time-drift.mjs --times "$RUNNER_TEMP/node-file-times.json" --swizzle "$RUNNER_TEMP/swizzle-proof.jsonl" --changed HEAD^1 # A Lab-only change may carry a Lab component's CLI discovery entry; the # committed list must match its generator (spec:AST-030 FR26). diff --git a/packages/cli/test/swizzle-proof/bound-worker.mjs b/packages/cli/test/swizzle-proof/bound-worker.mjs new file mode 100644 index 0000000000000..22551064a1a6b --- /dev/null +++ b/packages/cli/test/swizzle-proof/bound-worker.mjs @@ -0,0 +1,38 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file bound-worker.mjs + * @input workerData `{relevant, count}`: the change's component source files + * and the number of slices + * @output Two messages: `{listed: true}` once the targets are listed, then + * `{held}`: for each slice, how many of its targets ({@link sliceOf}) the + * change can affect ({@link affectedBound}) + * @position Run in a worker by scripts/vitest-shard-sequencer.mjs, so the + * Node legs' split can stop waiting at its time budget + */ + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {parentPort, workerData} from 'node:worker_threads'; + +import {affectedBound, createProject, listTargets, sliceOf} from './proof.mjs'; + +const project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-swizzle-bound-')); +try { + createProject(project); + const targets = await listTargets(project); + parentPort?.postMessage({listed: true}); + const affected = affectedBound(targets, workerData.relevant); + parentPort?.postMessage({ + held: Array.from( + {length: workerData.count}, + (_, index) => + sliceOf(targets, index, workerData.count).filter(t => + affected.has(t.key), + ).length, + ), + }); +} finally { + fs.rmSync(project, {recursive: true, force: true}); +} diff --git a/packages/cli/test/swizzle-proof/bound.test.mjs b/packages/cli/test/swizzle-proof/bound.test.mjs new file mode 100644 index 0000000000000..6467a366b1ed4 --- /dev/null +++ b/packages/cli/test/swizzle-proof/bound.test.mjs @@ -0,0 +1,110 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file bound.test.mjs + * @input Real swizzle copies of a few targets, and changes to a component, a + * shared helper, a layer helper, the theme tokens and a Lab component + * @output Proves the Node legs' affected bound (proof.mjs affectedBound) + * holds every target the slices prove (exactAffected), so the split never + * costs a slice below its work; and logs how long the split's bound takes + * @position Node test of proof.mjs's bound, beside the swizzle-proof slices + */ + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; + +import {boundWithin} from '../../../../scripts/vitest-shard-sequencer.mjs'; +import { + affectedBound, + createProject, + eject, + exactAffected, + listTargets, +} from './proof.mjs'; + +/** + * Targets of every kind of folder: a component folder (Core), a flat + * package (Charts, Rich Text), a shared folder (Lab's Chart), a folder of + * modules (Layer), and a leaf (Lab's DialogHeroHeader). + */ +const KEYS = [ + 'core__Button', + 'core__Badge', + 'core__Dialog', + 'core__Layer', + 'charts__ChartAxis', + 'lab__ChartArea', + 'lab__DialogHeroHeader', + 'richtext__RichTextEditorAutoLinkPlugin', + 'vega__VegaChart', +]; + +const CHANGES = [ + ['a component', ['packages/core/src/Button/Button.tsx']], + ['a press helper', ['packages/core/src/utils/pressClaim.ts']], + ['a layer helper', ['packages/core/src/Layer/inputHold.ts']], + ['the theme tokens', ['packages/core/src/theme/tokens.stylex.ts']], + [ + 'a Lab component', + ['packages/lab/src/DialogHeroHeader/DialogHeroHeader.tsx'], + ], +]; + +describe('the Node legs’ affected bound', () => { + /** @type {Array<{name: string, pkg: string, key: string}>} */ + let targets = []; + /** @type {Map} */ + const ejected = new Map(); + /** One set of caches for every change, as the same copies are read each time. */ + const caches = {}; + const project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-bound-')); + + beforeAll(async () => { + createProject(project); + targets = (await listTargets(project)).filter(t => KEYS.includes(t.key)); + await eject(targets, project, ejected, () => {}); + }, 300_000); + + afterAll(() => { + fs.rmSync(project, {recursive: true, force: true}); + }); + + it('copies every chosen target', () => { + expect(targets.map(t => t.key).sort()).toEqual([...KEYS].sort()); + expect(ejected.size).toBe(KEYS.length); + }); + + it.each(CHANGES)( + 'holds every target the slices prove for a change to %s', + (_change, relevant) => { + const exact = exactAffected(targets, ejected, relevant, caches).map( + t => t.key, + ); + const bound = affectedBound(targets, relevant); + expect(exact.filter(key => !bound.has(key))).toEqual([]); + }, + ); + + it('is not every target: a component change reaches some, and a Lab leaf almost none', () => { + expect( + exactAffected(targets, ejected, CHANGES[0][1], caches).length, + ).toBeGreaterThan(0); + expect(affectedBound(targets, CHANGES[4][1]).size).toBeLessThan(3); + }); + + it('counts each slice’s affected targets in a worker, within its budget or not at all', async () => { + const started = Date.now(); + const held = await boundWithin(CHANGES[0][1], 8); + const elapsed = Date.now() - started; + // The machine's own time, for the record of what the split spends. + console.log( + `SWIZZLE_BOUND ${JSON.stringify({ms: elapsed, held, cpus: os.availableParallelism()})}`, + ); + if (held !== null) { + expect(held).toHaveLength(8); + expect(held.every(n => Number.isInteger(n) && n >= 0)).toBe(true); + } + }, 60_000); +}); diff --git a/packages/cli/test/swizzle-proof/proof.mjs b/packages/cli/test/swizzle-proof/proof.mjs index 0d74caa6b5e22..b82f0bec1af85 100644 --- a/packages/cli/test/swizzle-proof/proof.mjs +++ b/packages/cli/test/swizzle-proof/proof.mjs @@ -266,7 +266,7 @@ export function keyOf(t) { * @param {Map} copies * @param {(key: string, step: string, error: unknown) => void} fail */ -async function eject(targets, project, copies, fail) { +export async function eject(targets, project, copies, fail) { const {swizzle} = await cliApi(); for (const t of targets) { const out = path.join( @@ -367,8 +367,6 @@ export function sourcesOf(t, copy, packages, memo, closures = new Map()) { if (componentSource == null) return null; /** @type {Set} */ const sources = new Set(); - const named = - /import\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\w+)?\s*(?:,\s*(\{[^}]*\}))?\s*from\s*['"](@astryxdesign\/[^'"]+)['"]/g; for (const file of copy.files) { // Swizzle writes the component's own files under its output folder, // whatever folder they come from; helpers keep their path in the @@ -386,46 +384,299 @@ export function sourcesOf(t, copy, packages, memo, closures = new Map()) { : path.join(srcOf(t.pkg), rel), ); } - if (!/\.tsx?$/.test(file)) continue; - for (const [, head, tail, spec] of fs - .readFileSync(file, 'utf8') - .matchAll(named)) { - const [, name, ...sub] = spec.split('/'); - const owner = packages.get(`@astryxdesign/${name}`); - if (!owner) continue; - const target = sourceExportTarget( - owner.manifest, - owner.dir, - sub.length ? `./${sub.join('/')}` : '.', + if (/\.tsx?$/.test(file)) + addImportedSources(file, packages, memo, closures, sources); + } + return sources; +} + +/** + * Adds what one module's package imports reach: the entry module of each + * package export it imports from, and the module that defines each public + * name it imports with every module that one imports. A slice reads a copy's + * files with it, and the Node legs' split reads the repository's own (see + * {@link affectedBound}) in the same order: a package export's entry module, + * then what it reaches. + * @param {string} file + * @param {Map} packages + * @param {Map>} memo + * @param {Map>} closures + * @param {Set} sources + */ +function addImportedSources(file, packages, memo, closures, sources) { + const named = + /import\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\w+)?\s*(?:,\s*(\{[^}]*\}))?\s*from\s*['"](@astryxdesign\/[^'"]+)['"]/g; + for (const [, head, tail, spec] of fs + .readFileSync(file, 'utf8') + .matchAll(named)) { + const [, name, ...sub] = spec.split('/'); + const owner = packages.get(`@astryxdesign/${name}`); + if (!owner) continue; + const target = sourceExportTarget( + owner.manifest, + owner.dir, + sub.length ? `./${sub.join('/')}` : '.', + ); + if (!target) continue; + // The export's entry module routes the import as the manifest does. + sources.add(target); + const list = [head, tail].filter(x => x && x.startsWith('{')); + if (list.length === 0) continue; + if (!memo.has(target)) { + let origins; + try { + origins = moduleExportOrigins(target, {types: true}); + } catch { + origins = new Map(); + } + memo.set(target, origins); + } + for (const entry of list.join(',').replace(/[{}]/g, '').split(',')) { + const imported = entry + .trim() + .replace(/^type\s+/, '') + .split(/\s+as\s+/)[0]; + if (!imported) continue; + const origin = memo.get(target).get(imported)?.file ?? target; + for (const file of localClosure(origin, closures)) sources.add(file); + } + } +} + +/** + * The targets slice `index` of `count` proves: every `count`-th target from + * `index`. The Node legs' split uses it too, so it costs each slice by the + * targets that slice holds. + * @template T + * @param {T[]} targets + * @param {number} index + * @param {number} count + * @returns {T[]} + */ +export function sliceOf(targets, index, count) { + return targets.filter((_, i) => i % count === index); +} + +/** + * A target's entry module in the repository: the shipped `.tsx` (or + * `.ts`) in its package's source, outside the generated translations, and the + * one in a folder of the same name when there are several. Null when there is + * no single one. + * @param {{name: string, pkg: string}} t + * @param {Map} packages + * @param {Map} listings cache of each package's shipped modules + */ +function entryModule(t, packages, listings) { + const owner = packages.get(t.pkg); + if (!owner) return null; + const src = path.join(owner.dir, 'src'); + if (!listings.has(src)) { + let files = []; + try { + files = fs + .readdirSync(src, {recursive: true}) + .map(String) + .filter( + rel => + /\.tsx?$/.test(rel) && + !NOT_SHIPPED.test(rel) && + !rel.startsWith(`i18n${path.sep}`), + ) + .map(rel => path.join(src, rel)); + } catch { + // A package without a source folder has no entry module. + } + listings.set(src, files); + } + const named = listings + .get(src) + .filter(file => /^(.*)\.tsx?$/.exec(path.basename(file))?.[1] === t.name); + const own = named.filter( + file => path.basename(path.dirname(file)) === t.name, + ); + if (own.length === 1) return own[0]; + return named.length === 1 ? named[0] : null; +} + +/** + * A module and every module it imports by relative path, transitively, as + * {@link localClosure} finds them, with each module read and resolved once + * across every call: the bound walks the same shared modules for many + * targets. The same read keeps the module's package import specifiers. + * @param {string} file + * @param {{edges: Map, closures: Map>, specs: Map}} caches + * @returns {Set} + */ +function cachedClosure(file, caches) { + const cached = caches.closures.get(file); + if (cached) return cached; + /** @type {Set} */ + const seen = new Set(); + const queue = [file]; + while (queue.length > 0) { + const next = /** @type {string} */ (queue.pop()); + if (seen.has(next)) continue; + seen.add(next); + let edges = caches.edges.get(next); + if (!edges) { + edges = []; + let code = ''; + try { + code = fs.readFileSync(next, 'utf8'); + } catch { + // A module that cannot be read imports nothing. + } + caches.specs.set( + next, + [...code.matchAll(/\bfrom\s*['"](@astryxdesign\/[^'"]+)['"]/g)].map( + match => match[1], + ), ); - if (!target) continue; - // The export's entry module routes the import as the manifest does. - sources.add(target); - const list = [head, tail].filter(x => x && x.startsWith('{')); - if (list.length === 0) continue; - if (!memo.has(target)) { - let origins; - try { - origins = moduleExportOrigins(target, {types: true}); - } catch { - origins = new Map(); - } - memo.set(target, origins); + for (const [, spec] of code.matchAll( + /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"](\.[^'"]+)['"]/g, + )) { + const resolved = resolveLocalModule(spec, next); + if (resolved) edges.push(resolved); } - for (const entry of list.join(',').replace(/[{}]/g, '').split(',')) { - const imported = entry - .trim() - .replace(/^type\s+/, '') - .split(/\s+as\s+/)[0]; - if (!imported) continue; - const origin = memo.get(target).get(imported)?.file ?? target; - for (const file of localClosure(origin, closures)) sources.add(file); + caches.edges.set(next, edges); + } + for (const each of edges) if (!seen.has(each)) queue.push(each); + } + caches.closures.set(file, seen); + return seen; +} + +/** + * The folder named after a target in its package's source: the top-level one, + * else the only one outside the generated translations, else null. + * @param {{name: string, pkg: string}} t + * @param {Map} packages + */ +function componentFolder(t, packages) { + const owner = packages.get(t.pkg); + if (!owner) return null; + const src = path.join(owner.dir, 'src'); + const top = path.join(src, t.name); + if (fs.existsSync(top) && fs.statSync(top).isDirectory()) return top; + let matches = []; + try { + matches = fs + .readdirSync(src, {recursive: true, withFileTypes: true}) + .filter(entry => entry.isDirectory() && entry.name === t.name) + .map(entry => path.join(entry.parentPath ?? entry.path, entry.name)) + .filter(dir => !path.relative(src, dir).startsWith(`i18n${path.sep}`)); + } catch { + // A package without a source folder has no component folder. + } + return matches.length === 1 ? matches[0] : null; +} + +/** + * Every shipped file under a folder, outside the generated translations. + * @param {string} folder + * @param {Map} listings cache, by folder + */ +function folderFiles(folder, listings) { + const key = `files:${folder}`; + if (!listings.has(key)) + listings.set( + key, + fs + .readdirSync(folder, {recursive: true, withFileTypes: true}) + .filter(entry => entry.isFile()) + .map(entry => path.join(entry.parentPath ?? entry.path, entry.name)) + .filter(file => { + const rel = path.relative(folder, file); + return !NOT_SHIPPED.test(rel) && !rel.startsWith(`i18n${path.sep}`); + }), + ); + return listings.get(key); +} + +/** + * Every source file a copy of the target can depend on, read from the + * repository without copying it: every shipped file of the folder that + * holds the target's entry module, each module those import by relative + * path, and what + * every module the entry of each package export they import reaches. This + * holds every file {@link sourcesOf} finds for a copy, and more: where + * {@link addImportedSources} follows each imported name to the module that + * defines it, this takes all the entry reaches, which needs no syntax tree + * and keeps it fast enough to run before the tests. A component with no + * entry module named after it uses its folder. Null when neither is found. + * @param {{name: string, pkg: string}} t + * @param {Map} packages + * @param {{closures: Map>, listings: Map, edges: Map, specs: Map, entries: Map}} caches + * @returns {Set | null} + */ +export function boundSources(t, packages, caches) { + const entry = entryModule(t, packages, caches.listings); + // A component without an entry module named after it is a folder of + // modules (Layer, Swipe): its folder is its source. + const folder = + entry == null ? componentFolder(t, packages) : path.dirname(entry); + if (folder == null) return null; + // A copy carries the component's folder, and a flat package's copy (Charts, + // Rich Text) or a shared folder's (Lab's Chart) carries its neighbours too: + // every shipped file of the folder is a root, so the bound never misses one. + const roots = folderFiles(folder, caches.listings); + /** @type {Set} */ + const sources = new Set(); + for (const file of roots) { + sources.add(file); + if (!/\.[cm]?[jt]sx?$/.test(file)) continue; + for (const reached of cachedClosure(file, caches)) { + sources.add(reached); + for (const spec of caches.specs.get(reached) ?? []) { + let entry = caches.entries.get(spec); + if (entry === undefined) { + const [, name, ...sub] = spec.split('/'); + const owner = packages.get(`@astryxdesign/${name}`); + entry = owner + ? sourceExportTarget( + owner.manifest, + owner.dir, + sub.length ? `./${sub.join('/')}` : '.', + ) + : null; + caches.entries.set(spec, entry); + } + if (entry) + for (const each of cachedClosure(entry, caches)) sources.add(each); } } } return sources; } +/** + * The targets a change can affect, read from the repository alone: those + * whose {@link boundSources} hold a changed file, and those whose folder + * cannot be found (fail closed). It never misses a target the slice proves, + * so the Node legs' split can cost the slices by it before any of them runs. + * @param {Array<{name: string, pkg: string, key: string}>} targets + * @param {string[]} relevant the changed component source files, repository-relative + * @returns {Set} target keys + */ +export function affectedBound(targets, relevant) { + const packages = workspacePackages(); + const caches = { + closures: new Map(), + listings: new Map(), + edges: new Map(), + specs: new Map(), + entries: new Map(), + }; + const changed = new Set(relevant.map(file => path.join(REPO, file))); + const keys = new Set(); + for (const t of targets) { + const sources = boundSources(t, packages, caches); + if (sources == null || [...sources].some(file => changed.has(file))) + keys.add(t.key); + } + return keys; +} + /** * Which targets a run proves: none, the affected ones, or all. When git * cannot read the change, a checkout without a parent commit proves none @@ -505,6 +756,35 @@ export function runScope({all = false} = {}) { return {base, changed, toolchain, relevant, scope}; } +/** + * The targets among `targets` a change affects, read from their copies: those + * whose copy depends on a changed source file ({@link sourcesOf}), and those + * that did not eject, cannot be mapped, or depend on a file that does not + * exist (each is proven, so its failure shows). The slices prove these, and + * {@link affectedBound} must hold every one of them. + * @param {Array<{name: string, pkg: string, key: string}>} targets + * @param {Map} ejected the copies, by target key + * @param {string[]} relevant the changed component source files, repository-relative + * @param {{memo?: Map, closures?: Map>}} [caches] + * kept across calls for the same targets (a test that asks about several changes) + * @returns {Array<{name: string, pkg: string, key: string}>} + */ +export function exactAffected(targets, ejected, relevant, caches = {}) { + const packages = workspacePackages(); + const memo = (caches.memo ??= new Map()); + const closures = (caches.closures ??= new Map()); + const changedFiles = new Set(relevant.map(file => path.join(REPO, file))); + return targets.filter(t => { + if (!ejected.has(t.key)) return true; + const sources = sourcesOf(t, ejected.get(t.key), packages, memo, closures); + if (sources == null) return true; + for (const file of sources) { + if (changedFiles.has(file) || !fs.existsSync(file)) return true; + } + return false; + }); +} + /** * Runs one slice of the proof: the targets at `index` of every `count`, in * the scope {@link proofScope} chooses. In the affected scope the slice @@ -534,9 +814,7 @@ export async function runSlice({ createProject(project); const timings = {}; const listStart = Date.now(); - const slice = (await listTargets(project)).filter( - (_, i) => i % count === index, - ); + const slice = sliceOf(await listTargets(project), index, count); timings.list = Date.now() - listStart; /** @type {Map} */ const ejected = new Map(); @@ -550,28 +828,8 @@ export async function runSlice({ let affected = slice; let reason = scope.mode === 'all' ? scope.reason : ''; if (!reason) { - const packages = workspacePackages(); - const memo = new Map(); - const closures = new Map(); - const changedFiles = new Set(relevant.map(file => path.join(REPO, file))); const affectStart = Date.now(); - affected = slice.filter(t => { - // A target that did not eject is proven, so its failure shows. - if (!ejected.has(t.key)) return true; - const sources = sourcesOf( - t, - ejected.get(t.key), - packages, - memo, - closures, - ); - if (sources == null) return true; - for (const file of sources) { - // A source that does not exist means the mapping is wrong: prove it. - if (changedFiles.has(file) || !fs.existsSync(file)) return true; - } - return false; - }); + affected = exactAffected(slice, ejected, relevant); timings.affected = Date.now() - affectStart; reason = `${relevant.length} changed source file(s); ${affected.length} of ${slice.length} target(s) in this slice depend on them`; } diff --git a/packages/cli/test/swizzle-proof/slice.mjs b/packages/cli/test/swizzle-proof/slice.mjs index 4c2d317c40501..a00ea27fd1754 100644 --- a/packages/cli/test/swizzle-proof/slice.mjs +++ b/packages/cli/test/swizzle-proof/slice.mjs @@ -35,17 +35,19 @@ export function proveSlice(index, count) { browser: process.env.SWIZZLE_PROOF_BROWSER === '1', }); const failures = run.results.filter(r => r.failure); - console.log( - `SWIZZLE_PROOF ${JSON.stringify({ - slice: `${index + 1}/${count}`, - offered: run.offered, - affected: run.affected, - reason: run.reason, - failed: failures.length, - timings: run.timings, - totalMs: run.totalMs, - })}`, - ); + const summary = JSON.stringify({ + slice: `${index + 1}/${count}`, + offered: run.offered, + affected: run.affected, + reason: run.reason, + failed: failures.length, + timings: run.timings, + totalMs: run.totalMs, + }); + console.log(`SWIZZLE_PROOF ${summary}`); + // The Node legs' drift check reads every slice's summary from here. + if (process.env.SWIZZLE_PROOF_SUMMARY) + fs.appendFileSync(process.env.SWIZZLE_PROOF_SUMMARY, `${summary}\n`); for (const r of failures) { console.log( `SWIZZLE_PROOF_FAIL ${r.key} [${r.failure.step}] ${r.failure.error}`, diff --git a/scripts/lib/swizzle-cost.mjs b/scripts/lib/swizzle-cost.mjs new file mode 100644 index 0000000000000..0158707a33251 --- /dev/null +++ b/scripts/lib/swizzle-cost.mjs @@ -0,0 +1,131 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file What a swizzle-proof slice takes, by the record's model. + * @input The record's `swizzleProof` model; the slices' summary lines + * (`SWIZZLE_PROOF {…}`, packages/cli/test/swizzle-proof/slice.mjs) + * @output A slice's cost for the targets it holds; the model fitted from + * summary lines; the slices that ran past the model + * @position Shared by the Node legs' split (scripts/vitest-shard-sequencer.mjs, + * which also records the model) and the drift check + * (.github/scripts/node-time-drift.mjs), so the cost the split uses is the + * cost the check judges + */ + +/** + * @typedef {{setupSeconds: number, proveBaseSeconds: number, perTargetSeconds: number}} SliceModel + * @typedef {{slice?: string, affected: number, timings?: Record, totalMs: number}} SliceSample + */ + +/** The steps a slice takes before it proves anything. */ +const SETUP_STEPS = ['list', 'eject', 'affected']; + +/** @param {number} value */ +const tenth = value => Math.round(value * 10) / 10; + +/** @param {number[]} values */ +function median(values) { + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +} + +/** + * What one slice takes: its setup (listing, copying and sorting its + * targets), and, when it holds an affected target, the proof's own setup + * (type-check, bundle and render each start once) and each target's time. + * Never more than `max`, the slice's recorded time. + * @param {SliceModel} model + * @param {number} held affected targets in the slice + * @param {number} [max] + */ +export function sliceCost(model, held, max = Infinity) { + const seconds = + model.setupSeconds + + (held > 0 ? model.proveBaseSeconds + model.perTargetSeconds * held : 0); + return Math.min(max, tenth(seconds)); +} + +/** + * The slices' summary lines in a log, as objects. A line that does not parse + * is left out. + * @param {string} text + * @returns {SliceSample[]} + */ +export function swizzleSamples(text) { + const plain = text.replace(/(?:\x1b|\^\[)\[[0-9;]*m/g, ''); + const samples = []; + for (const [, json] of plain.matchAll(/SWIZZLE_PROOF (\{.*\})\s*$/gm)) { + try { + const sample = JSON.parse(json); + if (Number.isFinite(sample.affected) && Number.isFinite(sample.totalMs)) + samples.push(sample); + } catch { + // A truncated line is not a sample. + } + } + return samples; +} + +/** @param {SliceSample} sample */ +const setupMs = sample => + SETUP_STEPS.reduce((sum, step) => sum + (sample.timings?.[step] ?? 0), 0); + +/** + * The model the samples show: the median setup, and a straight line through + * the proving time of the slices that proved something (its intercept is the + * proof's own setup, its slope each target's time). A part the samples + * cannot show keeps `previous`: no samples keep the setup, and fewer than + * three different affected counts keep the line. + * @param {SliceSample[]} samples + * @param {SliceModel} [previous] + * @returns {SliceModel | undefined} + */ +export function fitSwizzleModel(samples, previous) { + if (samples.length === 0) return previous; + const setupSeconds = tenth(median(samples.map(setupMs)) / 1000); + const points = samples + .filter(sample => sample.affected > 0) + .map(sample => [ + sample.affected, + (sample.totalMs - setupMs(sample)) / 1000, + ]); + const counts = new Set(points.map(([affected]) => affected)); + if (counts.size < 3) { + return previous ? {...previous, setupSeconds} : undefined; + } + const meanX = points.reduce((sum, [x]) => sum + x, 0) / points.length; + const meanY = points.reduce((sum, [, y]) => sum + y, 0) / points.length; + const slope = + points.reduce((sum, [x, y]) => sum + (x - meanX) * (y - meanY), 0) / + points.reduce((sum, [x]) => sum + (x - meanX) ** 2, 0); + const perTargetSeconds = Math.max(0, slope); + return { + setupSeconds, + proveBaseSeconds: tenth(Math.max(0, meanY - perTargetSeconds * meanX)), + perTargetSeconds: tenth(perTargetSeconds), + }; +} + +/** + * The slices that ran past the model, after the leg's own slowdown is taken + * out: more than `ratio` times the model's time and more than `margin` + * seconds over it. + * @param {SliceSample[]} samples + * @param {SliceModel} model + * @param {{factor?: number, ratio: number, margin: number}} limits + * @returns {{slice: string, affected: number, measured: number, expected: number}[]} + */ +export function slowSlices(samples, model, {factor = 1, ratio, margin}) { + return samples + .map(sample => ({ + slice: sample.slice ?? '?', + affected: sample.affected, + measured: tenth(sample.totalMs / 1000), + expected: tenth(sliceCost(model, sample.affected) * factor), + })) + .filter( + ({measured, expected}) => + measured > expected * ratio && measured - expected > margin, + ); +} diff --git a/scripts/lib/swizzle-cost.test.mjs b/scripts/lib/swizzle-cost.test.mjs new file mode 100644 index 0000000000000..1a48103b0f5f1 --- /dev/null +++ b/scripts/lib/swizzle-cost.test.mjs @@ -0,0 +1,104 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file Tests for swizzle-cost.mjs: a slice's cost by the record's model, + * the model fitted from the slices' summary lines, and the slow slices. + */ + +import {describe, expect, it} from 'vitest'; + +import { + fitSwizzleModel, + sliceCost, + slowSlices, + swizzleSamples, +} from './swizzle-cost.mjs'; + +const MODEL = {setupSeconds: 28, proveBaseSeconds: 97, perTargetSeconds: 4}; + +/** A slice summary: `setup` seconds of setup, `prove` seconds of proving. */ +const sample = (affected, setup, prove, slice = '1/8') => ({ + slice, + affected, + timings: {list: 1000, eject: (setup - 3) * 1000, affected: 2000}, + totalMs: (setup + prove) * 1000, +}); + +describe('a swizzle-proof slice cost', () => { + it('is its setup alone when it holds no affected target', () => { + expect(sliceCost(MODEL, 0)).toBe(28); + }); + + it('adds the proof setup once, then each target', () => { + expect(sliceCost(MODEL, 1)).toBe(129); + expect(sliceCost(MODEL, 16)).toBe(189); + }); + + it('never exceeds the slice’s recorded time', () => { + expect(sliceCost(MODEL, 21, 180.3)).toBe(180.3); + }); +}); + +describe('summary lines', () => { + it('reads each slice’s summary from a run log, with job columns and colour codes', () => { + const line = JSON.stringify(sample(3, 20, 100)); + const log = [ + `test-node (2)\tRun\t2026-11-14T00:00:00.0Z \u001b[33mSWIZZLE_PROOF ${line}`, + `test-node (3)\tRun\t2026-11-14T00:00:00.0Z SWIZZLE_PROOF ${line}`, + 'SWIZZLE_PROOF {"slice":"9/8",', + 'unrelated output', + ].join('\n'); + expect(swizzleSamples(log)).toEqual([ + sample(3, 20, 100), + sample(3, 20, 100), + ]); + }); +}); + +describe('the fitted model', () => { + it('takes the median setup and a straight line through the proving time', () => { + const samples = [ + sample(0, 18, 0), + sample(1, 30, 101), + sample(4, 26, 113), + sample(16, 28, 161), + sample(3, 40, 109), + ]; + expect(fitSwizzleModel(samples)).toEqual({ + setupSeconds: 28, + proveBaseSeconds: 97, + perTargetSeconds: 4, + }); + }); + + it('keeps the earlier line when the samples hold fewer than three affected counts', () => { + const samples = [sample(2, 30, 120), sample(2, 30, 140), sample(0, 20, 0)]; + expect(fitSwizzleModel(samples, MODEL)).toEqual({ + ...MODEL, + setupSeconds: 30, + }); + expect(fitSwizzleModel(samples)).toBeUndefined(); + }); + + it('keeps the earlier model when there is no sample', () => { + expect(fitSwizzleModel([], MODEL)).toBe(MODEL); + }); +}); + +describe('slow slices', () => { + it('names a slice past the model by the ratio and the margin, after the leg factor', () => { + const samples = [ + sample(1, 28, 101, '1/8'), + sample(1, 60, 250, '2/8'), + sample(0, 90, 0, '3/8'), + ]; + expect(slowSlices(samples, MODEL, {ratio: 1.5, margin: 60})).toEqual([ + {slice: '2/8', affected: 1, measured: 310, expected: 129}, + {slice: '3/8', affected: 0, measured: 90, expected: 28}, + ]); + // A leg running 1.2 times slow: slice 3 is then within the margin. + expect( + slowSlices(samples, MODEL, {factor: 1.2, ratio: 1.5, margin: 60}), + ).toEqual([{slice: '2/8', affected: 1, measured: 310, expected: 154.8}]); + }); +}); diff --git a/scripts/vitest-node-durations.json b/scripts/vitest-node-durations.json index a666807850afb..904206b834d32 100644 --- a/scripts/vitest-node-durations.json +++ b/scripts/vitest-node-durations.json @@ -1083,6 +1083,7 @@ "packages/cli/test/readme-prose.test.mjs": 0.5, "packages/cli/test/runner-commands.test.mjs": 2.6, "packages/cli/test/search-consumer-ranking.test.mjs": 3, + "packages/cli/test/swizzle-proof/bound.test.mjs": 21.0, "packages/cli/test/swizzle-proof/scope.test.mjs": 0, "packages/cli/test/swizzle-proof/swizzle-proof.1.test.mjs": 348, "packages/cli/test/swizzle-proof/swizzle-proof.2.test.mjs": 340, @@ -1230,5 +1231,10 @@ "Offline-media browser cases": 17, "Theme editor browser case": 30, "Run the theme-family contract": 42 + }, + "swizzleProof": { + "setupSeconds": 27.8, + "proveBaseSeconds": 96.8, + "perTargetSeconds": 3.8 } } diff --git a/scripts/vitest-shard-sequencer.mjs b/scripts/vitest-shard-sequencer.mjs index 83a5b5a867c3c..5c44d96ad0374 100644 --- a/scripts/vitest-shard-sequencer.mjs +++ b/scripts/vitest-shard-sequencer.mjs @@ -25,8 +25,14 @@ import fs from 'node:fs'; import path from 'node:path'; import {fileURLToPath, pathToFileURL} from 'node:url'; +import {Worker} from 'node:worker_threads'; import {BaseSequencer} from 'vitest/node'; import {costOf, slowestFirst, splitByDuration} from './lib/duration-split.mjs'; +import { + fitSwizzleModel, + sliceCost, + swizzleSamples, +} from './lib/swizzle-cost.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); export const DURATIONS = path.join(ROOT, 'scripts/vitest-node-durations.json'); @@ -48,12 +54,14 @@ export function partitionByDuration( files, count, seconds, - {legOneSeconds = 0, idle = new Set()} = {}, + {legOneSeconds = 0, idle = new Set(), costs = new Map()} = {}, ) { const recorded = costOf(files, seconds); // A file that runs no test in this run (the swizzle-proof slices when the - // change reaches no component) costs only its import. - const cost = file => (idle.has(file) ? 0 : recorded(file)); + // change reaches no component) costs only its import; a slice the change + // reaches costs what its targets take (swizzleSliceCosts). + const cost = file => + idle.has(file) ? 0 : (costs.get(file) ?? recorded(file)); // Every file also costs its import and transform, which its recorded time // leaves out; without it the hundreds of files recorded at 0 s would all go // to one leg. @@ -107,6 +115,15 @@ export function recordLegOneSteps(text, names) { ); } +/** The whole record, or an empty one when the file cannot be read. */ +export function readRecord(file = DURATIONS) { + try { + return JSON.parse(fs.readFileSync(file, 'utf8')); + } catch { + return {}; + } +} + /** Recorded seconds per file, or none when the file cannot be read. */ export function readDurations(file = DURATIONS) { try { @@ -179,6 +196,90 @@ export async function idleSwizzleSlices(files) { return new Set(scope.mode === 'none' ? slices : []); } +/** How long the split waits for the affected targets once they are listed. */ +export const BOUND_BUDGET_MS = 2000; +/** How long the split waits for the target list itself. */ +const LIST_BUDGET_MS = 10_000; + +/** + * For each slice, how many of its targets the change can affect, from + * swizzle-proof/bound-worker.mjs (the same functions the slices run), or + * null when the worker fails or misses its time budget. + * @param {string[]} relevant + * @param {number} count slices + * @param {{budgetMs?: number, listMs?: number}} [budget] + * @returns {Promise} + */ +export function boundWithin( + relevant, + count, + {budgetMs = BOUND_BUDGET_MS, listMs = LIST_BUDGET_MS} = {}, +) { + return new Promise(resolve => { + const worker = new Worker( + path.join(ROOT, 'packages/cli/test/swizzle-proof/bound-worker.mjs'), + {workerData: {relevant, count}}, + ); + let timer = setTimeout(() => finish(null), listMs); + let done = false; + const finish = result => { + if (done) return; + done = true; + clearTimeout(timer); + void worker.terminate(); + resolve(result); + }; + worker.on('message', message => { + if (message.listed) { + clearTimeout(timer); + timer = setTimeout(() => finish(null), budgetMs); + } else finish(message.held); + }); + worker.on('error', () => finish(null)); + worker.on('exit', () => finish(null)); + }); +} + +/** + * The swizzle-proof slices' cost in this run. In the scope `none` every slice + * is idle. In the scope `affected` each slice costs what the record's model + * gives for the targets it holds that the change can affect (the targets + * come from the same proof.mjs functions the slices run). Every other case + * keeps the slices' recorded time: the scope `all`, a record without the + * model, and a bound that fails or misses its budget. + * @param {string[]} files + * @param {any} record the whole record (readRecord) + * @param {{bound?: typeof boundWithin, plan?: () => {scope: {mode: string}, relevant: string[]}}} [inject] + * @returns {Promise<{idle: Set, costs: Map}>} + */ +export async function swizzleSliceCosts(files, record, inject = {}) { + const slices = files.filter(file => SWIZZLE_PROOF.test(file)); + const costs = new Map(); + if (slices.length === 0) return {idle: new Set(), costs}; + const plan = + inject.plan ?? + (async () => { + const {runScope} = await import( + pathToFileURL( + path.join(ROOT, 'packages/cli/test/swizzle-proof/proof.mjs'), + ).href + ); + return runScope({all: process.env.SWIZZLE_PROOF_ALL === '1'}); + }); + const {scope, relevant} = await plan(); + if (scope.mode === 'none') return {idle: new Set(slices), costs}; + const model = record?.swizzleProof; + if (scope.mode !== 'affected' || !model) return {idle: new Set(), costs}; + const held = await (inject.bound ?? boundWithin)(relevant, slices.length); + if (!held) return {idle: new Set(), costs}; + for (const file of slices) { + const index = Number(/swizzle-proof\.(\d+)\.test\./.exec(file)?.[1]) - 1; + if (!(index >= 0 && index < held.length)) return {idle: new Set(), costs}; + costs.set(file, sliceCost(model, held[index], record.seconds?.[file])); + } + return {idle: new Set(), costs}; +} + /** * The record after a run. The run's times replace those files' times; files * the run did not reach keep their earlier times; a swizzle-proof slice keeps @@ -223,10 +324,13 @@ export default class DurationShardSequencer extends BaseSequencer { const legOneSeconds = process.env.VITEST_LEG_ONE_RESERVE === '1' ? readLegOneSeconds() : 0; const files = node.map(relative); + const record = readRecord(); + const {idle, costs} = await swizzleSliceCosts(files, record); const mine = new Set( - partitionByDuration(files, count, readDurations(), { + partitionByDuration(files, count, record.seconds ?? {}, { legOneSeconds, - idle: await idleSwizzleSlices(files), + idle, + costs, })[index - 1], ); return [ @@ -290,6 +394,12 @@ if ( legOneSteps, recordLegOneSteps(fs.readFileSync(log, 'utf8'), Object.keys(legOneSteps)), ); + // The swizzle-proof slices' model, from their summary lines in the same + // logs; a part the logs cannot show keeps its earlier value. + const swizzleProof = fitSwizzleModel( + logs.flatMap(log => swizzleSamples(fs.readFileSync(log, 'utf8'))), + current.swizzleProof, + ); fs.writeFileSync( DURATIONS, `${JSON.stringify( @@ -298,6 +408,7 @@ if ( source: 'recorded Node leg logs', seconds: mergeRecord(current.seconds ?? {}, seconds), legOneSteps, + ...(swizzleProof ? {swizzleProof} : {}), }, null, 2, diff --git a/scripts/vitest-shard-sequencer.test.mjs b/scripts/vitest-shard-sequencer.test.mjs index 2ca5a8562796a..51e95f45fad89 100644 --- a/scripts/vitest-shard-sequencer.test.mjs +++ b/scripts/vitest-shard-sequencer.test.mjs @@ -15,6 +15,8 @@ import DurationShardSequencer, { readDurations, recordDurations, idleSwizzleSlices, + swizzleSliceCosts, + boundWithin, } from './vitest-shard-sequencer.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); @@ -373,6 +375,84 @@ describe('duration-balanced Node legs', () => { expect([...(await idleSwizzleSlices(files))]).toEqual([]); }); + describe('a slice the change reaches is costed by the targets it holds', () => { + const slices = Array.from( + {length: 8}, + (_, i) => + `packages/cli/test/swizzle-proof/swizzle-proof.${i + 1}.test.mjs`, + ); + const files = ['a.test.mjs', ...slices]; + const model = {setupSeconds: 28, proveBaseSeconds: 97, perTargetSeconds: 4}; + const record = { + seconds: Object.fromEntries(slices.map(file => [file, 300])), + swizzleProof: model, + }; + const scope = + (mode, relevant = []) => + () => ({scope: {mode}, relevant}); + const held = [16, 0, 1, 21, 3, 0, 2, 60]; + + it('by the model, held by held, capped at the recorded time', async () => { + const {idle, costs} = await swizzleSliceCosts(files, record, { + plan: scope('affected', ['packages/core/src/Button/Button.tsx']), + bound: async (relevant, count) => { + expect(relevant).toEqual(['packages/core/src/Button/Button.tsx']); + expect(count).toBe(8); + return held; + }, + }); + expect(idle.size).toBe(0); + expect(slices.map(file => costs.get(file))).toEqual([ + 189, 28, 129, 209, 137, 28, 133, 300, + ]); + }); + + it('at the recorded time when the bound misses its budget, the record has no model, or the scope is all', async () => { + const cases = [ + [record, scope('affected'), async () => null], + [{seconds: record.seconds}, scope('affected'), async () => held], + [record, scope('all'), async () => held], + ]; + for (const [rec, plan, bound] of cases) { + const {idle, costs} = await swizzleSliceCosts(files, rec, { + plan, + bound, + }); + expect(idle.size).toBe(0); + expect(costs.size).toBe(0); + } + }); + + it('idle in the scope none, without computing a bound', async () => { + const {idle, costs} = await swizzleSliceCosts(files, record, { + plan: scope('none'), + bound: async () => { + throw new Error('no bound in the scope none'); + }, + }); + expect([...idle].sort()).toEqual([...slices].sort()); + expect(costs.size).toBe(0); + }); + + it('spreads the legs by those costs', () => { + const costs = new Map(slices.map((file, i) => [file, i < 2 ? 300 : 28])); + const legs = partitionByDuration(files, 4, record.seconds, {costs}); + const legOf = file => legs.findIndex(leg => leg.includes(file)); + expect(legOf(slices[0])).not.toBe(legOf(slices[1])); + expect(legs.flat().sort()).toEqual([...files].sort()); + }); + + it('stops waiting for the bound at its budget', async () => { + const started = Date.now(); + expect( + await boundWithin(['packages/core/src/Button/Button.tsx'], 8, { + budgetMs: 1, + }), + ).toBeNull(); + expect(Date.now() - started).toBeLessThan(15_000); + }, 30_000); + }); + it('reads no swizzle-proof scope when no slice is in the run', async () => { expect([...(await idleSwizzleSlices(['a.test.mjs']))]).toEqual([]); });