Compare commits

...

6 Commits

10 changed files with 925 additions and 0 deletions

View File

@@ -184,6 +184,22 @@ jobs:
name: playwright-artifacts-${{ matrix.project }}-${{ matrix.shard }}
path: tests/e2e/artifacts/
retention-days: 5
- name: find-flaky
id: flaky
if: always()
run: |
results=tests/e2e/artifacts/json/results.json
if [ -f "$results" ] && [ "$(jq '.stats.flaky' "$results")" -gt 0 ]; then
echo "found=true" >> "$GITHUB_OUTPUT"
fi
# The weekly flakyci report reads these; the window is 7 days.
- name: upload-flaky
if: always() && steps.flaky.outputs.found == 'true'
uses: actions/upload-artifact@v4
with:
name: e2e-flaky-${{ matrix.project }}-${{ matrix.shard }}
path: tests/e2e/artifacts/json/results.json
retention-days: 8
# Required status check. Fails when e2e was needed but did not pass.
e2e:
# Runs for other labels must not report as e2e, or their pass would hide the real result.

26
.github/workflows/flakyci.yaml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: flakyci
on:
schedule:
- cron: "0 4 * * 1"
workflow_dispatch:
permissions:
actions: read
contents: read
jobs:
flaky-tests:
runs-on: ubuntu-latest
steps:
- name: self-checkout
uses: actions/checkout@v4
- name: node-install
uses: actions/setup-node@v5
with:
node-version: "22"
- name: report
env:
GH_TOKEN: ${{ github.token }}
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_FLAKY_TESTS_WEBHOOK }}
run: node frontend/scripts/flaky-test-report.mjs >> "$GITHUB_STEP_SUMMARY"

View File

