Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
192 changes: 183 additions & 9 deletions .github/scripts/cli-minimum-node.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,25 @@
* @file The CLI's declared minimum Node, and the one issue that reports a run
* on it.
* @input `minimum --package <package.json>` prints the lowest Node version its
* `engines.node` range allows. `reportIssue` takes actions/github-script's
* `github` and `context`, whether the run passed, the version and the run
* link.
* `engines.node` range allows; `slow --times <file> --record <file>` names
* one leg's files past their minimum-Node record. `reportIssue` takes
* actions/github-script's `github` and `context`, the run's verdict (pass,
* fail or none), the version and the run link.
* @output The version on stdout (exit 1 when the range has no lower bound this
* reads); an issue opened, commented on or closed.
* reads); warning lines and a step summary for slow files; an issue opened,
* commented on or closed.
* @position .github/workflows/cli-minimum-node.yml: the daily main-only run of
* the CLI's tests and global-mode smoke on that version. The version comes
* from the CLI's own `engines.node`, not from .nvmrc, which names the
* version the rest of CI uses.
*/

import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';

import {drifted} from './node-time-drift.mjs';
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved

export const ISSUE_TITLE = 'CLI fails on its minimum Node';
const BOT = 'github-actions[bot]';

Expand Down Expand Up @@ -91,13 +96,156 @@ async function findOpenIssue(github, context) {
);
}

/**
* Each leg's verdict from the files the CLI test legs upload
* (`{"shard": <n>, "verdict": "pass" | "fail" | "none"}`): "none" for a leg
* with no file, which the job limit cancelled before it could write one.
* @param {string} dir
* @param {number} count legs
* @returns {Array<'pass' | 'fail' | 'none'>}
*/
export function readLegVerdicts(dir, count) {
const verdicts = Array.from({length: count}, () => 'none');
let names = [];
try {
names = fs.readdirSync(dir);
} catch {
// No verdict was uploaded at all.
}
for (const name of names) {
try {
const {shard, verdict} = JSON.parse(
fs.readFileSync(path.join(dir, name), 'utf8'),
);
if (
Number.isInteger(shard) &&
shard >= 1 &&
shard <= count &&
['pass', 'fail', 'none'].includes(verdict)
)
verdicts[shard - 1] = verdict;
} catch {
// An unreadable file leaves that leg without a verdict.
}
}
return verdicts;
}

/** Seconds past its expected time a file must also run before it is named. */
export const SLOW_MARGIN_S = 10;

/**
* The files that ran past their minimum-Node record, by the Node legs' own
* drift rule (node-time-drift.mjs `drifted`): every timed file is judged, the
* run's own slowdown is taken out, and a file must also run SLOW_MARGIN_S
* past its expected time. A file the record lacks is not judged.
* @param {Record<string, number>} times seconds per test file, this run
* @param {Record<string, number>} recorded seconds per test file, the record
* @returns {{file: string, recorded: number, measured: number}[]}
*/
export function slowFiles(times, recorded) {
return drifted(times, recorded, [], {all: true, margin: SLOW_MARGIN_S}).map(
({file, recorded: before, measured}) => ({
file,
recorded: before,
measured,
}),
);
}
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved

/**
* The record with this run's times in it: each measured file takes its new
* time, every other file keeps its own, and a file `exists` no longer finds
* leaves it. `source` names the run the times came from.
* @param {{seconds?: Record<string, number>}} record
* @param {Record<string, number>} times
* @param {{source?: string, exists?: (file: string) => boolean}} [options]
*/
export function refreshRecord(
record,
times,
{source, exists = () => true} = {},
) {
const seconds = {...record.seconds, ...times};
return {
...record,
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
...(source
? {
$comment:
"Seconds per CLI test file on the CLI's minimum Node, which the \"CLI on minimum Node\" workflow packs its legs by (VITEST_DURATIONS_FILE). Refreshed from that workflow's run named in `source`; refresh it from the latest run's min-node-record artifact.",
source,
}
: {}),
seconds: Object.fromEntries(
Object.entries(seconds)
.filter(([file]) => exists(file))
.sort(([a], [b]) => a.localeCompare(b)),
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
),
};
}

