Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/autonomous-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,11 @@ renames it to `ci-ok-head`. See
recorded in `package.json`; one execution per supported Node line, plus the
changed-lines floor on the pull request diff)
- `build`
- `visual` (the UI matrix, when the diff reaches a rendered surface)
- `visual` (the UI matrix, when the diff reaches a rendered surface; the job
summary names every page, viewport and scheme with its own result, and the
shard aggregate refuses a run that measured fewer cells than the matrix
promises, so a dropped page or a cell measured twice fails the job instead of
shrinking the table)
- `docker` (image builds, scans and starts)
- `audit` (no high-severity advisory in either the runtime set or the full graph)
- `changelog` (fragments are well formed)
Expand Down
24 changes: 23 additions & 1 deletion scripts/visual-matrix.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
/// <reference lib="dom" />
import { spawn } from 'node:child_process'
import type { ChildProcess } from 'node:child_process'
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { appendFileSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { randomBytes } from 'node:crypto'
import { availableParallelism, tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import {
caseRows,
cellLabel,
focusFailures,
leftoverFailures,
Expand All @@ -16,6 +17,7 @@ import {
pageSlug,
partitionWorkload,
shardFailures,
summaryMarkdown,
touchFailures,
viewportHeight,
visualWorkload,
Expand Down Expand Up @@ -538,6 +540,23 @@ function report(summary: string): void {
process.exitCode = 1
}

/** The aggregate's reasons that belong to no single row: a share that died, a cell counted twice. */
function aggregateNotes(problems: readonly string[], cells: readonly VisualCell[]): string[] {
const labels = cells.map((cell) => cellLabel(cell))
return problems.filter((problem) => !labels.some((label) => problem.startsWith(`${label}: `)))
}

/** The job summary is optional: a local run has no GITHUB_STEP_SUMMARY to append to. */
function writeStepSummary(rows: readonly import('../src/lib/visualMatrix.js').VisualCaseResult[], notes: readonly string[]): void {
const target = process.env.GITHUB_STEP_SUMMARY
if (target === undefined || target === '') return
try {
appendFileSync(target, summaryMarkdown(rows, notes))
} catch (error) {
console.error(`visual matrix: the job summary was not written: ${error instanceof Error ? error.message : String(error)}`)
}
}

async function runCoordinator(): Promise<void> {
const workload = visualWorkload()
const shares = shardCount(workload.length)
Expand All @@ -563,6 +582,9 @@ async function runCoordinator(): Promise<void> {
}
})
failures.push(...problems)
// The table is written before the exit code is decided, so a red run still
// names every page, viewport and scheme instead of one line for the matrix.
writeStepSummary(caseRows(workload, results), aggregateNotes(problems, workload))
report(`${String(workload.length)} cell(s) over ${String(shares)} share(s)`)
}

Expand Down
100 changes: 100 additions & 0 deletions src/lib/visualMatrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,103 @@ export function shardFailures(
}
return failures
}

/**
* One row of the job summary: a cell as a reader sees it, with the mode it was
* measured in and every reason it failed. The row is derived from what the
* shares reported, so a cell that never ran cannot appear as a pass.
*/
export interface VisualCaseResult {
readonly locale: string
readonly width: number
readonly scheme: string
readonly path: string
readonly ok: boolean
readonly detail: readonly string[]
}

/** The scheme a cell is measured in: the sweep takes the host's, the gate forces one. */
function caseScheme(cell: VisualCell): string {
switch (cell.kind) {
case 'gate':
return cell.scheme
case 'theme':
return 'explicit-dark'
default:
return 'host'
}
}

/**
* The rows behind the summary, one per promised cell in workload order. A cell
* is a pass only when a share reported measuring it and no failure carries its
* label; a cell no share reported reads as a failure naming that, so a share
* that skipped work shrinks nothing.
*/
export function caseRows(
cells: readonly VisualCell[],
results: readonly (VisualShardResult | null)[],
): VisualCaseResult[] {
const labels = new Map(cells.map((cell) => [cellLabel(cell), cell]))
const reported = new Set<string>()
const reasons = new Map<string, string[]>()
for (const result of results) {
for (const label of result?.cells ?? []) reported.add(label)
for (const failure of result?.failures ?? []) {
for (const [label] of labels) {
const prefix = `${label}: `
if (!failure.startsWith(prefix)) continue
const list = reasons.get(label) ?? []
list.push(failure.slice(prefix.length))
reasons.set(label, list)
break
}
}
}
return cells.map((cell) => {
const label = cellLabel(cell)
const detail = reasons.get(label) ?? []
const ok = reported.has(label) && detail.length === 0
return {
locale: cell.locale,
width: cell.width,
scheme: caseScheme(cell),
path: cell.kind === 'theme' ? '/dashboard' : cell.path,
ok,
detail: ok ? [] : detail.length > 0 ? detail : ['the share that owned this cell reported no result'],
}
})
}

/** A cell of the table: a reason can carry a `|` of its own. */
function tableCell(value: string): string {
return value.split('|').join('\\|')
}

/**
* The summary a reader opens from the run page. Every promised case is a row —
* a pass is a row too — so a red run names the page, viewport and scheme that
* failed and a green run shows the table the matrix actually covered. `notes`
* carries the aggregate's own reasons (a share that died, a cell counted
* twice), which belong to no single row.
*/
export function summaryMarkdown(rows: readonly VisualCaseResult[], notes: readonly string[] = []): string {
const passed = rows.filter((row) => row.ok).length
const lines = [
`visual matrix: ${String(passed)}/${String(rows.length)} case(s) passed`,
'',
'| locale | viewport | scheme | page | result |',
'| --- | --- | --- | --- | --- |',
]
for (const row of rows) {
const result = row.ok ? 'pass' : `fail: ${row.detail.join('; ')}`
lines.push(
`| ${tableCell(row.locale)} | ${String(row.width)}px | ${tableCell(row.scheme)} | \`${tableCell(row.path)}\` | ${tableCell(result)} |`,
)
}
if (notes.length > 0) {
lines.push('', '**Aggregate notes**')
for (const note of notes) lines.push(`- ${tableCell(note)}`)
}
return `${lines.join('\n')}\n`
}
154 changes: 154 additions & 0 deletions test/visualJobCeiling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { test } from 'node:test'
import { fileURLToPath } from 'node:url'

// #787: the visual job's cost and its reporting are properties of the workflow
// and the runner, not of a page, so this suite reads both as text. #1208
// sharded the sweep, so the coverage half here is the shared aggregate guard
// and the summary is built from what the shares reported.

const root = fileURLToPath(new URL('..', import.meta.url))

function read(path: string): string {
return readFileSync(join(root, path), 'utf8')
}

function visualJob(): string {
const text = read('.github/workflows/ci.yml')
const start = text.indexOf('\n visual:\n')
assert.notEqual(start, -1, 'ci.yml has no visual job')
const end = text.indexOf('\n docker:\n', start)
assert.ok(end > start, 'the visual job is not followed by the docker job')
return text.slice(start, end)
}

const lib = (await import('../src/lib/visualMatrix.js')) as unknown as {
visualWorkload?: () => readonly ColumnCell[]
cellLabel?: (cell: ColumnCell) => string
caseRows?: (cells: readonly ColumnCell[], results: readonly (ShardResult | null)[]) => readonly Row[]
summaryMarkdown?: (rows: readonly Row[], notes?: readonly string[]) => string
}

interface ColumnCell {
readonly kind: 'sweep' | 'narrow' | 'gate' | 'theme'
readonly locale: string
readonly width: number
readonly scheme?: string
readonly path: string
}

interface ShardResult {
readonly share: number
readonly cells: readonly string[]
readonly failures: readonly string[]
}

interface Row {
readonly locale: string
readonly width: number
readonly scheme: string
readonly path: string
readonly ok: boolean
readonly detail: readonly string[]
}

test('the visual job keeps its name and its place in the required set', () => {
const workflow = read('.github/workflows/ci.yml')
assert.match(workflow, /\n {2}visual:\n/, 'the visual job was renamed or removed')
assert.match(
workflow,
/needs: \[ci-ok,[^\]]*\bvisual\b[^\]]*\]/,
'the visual job is not in the aggregate ci-ok needs, so a red matrix would not fail the required check',
)
})

