diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index cae5c7d..678369f 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1561,7 +1561,7 @@ block library — [doctor.md](../doctor.md)): bash .agents/skills/iapl-audit/scripts/audit.sh pnpm exec iapl-doctor # + --deep --url http://localhost:3000 on the built site node .agents/skills/iapl-seo-check/scripts/seo-check.mjs http://localhost:3000 -pnpm test:e2e performance # the budget gate (iapl-performance) on the built site +pnpm test:e2e e2e/performance.spec # the budget gate (iapl-performance) on the built site pnpm generate:types && pnpm tsc --noEmit pnpm build # --webpack in the script; locally, not only dev # hardcoding and the field zoo in blocks diff --git a/docs/agent/skills/iapl-performance/SKILL.md b/docs/agent/skills/iapl-performance/SKILL.md index 688c3ff..d7b9230 100644 --- a/docs/agent/skills/iapl-performance/SKILL.md +++ b/docs/agent/skills/iapl-performance/SKILL.md @@ -34,7 +34,7 @@ pnpm exec iapl-doctor --deep --only perf-images # stored ``` Lab numbers per page (phone on Slow 4G with a 4× slower CPU, and desktop): copy `resources/perf-lab.mjs` and `resources/performance.spec.template.ts` (→ `e2e/performance.spec.ts`), list one page of each template, run -`pnpm test:e2e performance`, then set each budget to what you measured plus ~20 %. From then on the test fails when +`pnpm test:e2e e2e/performance.spec`, then set each budget to what you measured plus ~20 %. From then on the test fails when a change makes a page slower. PageSpeed Insights on the deployed site shows the field data (real visitors). ## 3. Read the result diff --git a/docs/agent/skills/iapl-performance/resources/perf-lab.mjs b/docs/agent/skills/iapl-performance/resources/perf-lab.mjs index 4bccda1..0ca6bbc 100644 --- a/docs/agent/skills/iapl-performance/resources/perf-lab.mjs +++ b/docs/agent/skills/iapl-performance/resources/perf-lab.mjs @@ -13,7 +13,10 @@ * inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button), * scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type * (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to - * another origin before any consent is given). + * another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are + * counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run. + * Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host + * cannot hold the page's load event, and the numbers are the site's own. */ import { chromium } from '@playwright/test' @@ -45,7 +48,7 @@ const OBSERVERS = `(() => { * @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number, * fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number, * lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string }, - * load: null | number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number, + * load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number, * status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement */ @@ -62,7 +65,7 @@ const typeOf = (resourceType, mime = '') => { * @param {import('@playwright/test').Browser} browser * @param {string} url * @param {'mobile'|'desktop'} profileName - * @param {{ interact?: boolean, settleMs?: number }} [options] + * @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options] * @returns {Promise} */ export async function measurePage(browser, url, profileName, options = {}) { @@ -78,13 +81,19 @@ export async function measurePage(browser, url, profileName, options = {}) { await page.addInitScript(OBSERVERS) const origin = new URL(url).origin + if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())} const requests = new Map() - cdp.on('Network.requestWillBeSent', (e) => { if (!e.request.url.startsWith('data:')) {requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })} }) + let prefetches = 0 + cdp.on('Network.requestWillBeSent', (e) => { + if (e.request.url.startsWith('data:')) {return} + if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return} + requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url }) + }) cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} }) cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} }) - const response = await page.goto(url, { waitUntil: 'load' }) - await page.waitForLoadState('networkidle').catch(() => {}) + const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' }) + await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {}) await page.waitForTimeout(options.settleMs ?? 1000) let interaction = null @@ -124,6 +133,7 @@ export async function measurePage(browser, url, profileName, options = {}) { lcp: round(vitals.lcp?.at), lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null, load: round(nav.load), + prefetches, profile: profileName, renderBlocking: nav.blocking.map((u) => u.replace(origin, '')), requests: list.length, @@ -149,7 +159,7 @@ export const median = (values) => { * @param {string} url * @param {'mobile'|'desktop'} profileName * @param {number} [runs] - * @param {{ interact?: boolean, settleMs?: number }} [options] + * @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options] * @returns {Promise} */ export async function measureMedian(browser, url, profileName, runs = 3, options = {}) { diff --git a/docs/agent/skills/iapl-performance/resources/performance.spec.template.ts b/docs/agent/skills/iapl-performance/resources/performance.spec.template.ts index 7b739f0..a42218f 100644 --- a/docs/agent/skills/iapl-performance/resources/performance.spec.template.ts +++ b/docs/agent/skills/iapl-performance/resources/performance.spec.template.ts @@ -38,7 +38,8 @@ for (const page of PAGES) { for (const profile of ['mobile', 'desktop'] as const) { test(`${page.name} (${profile}) stays within its performance budget`, async ({ baseURL }) => { test.setTimeout(120_000) - const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs) + // third-party requests are recorded, then aborted: an external host cannot fail or hang the test + const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs, { blockThirdParty: true }) test.info().annotations.push({ description: JSON.stringify({ bytes: measured.bytes, cls: measured.cls, inp: measured.inp, lcp: measured.lcp, requests: measured.requests }), type: 'measured' }) expect(overBudget(measured, { ...budgets[profile], ...page.budget }), `${page.path} ${profile}`).toEqual([]) if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, 'the LCP image is lazy').not.toBe('lazy')} diff --git a/reference/e2e/perf-lab.mjs b/reference/e2e/perf-lab.mjs index 4bccda1..0ca6bbc 100644 --- a/reference/e2e/perf-lab.mjs +++ b/reference/e2e/perf-lab.mjs @@ -13,7 +13,10 @@ * inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button), * scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type * (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to - * another origin before any consent is given). + * another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are + * counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run. + * Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host + * cannot hold the page's load event, and the numbers are the site's own. */ import { chromium } from '@playwright/test' @@ -45,7 +48,7 @@ const OBSERVERS = `(() => { * @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number, * fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number, * lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string }, - * load: null | number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number, + * load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number, * status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement */ @@ -62,7 +65,7 @@ const typeOf = (resourceType, mime = '') => { * @param {import('@playwright/test').Browser} browser * @param {string} url * @param {'mobile'|'desktop'} profileName - * @param {{ interact?: boolean, settleMs?: number }} [options] + * @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options] * @returns {Promise} */ export async function measurePage(browser, url, profileName, options = {}) { @@ -78,13 +81,19 @@ export async function measurePage(browser, url, profileName, options = {}) { await page.addInitScript(OBSERVERS) const origin = new URL(url).origin + if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())} const requests = new Map() - cdp.on('Network.requestWillBeSent', (e) => { if (!e.request.url.startsWith('data:')) {requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })} }) + let prefetches = 0 + cdp.on('Network.requestWillBeSent', (e) => { + if (e.request.url.startsWith('data:')) {return} + if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return} + requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url }) + }) cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} }) cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} }) - const response = await page.goto(url, { waitUntil: 'load' }) - await page.waitForLoadState('networkidle').catch(() => {}) + const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' }) + await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {}) await page.waitForTimeout(options.settleMs ?? 1000) let interaction = null @@ -124,6 +133,7 @@ export async function measurePage(browser, url, profileName, options = {}) { lcp: round(vitals.lcp?.at), lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null, load: round(nav.load), + prefetches, profile: profileName, renderBlocking: nav.blocking.map((u) => u.replace(origin, '')), requests: list.length, @@ -149,7 +159,7 @@ export const median = (values) => { * @param {string} url * @param {'mobile'|'desktop'} profileName * @param {number} [runs] - * @param {{ interact?: boolean, settleMs?: number }} [options] + * @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options] * @returns {Promise} */ export async function measureMedian(browser, url, profileName, runs = 3, options = {}) { diff --git a/reference/e2e/performance.spec.ts b/reference/e2e/performance.spec.ts index 089d950..1c82dcd 100644 --- a/reference/e2e/performance.spec.ts +++ b/reference/e2e/performance.spec.ts @@ -14,7 +14,8 @@ import { measureMedian } from './perf-lab.mjs' * and a desktop, first visit. The numbers are this site's own, measured on 2026-12-01 (docs/dev/perf/*-after.json) * with headroom for lab noise: a change that makes a page heavier or slower fails here, in `pnpm e2e:built`, with both * bundlers. Loosen a number only with a reason in the comment next to it. - * PERF_RUNS (default 1) runs per page; the gate takes the median. + * PERF_RUNS (default 1) runs per page; the gate takes the median. Third-party requests are recorded (none may come + * before consent) and aborted, so an external host's speed cannot fail or hang the gate. */ const runs = Number(process.env.PERF_RUNS ?? 1) @@ -56,7 +57,7 @@ test.describe('performance budgets', () => { for (const profile of ['mobile', 'desktop'] as const) { test(`${page.name} (${profile}) stays within its budget`, async ({ baseURL }) => { const budget = { ...budgets[profile], ...page.budget?.[profile] } - const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs) + const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs, { blockThirdParty: true }) test.info().annotations.push({ description: JSON.stringify({ bytes: measured.bytes, cls: measured.cls, inp: measured.inp, lcp: measured.lcp, requests: measured.requests, tbt: measured.tbt }), type: 'measured' }) expect(overBudget(measured, budget), `${page.path} ${profile}${page.why ? ` (${page.why})` : ''}`).toEqual([]) // the LCP image is never lazy (web.dev/articles/lcp-lazy-loading) @@ -99,6 +100,7 @@ test.describe('queries per render', () => { expect(res.status).toBe(200) await db.command({ profile: 0 }) counts[p] = await db.collection('system.profile').countDocuments({ ns: { $not: /system\.profile$/ }, op: 'query' }) + expect(counts[p], `${p}: no query counted — the profiler did not record this database`).toBeGreaterThan(0) expect(counts[p], `${p}: ${counts[p]} queries (budget ${limit}, plugin default ${SERVER_BUDGET.queriesPerRender})`).toBeLessThanOrEqual(limit) } test.info().annotations.push({ description: JSON.stringify(counts), type: 'queries' }) diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index ff451cb..dea48bf 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -99,7 +99,7 @@ for (const bundler of bundlers) { console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`) run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look and the sign-in answers`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' }) // the budgets are the built site's own numbers: they hold for each bundler (docs/performance.md, docs/dev/perf/) - run(`${bundler}: performance budgets — every page type on a phone and a desktop, queries per render`, 'pnpm', ['exec', 'playwright', 'test', 'performance'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) + run(`${bundler}: performance budgets — every page type on a phone and a desktop, queries per render`, 'pnpm', ['exec', 'playwright', 'test', 'e2e/performance.spec'] /* a regex on the file path: a checkout path may hold "performance" */, site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) passed.push(bundler) } console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)