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.`, ]) }