diff --git a/README.md b/README.md index 5dd3f5719..c1d2eb018 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ Changes land on `main` through PRs, and the kit's tests in `test/` must pass. Ru - `--shard i/n`: the i-th of n shards (n from 1 to 8), balanced by the running Node major's weights in `test/timings.json`. - `--repeat n`: run every chosen file n times; a failure on any run fails the run. -`test/flaky.json` lists the known flaky files, at most 20, each with the evidence it is a flake, what is known of its cause, and the last day it counts. A listed file that fails runs once more after the others; if that passes, the run passes and prints `FLAKY: …` (on GitHub also as a warning). Nothing else is ever retried, a file that fails twice fails the run, and `--repeat` retries nothing. Fixing a listed file's cause takes it off the list. +`test/flaky.json` lists the known flaky files, at most 20, each with the evidence it is a flake (the runs where it failed, then passed on the same commit), what is known of its cause and who owns its fix, the last day it counts (at most 31 days ahead: renew it with fresh evidence, or fix it), and optionally `tests`, the tests in it known to flake, each by its path (its parents' names and its own, joined by ` > `). An entry whose reason or cause still starts with `TODO` counts for nothing. A listed file that fails runs once more after the others; if that passes, the run passes and prints `FLAKY: …` (on GitHub also as a warning and in the job's step summary). With `tests`, only a failure of those tests is retried that way. An unlisted file that fails is retried once too, when at most 3 unlisted files failed: passing then, it is a flake, but the run still fails, and prints `NOT LISTED FLAKY: …` with the ready-made entry to add (this run, job and commit as its evidence, the failing tests, 14 days; fill in the cause and the fix's owner). When no test failed (a crash, a timeout, a hook) it prints no entry and says why: an entry without `tests` would pass any failure of the file. A file that fails twice always fails the run, and `--repeat` retries nothing. Fixing a listed file's cause takes it off the list. A release is a `vX.Y.Z` tag on `main` with a GitHub Release whose notes have three sections, because projects' supervisors read them to decide what to fold in: diff --git a/test/flaky.json b/test/flaky.json index 4cd167881..d3b2d1ac3 100644 --- a/test/flaky.json +++ b/test/flaky.json @@ -1,5 +1,5 @@ { - "about": "Known flaky test files: test/run.mjs retries each once when it fails, prints FLAKY when the retry passes, and retries nothing else. At most 20. Each entry: reason (the evidence it is a flake: the same commit went green on a rerun), cause (what is known, and what is not), until (the last day it counts; past it the file is not retried, so fix it or renew it with fresh evidence). Counts are flaky CI jobs: 'fresh' is 77 jobs that failed and went green on a rerun of the same commit in 200 test.yml runs, 2026-12-01 to 12-03; 'older' is 800 runs before that (research/devteam-speed-ideation raw/ci/all.tsv).", + "about": "Known flaky test files: test/run.mjs retries each once when it fails, prints FLAKY when the retry passes; an unlisted file that fails is retried too, but fails the run either way and prints the entry it would need (NOT LISTED FLAKY). At most 20. Each entry: reason (the evidence it is a flake: the same commit went green on a rerun, by run id), cause (what is known, what is not, and the ticket or PR that owns the fix), until (the last day it counts, at most 31 days ahead; past it the file is not retried, so fix it or renew it with fresh evidence), and optionally tests (the tests known to flake, each by its path: its parents' names and its own joined by ' > '; only a failure of those is retried). A reason or cause starting with TODO is refused. Counts are flaky CI jobs: 'fresh' is 77 jobs that failed and went green on a rerun of the same commit in 200 test.yml runs, 2026-12-01 to 12-03; 'older' is 800 runs before that (research/devteam-speed-ideation raw/ci/all.tsv).", "files": { "test/dashboard-inbox-panel.controls.test.mjs": { "reason": "kit-1214's two waits in 'every control from the panel': 3 failures in 5 bounded loops of this file on one loaded machine (kit-1130), each started under load 20 with the load rising to 31-61 mid-run: test:1255 'closed: the page, the panel on Inbox' twice, test:1249 'the review's close' once; CI shows this file's older shapes as 25 of 77 fresh flaky jobs, 23 older failures", @@ -60,6 +60,16 @@ "reason": "1 of 77 fresh flaky jobs, 7 older", "cause": "'artifact notes on main go to the responder while it can take them' and the drawing case: a wait on the responder session. Not found", "until": "2027-01-03" + }, + "test/dashboard-inbox-panel.views.test.mjs": { + "reason": "failed and went green on a rerun of the same commit twice on 2026-12-05: run 47464377468 attempt 1, job 'kit (22, chrome 1/5)', a 30 s wait for the Inbox panel timed out (PR #997 head 42347592, no dashboard change); run 47519526820 attempt 1, job 'kit (24, chrome 1/5)', the panel wait at 900px timed out (PR #978 head 456aefba, no dashboard change); main's own run of that shard passed", + "cause": "not yet known: the same kind of fixed-time panel wait under a loaded runner as its sibling dashboard-inbox-panel.controls (kit-1214, kit-1130); no ticket owns it yet, devteam-dev is told to file one", + "until": "2027-01-04" + }, + "test/gateway-grant.test.mjs": { + "reason": "failed and went green on a rerun of the same commit on 2026-12-05: run 47516355250 attempt 1, job 'kit (18, rest 8/8)', the file hit its 120 s watchdog (its timing is 3.4 s) on Node 18 only, passing on Node 20, 22 and 24 in the same run (PR #982 head 6effc7a6, no gateway change)", + "cause": "not yet known: a hang seen on Node 18 only, under a loaded runner; no ticket owns it yet, devteam-dev is told to file one (Node 18 may leave CI, which would retire this entry)", + "until": "2027-01-04" } } } diff --git a/test/run-flaky.test.mjs b/test/run-flaky.test.mjs index e3b951ae6..aaa29bef9 100644 --- a/test/run-flaky.test.mjs +++ b/test/run-flaky.test.mjs @@ -1,5 +1,7 @@ -// test/run.mjs's one retry of a known flaky file (test/flaky.json): only a listed file is retried, -// once; a retried pass passes and says FLAKY; a file that fails every time still fails the run. +// test/run.mjs's one retry of a known flaky file (test/flaky.json): a listed file is retried once, +// and a retried pass passes and says FLAKY; a few unlisted failing files are retried once too, to +// find flakes, and fail the run either way, printing the entry they would need; an entry's "tests" +// narrow it to those tests; a file that fails every time still fails the run. import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; @@ -17,7 +19,10 @@ const fresh = (name) => fs.mkdtempSync(path.join(os.tmpdir(), `dtr-flaky-${name} const ONCE = (mark) => `import { test } from 'node:test';\nimport fs from 'node:fs';\ntest('once', () => { if (!fs.existsSync(${JSON.stringify(mark)})) { fs.writeFileSync(${JSON.stringify(mark)}, ''); throw new Error('the first run fails'); } });\n`; const ALWAYS = "import { test } from 'node:test';\nimport assert from 'node:assert/strict';\ntest('always', () => { assert.equal(1 + 1, 3, 'a real failure'); });\n"; const PASS = "import { test } from 'node:test';\ntest('pass', () => {});\n"; -const entry = (o = {}) => ({ reason: 'seen flaky', cause: 'a race', until: '2999-01-01', ...o }); +const TODAY = new Date().toISOString().slice(0, 10); +const entry = (o = {}) => ({ reason: 'seen flaky', cause: 'a race', until: R.addDays(TODAY, 10), ...o }); +// two tests, one of which (named) fails on the file's first run only +const TWO = (flaky, steady = 'steady') => (mark) => `import { test } from 'node:test';\nimport fs from 'node:fs';\ntest(${JSON.stringify(steady)}, () => {});\ntest(${JSON.stringify(flaky)}, () => { if (!fs.existsSync(${JSON.stringify(mark)})) { fs.writeFileSync(${JSON.stringify(mark)}, ''); throw new Error('the first run fails'); } });\n`; // A root of its own: run.mjs copied in (its ROOT is the copy's parent), the files, and its flaky.json. function root(t, files, flaky) { @@ -29,8 +34,9 @@ function root(t, files, flaky) { if (flaky !== undefined) fs.writeFileSync(path.join(dir, 'test', 'flaky.json'), JSON.stringify(flaky)); return dir; } -const env = () => { const e = { ...process.env }; for (const k of ['NODE_TEST_CONTEXT', 'GITHUB_ACTIONS', 'DEVTEAM_TEST_FIT_TIMEOUTS']) delete e[k]; return e; }; -const run = (dir, args = []) => spawnSync(process.execPath, [path.join(dir, 'test', 'run.mjs'), '--concurrency', '1', ...args], { cwd: dir, encoding: 'utf8', timeout: 60000, env: env() }); +// none of CI's own GITHUB_* either: a child run would write into this job's step summary +const env = () => { const e = { ...process.env }; for (const k of Object.keys(e)) if (k.startsWith('GITHUB_') || ['NODE_TEST_CONTEXT', 'DEVTEAM_TEST_FIT_TIMEOUTS'].includes(k)) delete e[k]; return e; }; +const run = (dir, args = [], extra = {}) => spawnSync(process.execPath, [path.join(dir, 'test', 'run.mjs'), '--concurrency', '1', ...args], { cwd: dir, encoding: 'utf8', timeout: 60000, env: { ...env(), ...extra } }); const L = (name) => `test/${name}.test.mjs`; const headers = (out, name) => out.split('\n').filter((l) => l.startsWith(`# ${L(name)}`)); @@ -54,28 +60,130 @@ test('a listed file that fails every time fails the run: the retry never turns a assert.doesNotMatch(r.stdout, /^FLAKY/m); }); -test('a file not in the list is never retried', (t) => { +test('an unlisted file that fails once is retried, fails the run all the same, and prints the entry it needs', (t) => { const dir = root(t, { flake: ONCE, other: ONCE }, { files: { [L('other')]: entry() } }); - const r = run(dir, [L('flake')].map((f) => path.join(dir, f))); + const r = run(dir, [path.join(dir, L('flake'))]); assert.equal(r.status, 1, r.stdout); - assert.equal(headers(r.stdout, 'flake').length, 1); - assert.doesNotMatch(r.stdout, /FLAKY|retry/); + assert.equal(headers(r.stdout, 'flake').length, 2, 'ran twice'); + assert.match(r.stdout, /^# test\/flake\.test\.mjs \(retry: it failed once and test\/flaky\.json does not list it;/m); + assert.match(r.stdout, /^failed: test\/flake\.test\.mjs \(failed \(exit 1\), then passed on its retry: flaky, not listed in test\/flaky\.json\)$/m); + assert.match(r.stdout, /^NOT LISTED FLAKY: test\/flake\.test\.mjs failed \(exit 1\), then passed on its retry; test\/flaky\.json does not list it, so the run fails\./m); + assert.doesNotMatch(r.stdout, /^FLAKY:/m); + // the ready-made entry parses, and is whole: flakyList takes it once its cause is filled in + const m = /^("test\/flake\.test\.mjs": \{[\s\S]*?\n\})$/m.exec(r.stdout); + assert.ok(m, r.stdout); + const e = JSON.parse(`{${m[1]}}`)['test/flake.test.mjs']; + assert.deepEqual(e.tests, ['once']); + assert.equal(e.until, R.addDays(TODAY, R.FLAKY_NEW_DAYS)); + assert.match(e.reason, /^a local run on Node \d+, commit unknown: failed \(exit 1\) in "once", then passed on its retry$/); + assert.match(e.cause, /^TODO: /); + // pasted unfilled, it is refused: an entry needs what is known and the fix's owner + const raw = R.flakyList({ files: { 'test/flake.test.mjs': e } }, TODAY); + assert.equal(raw.retry.size, 0); + assert.deepEqual(raw.skipped, ['test/flake.test.mjs: its test/flaky.json entry\'s reason or cause still starts with TODO (fill in what is known and who owns the fix): not retried']); + assert.equal(R.flakyList({ files: { 'test/flake.test.mjs': { ...e, cause: 'a race on the marker; fix owned by kit-1' } } }, TODAY).retry.size, 1, 'filled in, it is taken'); }); -test('no list, an entry past its day or missing a field, a list over 20, and --repeat retry nothing', (t) => { +test('on GitHub a ready-made entry names the run, the job and the commit, and goes to the step summary', (t) => { + const dir = root(t, { flake: ONCE }); + const sum = path.join(dir, 'summary.md'); + const r = run(dir, [], { GITHUB_ACTIONS: 'true', GITHUB_RUN_ID: '4242', GITHUB_RUN_ATTEMPT: '2', GITHUB_JOB: 'kit', GITHUB_SHA: 'abcdef0123456789', GITHUB_SERVER_URL: 'https://github.com', GITHUB_REPOSITORY: 'o/r', GITHUB_STEP_SUMMARY: sum }); + assert.equal(r.status, 1, r.stdout); + assert.match(r.stdout, /"reason": "run 4242 attempt 2 https:\/\/github\.com\/o\/r\/actions\/runs\/4242, job kit on Node \d+, commit abcdef01: failed \(exit 1\) in \\"once\\", then passed on its retry"/); + assert.match(r.stdout, /^::warning title=NOT LISTED FLAKY::NOT LISTED FLAKY: test\/flake\.test\.mjs/m); + const md = fs.readFileSync(sum, 'utf8'); + assert.match(md, /^### Flaky tests \(test\/run\.mjs\)$/m); + assert.match(md, /NOT LISTED FLAKY: test\/flake\.test\.mjs[\s\S]*```json\n"test\/flake\.test\.mjs": \{/); +}); + +test('an unlisted file that fails twice fails, with no flake line; over 3 unlisted failures retry none', (t) => { + const dir = root(t, { broken: ALWAYS }); + const r = run(dir); + assert.equal(r.status, 1, r.stdout); + assert.equal(headers(r.stdout, 'broken').length, 2, 'retried once, not more'); + assert.match(r.stdout, /^failed: test\/broken\.test\.mjs \(failed \(exit 1\), and on its retry failed \(exit 1\)\)$/m); + assert.doesNotMatch(r.stdout, /FLAKY/); + const many = root(t, { a: ONCE, b: ONCE, c: ONCE, e: ONCE, d: ONCE }, { files: { [L('d')]: entry() } }); + const r2 = run(many); + assert.equal(R.DETECT_MAX, 3); + assert.equal(r2.status, 1, r2.stdout); + for (const n of ['a', 'b', 'c', 'e']) assert.equal(headers(r2.stdout, n).length, 1, `${n}: four unlisted failures are a broken change, not flakes: ran once`); + assert.doesNotMatch(r2.stdout, /NOT LISTED/); + assert.equal(headers(r2.stdout, 'd').length, 2, 'a listed file is retried whatever else failed'); + assert.match(r2.stdout, /^FLAKY: test\/d\.test\.mjs/m); +}); + +test('an entry with tests passes a flake of those tests only', (t) => { + const dir = root(t, { named: TWO('flaky one'), other: TWO('another') }, { files: { [L('named')]: entry({ tests: ['flaky one'] }), [L('other')]: entry({ tests: ['flaky one'] }) } }); + const r = run(dir); + assert.equal(r.status, 1, r.stdout); + assert.match(r.stdout, /^FLAKY: test\/named\.test\.mjs failed \(exit 1\), then passed/m); + assert.match(r.stdout, /^test\/named\.test\.mjs\s+[\d.]+\s+ok, FLAKY/m); + // other's failing test isn't one its entry names: retried as an unlisted file's, and the run fails + assert.match(r.stdout, /^# test\/other\.test\.mjs \(retry: it failed once and test\/flaky\.json does not list it;/m); + assert.match(r.stdout, /^NOT LISTED FLAKY: test\/other\.test\.mjs failed \(exit 1\), then passed on its retry; test\/flaky\.json lists it for named tests only/m); + assert.match(r.stdout, /^failed: test\/other\.test\.mjs /m); + const m = /^("test\/other\.test\.mjs": \{[\s\S]*?\n\})$/m.exec(r.stdout); + const e = JSON.parse(`{${m[1]}}`)['test/other.test.mjs']; + assert.deepEqual(e.tests, ['flaky one', 'another'], 'its ready entry joins the tests'); + assert.equal(e.cause, 'a race', 'and keeps the entry\'s cause'); + assert.match(e.reason, /^seen flaky; a local run/); +}); + +// A file that exits 1 on its first run with no test failing (a crash), or whose before hook throws. +const CRASH = (mark) => `import { test } from 'node:test';\nimport fs from 'node:fs';\ntest('steady', () => {});\nif (!fs.existsSync(${JSON.stringify(mark)})) { fs.writeFileSync(${JSON.stringify(mark)}, ''); process.exitCode = 1; }\n`; +const HOOK = (mark) => `import { describe, it, before } from 'node:test';\nimport fs from 'node:fs';\ndescribe('suite', () => { before(() => { if (!fs.existsSync(${JSON.stringify(mark)})) { fs.writeFileSync(${JSON.stringify(mark)}, ''); throw new Error('the first run fails'); } }); it('leaf', () => {}); });\n`; + +test('a flake with no failing test (a crash, a hook) prints no ready entry: none could stay per-test', (t) => { + const dir = root(t, { crash: CRASH, hook: HOOK, free: CRASH }, { files: { [L('crash')]: entry({ tests: ['steady'] }), [L('hook')]: entry({ tests: ['suite > leaf'] }) } }); + const r = run(dir); + assert.equal(r.status, 1, r.stdout); + for (const n of ['crash', 'hook', 'free']) { + assert.equal(headers(r.stdout, n).length, 2, `${n}: retried`); + assert.match(r.stdout, new RegExp(`^NOT LISTED FLAKY: test/${n}\\.test\\.mjs `, 'm'), n); + assert.match(r.stdout, new RegExp(`^No ready entry for test/${n}\\.test\\.mjs: no test failed in its first run \\(a crash, a timeout or a hook\\), and an entry without "tests" would let any failure of the file pass\\.`, 'm'), n); + assert.doesNotMatch(r.stdout, new RegExp(`^"test/${n}\\.test\\.mjs": \\{`, 'm'), `${n}: no entry to paste`); + } + assert.doesNotMatch(r.stdout, /^FLAKY:/m); + // readyEntry itself: never an entry without tests, and a listed entry's tests are kept + assert.equal(R.readyEntry({ file: 'test/x.test.mjs', first: 'failed (exit 1)', tests: [], ref: 'r', today: TODAY, listed: entry({ tests: ['a'] }) }), null); + assert.equal(R.readyEntry({ file: 'test/x.test.mjs', first: 'failed (exit 1)', tests: [], ref: 'r', today: TODAY }), null); + const joined = JSON.parse(`{${R.readyEntry({ file: 'test/x.test.mjs', first: 'failed (exit 1)', tests: ['b'], ref: 'r', today: TODAY, listed: entry({ tests: ['a'] }) })}}`)['test/x.test.mjs']; + assert.deepEqual(joined.tests, ['a', 'b']); +}); + +// a nested test that fails on the first run only +const NESTED = (mark) => `import { describe, it } from 'node:test';\nimport fs from 'node:fs';\ndescribe('outer', () => { it('inner', () => { if (!fs.existsSync(${JSON.stringify(mark)})) { fs.writeFileSync(${JSON.stringify(mark)}, ''); throw new Error('the first run fails'); } }); });\n`; +test('tests name a test by its path: the leaf alone does not cover a nested test, the path does', (t) => { + const dir = root(t, { leaf: NESTED, whole: NESTED }, { files: { [L('leaf')]: entry({ tests: ['inner'] }), [L('whole')]: entry({ tests: ['outer > inner'] }) } }); + const r = run(dir); + assert.equal(r.status, 1, r.stdout); + assert.match(r.stdout, /^FLAKY: test\/whole\.test\.mjs /m); + assert.match(r.stdout, /^NOT LISTED FLAKY: test\/leaf\.test\.mjs /m); + assert.match(r.stdout, /"outer > inner"/, 'its ready entry names the path'); +}); + +test('no list, an entry past its day, too far ahead or missing a field, and a list over 20 let no retry pass; --repeat retries nothing', (t) => { const cases = [ ['no list', undefined, []], ['past its day', { files: { [L('flake')]: entry({ until: '2020-01-01' }) } }, [/^test\/flake\.test\.mjs: its test\/flaky\.json entry ran out on 2020-01-01: not retried$/m]], ['no cause', { files: { [L('flake')]: entry({ cause: ' ' }) } }, [/^test\/flake\.test\.mjs: its test\/flaky\.json entry needs reason, cause and until/m]], ['no reason', { files: { [L('flake')]: entry({ reason: undefined }) } }, [/needs reason, cause and until/]], ['a bad day', { files: { [L('flake')]: entry({ until: 'soon' }) } }, [/needs reason, cause and until/]], + ['too far ahead', { files: { [L('flake')]: entry({ until: R.addDays(TODAY, 32) }) } }, [new RegExp(`^test/flake\\.test\\.mjs: its test/flaky\\.json entry's until ${R.addDays(TODAY, 32)} is more than 31 days ahead \\(at most ${R.addDays(TODAY, 31)}\\): not retried$`, 'm')]], + ['tests not a list', { files: { [L('flake')]: entry({ tests: 'once' }) } }, [/entry's tests must be a list of test names: not retried/]], + ['cause TODO', { files: { [L('flake')]: entry({ cause: 'TODO: who owns it' }) } }, [/^test\/flake\.test\.mjs: its test\/flaky\.json entry's reason or cause still starts with TODO/m]], + ['reason todo', { files: { [L('flake')]: entry({ reason: ' todo later' }) } }, [/still starts with TODO/]], + ['tests empty', { files: { [L('flake')]: entry({ tests: [] }) } }, [/entry's tests must be a list of test names/]], ['over 20', { files: Object.fromEntries([L('flake'), ...Array.from({ length: 20 }, (_, k) => L(`x${k}`))].map((f) => [f, entry()])) }, [/^test\/flaky\.json lists 21 files, over 20: no file is retried$/m]], ]; for (const [what, flaky, says] of cases) { const dir = root(t, { flake: ONCE }, flaky); const r = run(dir); assert.equal(r.status, 1, `${what}: ${r.stdout}`); - assert.equal(headers(r.stdout, 'flake').length, 1, `${what}: ran once`); + assert.equal(headers(r.stdout, 'flake').length, 2, `${what}: retried as an unlisted file is`); + assert.doesNotMatch(r.stdout, /^FLAKY:/m, what); + assert.match(r.stdout, /^NOT LISTED FLAKY: test\/flake\.test\.mjs/m, what); for (const re of says) assert.match(r.stdout, re, what); } const dir = root(t, { flake: ONCE }, { files: { [L('flake')]: entry() } }); @@ -100,6 +208,81 @@ test('flakyList', () => { for (const bad of [null, [], 'x', { files: [] }, { files: 'x' }, {}]) assert.equal(R.flakyList(bad, today).retry.size, 0, JSON.stringify(bad)); }); +test('failedTests: the failing tests at any depth by path, never a parent failed by its subtest, a TODO, a cancelled one, a hook or the file', () => { + const tap = [ + '# Subtest: parent', + ' # Subtest: child \\# x', + ' not ok 1 - child \\# x', + ' ---', + " failureType: 'testCodeFailure'", + ' ...', + ' # Subtest: later', + ' not ok 2 - later', + ' ---', + " failureType: 'cancelledByParent'", + ' ...', + 'not ok 1 - parent', + ' ---', + " failureType: 'subtestsFailed'", + ' ...', + 'not ok 2 - todo # TODO', + " failureType: 'testCodeFailure'", + 'ok 3 - fine', + 'not ok 4 - flat', + ' ---', + " failureType: 'testCodeFailure'", + ' ...', + 'not ok 5 - flat', + 'not ok 6 - /abs/test/x.test.mjs', + " failureType: 'testCodeFailure'", + '# Subtest: suite', + ' # Subtest: leaf', + ' not ok 1 - leaf', + ' ---', + " failureType: 'cancelledByParent'", + ' ...', + 'not ok 7 - suite', + ' ---', + " failureType: 'hookFailed'", + ' ...', + '# Subtest: /abs/test/x.test.mjs', + ' # Subtest: wrapped', + ' not ok 1 - wrapped', + ' ---', + " failureType: 'testCodeFailure'", + ' ...', + ].join('\n'); + assert.deepEqual(R.failedTests(tap, 'test/x.test.mjs'), ['parent > child # x', 'flat', 'wrapped']); + assert.deepEqual(R.failedTests('', 'test/x.test.mjs'), []); +}); + +test('covers: an entry without tests covers any failure; with tests, only failures all among them', () => { + assert.equal(R.covers(null, ['a']), false); + assert.equal(R.covers({}, []), true, 'a timeout of a whole-file entry'); + assert.equal(R.covers({ tests: ['a', 'b'] }, ['a']), true); + assert.equal(R.covers({ tests: ['a'] }, ['a', 'c']), false); + assert.equal(R.covers({ tests: ['a'] }, []), false, 'no failing test (a timeout): not the named flake'); +}); + +test('pickDetect: at most 3 unlisted failures, never the chain, their first runs within 150 s together', () => { + const f = (file, seconds) => ({ file, seconds }); + const names = (rs) => R.pickDetect(rs).map((r) => r.file); + assert.deepEqual(names([f('a', 10), f('b', 20)]), ['a', 'b']); + assert.deepEqual(names([f('a', 1), f('b', 1), f('c', 1), f('d', 1)]), [], 'four: a broken change'); + assert.deepEqual(names([f('test/kit.test.mjs', 5), f('a', 5)]), ['a']); + assert.deepEqual(names([f('a', 100), f('b', 60), f('c', 50)]), ['a', 'c'], 'b would pass the budget; c still fits'); + assert.deepEqual(names([f('a', 151)]), []); + assert.deepEqual(names([f('a', 150)]), ['a']); +}); + +test('flakyList: until at most 31 days ahead, through its own day', () => { + const today = '2026-12-03'; + const { retry, skipped } = R.flakyList({ files: { a: entry({ until: '2027-01-03' }), b: entry({ until: '2027-01-04' }) } }, today); + assert.deepEqual([...retry.keys()], ['a']); + assert.match(skipped[0], /^b: its test\/flaky\.json entry's until 2027-01-04 is more than 31 days ahead \(at most 2027-01-03\): not retried$/); + assert.equal(R.addDays('2026-12-31', 1), '2027-01-01'); +}); + // The kit's own list: at most 20, every file there, every entry whole (the retry skips one that isn't). test('test/flaky.json: at most 20 files, each a test file here, with a reason, a cause and a day', () => { const json = JSON.parse(fs.readFileSync(path.join(testDir, 'flaky.json'), 'utf8')); @@ -114,6 +297,8 @@ test('test/flaky.json: at most 20 files, each a test file here, with a reason, a for (const k of ['reason', 'cause']) assert.ok(typeof e[k] === 'string' && e[k].trim().length >= 10, `${f}: ${k}`); assert.match(e.until, /^\d{4}-\d{2}-\d{2}$/, `${f}: until`); } - // every entry well formed: nothing of the list is skipped for its shape (past its day is fine) - assert.deepEqual(R.flakyList(json, '2000-01-01').skipped, []); + // every entry well formed: nothing of the list is skipped for its shape (past its day is fine), and + // none further ahead than FLAKY_DAYS from today (time passing only brings them closer) + assert.deepEqual(R.flakyList(json, TODAY).skipped.filter((w) => !/ran out on/.test(w)), []); + for (const f of names) if (json.files[f].tests) assert.ok(json.files[f].tests.every((n) => typeof n === 'string' && n.trim()), `${f}: tests`); }); diff --git a/test/run.mjs b/test/run.mjs index 6549367ff..8f16b0810 100644 --- a/test/run.mjs +++ b/test/run.mjs @@ -56,13 +56,28 @@ // weighs 1. A sharded run prints its shard's files with no time once, after the summary rows: // "unweighed on Node N …". // -// test/flaky.json: the known flaky files, at most FLAKY_MAX, each { "reason", "cause", "until" }: why -// it is listed, what is known of the cause, and the last day (YYYY-MM-DD, UTC) its entry counts. A -// listed file that fails (or times out) runs once more, after the run's other files; passing then, -// it counts as passed, and the run prints "FLAKY: …" with its first result and the entry's -// reason, in its row and after the summary. Failing again, it fails as any file does. A file not in -// the list, an entry past its day or missing a field, a list over FLAKY_MAX, and any run with -// --repeat over 1 (which looks for flakes) never retry anything. +// test/flaky.json: the known flaky files, at most FLAKY_MAX, each { "reason", "cause", "until" } and +// optionally "tests": why it is listed (the evidence: the runs where it failed, then passed on the +// same commit), what is known of the cause and who owns its fix, the last day (YYYY-MM-DD, UTC) its +// entry counts, at most FLAKY_DAYS ahead (renew it with fresh evidence), and the names of the tests +// in it known to flake. A listed file that fails (or times out) runs once more, after the run's other +// files; passing then, it counts as passed, and the run prints "FLAKY: …" with its first +// result and the entry's reason, in its row and after the summary. With "tests", only a failure of +// those tests is retried so: a failure of any other test of the file, or one with no failing test +// (a timeout, a crash, a hook), is treated as an unlisted file's. A test is named by its path, its +// parents' names and its own joined by " > " ("suite > test"; a top-level test by its name alone). +// A reason or cause that still starts with TODO counts for nothing: the entry needs its fix's owner. Failing again, it fails as any file does. +// An entry past its day, too far ahead, or missing a field, and a list over FLAKY_MAX, count for +// nothing; --repeat over 1 (which looks for flakes) never retries anything. +// An unlisted file that fails is retried once too, to tell a flake from a real failure, when at most +// DETECT_MAX unlisted files failed in the run (more is a broken change, not flakes), the first runs +// of those retried took at most DETECT_SECONDS together, and it isn't the chain. Its retry never +// passes the run: passing, it prints "NOT LISTED FLAKY: …" and the test/flaky.json entry it +// would need, its evidence (this run, job, Node major and commit) and failing tests filled in, so it +// can be added once its cause and owner are. With no failing test (a crash, a timeout, a hook) it +// prints no entry, and says so: an entry without "tests" would pass any failure of the file. +// The FLAKY and NOT LISTED FLAKY lines are GitHub warnings on GitHub, and go to the step's summary +// ($GITHUB_STEP_SUMMARY) when it is set. // // Each file runs with TMPDIR set to a scratch folder of its own (under /tmp/dtr- where /tmp is // writable), removed when the file ends, and DEVTEAM_TEST_SHARED_TMP naming the shared temp dir @@ -88,10 +103,21 @@ export const LONG = { 'test/recurring-registry.test.mjs': 600, 'test/auto-start. export const GROUPS = ['chain', 'alone', 'chrome', 'rest']; // test/flaky.json (above): the files a failure retries once, by name. Never more than this many. export const FLAKY_MAX = 20; +// An entry's until at most this many days after today: a quarantine is renewed with fresh evidence, +// never left to stand. A ready-made entry gets FLAKY_NEW_DAYS. +export const FLAKY_DAYS = 31; +export const FLAKY_NEW_DAYS = 14; +// Unlisted failing files are retried, to see if they are flakes, when at most DETECT_MAX unlisted +// files failed, and only as many as took DETECT_SECONDS together on their first runs (the retries +// must fit in the job's step). +export const DETECT_MAX = 3; +export const DETECT_SECONDS = 150; const DAY = /^\d{4}-\d{2}-\d{2}$/; const said = (v) => typeof v === 'string' && v.trim().length > 0; -// The list's entries that retry today, by file: { reason, cause, until }. An entry missing a field, -// or past its day, is left out, and so is every entry of a list over FLAKY_MAX. `skipped` says why. +export const addDays = (day, n) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 86400000).toISOString().slice(0, 10); +// The list's entries that retry today, by file: { reason, cause, until, tests? }. An entry missing a +// field, with a "tests" that isn't a list of names, past its day or more than FLAKY_DAYS ahead, is +// left out, and so is every entry of a list over FLAKY_MAX. `skipped` says why. export function flakyList(json, today = new Date().toISOString().slice(0, 10)) { const files = json && typeof json === 'object' && !Array.isArray(json) ? json.files : null; if (!files || typeof files !== 'object' || Array.isArray(files)) return { retry: new Map(), skipped: [] }; @@ -99,17 +125,92 @@ export function flakyList(json, today = new Date().toISOString().slice(0, 10)) { if (names.length > FLAKY_MAX) return { retry: new Map(), skipped: [`test/flaky.json lists ${names.length} files, over ${FLAKY_MAX}: no file is retried`] }; const retry = new Map(); const skipped = []; + const latest = addDays(today, FLAKY_DAYS); for (const f of names) { const e = files[f]; if (!e || !said(e.reason) || !said(e.cause) || !DAY.test(e.until ?? '') || Number.isNaN(Date.parse(e.until))) skipped.push(`${f}: its test/flaky.json entry needs reason, cause and until (YYYY-MM-DD): not retried`); + else if (/^\s*TODO\b/i.test(e.reason) || /^\s*TODO\b/i.test(e.cause)) skipped.push(`${f}: its test/flaky.json entry's reason or cause still starts with TODO (fill in what is known and who owns the fix): not retried`); + else if (e.tests !== undefined && (!Array.isArray(e.tests) || !e.tests.length || !e.tests.every(said))) skipped.push(`${f}: its test/flaky.json entry's tests must be a list of test names: not retried`); else if (e.until < today) skipped.push(`${f}: its test/flaky.json entry ran out on ${e.until}: not retried`); - else retry.set(f, { reason: e.reason, cause: e.cause, until: e.until }); + else if (e.until > latest) skipped.push(`${f}: its test/flaky.json entry's until ${e.until} is more than ${FLAKY_DAYS} days ahead (at most ${latest}): not retried`); + else retry.set(f, { reason: e.reason, cause: e.cause, until: e.until, ...(e.tests ? { tests: e.tests } : {}) }); } return { retry, skipped }; } export const readFlaky = (root) => { try { return JSON.parse(fs.readFileSync(path.join(root, 'test', 'flaky.json'), 'utf8')); } catch { return null; } }; // The line a retried pass prints: never quiet, so a flake stays in sight. export const flakyLine = (file, first, entry) => `FLAKY: ${file} ${first}, then passed on its one retry (test/flaky.json: ${entry.reason})`; + +// The tests that failed in a file's TAP, each once, in order, by path: its parents' names and its +// own, joined by PATH_SEP ("suite > test"; a top-level test is its name alone). Every `not ok` at any +// depth but a TODO, a parent that failed only because a subtest did, a test cancelled because its +// parent ended, a hook's failure (it names no test: a suite's before, a test's beforeEach) and the +// per-file wrapper (its description is the file's path; never part of a path either). +export const PATH_SEP = ' > '; +export function failedTests(tap, file) { + const lines = tap.split('\n'); + const unescape = (v) => v.replace(/\\([\\#])/g, '$1'); + const isFile = (name) => name === file || (path.isAbsolute(name) && name.endsWith(`/${file}`)); + const out = []; + // the open `# Subtest:` names by their indent: a test's parents are those indented less than it + let stack = []; + for (let k = 0; k < lines.length; k++) { + const sub = /^(\s*)# Subtest: (.*)$/.exec(lines[k]); + if (sub) { stack = stack.filter((e) => e.indent < sub[1].length); stack.push({ indent: sub[1].length, name: unescape(sub[2]) }); continue; } + const m = /^(\s*)not ok \d+(?: - (.*?))?(\s+# (?:SKIP|TODO)\b.*)?$/i.exec(lines[k]); + if (!m || m[2] === undefined || m[3]) continue; + const name = unescape(m[2]); + if (isFile(name)) continue; + // its YAML block: the lines below it indented deeper, up to its `...` + let type = null; + for (let j = k + 1; j < lines.length && lines[j].startsWith(`${m[1]} `); j++) { + const t = /^\s*failureType: '([^']*)'/.exec(lines[j]); + if (t) { type = t[1]; break; } + if (/^\s*\.\.\.\s*$/.test(lines[j])) break; + } + if (type === 'subtestsFailed' || type === 'cancelledByParent' || type === 'hookFailed') continue; + const parents = stack.filter((e) => e.indent < m[1].length && !isFile(e.name)).map((e) => e.name); + const full = [...parents, name].join(PATH_SEP); + if (!out.includes(full)) out.push(full); + } + return out; +} +// Whether a listed entry covers a failure whose failing tests are `names` (paths, as failedTests +// gives them): always, without "tests"; with it, only when some test failed and every one that did +// is named there, by its whole path. +export const covers = (entry, names) => !!entry && (!entry.tests || (names.length > 0 && names.every((n) => entry.tests.includes(n)))); + +// Where a ready-made entry's evidence points: this GitHub run and job, or a local run. +export function runRef(env, major = nodeMajor()) { + const sha = env.GITHUB_SHA ? `commit ${env.GITHUB_SHA.slice(0, 8)}` : 'commit unknown'; + if (!env.GITHUB_RUN_ID) return `a local run on Node ${major}, ${sha}`; + const url = env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY ? ` ${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : ''; + return `run ${env.GITHUB_RUN_ID}${env.GITHUB_RUN_ATTEMPT ? ` attempt ${env.GITHUB_RUN_ATTEMPT}` : ''}${url}, job ${env.GITHUB_JOB ?? 'unknown'} on Node ${major}, ${sha}`; +} +// The test/flaky.json entry an unlisted flake would need: evidence from this run, a cause for a +// person to fill (what is known, and the ticket or PR that owns the fix; flakyList refuses it while +// it starts with TODO), FLAKY_NEW_DAYS to fix it. A file already listed for other tests keeps its +// entry, its tests joined with these. null when no test failed (a crash, a timeout, a hook): a +// ready entry then could only be a whole-file one, covering any failure of the file, so none is made. +export function readyEntry({ file, first, tests, ref, today, listed = null }) { + if (!tests.length) return null; + const seen = `${ref}: ${first} in ${tests.map((n) => JSON.stringify(n)).join(', ')}, then passed on its retry`; + const e = listed + ? { reason: `${listed.reason}; ${seen}`, cause: listed.cause, until: listed.until, ...(listed.tests ? { tests: [...new Set([...listed.tests, ...tests])] } : {}) } + : { reason: seen, cause: 'TODO: what is known of the cause, and the ticket or PR that owns its fix', until: addDays(today, FLAKY_NEW_DAYS), tests }; + return `${JSON.stringify(file)}: ${JSON.stringify(e, null, 2)}`; +} +// What a flake with no failing test prints instead of an entry. +export const noEntryLine = (file) => `No ready entry for ${file}: no test failed in its first run (a crash, a timeout or a hook), and an entry without "tests" would let any failure of the file pass. Find the failing test in its log above, and list that test by its path.`; +// The unlisted failures retried to find flakes: none when over DETECT_MAX failed; never the chain; +// in order, while their first runs' seconds together stay within DETECT_SECONDS, so a broken change's +// job isn't pushed past its step's limit (which would lose the summary) by retries that fail anyway. +export function pickDetect(unlisted) { + if (unlisted.length > DETECT_MAX) return []; + let budget = DETECT_SECONDS; + return unlisted.filter((r) => r.file !== 'test/kit.test.mjs' && r.seconds <= budget && (budget -= r.seconds) >= 0); +} +export const unlistedLine = (file, first, listed) => `NOT LISTED FLAKY: ${file} ${first}, then passed on its retry; ${listed ? 'test/flaky.json lists it for named tests only' : 'test/flaky.json does not list it'}, so the run fails. Add it, with the owner of its fix in "cause", to let a flake of it pass:`; export class UsageError extends Error {} const posInt = (flag, v, min = 1, max = Number.MAX_SAFE_INTEGER) => { @@ -551,7 +652,7 @@ function startFile(p, run, ctx) { entry.seconds = (Date.now() - entry.start) / 1000; entry.result ??= error ? `failed (${error.message})` : code === 0 ? 'ok' : code !== null ? `failed (exit ${code})` : `failed (signal ${signal})`; ctx.running.delete(entry); - say(`# ${entry.file}${ctx.repeat > 1 ? ` (run ${run})` : ''}${p.retry ? ' (retry: it failed once, and test/flaky.json lists it)' : ''}\n${Buffer.concat(entry.out).toString()}`); + say(`# ${entry.file}${ctx.repeat > 1 ? ` (run ${run})` : ''}${p.retry === 'listed' ? ' (retry: it failed once, and test/flaky.json lists it)' : p.retry === 'detect' ? ' (retry: it failed once and test/flaky.json does not list it; this retry only tells a flake from a real failure, the run fails either way)' : ''}\n${Buffer.concat(entry.out).toString()}`); if (!/\n$/.test(Buffer.concat(entry.out).toString()) && entry.out.length) say('\n'); resolve(entry); }; @@ -711,19 +812,27 @@ async function runFiles(opts, plan, ctx) { results.push(...await runPool(st.files.map((p) => [p, run]), st.limit, ctx, st.caps)); } } - // test/flaky.json's files that failed: once more each, after the rest (never with --repeat) + // test/flaky.json's files that failed: once more each, after the rest (never with --repeat). And + // a few unlisted ones, to tell a flake from a real failure: their retry never passes the run. const flaky = opts.repeat > 1 ? { retry: new Map(), skipped: [] } : flakyList(readFlaky(ROOT)); - const again = results.filter((r) => r.result !== 'ok' && flaky.retry.has(r.file)); + const failedFirst = opts.repeat > 1 ? [] : results.filter((r) => r.result !== 'ok'); + for (const r of failedFirst) r.tests = failedTests(Buffer.concat(r.out ?? []).toString(), r.file); + const listed = failedFirst.filter((r) => covers(flaky.retry.get(r.file), r.tests)); + const unlisted = failedFirst.filter((r) => !listed.includes(r)); + const detect = pickDetect(unlisted); + const again = [...listed.map((r) => [r, 'listed']), ...detect.map((r) => [r, 'detect'])]; if (again.length && !ctx.stopping) { const byFile = new Map(plan.map((p) => [p.file, p])); - for (const st of schedule(again.map((r) => ({ ...byFile.get(r.file), retry: true })), opts.concurrency, opts.chromeConcurrency)) { + const how = new Map(again.map(([r, k]) => [r.file, k])); + for (const st of schedule(again.map(([r, k]) => ({ ...byFile.get(r.file), retry: k })), opts.concurrency, opts.chromeConcurrency)) { if (ctx.stopping) break; for (const second of await runPool(st.files.map((p) => [p, 1]), st.limit, ctx, st.caps)) { const first = results.find((r) => r.file === second.file && r.result !== 'ok' && !r.retried); first.retried = true; + if (second.result !== 'ok') first.result = `${first.result}, and on its retry ${second.result}`; // the retry's own time: the failed run's would inflate the weights --timings writes - if (second.result === 'ok') Object.assign(first, { result: 'ok', flaky: first.result, seconds: second.seconds, line: null }); - else first.result = `${first.result}, and on its retry ${second.result}`; + else if (how.get(first.file) === 'listed') Object.assign(first, { result: 'ok', flaky: first.result, seconds: second.seconds, line: null }); + else Object.assign(first, { unlistedFlaky: first.result, result: `${first.result}, then passed on its retry: flaky, not listed in test/flaky.json` }); } } } @@ -738,7 +847,20 @@ async function runFiles(opts, plan, ctx) { const recordedOf = new Map(plan.filter((p) => p.recorded !== undefined).map((p) => [p.file, p.recorded])); for (const r of results) if (r.result === 'ok' && isStale(r.seconds, recordedOf.get(r.file))) { const l = staleLine(r.file, r.seconds, recordedOf.get(r.file)); say(`${l}\n${process.env.GITHUB_ACTIONS === 'true' ? `::warning title=STALE TIME::${l}\n` : ''}`); } // on GitHub also a warning, so the run's page shows it beside a green check - for (const r of results) if (r.flaky) { const l = flakyLine(r.file, r.flaky, flaky.retry.get(r.file)); say(`${l}\n${process.env.GITHUB_ACTIONS === 'true' ? `::warning title=FLAKY::${l}\n` : ''}`); } + const gh = process.env.GITHUB_ACTIONS === 'true'; + const summary = []; + for (const r of results) if (r.flaky) { const l = flakyLine(r.file, r.flaky, flaky.retry.get(r.file)); say(`${l}\n${gh ? `::warning title=FLAKY::${l}\n` : ''}`); summary.push(`- ${l}`); } + // an unlisted flake: the run fails, and says the entry it would need + const today = new Date().toISOString().slice(0, 10); + for (const r of results) { + if (!r.unlistedFlaky) continue; + const l = unlistedLine(r.file, r.unlistedFlaky, flaky.retry.get(r.file)); + const e = readyEntry({ file: r.file, first: r.unlistedFlaky, tests: r.tests ?? [], ref: runRef(process.env), today, listed: flaky.retry.get(r.file) ?? null }); + const body = e ?? noEntryLine(r.file); + say(`${l}\n${body}\n${gh ? `::warning title=NOT LISTED FLAKY::${l}\n` : ''}`); + summary.push(e ? `- ${l}\n\n\`\`\`json\n${e}\n\`\`\`\n` : `- ${l}\n\n ${body}\n`); + } + if (summary.length && process.env.GITHUB_STEP_SUMMARY) { try { fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Flaky tests (test/run.mjs)\n\n${summary.join('\n')}\n\n`); } catch {} } // what of the list doesn't count: the whole list, or an entry for a file this run ran for (const why of flaky.skipped) { const f = /^(\S+\.test\.mjs):/.exec(why)?.[1]; if (!f || plan.some((p) => p.file === f)) say(`${why}\n`); } }