diff --git a/.github/workflows/docs-a11y-scan.yml b/.github/workflows/docs-a11y-scan.yml index 8512df32c62..22aa9744614 100644 --- a/.github/workflows/docs-a11y-scan.yml +++ b/.github/workflows/docs-a11y-scan.yml @@ -1,5 +1,5 @@ # Scans every docs guide on production for accessibility violations, daily. -# docs-master-alert.yml posts failures to Slack. +# docs-master-alert.yml posts to Slack when its list of failures changes. name: Docs Accessibility Scan @@ -58,6 +58,17 @@ jobs: run: pnpm run e2e:docs:all --grep @a11y env: PLAYWRIGHT_BASE_URL: https://supabase.com + DOCS_A11Y_FAILURES_FILE: ${{ github.workspace }}/e2e/docs/a11y-failures.json + + - name: Upload failures for the alert + # docs-alert.ts reads this file through RESULTS_WORKFLOWS + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: docs-failures-${{ github.run_attempt }} + path: e2e/docs/a11y-failures.json + retention-days: 7 + if-no-files-found: ignore - name: Upload Playwright report if: failure() diff --git a/.github/workflows/docs-master-alert.yml b/.github/workflows/docs-master-alert.yml index 6ba6c32926d..c0c308ee98a 100644 --- a/.github/workflows/docs-master-alert.yml +++ b/.github/workflows/docs-master-alert.yml @@ -1,3 +1,7 @@ +# Keeps a list of open failures for each docs workflow below, and posts to Slack when the list +# changes. Each failure names the commit that introduced it, or its possible commits. Docs E2E Tests +# reaches master only through a manual run. e2e/docs/scripts/docs-alert.ts holds the logic. + name: Alert on master breakage on: @@ -7,13 +11,10 @@ on: - '[Docs] Update last-changed dates' - 'Update JS Client Libraries Docs' - 'Update Mgmt Api Docs' - - 'Docs Navigation Checks' - - 'Docs removed anchors' - 'docs_sync' - 'Docs Production Smoke Tests' - 'Docs Accessibility Scan' - 'Ingest Docs Content for Search V2' - - 'Docs Tests' branches: [master] types: - completed @@ -21,44 +22,70 @@ on: permissions: contents: read actions: read + statuses: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.workflow_run.workflow_id }} + cancel-in-progress: false jobs: notify: - if: ${{ github.event.workflow_run.conclusion == 'failure' }} + if: >- + github.event.workflow_run.head_repository.full_name == github.repository && + (github.event.workflow_run.conclusion == 'success' || + github.event.workflow_run.conclusion == 'failure') runs-on: ubuntu-latest + env: + STATE_NAME: docs-open-failures-${{ github.event.workflow_run.workflow_id }} steps: - - name: Send Slack alert - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DOCS_WEBHOOK_URL }} - WORKFLOW_NAME: ${{ github.event.workflow_run.name }} - WORKFLOW_URL: ${{ github.event.workflow_run.html_url }} - TRIGGER: ${{ github.event.workflow_run.event }} - run: | - PAYLOAD=$(jq -n \ - --arg workflow_name "$WORKFLOW_NAME" \ - --arg workflow_url "$WORKFLOW_URL" \ - --arg trigger "$TRIGGER" \ - '(if $trigger == "push" then "push to master" elif $trigger == "schedule" then "scheduled run" elif $trigger == "workflow_dispatch" then "manual run" else "\($trigger) run" end) as $run - | { - text: ":rotating_light: \($workflow_name) failed on a \($run)", - blocks: [ - { - type: "header", - text: { - type: "plain_text", - text: ":rotating_light: \($workflow_name) failed" - } - }, - { - type: "section", - text: { - type: "mrkdwn", - text: "*Workflow:* <\($workflow_url)|\($workflow_name)> (\($run))" - } - } - ] - }') + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + sparse-checkout: | + e2e/docs + e2e/shared + apps/docs/content - curl -f -X POST "$SLACK_WEBHOOK_URL" \ - -H 'Content-Type: application/json' \ - -d "$PAYLOAD" + - name: Use Node.js + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version-file: '.nvmrc' + + - name: Download the saved list and the run's results + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.event.workflow_run.id }} + RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }} + run: | + mkdir -p "$RUNNER_TEMP/state-in" "$RUNNER_TEMP/state-out" "$RUNNER_TEMP/results" + # Only trust a saved list from a master run in this repo, not from a fork or a branch + ID=$(gh api "repos/$REPO/actions/artifacts?name=$STATE_NAME&per_page=100" \ + --jq '[.artifacts[] | select((.expired | not) + and .workflow_run.head_branch == "master" + and .workflow_run.head_repository_id == .workflow_run.repository_id)] + | max_by(.created_at) | .id // empty') + if [ -n "$ID" ]; then + gh api "repos/$REPO/actions/artifacts/$ID/zip" > "$RUNNER_TEMP/state.zip" + unzip -o -q "$RUNNER_TEMP/state.zip" open-failures.json -d "$RUNNER_TEMP/state-in" + fi + gh run download "$RUN_ID" --repo "$REPO" --name "docs-failures-$RUN_ATTEMPT" \ + --dir "$RUNNER_TEMP/results" || echo "No results artifact on this run." + + - name: Update the list and post changes + env: + GITHUB_TOKEN: ${{ github.token }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DOCS_WEBHOOK_URL }} + run: | + STATE_IN="$RUNNER_TEMP/state-in/open-failures.json" \ + STATE_OUT="$RUNNER_TEMP/state-out/open-failures.json" \ + RESULTS_DIR="$RUNNER_TEMP/results" \ + node --experimental-strip-types e2e/docs/scripts/docs-alert.ts + + - name: Save the list + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ${{ env.STATE_NAME }} + path: ${{ runner.temp }}/state-out/open-failures.json + retention-days: 90 + if-no-files-found: ignore diff --git a/.github/workflows/docs-tests-smoke.yml b/.github/workflows/docs-tests-smoke.yml index d5ff5297ccf..ede7fe00ec2 100644 --- a/.github/workflows/docs-tests-smoke.yml +++ b/.github/workflows/docs-tests-smoke.yml @@ -43,4 +43,14 @@ jobs: run: pnpm install --frozen-lockfile - name: Run tests - run: pnpm --prefix="apps/docs" run test:smoke + run: pnpm --prefix="apps/docs" run test:smoke --reporter=default --reporter=json --outputFile.json=smoke-results.json + + - name: Upload results for the alert + # docs-alert.ts reads this file through RESULTS_WORKFLOWS + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: docs-failures-${{ github.run_attempt }} + path: apps/docs/smoke-results.json + retention-days: 7 + if-no-files-found: ignore diff --git a/e2e/docs/README.md b/e2e/docs/README.md index e1507a6c9c0..81bc4d23c62 100644 --- a/e2e/docs/README.md +++ b/e2e/docs/README.md @@ -21,6 +21,7 @@ This page covers: - [Accessibility scans](#accessibility-scans) — WCAG coverage and skipped rules - [Debug failures](#debug-failures) — reports and traces - [How CI uses this suite](#how-ci-uses-this-suite) — pull request behavior +- [Failure alerts](#failure-alerts) — Slack alerts for docs workflows on `master` ## Set up @@ -172,11 +173,16 @@ staged and unstaged working-tree changes. The `@a11y`-tagged test scans each in-scope page with `@axe-core/playwright`. It reports WCAG 2.1 A/AA violations in the main article, and fails on the rules in -`ENFORCED_RULES` in `utils/axe-helpers.ts`, which it checks across the whole page. +`ENFORCED_RULES` in `utils/axe-rules.ts`, which it checks across the whole page. The scans are slow, so Docs E2E runs skip them. Instead, the Docs Accessibility Scan workflow (`.github/workflows/docs-a11y-scan.yml`) scans every MDX guide on -production daily at 05:17 UTC, and a failure posts to the docs alerts channel in -Slack. To start it by hand, run `gh workflow run docs-a11y-scan.yml`. +production daily at 05:17 UTC. To start it by hand, run +`gh workflow run docs-a11y-scan.yml`. + +When the daily scan finds a new failure or a fix, it posts to the docs alerts +channel in Slack. See [Failure alerts](#failure-alerts). + +To run the scan locally: ```bash PLAYWRIGHT_BASE_URL=https://supabase.com pnpm e2e:docs:a11y @@ -187,7 +193,7 @@ whatever you point `PLAYWRIGHT_BASE_URL` at. Production won't have your edits an will 404 on a page you just added, so use your pull request's preview to scan your own content. -`EXCLUDED_RULES` in `utils/axe-helpers.ts` lists the rules the scan skips. +`EXCLUDED_RULES` in `utils/axe-rules.ts` lists the rules the scan skips. `color-contrast` is most of the scan time and finds nothing inside an article, since docs contrast comes from shared tokens and chrome. The rest target ``, ``, and ``, which an article-scoped scan can't reach. @@ -227,3 +233,34 @@ owned docs content, partials, or `e2e/docs`. Draft pull requests stay skipped until you mark them ready for review. Manual `workflow_dispatch` runs require a `page_paths` input and accept an optional `base_url`, which defaults to production. + +## Failure alerts + +`.github/workflows/docs-master-alert.yml` keeps a list of open failures for each +of the following workflows when they run on `master`: + +- Docs Accessibility Scan, with one failure per page and axe rule +- Docs Production Smoke Tests, with one failure per test +- Docs E2E Tests, which runs on `master` only when started by hand +- [Docs] Update last-changed dates +- Update JS Client Libraries Docs +- Update Mgmt Api Docs +- docs_sync +- Ingest Docs Content for Search V2 + +For the workflows without their own results, each failed job or step is one +failure. + +| When | The alert | +| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| A failure is added | Posts it with the commit that introduced it, or the possible commits | +| A failure is fixed | Posts the fix | +| The list doesn't change | Posts nothing | +| A page or test times out, a page doesn't render, or a job or step is skipped | Keeps its earlier result | +| A page returns an error status, such as 404 | Counts a failure for that status in place of any earlier one, and keeps the page's earlier scan results | +| No smoke test passes and some time out | Counts one failure for the run | +| A run fails before it reports results | Posts that the run failed, and keeps the list as it was | + +For the scan, a new failure names the deployed commit that touched the page or a +partial it includes. When no single commit did, the alert lists the possible +commits as unconfirmed. diff --git a/e2e/docs/playwright.config.ts b/e2e/docs/playwright.config.ts index 84f934b3e29..7baa6278550 100644 --- a/e2e/docs/playwright.config.ts +++ b/e2e/docs/playwright.config.ts @@ -6,6 +6,8 @@ const IS_CI = !!process.env.CI const PAGE_COUNT = parsePagePaths(process.env.DOCS_E2E_PAGE_PATHS).length +const A11Y_FAILURES_FILE = process.env.DOCS_A11Y_FAILURES_FILE + export default defineConfig({ testDir: './features', testMatch: /.*\.spec\.ts/, @@ -42,12 +44,13 @@ export default defineConfig({ }, }, ], - reporter: IS_CI - ? [['list'], ['html', { open: 'never', outputFolder: './playwright-report' }]] - : [ - ['list'], - ['html', { open: 'never', outputFolder: './playwright-report' }], - ['json', { outputFile: './test-results/test-results.json' }], - ], + reporter: [ + ['list'], + ['html', { open: 'never', outputFolder: './playwright-report' }], + ...(IS_CI ? [] : [['json', { outputFile: './test-results/test-results.json' }] as const]), + ...(A11Y_FAILURES_FILE + ? [['./utils/a11y-failures-reporter.ts', { outputFile: A11Y_FAILURES_FILE }] as const] + : []), + ], outputDir: './test-results', }) diff --git a/e2e/docs/scripts/docs-alert.ts b/e2e/docs/scripts/docs-alert.ts new file mode 100644 index 00000000000..d9f76a60eec --- /dev/null +++ b/e2e/docs/scripts/docs-alert.ts @@ -0,0 +1,441 @@ +#!/usr/bin/env node +// Keeps the open-failures list for a docs workflow run on master and posts to Slack when it +// changes. Run by .github/workflows/docs-master-alert.yml. +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { + attribute, + baselineFor, + compareFailures, + deployedCommitsBetween, + failuresFromJobs, + failuresFromVitest, + formatAlert, + formatCrashAlert, + nextLastChecked, + parseFailureState, + parseRunFailures, + pushCandidates, + stateFromPassingRun, + titleOf, + type ActionsJob, + type ActionsRun, + type Attribution, + type Commit, + type Failure, + type FailureState, + type HistoryCommit, + type OpenFailure, + type RunFailures, + type RunRef, +} from '../utils/open-failures.ts' +import { pageSourceFiles } from '../utils/resolve-docs-scope.ts' + +const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '../../..') + +// Workflows that test production and upload their results as the `docs-failures-` +// artifact (see the upload steps in docs-a11y-scan.yml and docs-tests-smoke.yml) +const RESULTS_WORKFLOWS: Record< + string, + { file: string; narrowToPage: boolean; parse: (report: unknown) => RunFailures | null } +> = { + '.github/workflows/docs-a11y-scan.yml': { + file: 'a11y-failures.json', + narrowToPage: true, + parse: parseRunFailures, + }, + '.github/workflows/docs-tests-smoke.yml': { + file: 'smoke-results.json', + narrowToPage: false, + parse: failuresFromVitest, + }, +} + +const VERCEL_STATUS_CONTEXT = 'Vercel – docs' +const HISTORY_PADDING_MS = 3 * 24 * 60 * 60 * 1000 +const NEVER_CHECKED: Attribution = { + kind: 'none', + reason: 'no earlier run checked this since tracking started', +} + +type WorkflowRun = ActionsRun & { + id: number + run_attempt: number + name: string + path: string + event: string + run_started_at: string + updated_at: string + html_url: string + workflow_id: number +} + +const env = (name: string, fallback?: string): string => { + const value = process.env[name] ?? fallback + if (value === undefined) throw new Error(`${name} is not set.`) + return value +} + +const repo = env('GITHUB_REPOSITORY') +const token = env('GITHUB_TOKEN') +const apiUrl = env('GITHUB_API_URL', 'https://api.github.com') +const repoUrl = `${env('GITHUB_SERVER_URL', 'https://github.com')}/${repo}` + +// Response shapes follow GitHub's documented REST and GraphQL schemas +async function github(path: string, init?: RequestInit): Promise { + const response = await fetch(`${apiUrl}${path}`, { + ...init, + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token}`, + 'X-GitHub-Api-Version': '2022-11-28', + ...init?.headers, + }, + }) + if (!response.ok) { + throw new Error(`GitHub API ${path} returned ${response.status}: ${await response.text()}`) + } + return (await response.json()) as T +} + +function readJson(path: string | undefined): unknown { + if (!path || !existsSync(path)) return null + try { + return JSON.parse(readFileSync(path, 'utf8')) + } catch { + return null + } +} + +function toRunRef(run: WorkflowRun): RunRef { + return { + id: run.id, + attempt: run.run_attempt, + runNumber: run.run_number, + headSha: run.head_sha, + startedAt: run.run_started_at, + } +} + +function runLabel(event: string): string { + if (event === 'push') return 'push to master' + if (event === 'schedule') return 'scheduled run' + if (event === 'workflow_dispatch') return 'manual run' + return `${event} run` +} + +async function jobFailures(run: WorkflowRun): Promise { + const { jobs } = await github<{ jobs: ActionsJob[] }>( + `/repos/${repo}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100` + ) + return failuresFromJobs(jobs) +} + +// null when the run's results are missing or unreadable, so this run can't change the list +async function currentFailures(run: WorkflowRun, resultsDir: string): Promise { + const results = RESULTS_WORKFLOWS[run.path] + if (results) return results.parse(readJson(join(resultsDir, results.file))) + + // Read jobs on a passing run too, so a step its condition skipped keeps its earlier result + const fromJobs = await jobFailures(run) + if (run.conclusion === 'success' || fromJobs.failures.length > 0) return fromJobs + return { failures: [{ key: 'run' }], unchecked: fromJobs.unchecked } +} + +// With no saved list, a previous run that passed still says nothing was open +async function baselineFromApi(run: WorkflowRun): Promise { + const { workflow_runs: runs } = await github<{ workflow_runs: WorkflowRun[] }>( + `/repos/${repo}/actions/workflows/${run.workflow_id}/runs?branch=master&status=completed&per_page=20` + ) + const previous = runs.find( + (candidate) => + candidate.event !== 'pull_request' && + candidate.run_number < run.run_number && + (candidate.conclusion === 'success' || candidate.conclusion === 'failure') + ) + if (previous?.conclusion !== 'success') return null + // A results workflow's earlier artifact isn't read here, so its skipped pages count as checked + const skipped = RESULTS_WORKFLOWS[run.path] ? [] : (await jobFailures(previous)).unchecked + return stateFromPassingRun(toRunRef(previous), skipped) +} + +async function deployHistory(since: string): Promise { + const [owner, name] = repo.split('/') + const query = `query($owner: String!, $name: String!, $since: GitTimestamp!, $cursor: String) { + repository(owner: $owner, name: $name) { + ref(qualifiedName: "refs/heads/master") { + target { + ... on Commit { + history(first: 100, since: $since, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + oid + messageHeadline + status { context(name: "${VERCEL_STATUS_CONTEXT}") { state description createdAt } } + } + } + } + } + } + } + }` + + type Page = { + data: { + repository: { + ref: { + target: { + history: { + pageInfo: { hasNextPage: boolean; endCursor: string } + nodes: { + oid: string + messageHeadline: string + status: { context: HistoryCommit['status'] } | null + }[] + } + } + } + } + } + } + + const commits: HistoryCommit[] = [] + let cursor: string | null = null + for (let page = 0; page < 5; page++) { + const result: Page = await github('/graphql', { + method: 'POST', + body: JSON.stringify({ query, variables: { owner, name, since, cursor } }), + }) + const history = result.data.repository.ref.target.history + for (const node of history.nodes) { + commits.push({ + sha: node.oid, + title: node.messageHeadline, + status: node.status?.context ?? null, + }) + } + if (!history.pageInfo.hasNextPage) break + cursor = history.pageInfo.endCursor + } + return commits +} + +async function pushRange(run: WorkflowRun, baseline: RunRef): Promise { + const runs: WorkflowRun[] = [] + for (let page = 1; ; page++) { + const { workflow_runs: batch } = await github<{ workflow_runs: WorkflowRun[] }>( + `/repos/${repo}/actions/workflows/${run.workflow_id}/runs?branch=master&event=push&created=>=${baseline.startedAt.slice(0, 10)}&per_page=100&page=${page}` + ) + runs.push(...batch) + // Runs come newest first, so stop once a page reaches back to the baseline + if (batch.length < 100 || batch.some((item) => item.run_number <= baseline.runNumber)) break + } + return pushCandidates(runs, baseline.runNumber, run) +} + +type CommitRange = { commits: Commit[]; total: number } + +type Comparison = { + total_commits: number + commits: { sha: string; commit: { message: string } }[] +} + +// The compare API lists the oldest commits first and returns at most 250, so a longer range +// fetches its last two pages of 100 to list the newest commits +async function compareRange(base: string, head: string): Promise { + if (base === head) return { commits: [], total: 0 } + const path = `/repos/${repo}/compare/${base}...${head}` + const first = await github(`${path}?per_page=250`) + let commits = first.commits + if (first.total_commits > commits.length) { + const lastPage = Math.ceil(first.total_commits / 100) + const pages = await Promise.all( + [lastPage - 1, lastPage].map((page) => + github(`${path}?per_page=100&page=${page}`) + ) + ) + commits = pages.flatMap((page) => page.commits) + } + return { + commits: commits.map((commit) => ({ + sha: commit.sha, + title: titleOf(commit.commit.message), + })), + total: first.total_commits, + } +} + +async function attributeNew( + run: WorkflowRun, + state: FailureState, + added: Failure[] +): Promise> { + const attributions = new Map() + const results = RESULTS_WORKFLOWS[run.path] + + if (!results) { + const ranges = new Map() + for (const failure of added) { + const baseline = baselineFor(failure, state) + if (baseline === null) { + attributions.set(failure.key, NEVER_CHECKED) + continue + } + let range = ranges.get(baseline.id) + if (!range) { + if (run.event === 'push') { + const commits = await pushRange(run, baseline) + range = { commits, total: commits.length } + } else { + range = await compareRange(baseline.headSha, run.head_sha) + } + ranges.set(baseline.id, range) + } + attributions.set(failure.key, attribute(range.commits, null, range.total)) + } + return attributions + } + + const baselines = added.map((failure) => baselineFor(failure, state)) + const known = baselines.filter((baseline) => baseline !== null) + if (known.length === 0) { + for (const failure of added) attributions.set(failure.key, NEVER_CHECKED) + return attributions + } + const earliest = Math.min(...known.map((baseline) => Date.parse(baseline.startedAt))) + const since = new Date(earliest - HISTORY_PADDING_MS).toISOString() + const history = await deployHistory(since) + + const touchedByFile = new Map>() + const commitsTouching = async (file: string): Promise> => { + const cached = touchedByFile.get(file) + if (cached) return cached + const commits = await github<{ sha: string }[]>( + `/repos/${repo}/commits?sha=${run.head_sha}&path=${encodeURIComponent(file)}&since=${since}&per_page=100` + ) + const shas = new Set(commits.map((commit) => commit.sha)) + touchedByFile.set(file, shas) + return shas + } + + for (const [index, failure] of added.entries()) { + const baseline = baselines[index] + if (baseline === null) { + attributions.set(failure.key, NEVER_CHECKED) + continue + } + // The run's end, since a commit that deploys mid-scan reaches the pages scanned after it + const range = deployedCommitsBetween(history, baseline.startedAt, run.updated_at) + if (range === null) { + attributions.set(failure.key, { + kind: 'none', + reason: `couldn't tell which commit production was running`, + }) + continue + } + if (!results.narrowToPage || !failure.page || range.length === 0) { + attributions.set(failure.key, attribute(range, null)) + continue + } + const touched = new Set() + for (const file of await pageSourceFiles(REPO_ROOT, failure.page)) { + for (const sha of await commitsTouching(file)) touched.add(sha) + } + const matching = range.filter((commit) => touched.has(commit.sha)) + attributions.set(failure.key, attribute(range, matching)) + } + return attributions +} + +async function postToSlack(payload: unknown): Promise { + if (process.env.DRY_RUN) { + console.log(JSON.stringify(payload, null, 2)) + return + } + const response = await fetch(env('SLACK_WEBHOOK_URL'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }) + if (!response.ok) throw new Error(`Slack returned ${response.status}: ${await response.text()}`) +} + +function isOlderRun(run: WorkflowRun, lastRun: RunRef): boolean { + if (run.run_number !== lastRun.runNumber) return run.run_number < lastRun.runNumber + return run.run_attempt < lastRun.attempt +} + +async function main(): Promise { + const event = readJson(env('GITHUB_EVENT_PATH')) as { workflow_run?: WorkflowRun } | null + const run = event?.workflow_run + if (!run) throw new Error('No workflow_run in the event payload.') + if (run.conclusion !== 'success' && run.conclusion !== 'failure') return + + const stateOut = env('STATE_OUT') + const saved = parseFailureState(readJson(process.env.STATE_IN)) + const keepSaved = () => { + if (saved) writeFileSync(stateOut, JSON.stringify(saved, null, 2)) + } + if (saved && isOlderRun(run, saved.lastRun)) return keepSaved() + + const context = { + workflowName: run.name, + runUrl: run.html_url, + runLabel: runLabel(run.event), + repoUrl, + } + + const current = await currentFailures(run, env('RESULTS_DIR')) + if (current === null) { + keepSaved() + if (run.conclusion === 'failure') await postToSlack(formatCrashAlert(context)) + return + } + + const baseline = saved ?? (await baselineFromApi(run)) + const { added, stillOpen, fixed } = compareFailures(baseline?.open ?? [], current) + + let attributions = new Map() + if (baseline && added.length > 0) { + try { + attributions = await attributeNew(run, baseline, added) + } catch (error) { + console.error(error instanceof Error ? error.message : error) + for (const failure of added) { + attributions.set(failure.key, { kind: 'none', reason: `couldn't read the commit history` }) + } + } + } + + const open: OpenFailure[] = [ + ...stillOpen, + ...added.map((failure) => ({ + ...failure, + firstSeen: run.run_started_at, + attribution: attributions.get(failure.key) ?? { kind: 'preexisting' as const }, + })), + ] + + const state: FailureState = { + version: 1, + lastRun: toRunRef(run), + open, + lastChecked: nextLastChecked( + baseline?.lastChecked ?? {}, + current.unchecked, + baseline?.lastRun ?? null + ), + } + writeFileSync(stateOut, JSON.stringify(state, null, 2)) + + if (added.length === 0 && fixed.length === 0) return + const addedKeys = new Set(added.map((failure) => failure.key)) + await postToSlack(formatAlert(context, open, addedKeys, fixed)) +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error) + process.exit(1) +}) diff --git a/e2e/docs/utils/a11y-failures-reporter.test.ts b/e2e/docs/utils/a11y-failures-reporter.test.ts new file mode 100644 index 00000000000..99289107af7 --- /dev/null +++ b/e2e/docs/utils/a11y-failures-reporter.test.ts @@ -0,0 +1,61 @@ +import assert from 'node:assert/strict' +import { existsSync, mkdtempSync, readFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import type { Suite, TestCase } from '@playwright/test/reporter' + +import A11yFailuresReporter from './a11y-failures-reporter.ts' + +const scanTest = (page: string, scan: object, outcome: string) => + ({ + title: `${page} a11y`, + tags: ['@a11y'], + outcome: () => outcome, + results: [ + { + attachments: [{ name: 'axe-results.json', body: Buffer.from(JSON.stringify(scan)) }], + }, + ], + }) as unknown as TestCase + +test('fails a page that returned an error status, and leaves unchecked what no run observed', () => { + const outputFile = join(mkdtempSync(join(tmpdir(), 'a11y-reporter-')), 'failures.json') + const reporter = new A11yFailuresReporter({ outputFile }) + const tests = [ + scanTest( + '/docs/guides/a', + { loaded: false, status: 503, elementCount: 0, violations: [] }, + 'unexpected' + ), + scanTest( + '/docs/guides/b', + { loaded: true, status: 200, elementCount: 50, violations: [{ id: 'heading-order' }] }, + 'unexpected' + ), + scanTest( + '/docs/guides/c', + { loaded: false, status: null, elementCount: 0, violations: [] }, + 'unexpected' + ), + ] + reporter.onBegin({} as never, { allTests: () => tests } as unknown as Suite) + reporter.onEnd() + + assert.deepEqual(JSON.parse(readFileSync(outputFile, 'utf8')), { + failures: [ + { key: '/docs/guides/a: http-503', page: '/docs/guides/a' }, + { key: '/docs/guides/b: heading-order', page: '/docs/guides/b' }, + ], + unchecked: ['/docs/guides/a', '/docs/guides/c: http', '/docs/guides/c'], + }) +}) + +test('writes no file when no @a11y test ran, such as when a spec fails to load', () => { + const outputFile = join(mkdtempSync(join(tmpdir(), 'a11y-reporter-')), 'failures.json') + const reporter = new A11yFailuresReporter({ outputFile }) + reporter.onBegin({} as never, { allTests: () => [] } as unknown as Suite) + reporter.onEnd() + + assert.equal(existsSync(outputFile), false) +}) diff --git a/e2e/docs/utils/a11y-failures-reporter.ts b/e2e/docs/utils/a11y-failures-reporter.ts new file mode 100644 index 00000000000..a3ba9813717 --- /dev/null +++ b/e2e/docs/utils/a11y-failures-reporter.ts @@ -0,0 +1,61 @@ +import { readFileSync, writeFileSync } from 'node:fs' +import type { FullConfig, Reporter, Suite, TestCase } from '@playwright/test/reporter' + +import { blockingViolations, scanLooksEmpty, type A11yScanResult } from './axe-rules.ts' +import { httpFailureKey, statusCheckKey, type Failure, type RunFailures } from './open-failures.ts' + +function scanResult(test: TestCase): A11yScanResult | null { + const attachment = test.results + .at(-1) + ?.attachments.find((item) => item.name === 'axe-results.json') + if (!attachment) return null + const body = attachment.body ?? (attachment.path ? readFileSync(attachment.path) : null) + return body ? (JSON.parse(body.toString('utf8')) as A11yScanResult) : null +} + +// Writes the pages and axe rules that failed, for docs-master-alert.yml. A page that returned an +// error status fails as http-, and its axe rules stay unchecked. A page whose status or +// scan is missing, empty, or skipped is listed as unchecked, so a flaky run doesn't count as a new +// failure or a fix. A run with no @a11y tests, such as when a spec fails to load, writes no file. +export default class A11yFailuresReporter implements Reporter { + private suite: Suite | undefined + private outputFile: string + + constructor(options: { outputFile: string }) { + this.outputFile = options.outputFile + } + + onBegin(_config: FullConfig, suite: Suite) { + this.suite = suite + } + + onEnd() { + const failures: Failure[] = [] + const unchecked: string[] = [] + + const tests = (this.suite?.allTests() ?? []).filter((test) => test.tags.includes('@a11y')) + if (tests.length === 0) return + for (const test of tests) { + const page = test.title.split(' ')[0] + const result = scanResult(test) + if (result?.status == null) unchecked.push(statusCheckKey(page)) + if (result?.status != null && result.status >= 400) { + failures.push({ key: httpFailureKey(page, result.status), page }) + unchecked.push(page) + continue + } + if (test.outcome() === 'skipped' || !result?.loaded || scanLooksEmpty(result)) { + unchecked.push(page) + continue + } + if (test.outcome() !== 'unexpected') continue + + const blocking = blockingViolations(result) + if (blocking.length === 0) unchecked.push(page) + for (const violation of blocking) failures.push({ key: `${page}: ${violation.id}`, page }) + } + + const output: RunFailures = { failures, unchecked } + writeFileSync(this.outputFile, JSON.stringify(output, null, 2)) + } +} diff --git a/e2e/docs/utils/axe-helpers.ts b/e2e/docs/utils/axe-helpers.ts index a37dea4d0f2..839a8f82893 100644 --- a/e2e/docs/utils/axe-helpers.ts +++ b/e2e/docs/utils/axe-helpers.ts @@ -1,46 +1,12 @@ import type { Page, TestInfo } from '@playwright/test' -import type { Result } from 'axe-core' import { scan, scanResults } from '../../shared/axe.ts' +import { ENFORCED_RULES, EXCLUDED_RULES, type A11yScanResult } from './axe-rules.ts' + +export * from './axe-rules.ts' export const WCAG_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'] -export const ENFORCED_RULES = [ - 'heading-order', - 'page-has-heading-one', - 'button-name', - 'duplicate-id', - 'duplicate-id-active', - 'duplicate-id-aria', -] - -export const EXCLUDED_RULES = [ - 'color-contrast', - 'html-has-lang', - 'html-lang-valid', - 'html-xml-lang-mismatch', - 'document-title', - 'aria-hidden-body', - 'meta-viewport', - 'meta-refresh', - 'css-orientation-lock', -] - -export interface A11yScanResult { - surface: string - url: string - include: string - excludedRules: string[] - loaded: boolean - status: number | null - elementCount: number - violations: Result[] -} - -export function shouldEnforceAll(): boolean { - return !!process.env.A11Y_ENFORCE_ALL -} - export async function scanArticle( page: Page, surface: string, @@ -90,15 +56,6 @@ export function unloadedResult( } } -export const MIN_MEANINGFUL_ELEMENTS = 20 - -export function scanLooksEmpty( - result: A11yScanResult, - minElements: number = MIN_MEANINGFUL_ELEMENTS -): boolean { - return result.elementCount < minElements -} - export async function attachScanReport(testInfo: TestInfo, result: A11yScanResult): Promise { await testInfo.attach('axe-results.json', { body: JSON.stringify(result, null, 2), @@ -106,9 +63,4 @@ export async function attachScanReport(testInfo: TestInfo, result: A11yScanResul }) } -export function blockingViolations(result: A11yScanResult): Result[] { - if (shouldEnforceAll()) return result.violations - return result.violations.filter((violation) => ENFORCED_RULES.includes(violation.id)) -} - export { formatViolations, settleForAxe, violationIds } from '../../shared/axe.ts' diff --git a/e2e/docs/utils/axe-rules.ts b/e2e/docs/utils/axe-rules.ts new file mode 100644 index 00000000000..1cb616e7ed6 --- /dev/null +++ b/e2e/docs/utils/axe-rules.ts @@ -0,0 +1,54 @@ +import type { Result } from 'axe-core' + +// Kept apart from axe-helpers.ts, which loads axe at runtime, so the harness unit tests run with +// no installed packages + +export const ENFORCED_RULES = [ + 'heading-order', + 'page-has-heading-one', + 'button-name', + 'duplicate-id', + 'duplicate-id-active', + 'duplicate-id-aria', +] + +export const EXCLUDED_RULES = [ + 'color-contrast', + 'html-has-lang', + 'html-lang-valid', + 'html-xml-lang-mismatch', + 'document-title', + 'aria-hidden-body', + 'meta-viewport', + 'meta-refresh', + 'css-orientation-lock', +] + +export interface A11yScanResult { + surface: string + url: string + include: string + excludedRules: string[] + loaded: boolean + status: number | null + elementCount: number + violations: Result[] +} + +export function shouldEnforceAll(): boolean { + return !!process.env.A11Y_ENFORCE_ALL +} + +export const MIN_MEANINGFUL_ELEMENTS = 20 + +export function scanLooksEmpty( + result: A11yScanResult, + minElements: number = MIN_MEANINGFUL_ELEMENTS +): boolean { + return result.elementCount < minElements +} + +export function blockingViolations(result: A11yScanResult): Result[] { + if (shouldEnforceAll()) return result.violations + return result.violations.filter((violation) => ENFORCED_RULES.includes(violation.id)) +} diff --git a/e2e/docs/utils/failure-sequences.test.ts b/e2e/docs/utils/failure-sequences.test.ts new file mode 100644 index 00000000000..05891a14ae7 --- /dev/null +++ b/e2e/docs/utils/failure-sequences.test.ts @@ -0,0 +1,343 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import type { Suite, TestCase } from '@playwright/test/reporter' + +import A11yFailuresReporter from './a11y-failures-reporter.ts' +import { + EVERY_TEST_TIMED_OUT, + baselineFor, + compareFailures, + failuresFromJobs, + failuresFromVitest, + nextLastChecked, + stateFromPassingRun, + type ActionsJob, + type FailureState, + type OpenFailure, + type RunFailures, + type RunRef, +} from './open-failures.ts' + +// Runs every short sequence of run outcomes through the same steps as docs-alert.ts, and checks +// the result against a model that records, for each failure, what every run observed. + +type Observation = 'pass' | 'fail' | 'unchecked' + +type Outcome = { + name: string + results: () => RunFailures + observed: Record +} + +const runRef = (runNumber: number): RunRef => ({ + id: runNumber, + attempt: 1, + runNumber, + headSha: `sha${runNumber}`, + startedAt: new Date(Date.UTC(2026, 11, 1, runNumber)).toISOString(), +}) + +function* sequences(alphabet: T[], length: number): Generator { + if (length === 0) return yield [] + for (const rest of sequences(alphabet, length - 1)) { + for (const item of alphabet) yield [...rest, item] + } +} + +// With a saved list, run 0 stands for a run that checked every key and found nothing. With +// coldStart, there's no saved list, and run 0 is a passing run the alert reads from the API. +function checkSequence(outcomes: Outcome[], keys: string[], coldStart?: Outcome) { + const label = [coldStart && `cold start after ${coldStart.name}`, ...outcomes.map((o) => o.name)] + .filter(Boolean) + .join(' → ') + const start = runRef(0) + let state: FailureState = coldStart + ? stateFromPassingRun(start, coldStart.results().unchecked) + : { version: 1, lastRun: start, open: [], lastChecked: {} } + const history: Record[] = [ + coldStart?.observed ?? Object.fromEntries(keys.map((key) => [key, 'pass'])), + ] + + outcomes.forEach((outcome, index) => { + const run = runRef(index + 1) + const current = outcome.results() + const { added, stillOpen, fixed } = compareFailures(state.open, current) + history.push(outcome.observed) + + const lastObserved = (key: string, before: number) => { + for (let n = before; n >= 0; n--) { + if (history[n][key] !== 'unchecked') return { run: n, observation: history[n][key] } + } + return null + } + + const expectedOpen = keys.filter((key) => lastObserved(key, index + 1)?.observation === 'fail') + const open: OpenFailure[] = [ + ...stillOpen, + ...added.map((failure) => ({ + ...failure, + firstSeen: run.startedAt, + attribution: { kind: 'preexisting' as const }, + })), + ] + assert.deepEqual( + open.map((failure) => failure.key).sort(), + expectedOpen.sort(), + `open list after ${label}, run ${index + 1}` + ) + + for (const failure of fixed) { + assert.equal(outcome.observed[failure.key], 'pass', `fixed ${failure.key} in ${label}`) + } + + for (const failure of added) { + const baseline = baselineFor(failure, state) + const expected = lastObserved(failure.key, index) + if (expected) assert.equal(expected.observation, 'pass', `${failure.key} open in ${label}`) + assert.equal( + baseline?.runNumber ?? null, + expected?.run ?? null, + `baseline for ${failure.key} at run ${index + 1} of ${label}` + ) + } + + state = { + version: 1, + lastRun: run, + open, + lastChecked: nextLastChecked(state.lastChecked, current.unchecked, state.lastRun), + } + }) +} + +const UPLOAD = 'publish › Upload' +const BUILD = 'publish › Build' +const JOB_KEYS = [UPLOAD, BUILD, 'publish'] + +type StepConclusion = 'success' | 'failure' | 'skipped' | 'cancelled' | null + +function jobOutcome( + name: string, + steps: [StepConclusion, StepConclusion] | 'skipped' | 'empty', + jobConclusion?: string +) { + let jobs: ActionsJob[] + let observed: Record + if (steps === 'skipped' || steps === 'empty') { + const listed = steps === 'skipped' + const failed = jobConclusion === 'failure' + jobs = [ + { + name: 'publish', + conclusion: failed ? 'failure' : 'skipped', + steps: listed + ? [ + { name: 'Upload', conclusion: 'skipped' }, + { name: 'Build', conclusion: 'skipped' }, + ] + : [], + }, + ] + observed = { + [UPLOAD]: 'unchecked', + [BUILD]: 'unchecked', + publish: failed ? 'fail' : 'unchecked', + } + } else { + const [upload, build] = steps + const conclusion = jobConclusion ?? (steps.includes('failure') ? 'failure' : 'success') + jobs = [ + { + name: 'publish', + conclusion, + steps: [ + { name: 'Upload', conclusion: upload }, + { name: 'Build', conclusion: build }, + ], + }, + ] + const step = (result: StepConclusion): Observation => + result === 'failure' ? 'fail' : result === 'success' ? 'pass' : 'unchecked' + // The job itself fails only when it failed with no failing step + const jobFailed = conclusion !== 'success' && !steps.includes('failure') + observed = { + [UPLOAD]: step(upload), + [BUILD]: step(build), + publish: jobFailed ? 'fail' : 'pass', + } + } + return { name, results: () => failuresFromJobs(jobs), observed } +} + +const JOB_OUTCOMES: Outcome[] = [ + jobOutcome('job skipped, no steps', 'empty'), + jobOutcome('job failed, no steps', 'empty', 'failure'), + jobOutcome('job skipped', 'skipped'), + jobOutcome('pass', ['success', 'success']), + jobOutcome('upload fails', ['failure', 'skipped']), + jobOutcome('build fails', ['success', 'failure']), + jobOutcome('upload skipped', ['skipped', 'success']), + jobOutcome('build skipped', ['success', 'skipped']), + jobOutcome('upload skipped, build fails', ['skipped', 'failure']), + jobOutcome('job timed out during build', ['success', 'cancelled'], 'timed_out'), + jobOutcome('build never reported', ['success', null], 'failure'), +] + +test('tracks job and step failures across every sequence of four runs', () => { + for (const sequence of sequences(JOB_OUTCOMES, 4)) checkSequence(sequence, JOB_KEYS) +}) + +test('starts from a passing run when there is no saved list', () => { + const passing = JOB_OUTCOMES.filter((outcome) => outcome.results().failures.length === 0) + for (const start of passing) { + for (const sequence of sequences(JOB_OUTCOMES, 3)) checkSequence(sequence, JOB_KEYS, start) + } +}) + +const FILE = 'apps/docs/app/api/graphql/tests/schema.smoke.test.ts' +const SCHEMA = `${FILE} › prod smoke test schema` +const SEARCH = `${FILE} › prod smoke test search` +const FAILED_TO_RUN = `${FILE}: failed to run` +const SMOKE_KEYS = [SCHEMA, SEARCH, FAILED_TO_RUN, EVERY_TEST_TIMED_OUT] + +type TestStatus = 'passed' | 'failed' | 'timed out' | 'skipped' + +function smokeOutcome(name: string, tests: [TestStatus, TestStatus] | 'failed to load'): Outcome { + const loads = tests !== 'failed to load' + const statuses: TestStatus[] = loads ? tests : [] + const assertionResults = statuses.map((status, index) => ({ + fullName: ['prod smoke test schema', 'prod smoke test search'][index], + status: status === 'timed out' ? 'failed' : status, + failureMessages: + status === 'timed out' ? ['Test timed out in 5000ms.'] : status === 'failed' ? ['500'] : [], + })) + const report = { + testResults: [ + { + name: `/home/runner/work/supabase/supabase/${FILE}`, + status: + statuses.includes('failed') || statuses.includes('timed out') || !loads + ? 'failed' + : 'passed', + assertionResults, + }, + ], + } + const test = (status: TestStatus | undefined): Observation => + status === 'passed' ? 'pass' : status === 'failed' ? 'fail' : 'unchecked' + const passed = statuses.filter((status) => status === 'passed').length + const timedOut = statuses.filter((status) => status === 'timed out').length + return { + name, + results: () => failuresFromVitest(report) as RunFailures, + observed: { + [SCHEMA]: test(statuses[0]), + [SEARCH]: test(statuses[1]), + [FAILED_TO_RUN]: loads ? 'pass' : 'fail', + [EVERY_TEST_TIMED_OUT]: passed === 0 && timedOut > 0 ? 'fail' : 'pass', + }, + } +} + +const SMOKE_OUTCOMES: Outcome[] = [ + smokeOutcome('pass', ['passed', 'passed']), + smokeOutcome('schema fails', ['failed', 'passed']), + smokeOutcome('schema times out', ['timed out', 'passed']), + smokeOutcome('schema skipped', ['skipped', 'passed']), + smokeOutcome('every test times out', ['timed out', 'timed out']), + smokeOutcome('schema fails, search times out', ['failed', 'timed out']), + smokeOutcome('file fails to load', 'failed to load'), +] + +test('tracks smoke tests and their file across every sequence of four runs', () => { + for (const sequence of sequences(SMOKE_OUTCOMES, 4)) checkSequence(sequence, SMOKE_KEYS) +}) + +const PAGE = '/docs/guides/a' +const NOT_FOUND = `${PAGE}: http-404` +const UNAVAILABLE = `${PAGE}: http-503` +const HEADING = `${PAGE}: heading-order` +const PAGE_KEYS = [NOT_FOUND, UNAVAILABLE, HEADING] +const outputDir = mkdtempSync(join(tmpdir(), 'failure-sequences-')) +const outputFile = join(outputDir, 'failures.json') +test.after(() => rmSync(outputDir, { recursive: true, force: true })) + +type Scan = { loaded: boolean; status: number | null; elementCount: number; violations: object[] } + +function scanOutcome( + name: string, + scan: Scan | null, + outcome: string, + observed: Record +): Outcome { + const testCase = { + title: `${PAGE} a11y`, + tags: ['@a11y'], + outcome: () => outcome, + results: [ + { + attachments: scan + ? [{ name: 'axe-results.json', body: Buffer.from(JSON.stringify(scan)) }] + : [], + }, + ], + } as unknown as TestCase + const results = () => { + const reporter = new A11yFailuresReporter({ outputFile }) + reporter.onBegin({} as never, { allTests: () => [testCase] } as unknown as Suite) + reporter.onEnd() + return JSON.parse(readFileSync(outputFile, 'utf8')) as RunFailures + } + return { name, results, observed } +} + +const errorPage = (status: number): Scan => ({ + loaded: false, + status, + elementCount: 0, + violations: [], +}) +const scanned = (violations: object[], elementCount = 50): Scan => ({ + loaded: true, + status: 200, + elementCount, + violations, +}) +const status = (code: number | null): Record => ({ + [NOT_FOUND]: code === null ? 'unchecked' : code === 404 ? 'fail' : 'pass', + [UNAVAILABLE]: code === null ? 'unchecked' : code === 503 ? 'fail' : 'pass', +}) + +const SCAN_OUTCOMES: Outcome[] = [ + scanOutcome('no response', { ...errorPage(0), status: null }, 'unexpected', { + ...status(null), + [HEADING]: 'unchecked', + }), + scanOutcome('timed out mid-scan', null, 'timedOut', { + ...status(null), + [HEADING]: 'unchecked', + }), + scanOutcome('404', errorPage(404), 'unexpected', { ...status(404), [HEADING]: 'unchecked' }), + scanOutcome('503', errorPage(503), 'unexpected', { ...status(503), [HEADING]: 'unchecked' }), + scanOutcome('clean', scanned([]), 'expected', { ...status(200), [HEADING]: 'pass' }), + scanOutcome('heading-order', scanned([{ id: 'heading-order' }]), 'unexpected', { + ...status(200), + [HEADING]: 'fail', + }), + scanOutcome('empty scan', scanned([], 5), 'expected', { + ...status(200), + [HEADING]: 'unchecked', + }), + scanOutcome('skipped', null, 'skipped', { ...status(null), [HEADING]: 'unchecked' }), + scanOutcome('failed with no blocking rule', scanned([{ id: 'region' }]), 'unexpected', { + ...status(200), + [HEADING]: 'unchecked', + }), +] + +test('tracks a page status and its axe rules across every sequence of four runs', () => { + for (const sequence of sequences(SCAN_OUTCOMES, 4)) checkSequence(sequence, PAGE_KEYS) +}) diff --git a/e2e/docs/utils/open-failures.test.ts b/e2e/docs/utils/open-failures.test.ts new file mode 100644 index 00000000000..d1fc2878065 --- /dev/null +++ b/e2e/docs/utils/open-failures.test.ts @@ -0,0 +1,470 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { + EVERY_TEST_TIMED_OUT, + attribute, + baselineFor, + compareFailures, + deployedCommitsBetween, + failuresFromJobs, + failuresFromVitest, + formatAlert, + formatCrashAlert, + nextLastChecked, + parseFailureState, + parseRunFailures, + pickDeployedHead, + pushCandidates, + type FailureState, + type HistoryCommit, + type OpenFailure, + type RunRef, +} from './open-failures.ts' + +const commit = (sha: string) => ({ sha, title: `commit ${sha}` }) + +const open = (key: string, page?: string): OpenFailure => ({ + key, + page, + firstSeen: '2026-12-01T05:17:00Z', + attribution: { kind: 'introduced', commit: commit('aaaaaaa') }, +}) + +test('adds a second failure to a workflow that is already failing, and keeps the first', () => { + const first = open('/docs/guides/a: heading-order', '/docs/guides/a') + const result = compareFailures([first], { + failures: [ + { key: '/docs/guides/a: heading-order', page: '/docs/guides/a' }, + { key: '/docs/guides/b: duplicate-id', page: '/docs/guides/b' }, + ], + unchecked: [], + }) + + assert.deepEqual( + result.added.map((failure) => failure.key), + ['/docs/guides/b: duplicate-id'] + ) + assert.deepEqual(result.stillOpen, [first]) + assert.deepEqual(result.fixed, []) +}) + +test('drops a failure that no longer fails', () => { + const first = open('docs › Sync') + const result = compareFailures([first], { failures: [], unchecked: [] }) + + assert.deepEqual(result.fixed, [first]) + assert.deepEqual(result.stillOpen, []) +}) + +test('keeps a failure open when its page timed out instead of passing', () => { + const first = open('/docs/guides/a: heading-order', '/docs/guides/a') + const result = compareFailures([first], { failures: [], unchecked: ['/docs/guides/a'] }) + + assert.deepEqual(result.stillOpen, [first]) + assert.deepEqual(result.fixed, []) + assert.deepEqual(result.added, []) +}) + +test('names the one commit when the range has one', () => { + assert.deepEqual(attribute([commit('1111111')], null), { + kind: 'introduced', + commit: commit('1111111'), + }) +}) + +test('lists every commit as unconfirmed when the range has several and nothing narrows it', () => { + const result = attribute([commit('1'), commit('2')], null) + assert.equal(result.kind, 'unconfirmed') + assert.equal(result.kind === 'unconfirmed' && result.total, 2) +}) + +test('counts the whole range when only its newest commits were fetched', () => { + const result = attribute([commit('3'), commit('4')], null, 300) + assert.equal(result.kind === 'unconfirmed' && result.total, 300) +}) + +test('names the one commit that touched the failing page', () => { + const range = [commit('1'), commit('2'), commit('3')] + assert.deepEqual(attribute(range, [commit('2')]), { kind: 'introduced', commit: commit('2') }) +}) + +test('falls back to the whole range when no commit touched the failing page', () => { + const range = [commit('1'), commit('2')] + const result = attribute(range, []) + assert.equal(result.kind, 'unconfirmed') + assert.deepEqual(result.kind === 'unconfirmed' && result.commits, range) + assert.equal(result.kind === 'unconfirmed' && result.reason, 'no commit touched this page') +}) + +test('says there is no commit when the range is empty', () => { + assert.equal(attribute([], null).kind, 'none') +}) + +const built = (sha: string, createdAt: string): HistoryCommit => ({ + ...commit(sha), + status: { state: 'SUCCESS', description: 'Deployment has completed', createdAt }, +}) +const skipped = (sha: string, createdAt: string): HistoryCommit => ({ + ...commit(sha), + status: { state: 'SUCCESS', description: 'Skipped - Not affected', createdAt }, +}) +const pending = (sha: string): HistoryCommit => ({ + ...commit(sha), + status: { state: 'PENDING', description: 'Vercel is deploying your app', createdAt: 'z' }, +}) + +test('picks the newest build that finished before the run', () => { + const history = [ + built('c', '2026-12-02T06:00:00Z'), + built('b', '2026-12-02T04:00:00Z'), + built('a', '2026-12-01T00:00:00Z'), + ] + assert.equal(pickDeployedHead(history, '2026-12-02T05:17:00Z'), 'b') +}) + +test('counts skipped builds after a finished build as deployed', () => { + const history = [skipped('c', '2026-12-02T03:00:00Z'), built('b', '2026-12-02T02:00:00Z')] + assert.equal(pickDeployedHead(history, '2026-12-02T05:17:00Z'), 'c') +}) + +test('stops at a build that had not finished, even if a later build was skipped', () => { + const history = [ + skipped('c', '2026-12-02T03:00:00Z'), + pending('b'), + built('a', '2026-12-02T01:00:00Z'), + ] + assert.equal(pickDeployedHead(history, '2026-12-02T05:17:00Z'), 'a') +}) + +test('lists the built commits that reached production between two runs', () => { + const history = [ + built('e', '2026-12-02T06:00:00Z'), + built('d', '2026-12-02T04:00:00Z'), + skipped('c', '2026-12-02T03:00:00Z'), + built('b', '2026-12-02T02:00:00Z'), + built('a', '2026-12-01T04:00:00Z'), + ] + const range = deployedCommitsBetween(history, '2026-12-01T05:17:00Z', '2026-12-02T05:17:00Z') + assert.deepEqual( + range?.map((item) => item.sha), + ['b', 'd'] + ) +}) + +test('returns null when the earlier deploy is outside the history', () => { + const history = [built('b', '2026-12-02T02:00:00Z')] + assert.equal( + deployedCommitsBetween(history, '2026-12-01T05:17:00Z', '2026-12-02T05:17:00Z'), + null + ) +}) + +test('reads failed jobs and steps from the Actions API', () => { + const result = failuresFromJobs([ + { name: 'build', conclusion: 'success', steps: [] }, + { + name: 'sync', + conclusion: 'failure', + steps: [ + { name: 'Checkout', conclusion: 'success' }, + { name: 'Sync docs', conclusion: 'failure' }, + ], + }, + { name: 'setup', conclusion: 'failure', steps: [] }, + ]) + assert.deepEqual( + result.failures.map((failure) => failure.key), + ['sync › Sync docs', 'setup'] + ) +}) + +test('lists steps and jobs that never ran as unchecked', () => { + const result = failuresFromJobs([ + { + name: 'update', + conclusion: 'failure', + steps: [ + { name: 'Install deps', conclusion: 'failure' }, + { name: 'Refresh Management API docs', conclusion: 'skipped' }, + ], + }, + { name: 'publish', conclusion: 'skipped', steps: [] }, + ]) + assert.deepEqual( + result.failures.map((failure) => failure.key), + ['update › Install deps'] + ) + assert.deepEqual(result.unchecked, ['update › Refresh Management API docs', 'publish']) +}) + +test('retires an old error status when the page returns a new one, and keeps its axe failures', () => { + const page = '/docs/guides/a' + const notFound = open(`${page}: http-404`, page) + const headingOrder = open(`${page}: heading-order`, page) + const result = compareFailures([notFound, headingOrder], { + failures: [{ key: `${page}: http-503`, page }], + unchecked: [page], + }) + assert.deepEqual(result.fixed, [notFound]) + assert.deepEqual(result.stillOpen, [headingOrder]) +}) + +test('keeps an error status open when the page timed out', () => { + const page = '/docs/guides/a' + const notFound = open(`${page}: http-404`, page) + const result = compareFailures([notFound], { + failures: [], + unchecked: [`${page}: http`, page], + }) + assert.deepEqual(result.stillOpen, [notFound]) +}) + +test('keeps a step failure open when its whole job was skipped', () => { + const step = open('publish › Upload') + const result = compareFailures([step], { failures: [], unchecked: ['publish'] }) + assert.deepEqual(result.stillOpen, [step]) + assert.deepEqual(result.fixed, []) +}) + +test('measures a step failure from the last run that ran its job', () => { + const ran = runRef(1) + const skippedJob = runRef(2) + const state: FailureState = { + version: 1, + lastRun: skippedJob, + open: [], + lastChecked: nextLastChecked({}, ['publish'], ran), + } + assert.equal(baselineFor({ key: 'publish › Upload' }, state), ran) + assert.equal(baselineFor({ key: 'build › Upload' }, state), skippedJob) +}) + +test('keeps a step baseline when its job is skipped after the step was', () => { + const [r1, r2, r3] = [runRef(1), runRef(2), runRef(3)] + const afterStepSkipped = nextLastChecked({}, ['publish › Upload'], r1) + const afterJobSkipped = nextLastChecked(afterStepSkipped, ['publish'], r2) + const state: FailureState = { version: 1, lastRun: r3, open: [], lastChecked: afterJobSkipped } + assert.equal(baselineFor({ key: 'publish › Upload' }, state), r1) +}) + +test('takes the job baseline when a step is skipped after its job was', () => { + const [r1, r2, r3] = [runRef(1), runRef(2), runRef(3)] + const afterJobSkipped = nextLastChecked({}, ['publish'], r1) + const afterStepSkipped = nextLastChecked(afterJobSkipped, ['publish › Upload'], r2) + const state: FailureState = { version: 1, lastRun: r3, open: [], lastChecked: afterStepSkipped } + assert.equal(baselineFor({ key: 'publish › Upload' }, state), r1) +}) + +test('counts a smoke run where no test passed and some timed out as one failure', () => { + const result = failuresFromVitest({ + testResults: [ + { + assertionResults: [ + { + fullName: 'prod smoke test crawlers', + status: 'failed', + failureMessages: ['Test timed out in 5000ms.'], + }, + { + fullName: 'prod smoke test search', + status: 'failed', + failureMessages: ['Test timed out in 5000ms.'], + }, + ], + }, + ], + }) + assert.deepEqual(result?.failures, [{ key: EVERY_TEST_TIMED_OUT }]) + assert.deepEqual(result?.unchecked, [ + 'test file › prod smoke test crawlers', + 'test file › prod smoke test search', + ]) +}) + +test('treats a timed-out smoke test as unchecked, not failed', () => { + const result = failuresFromVitest({ + testResults: [ + { + assertionResults: [ + { + fullName: 'prod smoke test graphql', + status: 'failed', + failureMessages: ['expected 200'], + }, + { + fullName: 'prod smoke test crawlers', + status: 'failed', + failureMessages: ['Test timed out in 5000ms.'], + }, + { + fullName: 'prod smoke test skills', + status: 'failed', + failureMessages: ['TimeoutError: The operation was aborted due to timeout'], + }, + { fullName: 'prod smoke test search', status: 'passed' }, + ], + }, + ], + }) + assert.deepEqual(result?.failures, [{ key: 'test file › prod smoke test graphql' }]) + assert.deepEqual(result?.unchecked, [ + 'test file › prod smoke test crawlers', + 'test file › prod smoke test skills', + ]) +}) + +test('counts a smoke test file that failed to run as a failure', () => { + const result = failuresFromVitest({ + testResults: [ + { + name: '/home/runner/work/supabase/supabase/apps/docs/app/api/crawlers/route.smoke.test.ts', + status: 'failed', + message: 'Failed to load url', + assertionResults: [], + }, + ], + }) + assert.deepEqual(result?.failures, [ + { key: 'apps/docs/app/api/crawlers/route.smoke.test.ts: failed to run' }, + ]) + assert.deepEqual(result?.unchecked, ['apps/docs/app/api/crawlers/route.smoke.test.ts']) +}) + +test('rejects a results file that is not a Vitest report', () => { + assert.equal(failuresFromVitest({ failures: [] }), null) + // What Vitest writes when global setup crashes or no test file matches + assert.equal(failuresFromVitest({ success: false, testResults: [] }), null) + assert.equal(parseRunFailures({ failures: [{ page: 'no key' }], unchecked: [] }), null) +}) + +test('lists new failures first and marks fixed ones', () => { + const kept = open('/docs/guides/a: heading-order') + const added = { ...open('/docs/guides/b: duplicate-id'), firstSeen: '2026-12-02T05:17:00Z' } + const fixed = open('/docs/guides/c: button-name') + const message = formatAlert( + { + workflowName: 'Docs Accessibility Scan', + runUrl: 'https://example.com/run', + runLabel: 'scheduled run', + repoUrl: 'https://github.com/supabase/supabase', + }, + [kept, added], + new Set([added.key]), + [fixed] + ) + const body = message.blocks + .filter((block) => block.type === 'section') + .map((block) => (block as { text: { text: string } }).text.text) + .join('\n') + .split('\n') + + assert.equal(message.text, ':rotating_light: Docs Accessibility Scan: 2 open failures') + assert.match(body[0], /^:new: `\/docs\/guides\/b: duplicate-id`: introduced by/) + assert.match(body[1], /^• `\/docs\/guides\/a: heading-order`: .*first seen Dec 1$/) + assert.equal(body[2], ':white_check_mark: fixed: `/docs/guides/c: button-name`') +}) + +const runRef = (runNumber: number, startedAt = '2026-12-01T05:17:00Z'): RunRef => ({ + id: runNumber, + attempt: 1, + runNumber, + headSha: `sha${runNumber}`, + startedAt, +}) + +test('loads a saved list only when it has the current shape', () => { + const state: FailureState = { + version: 1, + lastRun: runRef(1), + open: [open('docs › Sync')], + lastChecked: {}, + } + const saved = JSON.parse(JSON.stringify(state)) + assert.deepEqual(parseFailureState(saved), saved) + assert.equal(parseFailureState({ ...state, version: 2 }), null) + assert.equal(parseFailureState({ ...state, lastRun: { runNumber: 'high' } }), null) + assert.equal( + parseFailureState({ + ...state, + open: [{ key: 'x', firstSeen: 'y', attribution: { kind: 'blame' } }], + }), + null + ) +}) + +test('measures a new failure from the last run that checked its page', () => { + const checked = runRef(1) + const timedOut = runRef(2) + const lastChecked = nextLastChecked({}, ['/docs/guides/a'], checked) + const afterSecondTimeout = nextLastChecked(lastChecked, ['/docs/guides/a'], timedOut) + const state: FailureState = { + version: 1, + lastRun: timedOut, + open: [], + lastChecked: afterSecondTimeout, + } + + assert.equal( + baselineFor({ key: '/docs/guides/a: heading-order', page: '/docs/guides/a' }, state), + checked + ) + assert.equal( + baselineFor({ key: '/docs/guides/b: heading-order', page: '/docs/guides/b' }, state), + timedOut + ) + assert.deepEqual(nextLastChecked(afterSecondTimeout, [], timedOut), {}) +}) + +const push = (run_number: number, conclusion: string | null) => ({ + run_number, + conclusion, + head_sha: `sha${run_number}`, + head_commit: { message: `commit ${run_number}\n\nbody` }, +}) + +test('names only the failing push when no run since the baseline went unprocessed', () => { + const result = pushCandidates([push(12, 'failure')], 11, push(12, 'failure')) + assert.deepEqual(result, [{ sha: 'sha12', title: 'commit 12' }]) +}) + +test('includes every push run since the baseline whose alert never ran, even one that passed', () => { + const runs = [ + push(14, 'failure'), + push(13, 'cancelled'), + push(12, 'success'), + push(11, 'failure'), + ] + const result = pushCandidates(runs, 10, push(15, 'failure')) + assert.deepEqual( + result.map((commit) => commit.sha), + ['sha11', 'sha12', 'sha13', 'sha14', 'sha15'] + ) +}) + +test('escapes the workflow name in the crash alert', () => { + const message = formatCrashAlert({ + workflowName: 'Docs ', + runUrl: 'https://example.com/run', + runLabel: 'scheduled run', + repoUrl: 'https://github.com/supabase/supabase', + }) + const section = message.blocks.find((block) => block.type === 'section') as { + text: { text: string } + } + assert.match(section.text.text, /^\*Docs <scan>\* failed before it reported any results/) +}) + +test('keeps a page that no run has checked without a baseline', () => { + const firstRun = runRef(1) + const afterFirst = nextLastChecked({}, ['/docs/guides/a'], null) + const afterSecond = nextLastChecked(afterFirst, ['/docs/guides/a'], firstRun) + const state: FailureState = { version: 1, lastRun: runRef(2), open: [], lastChecked: afterSecond } + + assert.deepEqual(afterSecond, { '/docs/guides/a': null }) + assert.equal( + baselineFor({ key: '/docs/guides/a: heading-order', page: '/docs/guides/a' }, state), + null + ) + assert.ok(parseFailureState(state)) +}) diff --git a/e2e/docs/utils/open-failures.ts b/e2e/docs/utils/open-failures.ts new file mode 100644 index 00000000000..a96185e6d35 --- /dev/null +++ b/e2e/docs/utils/open-failures.ts @@ -0,0 +1,497 @@ +export type Commit = { sha: string; title: string } + +export type Attribution = + | { kind: 'introduced'; commit: Commit } + | { kind: 'unconfirmed'; commits: Commit[]; total: number; reason: string } + | { kind: 'none'; reason: string } + | { kind: 'preexisting' } + +export type Failure = { key: string; page?: string } + +export type OpenFailure = Failure & { firstSeen: string; attribution: Attribution } + +export type RunRef = { + id: number + attempt: number + runNumber: number + headSha: string + startedAt: string +} + +export type FailureState = { + version: 1 + lastRun: RunRef + open: OpenFailure[] + // for pages or tests that went unchecked, the last run that did check them, or null if none did + lastChecked: Record +} + +export type RunFailures = { + failures: Failure[] + // keys this run couldn't check, such as a page that timed out or a skipped step, so they keep + // their earlier result + unchecked: string[] +} + +export type CommitStatus = { state: string; description: string | null; createdAt: string } + +export type HistoryCommit = Commit & { status: CommitStatus | null } + +export type ActionsJob = { + name: string + conclusion: string | null + steps?: { name: string; conclusion: string | null }[] +} + +export type ActionsRun = { + run_number: number + conclusion: string | null + head_sha: string + head_commit?: { message: string } | null +} + +const MAX_LISTED_COMMITS = 10 +const TIMEOUT_PATTERN = /timed out|aborted due to timeout|TimeoutError/i +export const EVERY_TEST_TIMED_OUT = 'every test timed out' + +const isObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value) + +const isString = (value: unknown): value is string => typeof value === 'string' + +function isRunRef(value: unknown): value is RunRef { + return ( + isObject(value) && + typeof value.id === 'number' && + typeof value.attempt === 'number' && + typeof value.runNumber === 'number' && + isString(value.headSha) && + isString(value.startedAt) + ) +} + +function isCommit(value: unknown): value is Commit { + return isObject(value) && isString(value.sha) && isString(value.title) +} + +function isAttribution(value: unknown): value is Attribution { + if (!isObject(value)) return false + switch (value.kind) { + case 'introduced': + return isCommit(value.commit) + case 'unconfirmed': + return ( + Array.isArray(value.commits) && + value.commits.every(isCommit) && + typeof value.total === 'number' && + isString(value.reason) + ) + case 'none': + return isString(value.reason) + case 'preexisting': + return true + default: + return false + } +} + +function isFailure(value: unknown): value is Failure { + return ( + isObject(value) && isString(value.key) && (value.page === undefined || isString(value.page)) + ) +} + +// The saved list comes from an artifact, so anything that isn't the current shape counts as no list +export function parseFailureState(value: unknown): FailureState | null { + if (!isObject(value) || value.version !== 1 || !isRunRef(value.lastRun)) return null + if (!Array.isArray(value.open) || !isObject(value.lastChecked)) return null + const openValid = value.open.every( + (failure) => + isFailure(failure) && + isString((failure as Record).firstSeen) && + isAttribution((failure as Record).attribution) + ) + const checkedValid = Object.values(value.lastChecked).every( + (run) => run === null || isRunRef(run) + ) + if (!openValid || !checkedValid) return null + return value as FailureState +} + +export function parseRunFailures(value: unknown): RunFailures | null { + if (!isObject(value) || !Array.isArray(value.failures) || !Array.isArray(value.unchecked)) { + return null + } + if (!value.failures.every(isFailure) || !value.unchecked.every(isString)) return null + return { failures: value.failures, unchecked: value.unchecked } +} + +export function compareFailures( + previous: OpenFailure[], + current: RunFailures +): { added: Failure[]; stillOpen: OpenFailure[]; fixed: OpenFailure[] } { + const currentKeys = new Set(current.failures.map((failure) => failure.key)) + const unchecked = new Set(current.unchecked) + const previousKeys = new Set(previous.map((failure) => failure.key)) + + const stillOpen: OpenFailure[] = [] + const fixed: OpenFailure[] = [] + for (const failure of previous) { + const carried = checkKeys(failure).some((key) => unchecked.has(key)) + if (currentKeys.has(failure.key) || carried) stillOpen.push(failure) + else fixed.push(failure) + } + + const added = current.failures.filter((failure) => !previousKeys.has(failure.key)) + return { added, stillOpen, fixed } +} + +const PARENT_SEPARATOR = ' › ' + +// A page's status is checked apart from its axe rules, since an error page has a status but no scan +export function statusCheckKey(page: string): string { + return `${page}: http` +} + +export function httpFailureKey(page: string, status: number): string { + return `${page}: http-${status}` +} + +// A step's parent is its job, and a smoke test's parent is its file +function parentOf(key: string): string | null { + const [parent] = key.split(PARENT_SEPARATOR) + return parent === key ? null : parent +} + +// The names a run uses when it can't check a failure: the page's status or scan, the test, or the +// step. A child is also unchecked when its parent is, since a skipped job or a test file that +// fails to load lists no children. +function checkKeys(failure: Failure): string[] { + const { key, page } = failure + if (page) return [key.startsWith(`${page}: http-`) ? statusCheckKey(page) : page] + const parent = parentOf(key) + return parent ? [key, parent] : [key] +} + +export function nextLastChecked( + previous: Record, + unchecked: string[], + lastRun: RunRef | null +): Record { + const skipped = new Set(unchecked) + const next: Record = {} + for (const key of unchecked) { + const parent = parentOf(key) + if (key in previous) next[key] = previous[key] + else if (parent !== null && parent in previous) next[key] = previous[parent] + else next[key] = lastRun + } + // A child keeps its own baseline while its parent is unchecked + for (const [key, run] of Object.entries(previous)) { + const parent = parentOf(key) + if (parent !== null && skipped.has(parent) && !(key in next)) next[key] = run + } + return next +} + +// The last run that checked this failure and didn't find it, or null when no run has checked it +export function baselineFor(failure: Failure, state: FailureState): RunRef | null { + const key = checkKeys(failure).find((key) => key in state.lastChecked) + return key === undefined ? state.lastRun : state.lastChecked[key] +} + +// total is the size of the range when only its newest commits were fetched +export function attribute( + range: Commit[], + matching: Commit[] | null, + total = range.length +): Attribution { + if (range.length === 0) { + return { kind: 'none', reason: 'no new commits since the last run without this failure' } + } + if (matching === null) { + if (range.length === 1) return { kind: 'introduced', commit: range[0] } + return unconfirmed(range, 'more than one commit since the last run without this failure', total) + } + if (matching.length === 1) return { kind: 'introduced', commit: matching[0] } + if (matching.length > 1) return unconfirmed(matching, 'more than one commit touched this page') + return unconfirmed(range, 'no commit touched this page') +} + +function unconfirmed(commits: Commit[], reason: string, total = commits.length): Attribution { + return { + kind: 'unconfirmed', + commits: commits.slice(-MAX_LISTED_COMMITS), + total, + reason, + } +} + +export function titleOf(message: string): string { + return message.split('\n')[0] +} + +// The push runs after the baseline that could have introduced a failure, including runs whose +// alert never ran because it was cancelled or dropped. A run between them that passed still counts, +// since it may have skipped the failing step. +export function pushCandidates( + runs: ActionsRun[], + baselineRunNumber: number, + current: ActionsRun +): Commit[] { + const between = runs + .filter((run) => run.run_number > baselineRunNumber && run.run_number < current.run_number) + .sort((a, b) => a.run_number - b.run_number) + + const commits = new Map() + for (const run of [...between, current]) { + commits.set(run.head_sha, { sha: run.head_sha, title: titleOf(run.head_commit?.message ?? '') }) + } + return [...commits.values()] +} + +function isSkipped(status: CommitStatus | null): boolean { + return !!status?.description?.startsWith('Skipped') +} + +function readyBy(status: CommitStatus | null, at: string): boolean { + return status?.state === 'SUCCESS' && status.createdAt <= at +} + +// history is newest first, like `git log`. A skipped build leaves the docs unchanged, so a run of +// skipped commits right after a finished build counts as deployed too. +export function pickDeployedHead(history: HistoryCommit[], at: string): string | null { + let head: string | null = null + let extendable = false + for (const commit of [...history].reverse()) { + if (readyBy(commit.status, at) && !isSkipped(commit.status)) { + head = commit.sha + extendable = true + } else if (extendable && readyBy(commit.status, at) && isSkipped(commit.status)) { + head = commit.sha + } else { + extendable = false + } + } + return head +} + +// The commits that reached production between two times, leaving out builds Vercel skipped. +// Returns null when the earlier deploy is outside the history. +export function deployedCommitsBetween( + history: HistoryCommit[], + from: string, + to: string +): Commit[] | null { + const base = pickDeployedHead(history, from) + const head = pickDeployedHead(history, to) + if (!base || !head) return null + + const oldestFirst = [...history].reverse() + const baseIndex = oldestFirst.findIndex((commit) => commit.sha === base) + const headIndex = oldestFirst.findIndex((commit) => commit.sha === head) + return oldestFirst + .slice(baseIndex + 1, headIndex + 1) + .filter((commit) => !isSkipped(commit.status)) + .map(({ sha, title }) => ({ sha, title })) +} + +const FAILED = new Set(['failure', 'timed_out']) + +// A job or step ran only when it passed or failed. Any other conclusion, such as skipped after a +// failed step, cancelled, or null, leaves it unchecked. A job that lists no steps, even a failed +// one, is unchecked too, so its steps keep their earlier results. +export function failuresFromJobs(jobs: ActionsJob[]): RunFailures { + const failures: Failure[] = [] + const unchecked: string[] = [] + const notRun = (conclusion: string | null) => + conclusion !== 'success' && !FAILED.has(conclusion ?? '') + + for (const job of jobs) { + if (notRun(job.conclusion) || (job.steps ?? []).length === 0) unchecked.push(job.name) + for (const step of job.steps ?? []) { + if (notRun(step.conclusion)) unchecked.push(`${job.name}${PARENT_SEPARATOR}${step.name}`) + } + if (!FAILED.has(job.conclusion ?? '')) continue + const steps = (job.steps ?? []).filter((step) => FAILED.has(step.conclusion ?? '')) + if (steps.length === 0) failures.push({ key: job.name }) + for (const step of steps) failures.push({ key: `${job.name}${PARENT_SEPARATOR}${step.name}` }) + } + return { failures, unchecked } +} + +// Reads Vitest's JSON report, keying each test as ` › `. A test file that failed with no +// failing test, such as an import error, counts as one failure for the file and leaves its tests +// unchecked. A skipped test is unchecked. When no test passed and some timed out, production is +// likely down, so that counts as one failure too. A report with no test files, such as after global +// setup crashes, counts as no results. +export function failuresFromVitest(report: unknown): RunFailures | null { + if (!isObject(report) || !Array.isArray(report.testResults)) return null + if (report.testResults.length === 0) return null + + const failures: Failure[] = [] + const unchecked: string[] = [] + let passed = 0 + let timedOut = 0 + for (const file of report.testResults) { + if (!isObject(file)) return null + const name = isString(file.name) ? file.name.replace(/^.*?(apps\/docs\/)/, '$1') : 'test file' + const tests = (Array.isArray(file.assertionResults) ? file.assertionResults : []).filter( + (test): test is Record => isObject(test) && isString(test.fullName) + ) + let failed = 0 + for (const test of tests) { + const key = `${name}${PARENT_SEPARATOR}${test.fullName}` + if (test.status === 'passed') { + passed++ + continue + } + if (test.status !== 'failed') { + unchecked.push(key) + continue + } + failed++ + const messages = Array.isArray(test.failureMessages) ? test.failureMessages : [] + if (messages.some((message) => isString(message) && TIMEOUT_PATTERN.test(message))) { + timedOut++ + unchecked.push(key) + } else failures.push({ key }) + } + + if (file.status === 'failed' && failed === 0) { + failures.push({ key: `${name}: failed to run` }) + unchecked.push(name) + } + } + if (passed === 0 && timedOut > 0) failures.push({ key: EVERY_TEST_TIMED_OUT }) + return { failures, unchecked } +} + +// With no saved list, a run that passed says nothing was open, and that it checked everything it +// didn't skip +export function stateFromPassingRun(run: RunRef, unchecked: string[]): FailureState { + return { + version: 1, + lastRun: run, + open: [], + lastChecked: Object.fromEntries(unchecked.map((key) => [key, null])), + } +} + +function shortSha(sha: string): string { + return sha.slice(0, 7) +} + +export type AlertContext = { + workflowName: string + runUrl: string + runLabel: string + repoUrl: string +} + +const MAX_LINES = 40 +const MAX_SECTION_CHARS = 2900 +const MAX_HEADER_CHARS = 150 +const MAX_TITLE_CHARS = 72 + +function escapeMrkdwn(text: string): string { + return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>') +} + +function commitLink(repoUrl: string, commit: Commit): string { + const title = + commit.title.length > MAX_TITLE_CHARS + ? `${commit.title.slice(0, MAX_TITLE_CHARS - 1)}…` + : commit.title + return `<${repoUrl}/commit/${commit.sha}|\`${shortSha(commit.sha)}\`> ${escapeMrkdwn(title)}` +} + +function describeAttribution(repoUrl: string, attribution: Attribution): string { + switch (attribution.kind) { + case 'introduced': + return `introduced by ${commitLink(repoUrl, attribution.commit)}` + case 'unconfirmed': { + const links = attribution.commits.map( + (commit) => `<${repoUrl}/commit/${commit.sha}|\`${shortSha(commit.sha)}\`>` + ) + const more = attribution.total - attribution.commits.length + return `unconfirmed, ${attribution.reason}: ${links.join(', ')}${more > 0 ? ` and ${more} more` : ''}` + } + case 'none': + return `no commit to point to, ${attribution.reason}` + case 'preexisting': + return 'already failing when tracking started' + } +} + +function formatDay(iso: string): string { + return new Date(iso).toLocaleDateString('en-US', { + month: 'short', + day: 'numeric', + timeZone: 'UTC', + }) +} + +function message(context: AlertContext, title: string, sections: string[]) { + return { + text: title, + blocks: [ + { type: 'header', text: { type: 'plain_text', text: title.slice(0, MAX_HEADER_CHARS) } }, + ...sections.map((text) => ({ type: 'section', text: { type: 'mrkdwn', text } })), + { + type: 'context', + elements: [ + { type: 'mrkdwn', text: `<${context.runUrl}|View the run> (${context.runLabel})` }, + ], + }, + ], + } +} + +export function formatAlert( + context: AlertContext, + open: OpenFailure[], + addedKeys: Set, + fixed: OpenFailure[] +) { + const lines: string[] = [] + const ordered = [ + ...open.filter((failure) => addedKeys.has(failure.key)), + ...open.filter((failure) => !addedKeys.has(failure.key)), + ] + for (const failure of ordered) { + const isNew = addedKeys.has(failure.key) + const seen = isNew ? '' : `, first seen ${formatDay(failure.firstSeen)}` + lines.push( + `${isNew ? ':new: ' : '• '}\`${escapeMrkdwn(failure.key)}\`: ${describeAttribution(context.repoUrl, failure.attribution)}${seen}` + ) + } + for (const failure of fixed) { + lines.push(`:white_check_mark: fixed: \`${escapeMrkdwn(failure.key)}\``) + } + + const shown = lines.slice(0, MAX_LINES) + if (lines.length > shown.length) shown.push(`…and ${lines.length - shown.length} more.`) + + const sections: string[] = [] + for (const line of shown) { + const last = sections.at(-1) + if (last !== undefined && last.length + line.length + 1 <= MAX_SECTION_CHARS) { + sections[sections.length - 1] = `${last}\n${line}` + } else { + sections.push(line.slice(0, MAX_SECTION_CHARS)) + } + } + + const title = + open.length === 0 + ? `:white_check_mark: ${context.workflowName}: no open failures` + : `:rotating_light: ${context.workflowName}: ${open.length} open failure${open.length === 1 ? '' : 's'}` + return message(context, title, sections) +} + +export function formatCrashAlert(context: AlertContext) { + return message(context, `:rotating_light: ${context.workflowName} failed`, [ + `*${escapeMrkdwn(context.workflowName)}* failed before it reported any results, so the list of open failures didn't change.`, + ]) +} diff --git a/e2e/docs/utils/resolve-docs-scope.test.ts b/e2e/docs/utils/resolve-docs-scope.test.ts index 63ea897b18c..e779bbd49f3 100644 --- a/e2e/docs/utils/resolve-docs-scope.test.ts +++ b/e2e/docs/utils/resolve-docs-scope.test.ts @@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url' import { GUIDE_LIST_COMPONENT, GUIDE_LIST_COMPONENT_PAGES, + pageSourceFiles, resolveAllDocsPages, resolveDocsScope, } from './resolve-docs-scope.ts' @@ -92,3 +93,10 @@ test('keeps the pages a guide list component change requires alongside the chang [...GUIDE_LIST_COMPONENT_PAGES, '/docs/guides/ai-tools/mcp'].sort() ) }) + +test('lists a guide and the partials it includes', async () => { + const files = await pageSourceFiles(repoRoot, '/docs/guides/auth') + + assert.equal(files[0], 'apps/docs/content/guides/auth.mdx') + assert.ok(files.includes('apps/docs/content/_partials/providers.mdx')) +}) diff --git a/e2e/docs/utils/resolve-docs-scope.ts b/e2e/docs/utils/resolve-docs-scope.ts index 77444167039..2e24563937b 100644 --- a/e2e/docs/utils/resolve-docs-scope.ts +++ b/e2e/docs/utils/resolve-docs-scope.ts @@ -113,6 +113,11 @@ export function changedFileToPagePath(filePath: string): string | null { return null } +export function pagePathToGuideFile(pagePath: string): string | null { + if (!pagePath.startsWith(DOCS_GUIDES_URL_PREFIX)) return null + return `${GUIDES_PREFIX}${pagePath.slice(DOCS_GUIDES_URL_PREFIX.length)}.mdx` +} + function partialRelPathFromChangedFile(filePath: string): string | null { const normalized = normalizeRepoPath(filePath) if (!normalized.startsWith(PARTIALS_PREFIX) || !normalized.endsWith('.mdx')) { @@ -292,6 +297,28 @@ export async function resolveDocsScope( } } +// The guide's MDX file and every partial it includes, directly or through other partials +export async function pageSourceFiles(repoRoot: string, pagePath: string): Promise { + const mdx = pagePathToGuideFile(pagePath) + if (!mdx) return [] + const files = new Set([mdx]) + const queue = [mdx] + + while (queue.length > 0) { + const file = queue.pop()! + const source = await readFile(join(repoRoot, file), 'utf8').catch(() => null) + if (source === null) continue + for (const ref of extractPartialRefs(source)) { + const partial = `${PARTIALS_PREFIX}${ref}` + if (files.has(partial)) continue + files.add(partial) + queue.push(partial) + } + } + + return [...files] +} + export async function resolveAllDocsPages(repoRoot: string): Promise { await assertFederatedSectionsInSync(repoRoot)