@ai-ecoverse/slicc-shared-web 2.12.4 → 2.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/bin/slicc-flaky.mjs +974 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Configuration shared by SLICC's web repos ([slicc-bios](https://github.com/ai-ec
|
|
|
10
10
|
| `tsconfig.json` | TypeScript base for Node's type stripping | `tsconfig.json`: `{ "extends": "@ai-ecoverse/slicc-shared-web/tsconfig.json", "include": ["src/**/*.ts"] }` |
|
|
11
11
|
| `lefthook.yml` | Pre-commit hooks: Biome, typecheck, no comments, no unit tests in git, AGENTS.md, and diff coverage over [only the unit tests the change reaches](#which-unit-tests-a-commit-runs) | `lefthook.yml`: the [fail-closed snippet below](#hooks-that-fail-closed), and `prepare`: `slicc-install-hooks` plus the committed `.githooks/` it writes ([one hooks directory per worktree](#one-hooks-directory-per-worktree)) |
|
|
12
12
|
| `mcr.config.mjs` | Unit-test coverage for JS and TS sources (`.js`, `.mjs`, `.cjs`, `.ts`, `.mts`, `.cts`) in `src/` or the `slicc.unitSources` directories (TS types are stripped first; TS that strip-only mode rejects, such as enums and parameter properties, is transformed with [amaro](https://github.com/nodejs/amaro) under the tests too, through an `--import` loader the config adds to `NODE_OPTIONS`, and its coverage is mapped back to the `.ts` lines; the same loader resolves a relative `./x.js`, `.mjs` or `.cjs` that isn't on disk to its `.ts`, `.mts` or `.cts` sibling, and imports a `.json` module, such as a package whose `main` is JSON, without `with { type: 'json' }`), written to `coverage/unit/lcov.info`. Every source file is in it, tested or not, and paths are matched relative to the repo root, so a checkout under a dot-directory such as `~/.bb/` still reports untested files to diff coverage. With `SLICC_UNIT_TESTS` set, `node --test` runs only those files ([below](#which-unit-tests-a-commit-runs)) | `test:unit`: `mcr -c node_modules/@ai-ecoverse/slicc-shared-web/mcr.config.mjs node --test 'test/unit/**/*.test.mjs'` |
|
|
13
|
-
| `bin/` | `slicc-lint` runs every check below plus Biome and, if the repo has one, `typecheck`. Every step prints its own `<step>: PASS …` line, and slicc-lint checks for it: a step that exits 0 without one fails the run with exit 70 (`slicc-lint: FAIL <step> (no PASS line from it)`), so a check that silently stops early can't pass. The last line, `slicc-lint: PASS`, comes only after every step has printed its PASS, and a gate can require it. `slicc-lint-comments` runs the [slicc no-comment checker](https://github.com/ai-ecoverse/slicc/tree/main/packages/dev-tools/no-comment) at a pinned commit, allowing AGENTS.md and [`# renovate:` annotations](#versions-pinned-in-workflow-files) in workflow and action files. `slicc-agents-md`, `slicc-no-unit-tests` and `slicc-diff-cover` complete the set, and `slicc-unit-cover` is the diff-coverage hook. `slicc-minidump <file.dmp>...` prints a crash dump's stack, described [below](#crash-dumps). `slicc-memory-peak` prints the job's [memory peak](#memory-peak). `slicc-install-hooks` installs the hooks into [this worktree's own directory](#one-hooks-directory-per-worktree), and on Windows does nothing and exits 0, so `npm ci` works there | `lint`: `slicc-lint`, and the hooks above |
|
|
13
|
+
| `bin/` | `slicc-lint` runs every check below plus Biome and, if the repo has one, `typecheck`. Every step prints its own `<step>: PASS …` line, and slicc-lint checks for it: a step that exits 0 without one fails the run with exit 70 (`slicc-lint: FAIL <step> (no PASS line from it)`), so a check that silently stops early can't pass. The last line, `slicc-lint: PASS`, comes only after every step has printed its PASS, and a gate can require it. `slicc-lint-comments` runs the [slicc no-comment checker](https://github.com/ai-ecoverse/slicc/tree/main/packages/dev-tools/no-comment) at a pinned commit, allowing AGENTS.md and [`# renovate:` annotations](#versions-pinned-in-workflow-files) in workflow and action files. `slicc-agents-md`, `slicc-no-unit-tests` and `slicc-diff-cover` complete the set, and `slicc-unit-cover` is the diff-coverage hook. `slicc-minidump <file.dmp>...` prints a crash dump's stack, described [below](#crash-dumps). `slicc-memory-peak` prints the job's [memory peak](#memory-peak). `slicc-flaky retry|verdict|report` is the pipeline's [flaky-test](#pipeline) rerun, gate and reporter. `slicc-install-hooks` installs the hooks into [this worktree's own directory](#one-hooks-directory-per-worktree), and on Windows does nothing and exits 0, so `npm ci` works there | `lint`: `slicc-lint`, and the hooks above |
|
|
14
14
|
| `pnpmfile.mjs` | pnpm's counterpart to the Renovate preset: an `updateConfig` hook that adds `@ai-ecoverse/*` to `minimumReleaseAgeExclude`, so pnpm 12 doesn't hold back our own fresh releases (`ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`) while third-party packages keep its age check | in a repo with a pnpm lockfile, as a [config dependency](https://pnpm.io/config-dependencies) in `pnpm-workspace.yaml`: `configDependencies: { '@ai-ecoverse/slicc-shared-web': X.Y.Z }` plus `pnpmfile: node_modules/.pnpm-config/@ai-ecoverse/slicc-shared-web/pnpmfile.mjs` |
|
|
15
15
|
| `harness/` | The CDP integration-test harness, described [below](#integration-test-harness) | `import { launch } from '@ai-ecoverse/slicc-shared-web/harness'`, and `--test-global-setup=node_modules/@ai-ecoverse/slicc-shared-web/harness/global.mjs` |
|
|
16
16
|
| `testing/` | Git fixtures that pass the AI git wrapper: `initFixtureRepo(dir, { hooks })` inits a throwaway repo with its own identity, no signing and no template hooks (`hooks: false` sets `core.hooksPath` to `/dev/null`), `commit(dir, message)` commits what is staged without `--no-verify`, and `commitAll(dir, message)` stages with `git add -A -- :/` first, all ignoring global and system git config, so a global `core.hooksPath` never runs in the fixture. Use them instead of `git add -A`, `git add .` or `--no-verify` in a test, which the wrapper refuses when an AI tool runs the suite | `import { commitAll, initFixtureRepo } from '@ai-ecoverse/slicc-shared-web/testing'` |
|
|
@@ -63,6 +63,7 @@ The caller cancels superseded runs on pull requests only, so a push to `main` ne
|
|
|
63
63
|
| `deploy`: `deploy` in the `staging` environment, only when the input is set | ✓ | ✓ | |
|
|
64
64
|
| `test` (one per shard) and `integration`, a check to require | ✓ | ✓ | |
|
|
65
65
|
| `windows`: `windows-test` on `windows-latest`, only when the input is set | ✓ | ✓ | |
|
|
66
|
+
| `flaky`: files and closes `flaky-test` issues, never a check, only with `flaky-retry` above 0 | ✓ | ✓ | |
|
|
66
67
|
| `context`, `reviewer` (Claude and Codex) and `post`, when the pull request [gets a review](#which-pull-requests-get-a-review) | ✓ | | |
|
|
67
68
|
| `review`, the other check to require | ✓ | always green | |
|
|
68
69
|
| `release`: `semantic-release` | | | ✓ |
|
|
@@ -81,6 +82,8 @@ The caller cancels superseded runs on pull requests only, so a push to `main` ne
|
|
|
81
82
|
windows-test: npm run test:windows
|
|
82
83
|
```
|
|
83
84
|
|
|
85
|
+
**Flaky tests.** With `flaky-retry` above 0 (this repo's own CI sets 3; the default, 0, runs the tests once, as before), a shard whose tests failed reruns its failing files once, right away, on the same runner and commit, through `slicc-flaky retry`, which the test, `integration` and `flaky` jobs take from the pipeline's own commit. A test that fails, then passes is a flip; one that fails twice is a failure. A test is its file and its top-level name, and its key is the first 16 hex digits of `sha256(file \0 name)`. There is no rerun, and the shard fails as before, without a JUnit report or a failing test in it, with more than `flaky-retry` failing files, or when less than the rerun's limit, min(15 min, a quarter of `timeout-minutes`), is left of `timeout-minutes`. A failing test whose JUnit `file=` isn't one of the run's `test-glob` files, such as Go's package directory, is never rerun (`not rerun: a failing test names no test file: <file>`), `integration` never excuses such a flip, whatever a shard's `flaky.json` says, and `flaky` logs it and files nothing. The rerun gets `SLICC_TEST_RETRY=1` and only those files, writes `junit/<shard>.retry.xml` (and no second `.files` list), keeps the first run's `artifacts/` and `coverage/` (its own artifacts go to `artifacts/retry/`), and is killed at the limit. `junit/<shard>.flaky.json` records each retried test's first and retry outcome, its first error and the runner. A flip passes the shard only if an open `flaky-test` issue has its key and has seen it on another commit (it has no `new` label, or its commit isn't this one), the test file doesn't match `strict-tests` and the pull request doesn't change it; every other flip stays red, and so does a test that is skipped, cancelled or missing on the rerun, a rerun that ran no test, wrote no JUnit report or timed out, and a test that passed first and failed on the rerun. Only the rerun's results count for those tests; its exit status doesn't, so a check after `node --test` in `test` (such as this repo's `verify.mjs`) doesn't fail a rerun of one file. `lint` reads the open `flaky-test` issues once (with `issues: read`) and the pull request's changed files, and hands them to the shards and `integration`; when it can't, no flake is known and every flip stays red. `integration` judges each shard's flips again from its JUnit reports and that list, counts only the failures it doesn't excuse, keeps every other check on the first run, and names the flakes: `integration: PASS … , 2 known flakes passed on retry (#916, #844)`. Each shard also uploads the tests that finally failed as `failed-<shard>-<attempt>`, and a test that failed on an earlier attempt of the run and passes now counts as a flip in the report, though not for the gate. The `flaky` job (`issues: write`, `actions: read`, `continue-on-error`) writes a table of the run's flips and failures to its step summary and files one issue per test: title `flaky: <file name> › <test name>`, label `flaky-test`, `new` until a second commit, `guard` for a strict row, whose issue and comments name only the test, the run and the commit, and ``Key: `<key>` `` in the body. It finds the issue among the open ones, then among those closed in the last 30 days, which it reopens, and otherwise opens one; it comments at most once per issue per run with the run and attempt, the event, the pull request, the shard, the runner, the commit and the first error (at most 3,000 characters). It posts nothing that holds the job token or a token-shaped string (the same scan the cert review's `post` had), nothing on a branch matching `flaky-quiet-branches`, nothing on a pull request whose run also has a failure or a shard that wasn't rerun, nothing for a test the pull request changes, and nothing at all when a run would open more than 5 issues (`flaky: <n> flips in one run, not filing (infrastructure?)`). In the merge queue, each open issue whose test passed first time gets `<!-- clean: <n> since <date> -->` in its body, which a flip clears; at `flaky-close-after` it is closed with `no flip in <n> clean merge-group runs since <date>; a new flip reopens it`. It needs `node --test` through the shared harness: `$TEST` must honour `SLICC_TEST_FILES` and write node's JUnit report with `file=`.
|
|
86
|
+
|
|
84
87
|
**Reviewer** runs twice, once with [claude-code-action](https://github.com/anthropics/claude-code-action) and once with [codex-action](https://github.com/openai/codex-action), on the same prompt, whether the tests passed or not. Both run on Amazon Bedrock with the org secret `AWS_BEARER_TOKEN_BEDROCK`, in the region of the org variable `CERT_AWS_REGION` (`us-west-2` without it). Claude uses the model in `CERT_BEDROCK_MODEL` (`global.anthropic.claude-opus-5-5` without it), as the cert reviews do. Codex uses its built-in `amazon-bedrock-runtime` provider (codex-action waits for its OpenAI proxy's `<run id>.json` in `codex-home` whenever it has a prompt, so the job writes a placeholder one) and the model in `CODEX_BEDROCK_MODEL` (`global.openai.gpt-6.1-sol` without it). Models that Bedrock serves only through inference profiles, as Sol 6.1 is, need the runtime provider and the profile's `global.` id; the `amazon-bedrock` provider's endpoint doesn't list them. The job token can only read. Each reviewer gets:
|
|
85
88
|
|
|
86
89
|
- the pull request's head, with full history, as the working directory, and its base in `$RUNNER_TEMP/base`, each after `npm ci` (claude-code-action needs the working directory to be a checkout, and a base nested inside it would break the head's Biome config). Everything else the reviewers get or write (the prompt, context, integration artifacts, `browsers.json`, findings and screenshots) is in `$RUNNER_TEMP/review`, outside the checkout, so a reviewer's `npm run lint` sees only the repository;
|
|
@@ -149,6 +152,10 @@ The commands in `lint`, `test`, `deploy`, `review-browser` and `after-release` r
|
|
|
149
152
|
| `review-renovate` | none | globs of Renovate group slugs whose pull requests get a review |
|
|
150
153
|
| `node-options` | none | node flags added to the test step's `NODE_OPTIONS`, such as `--max-old-space-size=8192` |
|
|
151
154
|
| `require-tests` | `true` | `integration` fails when no test ran |
|
|
155
|
+
| `flaky-retry` | `0` | the most failing files a shard reruns once, [flaky tests](#pipeline); `0` reruns and reports nothing |
|
|
156
|
+
| `strict-tests` | `**/*guard*.test.*` and `**/*security*.test.*` | newline-separated globs of test files whose flips stay red; a repo lists its own guard rows too |
|
|
157
|
+
| `flaky-quiet-branches` | `probe/**` | newline-separated globs of branches whose flips are never filed or commented |
|
|
158
|
+
| `flaky-close-after` | `20` | clean merge-queue runs before a `flaky-test` issue closes |
|
|
152
159
|
| `release-environment` | none | the GitHub environment the release job runs in |
|
|
153
160
|
| `after-release` | none | a command run after semantic-release, with `RELEASE_VERSION` |
|
|
154
161
|
| `release-secrets` | none | newline- or space-separated secret names (any case) that semantic-release and `after-release` get |
|
|
@@ -0,0 +1,974 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import {
|
|
5
|
+
appendFileSync,
|
|
6
|
+
cpSync,
|
|
7
|
+
existsSync,
|
|
8
|
+
globSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
readdirSync,
|
|
11
|
+
readFileSync,
|
|
12
|
+
realpathSync,
|
|
13
|
+
rmSync,
|
|
14
|
+
statSync,
|
|
15
|
+
writeFileSync,
|
|
16
|
+
} from 'node:fs';
|
|
17
|
+
import { basename, dirname, isAbsolute, join, matchesGlob, relative, sep } from 'node:path';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
import { inflateRawSync } from 'node:zlib';
|
|
20
|
+
|
|
21
|
+
export const LABEL = 'flaky-test';
|
|
22
|
+
const LABELS = [
|
|
23
|
+
[LABEL, 'fbca04', 'A test that failed, then passed on a retry'],
|
|
24
|
+
['new', 'c2e0c6', 'A flaky test seen on one commit so far'],
|
|
25
|
+
['guard', 'b60205', 'A strict (guard or security) test that flipped'],
|
|
26
|
+
];
|
|
27
|
+
const CAP = 5;
|
|
28
|
+
const ERROR = 3000;
|
|
29
|
+
const DAY = 86400000;
|
|
30
|
+
const NONE = /\/slicc-shared-web\/unit\/none\.mjs$/;
|
|
31
|
+
const ENTITIES = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
|
|
32
|
+
const TAG = /<(\/?)(testsuite|testcase|failure|error|skipped)\b((?:[^>"]|"[^"]*")*)>/g;
|
|
33
|
+
const SECRET_SHAPES = [
|
|
34
|
+
/gh[pousr]_[A-Za-z0-9]{20,}/,
|
|
35
|
+
/github_pat_[A-Za-z0-9_]{20,}/,
|
|
36
|
+
/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,
|
|
37
|
+
/ABSK[A-Za-z0-9+/=]{16,}/,
|
|
38
|
+
/eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,
|
|
39
|
+
/-----BEGIN [A-Z0-9 ]*-----/,
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
export function key({ file, name }) {
|
|
43
|
+
return createHash('sha256').update(`${file}\u0000${name}`).digest('hex').slice(0, 16);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function title({ file, name }) {
|
|
47
|
+
const text = `flaky: ${basename(file)} › ${name}`;
|
|
48
|
+
return text.length > 240 ? `${text.slice(0, 239)}…` : text;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function fence(log) {
|
|
52
|
+
const text = (log || 'no error message').slice(0, ERROR);
|
|
53
|
+
return `~~~~\n${text.replaceAll('~~~~', '~ ~ ~ ~')}\n~~~~`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function carriesSecret(text, secrets = []) {
|
|
57
|
+
const raw = String(text);
|
|
58
|
+
const lower = raw.toLowerCase();
|
|
59
|
+
for (const value of secrets.filter(
|
|
60
|
+
(secret) => typeof secret === 'string' && secret.length >= 8
|
|
61
|
+
)) {
|
|
62
|
+
const bytes = Buffer.from(value);
|
|
63
|
+
const forms = [
|
|
64
|
+
value,
|
|
65
|
+
JSON.stringify(value).slice(1, -1),
|
|
66
|
+
bytes.toString('base64'),
|
|
67
|
+
bytes.toString('base64').replace(/=+$/, ''),
|
|
68
|
+
bytes.toString('base64url'),
|
|
69
|
+
bytes.toString('hex'),
|
|
70
|
+
encodeURIComponent(value),
|
|
71
|
+
value.split('').reverse().join(''),
|
|
72
|
+
];
|
|
73
|
+
if (forms.some((form) => raw.includes(form) || lower.includes(form.toLowerCase()))) {
|
|
74
|
+
return 'a secret value this run holds';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const shape = SECRET_SHAPES.find((pattern) => pattern.test(raw));
|
|
78
|
+
return shape ? `a token-shaped string (${shape.source.slice(0, 16)}…)` : '';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function decode(text) {
|
|
82
|
+
return text.replace(/&(?:#x([0-9a-f]+)|#(\d+)|([a-z]+));/gi, (all, hex, dec, named) => {
|
|
83
|
+
if (hex) return String.fromCodePoint(Number.parseInt(hex, 16));
|
|
84
|
+
if (dec) return String.fromCodePoint(Number(dec));
|
|
85
|
+
return ENTITIES[named] ?? all;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function attribute(attrs, name) {
|
|
90
|
+
const found = new RegExp(`(?:^|\\s)${name}="([^"]*)"`).exec(attrs);
|
|
91
|
+
return found ? decode(found[1]) : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function local(file, root) {
|
|
95
|
+
if (!root || !isAbsolute(file)) return file;
|
|
96
|
+
return relative(root, file).split(sep).join('/');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function statusOf(test) {
|
|
100
|
+
const all = [...test.leaves.values()];
|
|
101
|
+
if (all.includes('fail')) return 'fail';
|
|
102
|
+
return all.includes('pass') ? 'pass' : 'skip';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function settle(tests, leaf, root) {
|
|
106
|
+
if (NONE.test(leaf.file)) return;
|
|
107
|
+
const status = leaf.skipped ? 'skip' : leaf.failed ? 'fail' : 'pass';
|
|
108
|
+
const [name] = leaf.path;
|
|
109
|
+
const file = local(leaf.top, root);
|
|
110
|
+
const id = `${file}\u0000${name}`;
|
|
111
|
+
const test = tests.get(id) ?? { file, name, leaves: new Map(), error: '', failed: 0 };
|
|
112
|
+
const path = leaf.path.join(' › ');
|
|
113
|
+
if (test.leaves.get(path) !== 'fail') test.leaves.set(path, status);
|
|
114
|
+
if (status === 'fail') {
|
|
115
|
+
test.failed += 1;
|
|
116
|
+
test.error ||= leaf.error.slice(0, ERROR);
|
|
117
|
+
}
|
|
118
|
+
tests.set(id, test);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function suite(state, { close, attrs, single }) {
|
|
122
|
+
if (close) state.stack.pop();
|
|
123
|
+
else if (!single) {
|
|
124
|
+
if (state.stack.length === 0) state.top = undefined;
|
|
125
|
+
state.stack.push(attribute(attrs, 'name') ?? '');
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function testcase(state, { close, attrs, single }) {
|
|
130
|
+
if (!close) {
|
|
131
|
+
const file = attribute(attrs, 'file') ?? '';
|
|
132
|
+
if (state.stack.length === 0 || state.top === undefined) state.top = file;
|
|
133
|
+
state.leaf = {
|
|
134
|
+
path: [...state.stack, attribute(attrs, 'name') ?? ''],
|
|
135
|
+
file,
|
|
136
|
+
top: state.top,
|
|
137
|
+
error: '',
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
if (close || single) {
|
|
141
|
+
if (state.leaf) settle(state.tests, state.leaf, state.root);
|
|
142
|
+
state.leaf = undefined;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function parse(xml, root, tests = new Map()) {
|
|
147
|
+
const state = { stack: [], leaf: undefined, text: undefined, top: undefined, tests, root };
|
|
148
|
+
for (const match of xml.matchAll(TAG)) {
|
|
149
|
+
const [whole, close, tag, rest] = match;
|
|
150
|
+
const single = rest.endsWith('/');
|
|
151
|
+
const part = {
|
|
152
|
+
whole,
|
|
153
|
+
close,
|
|
154
|
+
tag,
|
|
155
|
+
attrs: single ? rest.slice(0, -1) : rest,
|
|
156
|
+
single,
|
|
157
|
+
at: match.index,
|
|
158
|
+
};
|
|
159
|
+
if (tag === 'testsuite') suite(state, part);
|
|
160
|
+
else if (tag === 'testcase') testcase(state, part);
|
|
161
|
+
else if (state.leaf) inside(state, xml, part);
|
|
162
|
+
}
|
|
163
|
+
return tests;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function inside(state, xml, { whole, close, tag, attrs, single, at }) {
|
|
167
|
+
if (tag === 'skipped') {
|
|
168
|
+
if (!close) state.leaf.skipped = true;
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!close) {
|
|
172
|
+
state.leaf.failed = true;
|
|
173
|
+
const message = attribute(attrs, 'message') ?? '';
|
|
174
|
+
if (single) state.leaf.error ||= message;
|
|
175
|
+
else state.text = { from: at + whole.length, message };
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (state.text) {
|
|
179
|
+
state.leaf.error ||= decode(xml.slice(state.text.from, at)).trim() || state.text.message;
|
|
180
|
+
state.text = undefined;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function load(files, root) {
|
|
185
|
+
const tests = new Map();
|
|
186
|
+
for (const file of files) parse(readFileSync(file, 'utf8'), root, tests);
|
|
187
|
+
return tests;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function firstReports(dir, shard) {
|
|
191
|
+
const own = new RegExp(`^${shard.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(-\\d+)?\\.xml$`);
|
|
192
|
+
return (existsSync(dir) ? readdirSync(dir) : [])
|
|
193
|
+
.filter((name) => own.test(name))
|
|
194
|
+
.sort()
|
|
195
|
+
.map((name) => join(dir, name));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function globs(text) {
|
|
199
|
+
return (text ?? '')
|
|
200
|
+
.split('\n')
|
|
201
|
+
.map((line) => line.trim())
|
|
202
|
+
.filter(Boolean);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function lint(text) {
|
|
206
|
+
try {
|
|
207
|
+
const parsed = JSON.parse(text || 'null');
|
|
208
|
+
return { known: parsed?.known ?? {}, changed: parsed?.changed ?? [] };
|
|
209
|
+
} catch {
|
|
210
|
+
return { known: {}, changed: [] };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function isKnown(entry, sha) {
|
|
215
|
+
return (
|
|
216
|
+
Boolean(entry) && (entry.commit === null || (Boolean(entry.commit) && entry.commit !== sha))
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function listed(text) {
|
|
221
|
+
try {
|
|
222
|
+
const parsed = JSON.parse(text || '[]');
|
|
223
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
224
|
+
} catch {
|
|
225
|
+
return [];
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function category(test, { known, strict, changed, sha, tests }) {
|
|
230
|
+
if (!tests.includes(test.file)) return 'unattributed';
|
|
231
|
+
if (strict.some((glob) => matchesGlob(test.file, glob))) return 'strict';
|
|
232
|
+
if (changed.includes(test.file)) return 'changed';
|
|
233
|
+
return isKnown(known[key(test)], sha) ? 'known' : 'new';
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function problem(rerun, retry) {
|
|
237
|
+
if (!rerun) return 'not rerun';
|
|
238
|
+
if (rerun.timedOut) return 'the rerun timed out';
|
|
239
|
+
if (!retry) return 'the rerun wrote no JUnit report';
|
|
240
|
+
const ran = [...retry.values()].some(
|
|
241
|
+
(test) => statusOf(test) === 'fail' || (statusOf(test) === 'pass' && test.name !== test.file)
|
|
242
|
+
);
|
|
243
|
+
return ran ? '' : 'the rerun ran no test';
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function recovered(before, after) {
|
|
247
|
+
if (!after || statusOf(after) === 'fail') return false;
|
|
248
|
+
return [...before.leaves].every(
|
|
249
|
+
([path, status]) => status !== 'fail' || after.leaves.get(path) === 'pass'
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function row(before, after, broken, rules) {
|
|
254
|
+
const test = before ?? after;
|
|
255
|
+
const base = {
|
|
256
|
+
file: test.file,
|
|
257
|
+
name: test.name,
|
|
258
|
+
key: key(test),
|
|
259
|
+
first: before ? statusOf(before) : 'missing',
|
|
260
|
+
retry: after ? statusOf(after) : 'missing',
|
|
261
|
+
error: (before?.error || after?.error || '').slice(0, ERROR),
|
|
262
|
+
back: false,
|
|
263
|
+
excused: false,
|
|
264
|
+
};
|
|
265
|
+
if (base.first === 'fail') {
|
|
266
|
+
if (broken || !recovered(before, after)) return { ...base, kind: 'failure' };
|
|
267
|
+
const kind = category(test, rules);
|
|
268
|
+
return { ...base, kind, excused: kind === 'known', issue: rules.known[base.key]?.issue };
|
|
269
|
+
}
|
|
270
|
+
if (base.retry !== 'fail') return { ...base, kind: 'pass' };
|
|
271
|
+
if (base.first !== 'pass') return { ...base, kind: 'failure' };
|
|
272
|
+
return { ...base, kind: category(test, rules), back: true };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function judge({ first, retry, rerun, ...rules }) {
|
|
276
|
+
const broken = problem(rerun, retry);
|
|
277
|
+
const files = new Set(rerun?.files ?? []);
|
|
278
|
+
const ids = new Set([...first.keys(), ...(retry?.keys() ?? [])]);
|
|
279
|
+
const rows = [];
|
|
280
|
+
for (const id of ids) {
|
|
281
|
+
const before = first.get(id);
|
|
282
|
+
const failedFirst = before && statusOf(before) === 'fail';
|
|
283
|
+
const after = failedFirst || !broken ? retry?.get(id) : undefined;
|
|
284
|
+
const test = before ?? after;
|
|
285
|
+
if (!test || (!failedFirst && !files.has(test.file))) continue;
|
|
286
|
+
rows.push(row(before, after, broken, rules));
|
|
287
|
+
}
|
|
288
|
+
const failing = rows.filter((entry) => entry.first === 'fail');
|
|
289
|
+
const ok =
|
|
290
|
+
!broken && failing.length > 0 && rows.every((entry) => entry.kind === 'pass' || entry.excused);
|
|
291
|
+
return { rows, ok, broken };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function describe(entry, reason) {
|
|
295
|
+
if (entry.kind === 'failure') return reason ? `failed, not rerun: ${reason}` : 'failed twice';
|
|
296
|
+
if (entry.manual) {
|
|
297
|
+
const note =
|
|
298
|
+
{ strict: ' (a strict row)', changed: ' (the PR changes this test)' }[entry.kind] ?? '';
|
|
299
|
+
return `failed on attempt ${entry.from}, then passed on attempt ${entry.attempt}${note}`;
|
|
300
|
+
}
|
|
301
|
+
if (entry.back) return 'passed, then failed on retry';
|
|
302
|
+
if (entry.kind === 'known')
|
|
303
|
+
return `known flake${entry.issue ? ` #${entry.issue}` : ''}, passed on retry`;
|
|
304
|
+
if (entry.kind === 'strict')
|
|
305
|
+
return 'strict row flipped: failed, then passed on retry, so it stays red';
|
|
306
|
+
if (entry.kind === 'changed')
|
|
307
|
+
return "this PR's test is nondeterministic: it flipped, and the PR changes its file";
|
|
308
|
+
return 'first flip: failed, then passed on retry, so it stays red until it flips on another commit too';
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function bounded(command, env, ms) {
|
|
312
|
+
return new Promise((resolve) => {
|
|
313
|
+
const child = spawn('bash', ['-eo', 'pipefail', '-c', command], {
|
|
314
|
+
env,
|
|
315
|
+
stdio: 'inherit',
|
|
316
|
+
detached: true,
|
|
317
|
+
});
|
|
318
|
+
const kill = (signal) => {
|
|
319
|
+
try {
|
|
320
|
+
process.kill(-child.pid, signal);
|
|
321
|
+
} catch {}
|
|
322
|
+
};
|
|
323
|
+
let late = false;
|
|
324
|
+
const timer = setTimeout(() => {
|
|
325
|
+
late = true;
|
|
326
|
+
kill('SIGKILL');
|
|
327
|
+
}, ms);
|
|
328
|
+
child.on('close', (status) => {
|
|
329
|
+
clearTimeout(timer);
|
|
330
|
+
kill('SIGKILL');
|
|
331
|
+
resolve({ status: status ?? 1, late });
|
|
332
|
+
});
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function move(from, to) {
|
|
337
|
+
if (!existsSync(from)) return;
|
|
338
|
+
cpSync(from, to, { recursive: true });
|
|
339
|
+
rmSync(from, { recursive: true, force: true });
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function rerunFiles(files, ms, env, shard) {
|
|
343
|
+
const scratch = join(env.RUNNER_TEMP, 'slicc-flaky', 'retry');
|
|
344
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
345
|
+
mkdirSync(scratch, { recursive: true });
|
|
346
|
+
const junit = join(scratch, `${shard}.xml`);
|
|
347
|
+
const options = (env.NODE_OPTIONS ?? '').replace(
|
|
348
|
+
`--test-reporter-destination=${env.SLICC_TEST_JUNIT}`,
|
|
349
|
+
`--test-reporter-destination=${junit}`
|
|
350
|
+
);
|
|
351
|
+
const stash = join(scratch, 'first');
|
|
352
|
+
move('artifacts', join(stash, 'artifacts'));
|
|
353
|
+
move('coverage', join(stash, 'coverage'));
|
|
354
|
+
const started = Date.now();
|
|
355
|
+
const { status, late } = await bounded(
|
|
356
|
+
env.TEST,
|
|
357
|
+
{
|
|
358
|
+
...env,
|
|
359
|
+
NODE_OPTIONS: options,
|
|
360
|
+
SLICC_TEST_FILES: files.join('\n'),
|
|
361
|
+
SLICC_TEST_SHARD: 'retry',
|
|
362
|
+
SLICC_TEST_JUNIT: junit,
|
|
363
|
+
SLICC_TEST_RETRY: '1',
|
|
364
|
+
},
|
|
365
|
+
ms
|
|
366
|
+
);
|
|
367
|
+
const took = Date.now() - started;
|
|
368
|
+
move('artifacts', join(stash, 'artifacts', 'retry'));
|
|
369
|
+
rmSync('coverage', { recursive: true, force: true });
|
|
370
|
+
move(join(stash, 'artifacts'), 'artifacts');
|
|
371
|
+
move(join(stash, 'coverage'), 'coverage');
|
|
372
|
+
const reports = readdirSync(scratch).filter((name) => name.endsWith('.xml'));
|
|
373
|
+
const inner = reports.map((name) =>
|
|
374
|
+
readFileSync(join(scratch, name), 'utf8')
|
|
375
|
+
.replace(/<\?xml[^>]*\?>/, '')
|
|
376
|
+
.replace(/<\/?testsuites>/g, '')
|
|
377
|
+
.trim()
|
|
378
|
+
);
|
|
379
|
+
if (reports.length > 0) {
|
|
380
|
+
writeFileSync(
|
|
381
|
+
join('junit', `${shard}.retry.xml`),
|
|
382
|
+
`<?xml version="1.0" encoding="utf-8"?>\n<testsuites>\n${inner.join('\n')}\n</testsuites>\n`
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
return { files, ms: took, exit: status, timedOut: late };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function context(env) {
|
|
389
|
+
return {
|
|
390
|
+
shard: env.SHARD,
|
|
391
|
+
attempt: Number(env.GITHUB_RUN_ATTEMPT || 1),
|
|
392
|
+
sha: env.SHA || env.GITHUB_SHA || '',
|
|
393
|
+
runner: env.RUNNER_NAME || '',
|
|
394
|
+
root: process.cwd(),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function rules(env, tests) {
|
|
399
|
+
const { known, changed } = lint(env.FLAKY);
|
|
400
|
+
return {
|
|
401
|
+
known,
|
|
402
|
+
changed,
|
|
403
|
+
strict: globs(env.STRICT),
|
|
404
|
+
sha: env.SHA || env.GITHUB_SHA || '',
|
|
405
|
+
tests,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function regular(file, root) {
|
|
410
|
+
try {
|
|
411
|
+
return statSync(join(root, file)).isFile();
|
|
412
|
+
} catch {
|
|
413
|
+
return false;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function skipReason({
|
|
418
|
+
reports,
|
|
419
|
+
failing,
|
|
420
|
+
files,
|
|
421
|
+
tests,
|
|
422
|
+
root,
|
|
423
|
+
most,
|
|
424
|
+
elapsed,
|
|
425
|
+
limit,
|
|
426
|
+
budget,
|
|
427
|
+
options,
|
|
428
|
+
}) {
|
|
429
|
+
if (reports.length === 0) return 'no JUnit report';
|
|
430
|
+
if (failing.length === 0) return 'no failing test in the JUnit report';
|
|
431
|
+
const nameless = files.find((file) => !tests.includes(file) || !regular(file, root));
|
|
432
|
+
if (nameless !== undefined) return `a failing test names no test file: ${nameless}`;
|
|
433
|
+
if (files.length > most) return `${files.length} files failed, more than flaky-retry (${most})`;
|
|
434
|
+
if (elapsed + limit > budget) return 'past the time budget';
|
|
435
|
+
if (!options) return 'NODE_OPTIONS names no JUnit destination';
|
|
436
|
+
return '';
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function announce(entries, reason) {
|
|
440
|
+
for (const entry of entries) {
|
|
441
|
+
const line = `${entry.file} › ${entry.name}: ${describe(entry, reason)}`;
|
|
442
|
+
if (entry.kind === 'pass') continue;
|
|
443
|
+
if (entry.excused) console.log(`::notice title=Flaky::${line}`);
|
|
444
|
+
else console.log(`::error title=Flaky::${line}`);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export async function retry(env = process.env) {
|
|
449
|
+
const started = Date.now();
|
|
450
|
+
const first = spawnSync('bash', ['-eo', 'pipefail', '-c', env.TEST], { env, stdio: 'inherit' });
|
|
451
|
+
const status = first.status ?? 1;
|
|
452
|
+
const record = { ...context(env), rerun: null, skipped: null, ok: status === 0, rows: [] };
|
|
453
|
+
const shard = record.shard;
|
|
454
|
+
mkdirSync('junit', { recursive: true });
|
|
455
|
+
const save = () =>
|
|
456
|
+
writeFileSync(join('junit', `${shard}.flaky.json`), `${JSON.stringify(record, null, 2)}\n`);
|
|
457
|
+
if (status === 0) {
|
|
458
|
+
save();
|
|
459
|
+
return 0;
|
|
460
|
+
}
|
|
461
|
+
const reports = firstReports('junit', shard);
|
|
462
|
+
const tests = load(reports, record.root);
|
|
463
|
+
const failing = [...tests.values()].filter((test) => statusOf(test) === 'fail');
|
|
464
|
+
const files = [...new Set(failing.map((test) => test.file))];
|
|
465
|
+
const budget = Number(env.TIMEOUT_MINUTES) * 60000;
|
|
466
|
+
const limit = Math.min(15 * 60000, budget / 4);
|
|
467
|
+
const options =
|
|
468
|
+
Boolean(env.SLICC_TEST_JUNIT) &&
|
|
469
|
+
(env.NODE_OPTIONS ?? '').includes(`--test-reporter-destination=${env.SLICC_TEST_JUNIT}`);
|
|
470
|
+
const most = Number(env.FLAKY_RETRY);
|
|
471
|
+
const given = rules(env, globs(env.SLICC_TEST_ALL));
|
|
472
|
+
const skipped = skipReason({
|
|
473
|
+
reports,
|
|
474
|
+
failing,
|
|
475
|
+
files,
|
|
476
|
+
tests: given.tests,
|
|
477
|
+
root: record.root,
|
|
478
|
+
most,
|
|
479
|
+
elapsed: Date.now() - started,
|
|
480
|
+
limit,
|
|
481
|
+
budget,
|
|
482
|
+
options,
|
|
483
|
+
});
|
|
484
|
+
if (skipped) {
|
|
485
|
+
record.skipped = skipped;
|
|
486
|
+
record.rows = judge({ first: tests, retry: undefined, rerun: null, ...given }).rows;
|
|
487
|
+
console.log(`flaky: shard ${shard}: not rerun: ${skipped}`);
|
|
488
|
+
} else {
|
|
489
|
+
console.log(
|
|
490
|
+
`flaky: shard ${shard}: rerunning ${files.join(' ')} (at most ${Math.round(limit / 1000)} s)`
|
|
491
|
+
);
|
|
492
|
+
record.rerun = await rerunFiles(files, limit, env, shard);
|
|
493
|
+
const retried = join('junit', `${shard}.retry.xml`);
|
|
494
|
+
const after = existsSync(retried) ? load([retried], record.root) : undefined;
|
|
495
|
+
const verdict = judge({ first: tests, retry: after, rerun: record.rerun, ...given });
|
|
496
|
+
record.rows = verdict.rows;
|
|
497
|
+
record.ok = verdict.ok;
|
|
498
|
+
if (verdict.broken) console.log(`flaky: shard ${shard}: ${verdict.broken}`);
|
|
499
|
+
}
|
|
500
|
+
announce(record.rows, skipped);
|
|
501
|
+
save();
|
|
502
|
+
const failures = record.rows.filter((entry) => entry.kind === 'failure');
|
|
503
|
+
if (failures.length > 0) {
|
|
504
|
+
const dir = join(env.RUNNER_TEMP, 'slicc-flaky', 'failed');
|
|
505
|
+
mkdirSync(dir, { recursive: true });
|
|
506
|
+
const { rows, rerun, ok, ...rest } = record;
|
|
507
|
+
const failed = failures.map(({ file, name, key: id, error }) => ({
|
|
508
|
+
file,
|
|
509
|
+
name,
|
|
510
|
+
key: id,
|
|
511
|
+
error,
|
|
512
|
+
}));
|
|
513
|
+
writeFileSync(
|
|
514
|
+
join(dir, `failed-${shard}-${record.attempt}.json`),
|
|
515
|
+
`${JSON.stringify({ ...rest, failed }, null, 2)}\n`
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
const passed = record.rows.filter((entry) => entry.excused);
|
|
519
|
+
if (record.ok) {
|
|
520
|
+
const issues = passed.map((entry) => (entry.issue ? `#${entry.issue}` : entry.key)).join(', ');
|
|
521
|
+
console.log(
|
|
522
|
+
`flaky: shard ${shard}: PASS, ${passed.length} known flake${passed.length === 1 ? '' : 's'} passed on retry (${issues})`
|
|
523
|
+
);
|
|
524
|
+
return 0;
|
|
525
|
+
}
|
|
526
|
+
console.log(`flaky: shard ${shard}: FAIL`);
|
|
527
|
+
return skipped ? status : 1;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
export function verdict(env = process.env, dir = 'junit') {
|
|
531
|
+
const given = rules(env, listed(env.FILES));
|
|
532
|
+
const covered = new Set();
|
|
533
|
+
const passed = [];
|
|
534
|
+
let failed = 0;
|
|
535
|
+
for (const json of globSync(`${dir}/**/*.flaky.json`).sort()) {
|
|
536
|
+
const record = JSON.parse(readFileSync(json, 'utf8'));
|
|
537
|
+
const shard = basename(json, '.flaky.json');
|
|
538
|
+
const here = dirname(json);
|
|
539
|
+
const reports = firstReports(here, shard);
|
|
540
|
+
for (const report of reports) covered.add(report);
|
|
541
|
+
const first = load(reports, record.root);
|
|
542
|
+
const retried = join(here, `${shard}.retry.xml`);
|
|
543
|
+
const after = existsSync(retried) ? load([retried], record.root) : undefined;
|
|
544
|
+
const result = judge({ first, retry: after, rerun: record.rerun, ...given });
|
|
545
|
+
const excused = new Set(
|
|
546
|
+
result.ok ? result.rows.filter((entry) => entry.excused).map((entry) => entry.key) : []
|
|
547
|
+
);
|
|
548
|
+
for (const test of first.values()) if (!excused.has(key(test))) failed += test.failed;
|
|
549
|
+
passed.push(...result.rows.filter((entry) => excused.has(entry.key)));
|
|
550
|
+
}
|
|
551
|
+
for (const report of globSync(`${dir}/**/*.xml`).sort()) {
|
|
552
|
+
if (covered.has(report) || report.endsWith('.retry.xml')) continue;
|
|
553
|
+
for (const test of load([report]).values()) failed += test.failed;
|
|
554
|
+
}
|
|
555
|
+
const known = passed.map((entry) => (entry.issue ? `#${entry.issue}` : entry.key));
|
|
556
|
+
const out = join(env.RUNNER_TEMP, 'slicc-flaky');
|
|
557
|
+
mkdirSync(out, { recursive: true });
|
|
558
|
+
writeFileSync(join(out, 'verdict.json'), `${JSON.stringify({ failed, known })}\n`);
|
|
559
|
+
console.log(
|
|
560
|
+
`flaky: verdict: ${failed} failing tests left, ${known.length} known flakes passed on retry${known.length ? ` (${known.join(', ')})` : ''}`
|
|
561
|
+
);
|
|
562
|
+
return 0;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function runUrl(ctx, attempt) {
|
|
566
|
+
return `${ctx.server}/${ctx.repo}/actions/runs/${ctx.run}/attempts/${attempt}`;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function lead(flip) {
|
|
570
|
+
if (flip.manual) return `Attempt ${flip.from} failed with:`;
|
|
571
|
+
return flip.back ? 'The retry failed with:' : 'The first run failed with:';
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
export function occurrence(flip, ctx) {
|
|
575
|
+
return [
|
|
576
|
+
`- Run: ${runUrl(ctx, flip.attempt)}`,
|
|
577
|
+
`- Event: ${ctx.event}${ctx.pr ? `, PR #${ctx.pr}` : ''}, shard ${flip.shard}`,
|
|
578
|
+
`- Runner: ${flip.runner || 'unknown'}`,
|
|
579
|
+
`- Commit: ${flip.sha || 'unknown'}`,
|
|
580
|
+
'',
|
|
581
|
+
lead(flip),
|
|
582
|
+
'',
|
|
583
|
+
fence(flip.error),
|
|
584
|
+
].join('\n');
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function sentence(flip) {
|
|
588
|
+
const test = `\`${flip.file}\` › ${flip.name}`;
|
|
589
|
+
if (flip.manual) {
|
|
590
|
+
return `${test} failed on attempt ${flip.from} of a run, then passed on attempt ${flip.attempt} of it, on the same commit.`;
|
|
591
|
+
}
|
|
592
|
+
if (flip.back)
|
|
593
|
+
return `${test} passed, then failed when its shard ran the file again on the same commit.`;
|
|
594
|
+
return `${test} failed, then passed when its shard ran the file again on the same commit.`;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export function body(flip, ctx) {
|
|
598
|
+
const marker = `Every later flip of this test adds a comment here. Key: \`${key(flip)}\``;
|
|
599
|
+
if (flip.strict) {
|
|
600
|
+
return [
|
|
601
|
+
`\`${flip.file}\` › ${flip.name} flipped. It is a strict row, so the details stay in the run.`,
|
|
602
|
+
'',
|
|
603
|
+
`- Run: ${runUrl(ctx, flip.attempt)}`,
|
|
604
|
+
`- Commit: ${flip.sha || 'unknown'}`,
|
|
605
|
+
'',
|
|
606
|
+
marker,
|
|
607
|
+
].join('\n');
|
|
608
|
+
}
|
|
609
|
+
return [sentence(flip), '', occurrence(flip, ctx), '', marker].join('\n');
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
export function comment(flip, ctx) {
|
|
613
|
+
if (flip.strict)
|
|
614
|
+
return `\`${flip.file}\` › ${flip.name} flipped again: ${runUrl(ctx, flip.attempt)}`;
|
|
615
|
+
return occurrence(flip, ctx);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
export function clean(text) {
|
|
619
|
+
const found = /<!-- clean: (\d+) since (\S+) -->/.exec(text ?? '');
|
|
620
|
+
return found ? { count: Number(found[1]), since: found[2] } : { count: 0, since: undefined };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
export function withClean(text, count, since) {
|
|
624
|
+
const stripped = (text ?? '').replace(/\n*<!-- clean: \d+ since \S+ -->/, '');
|
|
625
|
+
return count > 0 ? `${stripped}\n\n<!-- clean: ${count} since ${since} -->` : stripped;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export function unzip(zip) {
|
|
629
|
+
const entries = [];
|
|
630
|
+
const end = zip.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
|
|
631
|
+
for (let at = zip.readUInt32LE(end + 16), left = zip.readUInt16LE(end + 10); left > 0; left--) {
|
|
632
|
+
const size = zip.readUInt32LE(at + 20);
|
|
633
|
+
const named = zip.readUInt16LE(at + 28);
|
|
634
|
+
const name = zip.toString('utf8', at + 46, at + 46 + named);
|
|
635
|
+
const start = zip.readUInt32LE(at + 42);
|
|
636
|
+
const from = start + 30 + zip.readUInt16LE(start + 26) + zip.readUInt16LE(start + 28);
|
|
637
|
+
const data = zip.subarray(from, from + size);
|
|
638
|
+
entries.push([name, String(zip.readUInt16LE(at + 10) === 8 ? inflateRawSync(data) : data)]);
|
|
639
|
+
at += 46 + named + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32);
|
|
640
|
+
}
|
|
641
|
+
return entries;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function client(ctx) {
|
|
645
|
+
return async (method, path, payload) => {
|
|
646
|
+
const response = await fetch(`${ctx.api}/${path}`, {
|
|
647
|
+
method,
|
|
648
|
+
headers: {
|
|
649
|
+
authorization: `Bearer ${ctx.token}`,
|
|
650
|
+
accept: 'application/vnd.github+json',
|
|
651
|
+
'x-github-api-version': '2022-11-28',
|
|
652
|
+
...(payload ? { 'content-type': 'application/json' } : {}),
|
|
653
|
+
},
|
|
654
|
+
body: payload ? JSON.stringify(payload) : undefined,
|
|
655
|
+
signal: AbortSignal.timeout(60000),
|
|
656
|
+
});
|
|
657
|
+
if (!response.ok) {
|
|
658
|
+
const error = new Error(
|
|
659
|
+
`${method} ${path}: ${response.status} ${(await response.text()).slice(0, 200)}`
|
|
660
|
+
);
|
|
661
|
+
error.status = response.status;
|
|
662
|
+
throw error;
|
|
663
|
+
}
|
|
664
|
+
if (response.status === 204) return null;
|
|
665
|
+
return path.endsWith('/zip') ? Buffer.from(await response.arrayBuffer()) : response.json();
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async function pages(call, path) {
|
|
670
|
+
const found = [];
|
|
671
|
+
for (let page = 1; page <= 10; page++) {
|
|
672
|
+
const batch = await call(
|
|
673
|
+
'GET',
|
|
674
|
+
`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`
|
|
675
|
+
);
|
|
676
|
+
const items = Array.isArray(batch) ? batch : (batch.artifacts ?? []);
|
|
677
|
+
found.push(...items);
|
|
678
|
+
if (items.length < 100) break;
|
|
679
|
+
}
|
|
680
|
+
return found;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function shards(dir) {
|
|
684
|
+
return globSync(`${dir}/**/*.flaky.json`)
|
|
685
|
+
.sort()
|
|
686
|
+
.map((json) => {
|
|
687
|
+
const record = JSON.parse(readFileSync(json, 'utf8'));
|
|
688
|
+
const first = load(firstReports(dirname(json), basename(json, '.flaky.json')), record.root);
|
|
689
|
+
return { record, first };
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async function failedBefore(call, ctx) {
|
|
694
|
+
const artifacts = await pages(call, `repos/${ctx.repo}/actions/runs/${ctx.run}/artifacts`);
|
|
695
|
+
const failed = new Map();
|
|
696
|
+
for (const artifact of artifacts) {
|
|
697
|
+
const attempt = Number(/^failed-.+-(\d+)$/.exec(artifact.name)?.[1]);
|
|
698
|
+
if (artifact.expired || !(attempt < ctx.attempt)) continue;
|
|
699
|
+
const zip = await call('GET', `repos/${ctx.repo}/actions/artifacts/${artifact.id}/zip`);
|
|
700
|
+
for (const [, text] of unzip(zip)) {
|
|
701
|
+
const list = JSON.parse(text);
|
|
702
|
+
for (const test of list.failed) {
|
|
703
|
+
if ((failed.get(test.key)?.from ?? 0) < list.attempt)
|
|
704
|
+
failed.set(test.key, { ...test, from: list.attempt });
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return failed;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async function earlier(call, ctx, found, given) {
|
|
712
|
+
if (ctx.attempt <= 1) return [];
|
|
713
|
+
const failed = await failedBefore(call, ctx);
|
|
714
|
+
const flips = [];
|
|
715
|
+
for (const { record, first } of found) {
|
|
716
|
+
for (const test of first.values()) {
|
|
717
|
+
const before = failed.get(key(test));
|
|
718
|
+
if (!before || statusOf(test) !== 'pass' || record.attempt <= before.from) continue;
|
|
719
|
+
const kind = category(test, given);
|
|
720
|
+
flips.push({
|
|
721
|
+
...before,
|
|
722
|
+
kind: kind === 'strict' || kind === 'changed' ? kind : 'manual',
|
|
723
|
+
manual: true,
|
|
724
|
+
attempt: record.attempt,
|
|
725
|
+
shard: record.shard,
|
|
726
|
+
runner: record.runner,
|
|
727
|
+
sha: record.sha,
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
return flips;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function quietReason(ctx, found) {
|
|
735
|
+
const glob = ctx.quiet.find((pattern) => matchesGlob(ctx.branch, pattern));
|
|
736
|
+
if (glob) return `quiet branch (${glob})`;
|
|
737
|
+
const broken = found.some(
|
|
738
|
+
({ record }) => record.skipped || record.rows.some((entry) => entry.kind === 'failure')
|
|
739
|
+
);
|
|
740
|
+
if (ctx.event === 'pull_request' && broken) return 'the run also has real failures';
|
|
741
|
+
return '';
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
async function labels(call, ctx) {
|
|
745
|
+
for (const [name, color, description] of LABELS) {
|
|
746
|
+
await call('POST', `repos/${ctx.repo}/labels`, { name, color, description }).catch((error) => {
|
|
747
|
+
if (error.status !== 422) throw error;
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function keyOf(issue) {
|
|
753
|
+
return /Key: `([0-9a-f]{16})`/.exec(issue.body ?? '')?.[1];
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async function recur(call, ctx, flip, issue, closed) {
|
|
757
|
+
const text = comment(flip, ctx);
|
|
758
|
+
const secret = carriesSecret(text, [ctx.token]);
|
|
759
|
+
if (secret) return `not posted: it carries ${secret}`;
|
|
760
|
+
const path = `repos/${ctx.repo}/issues/${issue.number}`;
|
|
761
|
+
const names = issue.labels.map((label) => (typeof label === 'string' ? label : label.name));
|
|
762
|
+
const reset = withClean(issue.body, 0);
|
|
763
|
+
if (closed || reset !== (issue.body ?? '')) {
|
|
764
|
+
await call('PATCH', path, { ...(closed ? { state: 'open' } : {}), body: reset });
|
|
765
|
+
}
|
|
766
|
+
await call('POST', `${path}/comments`, { body: text });
|
|
767
|
+
const commit = /^- Commit: (\S+)/m.exec(issue.body ?? '')?.[1];
|
|
768
|
+
if (names.includes('new') && commit && commit !== flip.sha) {
|
|
769
|
+
await call('DELETE', `${path}/labels/new`).catch((error) => {
|
|
770
|
+
if (error.status !== 404) throw error;
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
if (flip.strict && !names.includes('guard'))
|
|
774
|
+
await call('POST', `${path}/labels`, { labels: ['guard'] });
|
|
775
|
+
return `#${issue.number}${closed ? ' (reopened)' : ''}`;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function create(call, ctx, flip) {
|
|
779
|
+
const name = title(flip);
|
|
780
|
+
const text = body(flip, ctx);
|
|
781
|
+
const secret = carriesSecret(`${name}\n${text}`, [ctx.token]);
|
|
782
|
+
if (secret) return `not posted: it carries ${secret}`;
|
|
783
|
+
const created = await call('POST', `repos/${ctx.repo}/issues`, {
|
|
784
|
+
title: name,
|
|
785
|
+
body: text,
|
|
786
|
+
labels: [LABEL, 'new', ...(flip.strict ? ['guard'] : [])],
|
|
787
|
+
});
|
|
788
|
+
return `#${created.number} (new)`;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
async function sweep(call, ctx, open, touched, passing) {
|
|
792
|
+
const today = new Date(ctx.now).toISOString().slice(0, 10);
|
|
793
|
+
for (const issue of open) {
|
|
794
|
+
const id = keyOf(issue);
|
|
795
|
+
if (!id || touched.has(issue.number) || !passing.has(id)) continue;
|
|
796
|
+
const { count, since = today } = clean(issue.body);
|
|
797
|
+
const next = withClean(issue.body, count + 1, since);
|
|
798
|
+
const path = `repos/${ctx.repo}/issues/${issue.number}`;
|
|
799
|
+
if (count + 1 < ctx.closeAfter) {
|
|
800
|
+
await call('PATCH', path, { body: next });
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
await call('POST', `${path}/comments`, {
|
|
804
|
+
body: `no flip in ${ctx.closeAfter} clean merge-group runs since ${since}; a new flip reopens it`,
|
|
805
|
+
});
|
|
806
|
+
await call('PATCH', path, { body: next, state: 'closed', state_reason: 'completed' });
|
|
807
|
+
console.log(`flaky: closed #${issue.number} after ${ctx.closeAfter} clean merge-group runs`);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
async function file(call, ctx, flips, passing) {
|
|
812
|
+
const notes = new Map();
|
|
813
|
+
const listed = (state) =>
|
|
814
|
+
pages(
|
|
815
|
+
call,
|
|
816
|
+
`repos/${ctx.repo}/issues?labels=${LABEL}&state=${state}${state === 'closed' ? `&since=${new Date(ctx.now - 30 * DAY).toISOString()}` : ''}`
|
|
817
|
+
);
|
|
818
|
+
const open = (await listed('open')).filter((issue) => !issue.pull_request);
|
|
819
|
+
const cutoff = ctx.now - 30 * DAY;
|
|
820
|
+
const closed = (await listed('closed')).filter(
|
|
821
|
+
(issue) => !issue.pull_request && Date.parse(issue.closed_at) >= cutoff
|
|
822
|
+
);
|
|
823
|
+
const find = (list, id) => list.find((issue) => keyOf(issue) === id);
|
|
824
|
+
const plan = flips.map((flip) => ({
|
|
825
|
+
flip,
|
|
826
|
+
open: find(open, flip.key),
|
|
827
|
+
closed: find(closed, flip.key),
|
|
828
|
+
}));
|
|
829
|
+
const fresh = plan.filter((entry) => !entry.open && !entry.closed).length;
|
|
830
|
+
if (fresh > CAP) {
|
|
831
|
+
const line = `flaky: ${flips.length} flips in one run, not filing (infrastructure?)`;
|
|
832
|
+
console.log(line);
|
|
833
|
+
for (const flip of flips) notes.set(flip.key, 'not filed: too many flips in one run');
|
|
834
|
+
return { notes, line };
|
|
835
|
+
}
|
|
836
|
+
if (fresh > 0) await labels(call, ctx);
|
|
837
|
+
const touched = new Set();
|
|
838
|
+
for (const entry of plan) {
|
|
839
|
+
const issue = entry.open ?? entry.closed;
|
|
840
|
+
if (issue) touched.add(issue.number);
|
|
841
|
+
const note = issue
|
|
842
|
+
? await recur(call, ctx, entry.flip, issue, !entry.open)
|
|
843
|
+
: await create(call, ctx, entry.flip);
|
|
844
|
+
notes.set(entry.flip.key, note);
|
|
845
|
+
console.log(`flaky: ${title(entry.flip)}: ${note}`);
|
|
846
|
+
}
|
|
847
|
+
if (ctx.event === 'merge_group') await sweep(call, ctx, open, touched, passing);
|
|
848
|
+
return { notes, line: '' };
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function cell(text) {
|
|
852
|
+
return String(text)
|
|
853
|
+
.replace(/\|/g, '\\|')
|
|
854
|
+
.replace(/\s*\n\s*/g, ' ');
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
export function table(entries, notes, lines) {
|
|
858
|
+
const head = ['### Flaky tests', '', ...lines.filter(Boolean).flatMap((line) => [line, ''])];
|
|
859
|
+
if (entries.length === 0) return [...head, 'No flips or failures.', ''].join('\n');
|
|
860
|
+
return [
|
|
861
|
+
...head,
|
|
862
|
+
'| Test | Shard | Outcome | Issue |',
|
|
863
|
+
'|---|---|---|---|',
|
|
864
|
+
...entries.map(
|
|
865
|
+
(entry) =>
|
|
866
|
+
`| ${cell(`\`${entry.file}\` › ${entry.name}`)} | ${cell(entry.shard)} | ${cell(describe(entry, entry.reason))} | ${cell(notes.get(entry.key) ?? '')} |`
|
|
867
|
+
),
|
|
868
|
+
'',
|
|
869
|
+
].join('\n');
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function reportContext(env) {
|
|
873
|
+
const ref = env.GITHUB_REF_NAME ?? '';
|
|
874
|
+
return {
|
|
875
|
+
api: env.GITHUB_API_URL || 'https://api.github.com',
|
|
876
|
+
server: env.GITHUB_SERVER_URL || 'https://github.com',
|
|
877
|
+
repo: env.GITHUB_REPOSITORY,
|
|
878
|
+
run: env.GITHUB_RUN_ID,
|
|
879
|
+
attempt: Number(env.GITHUB_RUN_ATTEMPT || 1),
|
|
880
|
+
event: env.GITHUB_EVENT_NAME,
|
|
881
|
+
branch: env.GITHUB_HEAD_REF || ref,
|
|
882
|
+
pr: env.PR || /\/pr-(\d+)-/.exec(ref)?.[1] || '',
|
|
883
|
+
token: env.GH_TOKEN ?? '',
|
|
884
|
+
quiet: globs(env.QUIET),
|
|
885
|
+
closeAfter: Number(env.CLOSE_AFTER || 20),
|
|
886
|
+
now: Date.now(),
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function named(entry, tests) {
|
|
891
|
+
if (entry.kind === 'failure' || tests.includes(entry.file)) return true;
|
|
892
|
+
console.log(`flaky: ${entry.file} › ${entry.name}: not filed: it names no test file`);
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function collect(found, ctx, tests) {
|
|
897
|
+
const entries = [];
|
|
898
|
+
const passing = new Set();
|
|
899
|
+
for (const { record, first } of found) {
|
|
900
|
+
for (const test of first.values()) if (statusOf(test) === 'pass') passing.add(key(test));
|
|
901
|
+
if (record.attempt !== ctx.attempt) continue;
|
|
902
|
+
for (const entry of record.rows) {
|
|
903
|
+
if (entry.kind === 'pass') continue;
|
|
904
|
+
entries.push({
|
|
905
|
+
...entry,
|
|
906
|
+
shard: record.shard,
|
|
907
|
+
attempt: record.attempt,
|
|
908
|
+
runner: record.runner,
|
|
909
|
+
sha: record.sha,
|
|
910
|
+
reason: record.skipped,
|
|
911
|
+
strict: entry.kind === 'strict',
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
for (const entry of entries) if (entry.kind !== 'failure') passing.delete(entry.key);
|
|
916
|
+
return { entries: entries.filter((entry) => named(entry, tests)), passing };
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
export async function report(env = process.env, dir = 'junit') {
|
|
920
|
+
const ctx = reportContext(env);
|
|
921
|
+
const given = rules(env, listed(env.FILES));
|
|
922
|
+
const found = shards(dir);
|
|
923
|
+
const { entries, passing } = collect(found, ctx, given.tests);
|
|
924
|
+
const call = client(ctx);
|
|
925
|
+
const lines = [];
|
|
926
|
+
let notes = new Map();
|
|
927
|
+
try {
|
|
928
|
+
const seen = new Set(entries.map((entry) => entry.key));
|
|
929
|
+
for (const flip of ctx.token ? await earlier(call, ctx, found, given) : []) {
|
|
930
|
+
if (seen.has(flip.key) || !named(flip, given.tests)) continue;
|
|
931
|
+
seen.add(flip.key);
|
|
932
|
+
entries.push({ ...flip, strict: flip.kind === 'strict' });
|
|
933
|
+
passing.delete(flip.key);
|
|
934
|
+
}
|
|
935
|
+
const flips = entries.filter((entry) => entry.kind !== 'failure');
|
|
936
|
+
const reportable = flips.filter((entry) => entry.kind !== 'changed');
|
|
937
|
+
for (const entry of flips)
|
|
938
|
+
if (entry.kind === 'changed') notes.set(entry.key, 'not filed: the PR changes this test');
|
|
939
|
+
const quiet = quietReason(ctx, found);
|
|
940
|
+
if (!ctx.token) lines.push('flaky: no token, nothing filed');
|
|
941
|
+
else if (quiet) {
|
|
942
|
+
lines.push(`flaky: not filing: ${quiet}`);
|
|
943
|
+
for (const flip of reportable) notes.set(flip.key, `not filed: ${quiet}`);
|
|
944
|
+
} else if (reportable.length > 0 || ctx.event === 'merge_group') {
|
|
945
|
+
const filed = await file(call, ctx, reportable, passing);
|
|
946
|
+
notes = new Map([...notes, ...filed.notes]);
|
|
947
|
+
lines.push(filed.line);
|
|
948
|
+
}
|
|
949
|
+
} catch (error) {
|
|
950
|
+
const line =
|
|
951
|
+
error.status === 403
|
|
952
|
+
? 'flaky: no issues: write, so nothing more was filed'
|
|
953
|
+
: `flaky: GitHub API failed, so nothing more was filed (${error.message.split('\n')[0]})`;
|
|
954
|
+
lines.push(line);
|
|
955
|
+
console.log(`::warning title=Flaky::${line}`);
|
|
956
|
+
}
|
|
957
|
+
const text = table(entries, notes, lines);
|
|
958
|
+
console.log(text);
|
|
959
|
+
if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, text);
|
|
960
|
+
return 0;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
export async function main(argv = process.argv.slice(2), env = process.env) {
|
|
964
|
+
const [mode] = argv;
|
|
965
|
+
if (mode === 'retry') return retry(env);
|
|
966
|
+
if (mode === 'verdict') return verdict(env);
|
|
967
|
+
if (mode === 'report') return report(env);
|
|
968
|
+
console.error('usage: slicc-flaky retry|verdict|report');
|
|
969
|
+
return 2;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
973
|
+
process.exitCode = await main();
|
|
974
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-ecoverse/slicc-shared-web",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.13.1",
|
|
4
4
|
"description": "Shared Renovate, Biome, TypeScript, lefthook and GitHub Actions configuration, plus the CDP integration-test harness, for SLICC's web repos",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
"bin": {
|
|
36
36
|
"slicc-agents-md": "bin/slicc-agents-md.sh",
|
|
37
37
|
"slicc-diff-cover": "bin/slicc-diff-cover.sh",
|
|
38
|
+
"slicc-flaky": "bin/slicc-flaky.mjs",
|
|
38
39
|
"slicc-install-hooks": "bin/slicc-install-hooks.mjs",
|
|
39
40
|
"slicc-lint": "bin/slicc-lint.sh",
|
|
40
41
|
"slicc-lint-comments": "bin/slicc-lint-comments.sh",
|
|
@@ -66,8 +67,8 @@
|
|
|
66
67
|
"release": "semantic-release"
|
|
67
68
|
},
|
|
68
69
|
"devDependencies": {
|
|
69
|
-
"@ai-ecoverse/slicc-browsers": "1.18.
|
|
70
|
-
"@ai-ecoverse/slicc-cdp": "1.41.
|
|
70
|
+
"@ai-ecoverse/slicc-browsers": "1.18.15",
|
|
71
|
+
"@ai-ecoverse/slicc-cdp": "1.41.22",
|
|
71
72
|
"@biomejs/biome": "2.5.15",
|
|
72
73
|
"lefthook": "2.2.2",
|
|
73
74
|
"monocart-coverage-reports": "2.13.2",
|