Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/scripts/ci-node-leg-bounds.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
});

Expand Down
50 changes: 45 additions & 5 deletions .github/scripts/node-time-drift.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file> (the shard watchdog's per-file seconds),
* @input --times <file> (the shard watchdog's per-file seconds), --swizzle
* <file> (optional: each swizzle-proof slice's summary, one JSON a line),
* --changed <base> (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
Expand All @@ -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;
Expand Down Expand Up @@ -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];
Expand All @@ -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'],
Expand Down Expand Up @@ -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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One malformed line throws here and fails the leg's drift step with a stack trace. swizzleSamples in scripts/lib/swizzle-cost.mjs already skips a line it cannot parse and keeps only samples whose affected and totalMs are finite; without that check a line that parses but carries no totalMs also reaches slowSlices, where the NaN comparisons drop it silently. Reuse that reader's validation for the JSONL file.

: [];
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 (
Expand Down
44 changes: 44 additions & 0 deletions .github/scripts/node-time-drift.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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: []});
});
});
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down
38 changes: 38 additions & 0 deletions packages/cli/test/swizzle-proof/bound-worker.mjs
Original file line number Diff line number Diff line change
@@ -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});
}
110 changes: 110 additions & 0 deletions packages/cli/test/swizzle-proof/bound.test.mjs
Original file line number Diff line number Diff line change
@@ -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<string, any>} */
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);
});
Loading