@@ -69,6 +69,9 @@ const config: Config.InitialOptions = {
testEnvironment: '<rootDir>/jest.environment.cjs',
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
...(process.env.GITHUB_STEP_SUMMARY
? { reporters: ['default', '<rootDir>/scripts/slow-test-reporter.mjs'] }
: {}),
coverageThreshold: {
global: {
statements: 80,

View File

@@ -0,0 +1,245 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { slackMessages } from '../flaky-test-format.mjs';
import { findFlaky, prOf } from '../flaky-test-report.mjs';
import { rateLimitWait } from '../github-api.mjs';
import {
parseJest,
parsePlaywright,
parsePlaywrightReport,
} from '../test-log-parsers.mjs';
const JEST_LOG = [
'2026-11-10T10:00:00.0000000Z \x1b[1mFAIL\x1b[22m src/a/A.test.tsx (12.1 s)',
'2026-11-10T10:00:00.0000001Z \x1b[1m● A › saves the form\x1b[22m',
'2026-11-10T10:00:00.0000002Z ',
'2026-11-10T10:00:00.0000003Z thrown: "Exceeded timeout of 5000 ms for a test.',
'2026-11-10T10:00:00.0000004Z FAIL src/b/B.test.tsx',
'2026-11-10T10:00:00.0000005Z ● B › shows the error',
'2026-11-10T10:00:00.0000006Z expect(received).toBe(expected)',
'2026-11-10T10:00:00.0000007Z ● Test suite failed to run',
'2026-11-10T10:00:00.0000008Z FAIL src/a/A.test.tsx (12.1 s)',
'2026-11-10T10:00:00.0000009Z ● A › saves the form',
].join('\n');
const STORYBOOK_LOG = [
'2026-11-24T14:52:01.9166715Z \x1b[0m\x1b[7m\x1b[1m\x1b[31m FAIL \x1b[39m\x1b[22m\x1b[27m\x1b[0m \x1b[0m\x1b[7m\x1b[33m browser: chromium \x1b[39m\x1b[27m\x1b[0m \x1b[2msrc/q/stories/\x1b[22m\x1b[1mQ.stories.tsx\x1b[22m (\x1b[0m',
'2026-11-24T14:52:01.9168486Z \x1b[1m\x1b[31m \x1b[1m● \x1b[22m\x1b[1mComponents/Q › WhereClauseSuggestions › play-test\x1b[39m\x1b[22m',
'2026-11-24T14:52:01.9168487Z [error] AssertionError: expected 0 to be greater than 0',
'2026-11-24T14:54:46.4233854Z \x1b[0m\x1b[7m\x1b[1m\x1b[31m FAIL \x1b[39m\x1b[22m\x1b[27m\x1b[0m \x1b[2mfrontend/src/q/stories/\x1b[22m\x1b[1mQ.stories.tsx\x1b[22m (34.267 s)',
'2026-11-24T14:54:46.4236531Z \x1b[1m\x1b[31m \x1b[1m● \x1b[22m\x1b[1mComponents/Q › WhereClauseSuggestions › play-test\x1b[39m\x1b[22m',
].join('\n');
const PLAYWRIGHT_LOG = [
'2026-11-24T17:12:13.5413743Z ✓ 55 [chromium] › tests/s/detail.spec.ts:70:6 › Services, detail › TC-04 tabs render (retry #1) (18.3s)',
'2026-11-24T17:15:01.8981922Z 1) [chromium] › tests/s/list.spec.ts:32:6 › Services, list › TC-02 opens the overview ',
'2026-11-24T17:15:01.8982565Z ',
'2026-11-24T17:15:01.8982929Z Error: \x1b[2mexpect(\x1b[22mreceived).toEqual(expected) // deep equality',
'2026-11-24T17:15:01.9025205Z 2) [chromium] › tests/s/detail.spec.ts:70:6 › Services, detail › TC-04 tabs render ',
'2026-11-24T17:15:01.9025206Z Error: locator.click: Timeout 15000ms exceeded.',
'2026-11-24T17:15:01.9032403Z 1 failed',
'2026-11-24T17:15:01.9032812Z [chromium] › tests/s/list.spec.ts:32:6 › Services, list › TC-02 opens the overview ',
'2026-11-24T17:15:01.9033155Z 1 flaky',
'2026-11-24T17:15:01.9033637Z [chromium] › tests/s/detail.spec.ts:70:6 › Services, detail › TC-04 tabs render ',
'2026-11-24T17:15:01.9034012Z 77 passed (7.4m)',
].join('\n');
const JEST = { name: 'Jest', root: 'frontend/' };
const E2E = { name: 'E2E', root: 'tests/e2e/' };
test('parseJest reads each failing test once with its first error line', () => {
assert.deepEqual(parseJest(JEST_LOG), [
{
file: 'src/a/A.test.tsx',
test: 'A › saves the form',
error: 'thrown: "Exceeded timeout of 5000 ms for a test.',
retried: false,
},
{
file: 'src/b/B.test.tsx',
test: 'B › shows the error',
error: 'expect(received).toBe(expected)',
retried: false,
},
]);
});
test('parseJest reads the storybook runner file under both of its prefixes', () => {
assert.deepEqual(parseJest(STORYBOOK_LOG), [
{
file: 'src/q/stories/Q.stories.tsx',
test: 'Components/Q › WhereClauseSuggestions › play-test',
error: '[error] AssertionError: expected 0 to be greater than 0',
retried: false,
},
]);
});
test('parsePlaywright reads the tests that failed every retry', () => {
assert.deepEqual(parsePlaywright(PLAYWRIGHT_LOG), [
{
file: 'tests/s/list.spec.ts',
test: 'Services, list › TC-02 opens the overview',
error: 'Error: expect(received).toEqual(expected) // deep equality',
retried: false,
},
]);
});
test('parsePlaywrightReport reads the tests that passed on a retry', () => {
const spec = (title, status, error) => ({
title,
file: 's/detail.spec.ts',
tests: [
{
status,
results: [
{ status: 'failed', ...(error && { error: { message: error } }) },
],
},
],
});
const report = {
config: { rootDir: '/home/runner/work/signoz/signoz/tests/e2e/tests' },
suites: [
{
title: 's/detail.spec.ts',
specs: [spec('TC-01 loads', 'expected')],
suites: [
{
title: 'Services, detail',
specs: [
spec(
'TC-04 tabs render',
'flaky',
'Error: \x1b[2mlocator.click\x1b[22m: Timeout\n at detail.spec.ts:70',
),
spec('TC-05 failed every retry', 'unexpected', 'Error: nope'),
],
},
],
},
],
};
assert.deepEqual(parsePlaywrightReport(report), [
{
file: 'tests/s/detail.spec.ts',
test: 'Services, detail › TC-04 tabs render',
error: 'Error: locator.click: Timeout',
retried: true,
},
]);
});
test('findFlaky keeps retry, re-run and multi-PR failures only', () => {
const failure = (test, extra) => ({
suite: JEST,
file: 'src/x.test.tsx',
test,
error: '',
retried: false,
event: 'pull_request',
pr: 1,
passedOnRerun: false,
...extra,
});
const flaky = findFlaky([
failure('one PR only'),
failure('one PR only'),
failure('re-run', { passedOnRerun: true }),
failure('retry', { suite: E2E, retried: true }),
failure('queue once', { event: 'merge_group', pr: 7 }),
failure('spread', { pr: 1 }),
failure('spread', { event: 'merge_group', pr: 2 }),
failure('spread', { pr: 3 }),
failure('spread', { suite: E2E, pr: 4 }),
]);
assert.deepEqual(
flaky.map((entry) => `${entry.suite.name} ${entry.test}`),
['Jest spread', 'Jest re-run', 'E2E retry'],
);
});
test('prOf reads the PR number from a merge queue branch', () => {
assert.equal(
prOf({
event: 'merge_group',
head_branch: 'gh-readonly-queue/main/pr-13616-0a1ca00c27f1',
}),
13616,
);
assert.equal(
prOf({ event: 'pull_request', pull_requests: [{ number: 42 }] }),
42,
);
});
test('rateLimitWait waits for retry-after or the hourly reset, and nothing else', () => {
const response = (status, headers) => ({
status,
headers: new Headers(headers),
});
const now = 1_000_000;
assert.equal(
rateLimitWait(response(429, { 'retry-after': '30' }), now),
30_000,
);
assert.equal(
rateLimitWait(
response(403, { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': '1060' }),
now,
),
61_000,
);
assert.equal(
rateLimitWait(response(403, { 'x-ratelimit-remaining': '12' }), now),
null,
);
assert.equal(rateLimitWait(response(500, {}), now), null);
});
test('slackMessages posts each suite on its own, escaped, top 10 with a link to the run', () => {
const STORYBOOK = { name: 'Storybook', root: 'frontend/' };
const entry = (suite, index) => ({
suite,
file: `src/t${index}.test.tsx`,
test: `T${index} › shows <Empty> & more`,
failures: 20 - index,
passedOnRerun: 1,
passedOnRetry: 0,
mergeQueue: 0,
prs: new Set([1]),
change: { who: 'dev' },
});
const messages = slackMessages(
'SigNoz/signoz',
'2026-11-17',
[JEST, STORYBOOK, E2E],
[
...Array.from({ length: 12 }, (_, index) => entry(JEST, index)),
entry(E2E, 0),
],
'https://github.com/SigNoz/signoz/actions/runs/1',
);
assert.deepEqual(
messages.map((message) => message.text),
['12 flaky Jest tests since 2026-11-17', '1 flaky E2E test since 2026-11-17'],
);
const sections = (message) =>
message.blocks.filter((block) => block.type === 'section');
assert.equal(sections(messages[0]).length, 10);
assert.equal(
sections(messages[0])[0].text.text,
'*20 failures* <https://github.com/SigNoz/signoz/blob/main/frontend/src/t0.test.tsx|T0 › shows &lt;Empty&gt; &amp; more>\npassed on re-run (1), last changed by dev',
);
assert.match(
sections(messages[1])[0].text.text,
/blob\/main\/tests\/e2e\/src\/t0\.test\.tsx/,
);
assert.equal(
messages[1].blocks.at(-1).elements[0].text,
'<https://github.com/SigNoz/signoz/actions/runs/1|All tests and their first error line>',
);
});

View File

@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { test } from 'node:test';
import SlowTestReporter from '../slow-test-reporter.mjs';
const result = {
testFilePath: path.join(process.cwd(), 'src/a/A.test.tsx'),
testResults: [
{ fullName: 'A › saves', duration: 2500 },
{ fullName: 'A › loads', duration: 100 },
{ fullName: 'A › reads a | b', duration: 4000 },
],
};
test('lists tests over 2 s in the job summary, slowest first', (t) => {
const summary = path.join(
mkdtempSync(path.join(tmpdir(), 'slow-')),
'summary.md',
);
writeFileSync(summary, '');
t.after(() => delete process.env.GITHUB_STEP_SUMMARY);
process.env.GITHUB_STEP_SUMMARY = summary;
const reporter = new SlowTestReporter();
reporter.onTestResult(undefined, result);
reporter.onRunComplete();
assert.equal(
readFileSync(summary, 'utf8'),
[
'### Jest tests over 2 s',
'',
'| Test | File | Time |',
'| --- | --- | --- |',
'| A › reads a \\| b | `src/a/A.test.tsx` | 4.0 s |',
'| A › saves | `src/a/A.test.tsx` | 2.5 s |',
'',
].join('\n'),
);
});

View File

@@ -0,0 +1,86 @@
const SLACK_LIMIT = 10;
function signal(entry) {
return [
entry.passedOnRetry && `passed on retry (${entry.passedOnRetry})`,
entry.passedOnRerun && `passed on re-run (${entry.passedOnRerun})`,
entry.mergeQueue && `merge queue (${entry.mergeQueue})`,
entry.prs.size > 1 && `${entry.prs.size} PRs`,
]
.filter(Boolean)
.join(', ');
}
const cell = (text) => text.replace(/\|/g, '\\|');
const changeCell = (change) =>
change
? `${change.who}, ${change.when}, [${change.sha}](${change.url})`
: 'unknown';
function suiteTable(suite, flaky) {
const rows = flaky
.filter((entry) => entry.suite === suite)
.map(
(entry) =>
`| ${cell(entry.test)} | \`${entry.file}\` | ${entry.failures} | ${signal(entry)} | ${cell(entry.error.slice(0, 80))} | ${changeCell(entry.change)} |`,
);
if (rows.length === 0) {
return [`### ${suite.name}`, '', 'No flaky tests found.', ''];
}
return [
`### ${suite.name}`,
'',
'| Test | File | Failures | Signal | First error line | Last change |',
'| --- | --- | --- | --- | --- | --- |',
...rows,
'',
];
}
export function report(since, suites, flaky) {
return [
`## Flaky tests since ${since}`,
'',
"A test is listed when it failed and then passed on a re-run of the same commit or on Playwright's own retry, or failed on 3 or more PRs. A merge queue run counts for the PR it was merging.",
'',
...suites.flatMap((suite) => suiteTable(suite, flaky)),
].join('\n');
}
// Slack mrkdwn treats these three as control characters.
const slackEscape = (text) =>
text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function slackMessage(repo, since, suite, flaky, runUrl) {
const title = `${flaky.length} flaky ${suite.name} ${flaky.length === 1 ? 'test' : 'tests'} since ${since}`;
return {
text: title,
blocks: [
{ type: 'header', text: { type: 'plain_text', text: title } },
...flaky.slice(0, SLACK_LIMIT).map((entry) => ({
type: 'section',
text: {
type: 'mrkdwn',
text: `*${entry.failures} failures* <https://github.com/${repo}/blob/main/${suite.root}${entry.file}|${slackEscape(entry.test)}>\n${signal(entry)}, last changed by ${slackEscape(entry.change?.who ?? 'unknown')}`,
},
})),
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `<${runUrl}|All tests and their first error line>`,
},
],
},
],
};
}
export function slackMessages(repo, since, suites, flaky, runUrl) {
return suites
.map((suite) => [suite, flaky.filter((entry) => entry.suite === suite)])
.filter(([, entries]) => entries.length > 0)
.map(([suite, entries]) => slackMessage(repo, since, suite, entries, runUrl));
}

View File

@@ -0,0 +1,232 @@
#!/usr/bin/env node
import { pathToFileURL } from 'node:url';
import {
artifactFile,
artifactsSince,
gh,
mapLimit,
paginate,
} from './github-api.mjs';
import {
parseJest,
parsePlaywright,
parsePlaywrightReport,
} from './test-log-parsers.mjs';
import { report, slackMessages } from './flaky-test-format.mjs';
const MIN_PRS = 3;
const PARALLEL_RUNS = 8;
const DAY_MS = 24 * 60 * 60 * 1000;
const SUITES = [
{
name: 'Jest',
workflow: 'jsci.yaml',
job: /^test-shard \(\d+\)$|^test \/ js$/,
root: 'frontend/',
parse: parseJest,
},
{
name: 'Storybook',
workflow: 'jsci.yaml',
job: /^storybook \(\d+\)$/,
root: 'frontend/',
parse: parseJest,
},
{
name: 'E2E',
workflow: 'e2eci.yaml',
job: /^test \(/,
root: 'tests/e2e/',
parse: parsePlaywright,
// Uploaded by e2eci's upload-flaky step, only for shards with a test that passed on retry.
artifact: { prefix: 'e2e-flaky-', file: 'results.json' },
parseArtifact: parsePlaywrightReport,
},
];
export function findFlaky(failures) {
const byTest = new Map();
failures.forEach((failure) => {
const key = `${failure.suite.name}\0${failure.file}\0${failure.test}`;
const entry = byTest.get(key) ?? {
suite: failure.suite,
file: failure.file,
test: failure.test,
error: failure.error,
failures: 0,
prs: new Set(),
passedOnRerun: 0,
passedOnRetry: 0,
mergeQueue: 0,
};
entry.failures += 1;
if (failure.pr) {
entry.prs.add(failure.pr);
}
entry.passedOnRerun += failure.passedOnRerun ? 1 : 0;
entry.passedOnRetry += failure.retried ? 1 : 0;
entry.mergeQueue += failure.event === 'merge_group' ? 1 : 0;
byTest.set(key, entry);
});
return [...byTest.values()]
.filter(
(entry) =>
entry.passedOnRerun > 0 ||
entry.passedOnRetry > 0 ||
entry.prs.size >= MIN_PRS,
)
.sort((a, b) => b.failures - a.failures);
}
// Merge queue branches are named gh-readonly-queue/<base>/pr-<number>-<sha>.
export function prOf(run) {
if (run.event === 'merge_group') {
return Number(run.head_branch.match(/\/pr-(\d+)-/)?.[1]) || run.head_branch;
}
return run.pull_requests[0]?.number ?? run.head_branch;
}
async function runFailures(repo, run, suites) {
const jobs = await paginate(
`/repos/${repo}/actions/runs/${run.id}/jobs?filter=all&per_page=100`,
'jobs',
);
const failures = [];
for (const suite of suites) {
const suiteJobs = jobs.filter((job) => suite.job.test(job.name));
for (const job of suiteJobs.filter(
(failed) => failed.conclusion === 'failure',
)) {
const passedOnRerun = suiteJobs.some(
(later) =>
later.name === job.name &&
later.run_attempt > job.run_attempt &&
later.conclusion === 'success',
);
let log;
try {
log = await (await gh(`/repos/${repo}/actions/jobs/${job.id}/logs`)).text();
} catch (error) {
process.stderr.write(`skipped job ${job.id}: ${error.message}\n`);
continue;
}
suite.parse(log).forEach((failure) =>
failures.push({
...failure,
suite,
event: run.event,
pr: prOf(run),
passedOnRerun,
}),
);
}
}
return failures;
}
async function collectFailures(repo, since) {
const workflows = [...new Set(SUITES.map((suite) => suite.workflow))];
const failures = await Promise.all(
workflows.map(async (workflow) => {
const suites = SUITES.filter((suite) => suite.workflow === workflow);
const runs = await paginate(
`/repos/${repo}/actions/workflows/${workflow}/runs?created=>=${since}&per_page=100`,
'workflow_runs',
);
const candidates = runs.filter(
(run) => run.run_attempt > 1 || run.conclusion === 'failure',
);
const fromLogs = await mapLimit(candidates, PARALLEL_RUNS, (run) =>
runFailures(repo, run, suites),
);
const fromArtifacts = await Promise.all(
suites
.filter((suite) => suite.artifact)
.map((suite) => artifactFailures(repo, since, suite, runs)),
);
return [...fromLogs, ...fromArtifacts].flat(2);
}),
);
return failures.flat();
}
async function artifactFailures(repo, since, suite, runs) {
const runsById = new Map(runs.map((run) => [run.id, run]));
const artifacts = (await artifactsSince(repo, since)).filter(
(artifact) =>
artifact.name.startsWith(suite.artifact.prefix) &&
!artifact.expired &&
runsById.has(artifact.workflow_run.id),
);
return mapLimit(artifacts, PARALLEL_RUNS, async (artifact) => {
const run = runsById.get(artifact.workflow_run.id);
let report;
try {
report = JSON.parse(
await artifactFile(repo, artifact.id, suite.artifact.file),
);
} catch (error) {
process.stderr.write(`skipped artifact ${artifact.id}: ${error.message}\n`);
return [];
}
return suite.parseArtifact(report).map((failure) => ({
...failure,
suite,
event: run.event,
pr: prOf(run),
passedOnRerun: false,
}));
});
}
async function lastChange(repo, path) {
const [commit] = await (
await gh(`/repos/${repo}/commits?path=${path}&per_page=1`)
).json();
if (!commit) {
return null;
}
return {
who: commit.author?.login ?? commit.commit.author.name,
when: commit.commit.author.date.slice(0, 10),
sha: commit.sha.slice(0, 7),
url: commit.html_url,
};
}
async function postToSlack(webhook, message) {
const response = await fetch(webhook, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(message),
});
if (!response.ok) {
throw new Error(`${response.status} POST Slack webhook`);
}
}
async function main() {
const repo = process.env.GITHUB_REPOSITORY;
const days = Number(process.env.DAYS ?? 7);
const since = new Date(Date.now() - days * DAY_MS).toISOString().slice(0, 10);
const flaky = await Promise.all(
findFlaky(await collectFailures(repo, since)).map(async (entry) => ({
...entry,
change: await lastChange(repo, entry.suite.root + entry.file),
})),
);
process.stdout.write(report(since, SUITES, flaky));
const webhook = process.env.SLACK_WEBHOOK_URL;
if (webhook) {
const runUrl = `${process.env.GITHUB_SERVER_URL}/${repo}/actions/runs/${process.env.GITHUB_RUN_ID}`;
for (const message of slackMessages(repo, since, SUITES, flaky, runUrl)) {
await postToSlack(webhook, message);
}
}
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
await main();
}

View File

@@ -0,0 +1,119 @@
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const API = 'https://api.github.com';
const MAX_ATTEMPTS = 4;
const RETRY_BACKOFF_MS = 2000;
const MAX_ARTIFACT_BYTES = 64 * 1024 * 1024;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// GitHub sends `retry-after` (seconds) for a secondary limit, and `x-ratelimit-reset`
// (epoch seconds) once the hourly budget is spent.
export function rateLimitWait(response, now = Date.now()) {
if (response.status !== 403 && response.status !== 429) {
return null;
}
const retryAfter = Number(response.headers.get('retry-after'));
if (retryAfter) {
return retryAfter * 1000;
}
if (response.headers.get('x-ratelimit-remaining') !== '0') {
return null;
}
const reset = Number(response.headers.get('x-ratelimit-reset')) * 1000;
return Math.max(reset - now, 0) + 1000;
}
export async function gh(path, init = {}, attempt = 1) {
const retry = !init.method && attempt < MAX_ATTEMPTS;
let response;
try {
response = await fetch(path.startsWith('http') ? path : API + path, {
...init,
headers: {
accept: 'application/vnd.github+json',
authorization: `Bearer ${process.env.GH_TOKEN}`,
...init.headers,
},
});
} catch (error) {
if (!retry) {
throw error;
}
await sleep(attempt * RETRY_BACKOFF_MS);
return gh(path, init, attempt + 1);
}
const wait = rateLimitWait(response);
if (wait !== null) {
process.stderr.write(`rate limited, waiting ${Math.ceil(wait / 1000)} s\n`);
await sleep(wait);
return gh(path, init, attempt);
}
if (retry && response.status >= 500) {
await sleep(attempt * RETRY_BACKOFF_MS);
return gh(path, init, attempt + 1);
}
if (!response.ok) {
throw new Error(`${response.status} ${init.method ?? 'GET'} ${path}`);
}
return response;
}
export async function mapLimit(items, limit, fn) {
const results = [];
let next = 0;
await Promise.all(
Array.from({ length: limit }, async () => {
while (next < items.length) {
const index = next;
next += 1;
results[index] = await fn(items[index]);
}
}),
);
return results;
}
export async function paginate(path, key) {
const items = [];
let next = API + path;
while (next) {
const response = await gh(next);
const body = await response.json();
items.push(...(key ? body[key] : body));
next = response.headers.get('link')?.match(/<([^>]+)>; rel="next"/)?.[1];
}
return items;
}
// The artifacts list is newest first, so paging stops at the first page that reaches past `since`.
export async function artifactsSince(repo, since) {
const artifacts = [];
for (let page = 1; ; page += 1) {
const { artifacts: batch } = await (
await gh(`/repos/${repo}/actions/artifacts?per_page=100&page=${page}`)
).json();
artifacts.push(...batch.filter((artifact) => artifact.created_at >= since));
if (batch.length < 100 || batch.at(-1).created_at < since) {
return artifacts;
}
}
}
export async function artifactFile(repo, id, name) {
const dir = mkdtempSync(join(tmpdir(), 'artifact-'));
try {
const zip = join(dir, 'artifact.zip');
const response = await gh(`/repos/${repo}/actions/artifacts/${id}/zip`);
writeFileSync(zip, Buffer.from(await response.arrayBuffer()));
return execFileSync('unzip', ['-p', zip, name], {
encoding: 'utf8',
maxBuffer: MAX_ARTIFACT_BYTES,
});
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

View File

@@ -0,0 +1,45 @@
import fs from 'node:fs';
import path from 'node:path';
const budgetMs = Number(process.env.SLOW_TEST_MS ?? 2000);
class SlowTestReporter {
constructor() {
this.slow = [];
}
onTestResult(_test, result) {
const file = path.relative(process.cwd(), result.testFilePath);
result.testResults.forEach((test) => {
if ((test.duration ?? 0) > budgetMs) {
this.slow.push({ file, name: test.fullName, ms: test.duration });
}
});
}
onRunComplete() {
const summaryFile = process.env.GITHUB_STEP_SUMMARY;
if (!summaryFile || this.slow.length === 0) {
return;
}
const rows = this.slow
.sort((a, b) => b.ms - a.ms)
.map(
(test) =>
`| ${test.name.replace(/\|/g, '\\|')} | \`${test.file}\` | ${(test.ms / 1000).toFixed(1)} s |`,
);
fs.appendFileSync(
summaryFile,
[
`### Jest tests over ${budgetMs / 1000} s`,
'',
'| Test | File | Time |',
'| --- | --- | --- |',
...rows,
'',
].join('\n'),
);
}
}
export default SlowTestReporter;

View File

@@ -0,0 +1,110 @@
function cleanLines(log) {
return log.split('\n').map((line) =>
line
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[[0-9;]*m/g, '')
.replace(/^\d{4}-\d\d-\d\dT[\d:.]+Z /, ''),
);
}
const firstLineAfter = (lines, index) =>
lines
.slice(index + 1, index + 8)
.map((next) => next.trim())
.find(Boolean) ?? '';
// Storybook's test runner prints `FAIL browser: chromium <file>`, then repeats
// the file with a `frontend/` prefix in its closing summary.
export function parseJest(log) {
const lines = cleanLines(log);
const failures = new Map();
let file = null;
lines.forEach((line, index) => {
const failedFile = line.match(
/^\s*FAIL\s+(?:browser: \S+\s+)?(?:frontend\/)?(\S+)/,
);
if (failedFile) {
[, file] = failedFile;
return;
}
const failedTest = line.match(/^\s*● (.+ › .+)$/);
if (!failedTest || !file) {
return;
}
const test = failedTest[1].trim();
const key = `${file}\0${test}`;
if (!failures.has(key)) {
failures.set(key, {
file,
test,
error: firstLineAfter(lines, index),
retried: false,
});
}
});
return [...failures.values()];
}
// Playwright's list reporter numbers each failure (`1) [chromium] › <file>:<line>:<col> › <title>`)
// and lists the tests that failed every retry under a closing `N failed` line.
export function parsePlaywright(log) {
const lines = cleanLines(log);
const testLine = /\[[^\]]+\] › (\S+?):\d+:\d+ › (.+?)\s*$/;
const errors = new Map();
const failures = [];
let section = null;
lines.forEach((line, index) => {
const header = line.match(/^\s*\d+\) /) && line.match(testLine);
if (header) {
errors.set(`${header[1]}\0${header[2]}`, firstLineAfter(lines, index));
return;
}
const count = line.match(
/^\s*\d+ (failed|flaky|passed|skipped|interrupted|did not run)\b/,
);
if (count) {
[, section] = count;
return;
}
const listed = section === 'failed' ? line.match(testLine) : null;
if (listed) {
const [, file, title] = listed;
failures.push({
file,
test: title,
error: errors.get(`${file}\0${title}`) ?? '',
retried: false,
});
}
});
return failures;
}
// Reads Playwright's JSON report. A flaky test failed and then passed on one of
// Playwright's own retries; spec files are relative to `config.rootDir`.
export function parsePlaywrightReport(report) {
const dir = report.config.rootDir.split('/tests/e2e/')[1];
const flaky = [];
const walk = (suite, titles) => {
suite.specs?.forEach((spec) => {
if (!spec.tests.some((test) => test.status === 'flaky')) {
return;
}
const error = spec.tests
.flatMap((test) => test.results)
.find((result) => result.error)?.error.message;
flaky.push({
file: [dir, spec.file].filter(Boolean).join('/'),
test: [...titles, spec.title].join(' › '),
error:
cleanLines(error ?? '')
.find((line) => line.trim())
?.trim() ?? '',
retried: true,
});
});
suite.suites?.forEach((child) => walk(child, [...titles, child.title]));
};
report.suites.forEach((fileSuite) => walk(fileSuite, []));
return flaky;
}