/**
* Every leg's per-file times, as one map, from the files the legs upload:
* each artifact downloads into its own folder under `dir`.
* @param {string} dir
* @returns {Record<string, number>}
*/
export function readLegTimes(dir) {
const times = {};
let files = [];
try {
files = fs
.readdirSync(dir, {recursive: true, withFileTypes: true})
.filter(entry => entry.isFile() && entry.name.endsWith('.json'))
.map(entry => path.join(entry.parentPath ?? entry.path, entry.name));
} catch {
// No leg uploaded its times.
}
for (const file of files) {
try {
Object.assign(times, JSON.parse(fs.readFileSync(file, 'utf8')));
} catch {
// An unreadable file adds no times.
}
}
return times;
}

/** A job's result as a verdict: only success passes and only failure fails. */
const jobVerdict = result =>
result === 'success' ? 'pass' : result === 'failure' ? 'fail' : 'none';

/**
* The run's verdict: "fail" when any part failed a check, else "none" when
* any part judged nothing (stopped, cancelled or skipped), else "pass".
* @param {{version: string, legs: Array<'pass' | 'fail' | 'none'>, pack: string, smoke: string}} parts
* @returns {'pass' | 'fail' | 'none'}
*/
export function runVerdict({version, legs, pack, smoke}) {
if (version !== 'success') return 'none';
const all = [...legs, jobVerdict(pack), jobVerdict(smoke)];
if (all.includes('fail')) return 'fail';
return all.includes('none') ? 'none' : 'pass';
}

/**
* A failed run opens the issue, or comments on the open one; a passing run
* closes an open issue this job opened. Returns what it did.
* closes an open issue this job opened; a run with no verdict only notes it
* on an open issue. Returns what it did.
*/
export async function reportIssue({github, context, ok, version, runUrl}) {
export async function reportIssue({github, context, verdict, version, runUrl}) {
const issue = await findOpenIssue(github, context);
if (ok) {
// No verdict neither closes the issue nor says the CLI failed.
if (verdict === 'none') {
if (!issue) return 'none';
await github.rest.issues.createComment({
...context.repo,
issue_number: issue.number,
body: `No verdict on Node ${version}: part of the run stopped, was cancelled or was skipped before it judged anything ([run](${runUrl})). This issue stays as it is.`,
});
return 'no verdict noted';
}
if (verdict === 'pass') {
if (!issue) return 'none';
await github.rest.issues.createComment({
...context.repo,
Expand Down Expand Up @@ -133,10 +281,36 @@ if (
process.argv[1] &&
fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const [, , command, flag, file] = process.argv;
const [, , command, flag, file, recordFlag, recordFile] = process.argv;
if (command === 'slow' && flag === '--times' && recordFlag === '--record') {
// One leg's files past their minimum-Node record: a warning each, and a
// line in the step summary. Never a failure.
let times = {};
try {
times = JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
console.log(`No per-file times at ${file}.`);
process.exit(0);
}
const recorded =
JSON.parse(fs.readFileSync(recordFile, 'utf8')).seconds ?? {};
const slow = slowFiles(times, recorded);
for (const {file: test, recorded: before, measured} of slow)
console.log(
`::warning file=${test},title=Past its minimum-Node time::${test} ran ${measured} s; ${recordFile} records ${before} s.`,
);
if (slow.length && process.env.GITHUB_STEP_SUMMARY)
fs.appendFileSync(
process.env.GITHUB_STEP_SUMMARY,
`### Files past their minimum-Node time\n\n${slow.map(({file: test, recorded: before, measured}) => `- \`${test}\`: ${measured} s (recorded ${before} s)`).join('\n')}\n`,
);
if (!slow.length)
console.log('Every file ran within its minimum-Node time.');
process.exit(0);
}
if (command !== 'minimum' || flag !== '--package' || !file) {
console.error(
'usage: cli-minimum-node.mjs minimum --package <package.json>',
'usage: cli-minimum-node.mjs minimum --package <package.json>\n cli-minimum-node.mjs slow --times <file> --record <file>',
);
process.exit(2);
}
Expand Down
Loading