test('a broken cell reaches the required check instead of stopping at the job', () => {
const job = visualJob()
assert.match(job, /\n {6}- run: npx playwright install --with-deps chromium\n/, 'the install step is missing or guarded')
assert.match(job, /\n {6}- run: npm run visual:matrix\n/, 'the matrix step is missing or guarded')
assert.doesNotMatch(job, /continue-on-error/, 'a failing matrix must not be allowed to finish green')
const runner = read('scripts/visual-matrix.ts')
assert.match(runner, /process\.exitCode = 1/, 'a failure no longer sets a red exit code')
})

test('the aggregate refuses a matrix that would collapse coverage', () => {
// The guard is the shard aggregate: a share that measured nothing, a result
// that never arrived, a cell missing from a share that ran, and a cell
// measured twice all fail the run. Pinned here as the runner wiring this job
// depends on; the rule itself is unit-tested in `visualMatrixShards.test.ts`.
const runner = read('scripts/visual-matrix.ts')
assert.match(runner, /shardFailures\(/, 'the aggregate no longer uses the shared coverage guard')
const text = read('src/lib/visualMatrix.ts')
assert.match(text, /was assigned no cells/, 'an empty share no longer fails the run')
assert.match(text, /reported no result/, 'a missing share result no longer fails the run')
assert.match(text, /did not report/, 'a dropped cell no longer fails the run')
assert.match(text, /was measured .* times/, 'a duplicated cell no longer fails the run')
})

test('the coordinator publishes the case table to the job summary', () => {
const runner = read('scripts/visual-matrix.ts')
assert.match(runner, /GITHUB_STEP_SUMMARY/, 'the runner never reads GITHUB_STEP_SUMMARY')
assert.match(runner, /summaryMarkdown\(/, 'the runner does not build the case table')
assert.match(runner, /appendFileSync\(target, summaryMarkdown/, 'the runner does not append the case table')
})

test('the summary names the page, viewport and scheme of every case', () => {
const formatter = lib.summaryMarkdown
assert.ok(formatter !== undefined, 'summaryMarkdown is not exported')
const out = formatter!([
{ locale: 'en', width: 360, scheme: 'dark', path: '/settings', ok: true, detail: [] },
{
locale: 'zh',
width: 768,
scheme: 'light',
path: '/dashboard',
ok: false,
detail: ['button[name] is 39px tall'],
},
])
assert.match(out, /^visual matrix: 1\/2 case\(s\) passed$/m)
assert.match(out, /^\| locale \| viewport \| scheme \| page \| result \|$/m)
assert.match(out, /^\| en \| 360px \| dark \| `\/settings` \| pass \|$/m)
assert.match(out, /^\| zh \| 768px \| light \| `\/dashboard` \| fail: button\[name\] is 39px tall \|$/m)
})

test('a reason with a pipe cannot break the table', () => {
const formatter = lib.summaryMarkdown
assert.ok(formatter !== undefined, 'summaryMarkdown is not exported')
const out = formatter!([{ locale: 'en', width: 1280, scheme: 'host', path: '/', ok: false, detail: ['a | b'] }])
assert.match(out, /a \\\| b/, 'a pipe in a reason is not escaped')
})

test('a cell no share reported reads as a failure in the table', () => {
const workload = lib.visualWorkload
const label = lib.cellLabel
const rowsOf = lib.caseRows
assert.ok(workload !== undefined && label !== undefined && rowsOf !== undefined, 'caseRows is not exported')

const cells = workload!().slice(0, 2)
const measured = label!(cells[0]!)
const results: (ShardResult | null)[] = [
{ share: 1, cells: [measured], failures: [`${measured}: element outside the viewport`] },
null,
]
const rows = rowsOf!(cells, results)
assert.equal(rows.length, 2, 'the table has one row per promised cell')
assert.equal(rows[0]!.ok, false, 'a cell whose failure the share reported must read as a failure')
assert.deepEqual(rows[0]!.detail, ['element outside the viewport'], 'the reason keeps its text without the cell prefix')
assert.equal(rows[1]!.ok, false, 'a cell no share reported must not read as a pass')
assert.match(String(rows[1]!.detail[0]), /never measured|reported no result/, 'an unmeasured cell names why it is not verified')
})

test('the scheme column says which mode the cell was measured in', () => {
const workload = lib.visualWorkload
const rowsOf = lib.caseRows
assert.ok(workload !== undefined && rowsOf !== undefined, 'caseRows is not exported')
const all = workload!()
const rows = rowsOf!(all, [])
const schemes = new Set(rows.map((row) => row.scheme))
assert.ok(schemes.has('host'), 'the sweep rows do not name the host colour scheme')
assert.ok(schemes.has('light') && schemes.has('dark'), 'the gate rows do not name their forced scheme')
assert.ok(schemes.has('explicit-dark'), 'the theme probe row does not name its scheme')
})
Loading