Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
ci(webv2): judge byte budgets as a delta against the base branch
Lincoln Stein846275300064
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.ymlindex 69cf866651..2437b3e1da 100644--- a/.github/workflows/frontend-tests.yml+++ b/.github/workflows/frontend-tests.yml@@ -105,10 +105,58 @@ jobs:run: 'pnpm exec playwright install --with-deps chromium'shell: bash+ # A pull request into main, or a merge group, is judged as a delta against the base branch's+ # own measurements, restored from the cache every push to main fills below: the exact base+ # commit when it has an entry, otherwise the most recent main entry (a main job that failed or+ # is still running leaves no hole). Anything else compares against the committed baseline. The+ # gate logs which it used, and the restored key is passed through so reports can name it.+ - name: restore performance reference+ id: perf-ref+ if: ${{ (steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true) && ((github.event_name == 'pull_request' && github.base_ref == 'main') || (github.event_name == 'merge_group' && github.event.merge_group.base_ref == 'refs/heads/main')) }}+ uses: actions/cache/restore@v5+ with:+ path: invokeai/frontend/webv2/artifacts/perf-reference+ key: webv2-perf-reference-${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}+ restore-keys: webv2-perf-reference-++ - name: note a missing performance reference+ if: ${{ steps.perf-ref.outcome == 'success' && steps.perf-ref.outputs.cache-matched-key == '' }}+ run: 'echo "::warning::No performance reference was restored; byte budgets are compared against the committed baseline."'+ shell: bash+- name: architecture completion gatesif: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}run: 'pnpm check:architecture'shell: bash+ env:+ WEBV2_PERF_REFERENCE_DIR: ${{ steps.perf-ref.outputs.cache-matched-key != '' && 'artifacts/perf-reference' || '' }}+ WEBV2_PERF_REFERENCE_LABEL: ${{ steps.perf-ref.outputs.cache-matched-key }}++ # Recorded even when the gate failed: a main that has outgrown the committed baseline is+ # still the right thing for a pull request to be compared with. A main job that ran the gate+ # but produced no reference (a failure before the browser stage) records nothing and says so;+ # one that left webv2 untouched has nothing to record. Pull requests based on either restore+ # the most recent main entry instead.+ - name: stage performance reference+ id: perf-ref-stage+ if: ${{ always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && (steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true) }}+ run: |+ if [ -f artifacts/architecture-performance/build-reference.json ] && [ -f artifacts/architecture-performance/browser-reference.json ]; then+ mkdir -p artifacts/perf-reference+ cp artifacts/architecture-performance/build-reference.json artifacts/architecture-performance/browser-reference.json artifacts/perf-reference/+ echo "ready=true" >> "$GITHUB_OUTPUT"+ else+ echo "ready=false" >> "$GITHUB_OUTPUT"+ echo "::warning::No performance reference recorded for ${{ github.sha }}; pull requests based on it fall back to the most recent main reference."+ fi+ shell: bash++ - name: save performance reference+ if: ${{ always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.perf-ref-stage.outputs.ready == 'true' }}+ uses: actions/cache/save@v5+ with:+ path: invokeai/frontend/webv2/artifacts/perf-reference+ key: webv2-perf-reference-${{ github.sha }}- name: upload architecture review artifactsif: ${{ always() && (steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true) }}diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 45cfd238d1..ac0dd7a762 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -47,6 +47,8 @@ Contracts live with the module that owns their invariants. The retired `workbencFeature callers import a feature's public entry modules; imports of another feature's `core/`, `data/`, `ui/`, or runtime implementation are rejected outside a ticketed migration exception. Wildcard exports may aggregate files inside one owner, but may not cross an ownership seam. The contract caller matrix and development-invalidation budgets are generated by `pnpm architecture:check` and `pnpm test:performance:build` respectively.+The byte budgets in `performance/architecture-baseline.json` and `performance/browser-baseline.json` record measurements only; each ceiling is derived at check time as the lower of `max(1%, 4 KB)` over the baseline being compared against and `max(10%, 32 KB)` over the committed one (`deriveLimit` in `scripts/performance-budgets.mjs`). In CI a pull request into `main` is compared against `main`'s own measurements, restored from the Actions cache (`WEBV2_PERF_REFERENCE_DIR`), so it answers for what it adds rather than for growth `main` has already accepted; pushes to `main` compare against the committed files, so a `main` that outgrows the allowance fails as the signal to re-record deliberately with `pnpm test:performance:build:update-baseline` and `pnpm test:performance:browser:update-baseline`. Source-owner sets are pinned exactly in every mode: a module entering a route's initial graph fails at zero bytes. Request counts carry no allowance: their limit is the lower of the reference and committed counts. Pull requests whose base is a branch other than `main` (stacked PRs) receive no reference and are compared against the committed files.+Compatibility exports under `workbench/` are temporary. New behavior belongs behind the target module interface and compatibility files must not acquire new implementation logic.## Workbench ownership destinationsdiff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex deb35ccf27..05cd23ac98 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -35,6 +35,7 @@"test:performance:browser": "node scripts/measure-architecture-performance.mjs","test:performance:browser:update-baseline": "node scripts/measure-architecture-performance.mjs --update-baseline","test:performance:build": "pnpm run test:performance:contracts && vite build && node scripts/check-architecture-performance.mjs",+ "test:performance:build:update-baseline": "pnpm run test:performance:contracts && vite build && node scripts/check-architecture-performance.mjs --update-baseline","test:performance:contracts": "node --test scripts/performance-budgets.test.mjs","test:project-files": "vite build && pnpm run test:project-files:browser","test:project-files:browser": "node scripts/run-project-file-journey.mjs"diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 8ad42fbb50..c2e8f0ce7d 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -310,19 +310,6 @@"source:src/workbench/settings/store.ts"]},- "limits": {- "brotliBytes": 867936,- "cssRawBytes": 2181,- "fontRawBytes": 221675,- "gzipBytes": 867069,- "imageRawBytes": 157940,- "initialRawBytes": 2030955,- "largestAssetRawBytes": 754691,- "otherAssetRawBytes": 0,- "ownedRawBytes": 74443,- "requestCount": 44,- "scriptRequestCount": 28- },"owner": "app","remediationTicket": "set-performance-budgets","source": "index.html"@@ -1025,19 +1012,6 @@"source:src/workbench/workbenchStore.ts"]},- "limits": {- "brotliBytes": 1194117,- "cssRawBytes": 2181,- "fontRawBytes": 221675,- "gzipBytes": 1188183,- "imageRawBytes": 157940,- "initialRawBytes": 3022507,- "largestAssetRawBytes": 754691,- "otherAssetRawBytes": 0,- "ownedRawBytes": 132915,- "requestCount": 106,- "scriptRequestCount": 90- },"owner": "workbench","remediationTicket": "deepen-widget-registry-loading","source": "src/app/WorkbenchApp.tsx"diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 86d473b510..4bdc0cfe05 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -14,17 +14,6 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 0,- "otherRawBytes": 0,- "requestCount": 0,- "scriptRawBytes": 0,- "scriptRequestCount": 0,- "totalRawBytes": 0- },"domContentLoadedMedianMs": 116.20000000298023,"id": "launchpad","layoutAckMedianMs": 0,@@ -47,17 +36,6 @@"scriptRequestCount": 35,"totalRawBytes": 1853379},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 0,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 39,- "scriptRawBytes": 1693718,- "scriptRequestCount": 35,- "totalRawBytes": 1871913- },"routeReadyMedianMs": 260.80000000447035,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"@@ -74,17 +52,6 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 0,- "otherRawBytes": 0,- "requestCount": 0,- "scriptRawBytes": 0,- "scriptRequestCount": 0,- "totalRawBytes": 0- },"domContentLoadedMedianMs": 118.5,"id": "launchpad","layoutAckMedianMs": 0,@@ -107,17 +74,6 @@"scriptRequestCount": 35,"totalRawBytes": 1853379},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 0,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 39,- "scriptRawBytes": 1693718,- "scriptRequestCount": 35,- "totalRawBytes": 1871913- },"routeReadyMedianMs": 280.20000000298023,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"@@ -134,17 +90,6 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 0,- "otherRawBytes": 0,- "requestCount": 0,- "scriptRawBytes": 0,- "scriptRequestCount": 0,- "totalRawBytes": 0- },"domContentLoadedMedianMs": 116.69999999552965,"id": "editor-minimal","layoutAckMedianMs": 0,@@ -167,17 +112,6 @@"scriptRequestCount": 117,"totalRawBytes": 3844356},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 122,- "scriptRawBytes": 3546665,- "scriptRequestCount": 117,- "totalRawBytes": 3882800- },"routeReadyMedianMs": 427,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"@@ -194,17 +128,6 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 0,- "otherRawBytes": 0,- "requestCount": 0,- "scriptRawBytes": 0,- "scriptRequestCount": 0,- "totalRawBytes": 0- },"domContentLoadedMedianMs": 119,"id": "editor-minimal","layoutAckMedianMs": 0,@@ -227,17 +150,6 @@"scriptRequestCount": 117,"totalRawBytes": 3844356},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 122,- "scriptRawBytes": 3546665,- "scriptRequestCount": 117,- "totalRawBytes": 3882800- },"routeReadyMedianMs": 434.1000000014901,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"@@ -254,17 +166,6 @@"scriptRequestCount": 10,"totalRawBytes": 501642},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 322887,- "otherRawBytes": 0,- "requestCount": 10,- "scriptRawBytes": 506659,- "scriptRequestCount": 10,- "totalRawBytes": 506659- },"domContentLoadedMedianMs": 118.09999999403954,"id": "editor-canvas","layoutAckMedianMs": 2.3000000044703484,@@ -287,17 +188,6 @@"scriptRequestCount": 127,"totalRawBytes": 4345998},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 132,- "scriptRawBytes": 4053323,- "scriptRequestCount": 127,- "totalRawBytes": 4389458- },"routeReadyMedianMs": 1114.5,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"@@ -314,17 +204,6 @@"scriptRequestCount": 10,"totalRawBytes": 501642},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 322887,- "otherRawBytes": 0,- "requestCount": 10,- "scriptRawBytes": 506659,- "scriptRequestCount": 10,- "totalRawBytes": 506659- },"domContentLoadedMedianMs": 118.79999999701977,"id": "editor-canvas","layoutAckMedianMs": 3.0999999940395355,@@ -347,17 +226,6 @@"scriptRequestCount": 127,"totalRawBytes": 4345998},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 132,- "scriptRawBytes": 4053323,- "scriptRequestCount": 127,- "totalRawBytes": 4389458- },"routeReadyMedianMs": 1118.8999999985099,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"@@ -374,17 +242,6 @@"scriptRequestCount": 6,"totalRawBytes": 383691},- "activatedResourceLimits": {- "cssRawBytes": 15568,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 175873,- "otherRawBytes": 0,- "requestCount": 7,- "scriptRawBytes": 371961,- "scriptRequestCount": 6,- "totalRawBytes": 387528- },"domContentLoadedMedianMs": 119.5,"id": "editor-workflow","layoutAckMedianMs": 2.4000000059604645,@@ -407,17 +264,6 @@"scriptRequestCount": 123,"totalRawBytes": 4228047},- "resourceLimits": {- "cssRawBytes": 17748,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 129,- "scriptRawBytes": 3918626,- "scriptRequestCount": 123,- "totalRawBytes": 4270328- },"routeReadyMedianMs": 1104.7999999970198,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"@@ -434,17 +280,6 @@"scriptRequestCount": 6,"totalRawBytes": 383691},- "activatedResourceLimits": {- "cssRawBytes": 15568,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 175873,- "otherRawBytes": 0,- "requestCount": 7,- "scriptRawBytes": 371961,- "scriptRequestCount": 6,- "totalRawBytes": 387528- },"domContentLoadedMedianMs": 116.69999999552965,"id": "editor-workflow","layoutAckMedianMs": 3.2999999970197678,@@ -467,17 +302,6 @@"scriptRequestCount": 123,"totalRawBytes": 4228047},- "resourceLimits": {- "cssRawBytes": 17748,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 129,- "scriptRawBytes": 3918626,- "scriptRequestCount": 123,- "totalRawBytes": 4270328- },"routeReadyMedianMs": 1149.8999999985099,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"@@ -494,17 +318,6 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 0,- "otherRawBytes": 0,- "requestCount": 0,- "scriptRawBytes": 0,- "scriptRequestCount": 0,- "totalRawBytes": 0- },"domContentLoadedMedianMs": 114.20000000298023,"id": "editor-gallery","layoutAckMedianMs": 0,@@ -527,17 +340,6 @@"scriptRequestCount": 117,"totalRawBytes": 3844356},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 122,- "scriptRawBytes": 3546665,- "scriptRequestCount": 117,- "totalRawBytes": 3882800- },"routeReadyMedianMs": 1309.3999999985099,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"@@ -554,17 +356,6 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "activatedResourceLimits": {- "cssRawBytes": 0,- "fontRawBytes": 0,- "imageRawBytes": 0,- "largestAssetRawBytes": 0,- "otherRawBytes": 0,- "requestCount": 0,- "scriptRawBytes": 0,- "scriptRequestCount": 0,- "totalRawBytes": 0- },"domContentLoadedMedianMs": 116.30000000447035,"id": "editor-gallery","layoutAckMedianMs": 0,@@ -587,17 +378,6 @@"scriptRequestCount": 117,"totalRawBytes": 3844356},- "resourceLimits": {- "cssRawBytes": 2181,- "fontRawBytes": 23901,- "imageRawBytes": 157940,- "largestAssetRawBytes": 754682,- "otherRawBytes": 153744,- "requestCount": 122,- "scriptRawBytes": 3546665,- "scriptRequestCount": 117,- "totalRawBytes": 3882800- },"routeReadyMedianMs": 1329.0999999940395,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"diff --git a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjsindex f3b366e4eb..8d339971f5 100644--- a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs+++ b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs@@ -1,13 +1,21 @@import assert from 'node:assert/strict';import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';-import { dirname, resolve } from 'node:path';+import { resolve } from 'node:path';import { analyzeSource, closeSourceAnalysis, primeSourceAnalysis } from '#architecture/source-analysis';import {+ applyBuildReference,+ BUDGET_REMEDY,BUILD_METRIC_KEYS,+ BUILD_REFERENCE_FILE,checkRouteBudget,+ createBuildReference,+ isBudgetFailure,+ loadPerformanceReference,measureRouteBuild,+ PERFORMANCE_REFERENCE_DIR_VARIABLE,+ PERFORMANCE_REFERENCE_LABEL_VARIABLE,validateArchitectureBaseline,validateChunkSourceManifest,} from './performance-budgets.mjs';@@ -22,6 +30,9 @@ const chunkSourceManifest = validateChunkSourceManifest();const readAsset = async (file) => new Uint8Array(await readFile(resolve(root, 'dist', file)));const updateBaseline = process.argv.includes('--update-baseline');+const referenceDir = process.env[PERFORMANCE_REFERENCE_DIR_VARIABLE] || null;+const referenceLabel = process.env[PERFORMANCE_REFERENCE_LABEL_VARIABLE] || null;+const artifactDir = resolve(root, 'artifacts/architecture-performance');const assetCache = new Map();for (const chunk of Object.values(manifest)) {@@ -32,39 +43,16 @@ for (const chunk of Object.values(manifest)) {}}-const getLegacyOwnedLimit = (budget, measurement) => {- if (- typeof budget.baselineOwnedRawBytes !== 'number' ||- typeof budget.maxGrowthPercent !== 'number' ||- typeof budget.maxGrowthRawBytes !== 'number'- ) {- return measurement.ownedRawBytes;- }-- return Math.max(- measurement.ownedRawBytes,- budget.baselineOwnedRawBytes +- Math.min(budget.maxGrowthRawBytes, Math.floor(budget.baselineOwnedRawBytes * budget.maxGrowthPercent))- );-};--const createLimits = (measurement, legacyBudget) =>- Object.fromEntries(- BUILD_METRIC_KEYS.map((key) => {- if (key === 'ownedRawBytes') {- return [key, getLegacyOwnedLimit(legacyBudget, measurement)];- }- if (key === 'requestCount' || key === 'scriptRequestCount') {- return [key, measurement[key]];- }- return [key, Math.ceil(measurement[key] * 1.01)];- })- );-const routeEntries = Object.entries(baselineInput.build);const measurements = routeEntries.map(([routeId, budget]) =>measureRouteBuild(manifest, chunkSourceManifest, routeId, budget.source, (file) => assetCache.get(file)));+// Written before any check so a failing main still records what it measured for the next PR.+await mkdir(artifactDir, { recursive: true });+await writeFile(+ resolve(artifactDir, BUILD_REFERENCE_FILE),+ `${JSON.stringify(createBuildReference(measurements), null, 2)}\n`+);let baseline;if (updateBaseline) {@@ -78,7 +66,6 @@ if (updateBaseline) {...Object.fromEntries(BUILD_METRIC_KEYS.map((key) => [key, measurement[key]])),sourceOwners: measurement.sourceOwners,},- limits: createLimits(measurement, previousBudget),owner: previousBudget.owner,remediationTicket: previousBudget.remediationTicket,source: previousBudget.source,@@ -103,9 +90,33 @@ if (updateBaseline) {baseline = validateArchitectureBaseline(baselineInput);}-const failures = measurements.flatMap((measurement) =>- checkRouteBudget(measurement, baseline.build[measurement.routeId])+const referenceName = referenceLabel ? `base-branch reference ${referenceLabel}` : 'base-branch reference';+let reference = null;+let referenceReason = null;+if (referenceDir && !updateBaseline) {+ const loaded = await loadPerformanceReference({+ directory: referenceDir,+ fileName: BUILD_REFERENCE_FILE,+ kind: 'build',+ metricKeys: BUILD_METRIC_KEYS,+ root,+ });+ referenceReason = loaded.reason;+ reference = loaded.reason ? null : loaded.reference;+}+const { build: budgets, uncovered: uncoveredRoutes } = applyBuildReference(baseline.build, reference);+process.stdout.write(+ reference+ ? `Byte budgets: delta against ${referenceName} captured ${reference.capturedAt}.\n`+ : referenceReason+ ? `Byte budgets: against committed baseline captured ${baseline.capturedAt}; ${referenceName} was recorded with ${referenceReason} and cannot be applied.\n`+ : `Byte budgets: against committed baseline captured ${baseline.capturedAt}.\n`);+if (uncoveredRoutes.length > 0) {+ process.stdout.write(`Routes absent from the reference use the committed baseline: ${uncoveredRoutes.join(', ')}.\n`);+}++const failures = measurements.flatMap((measurement) => checkRouteBudget(measurement, budgets[measurement.routeId]));const launchpad = measurements.find((measurement) => measurement.routeId === 'launchpad');const editor = measurements.find((measurement) => measurement.routeId === 'editor');// Shared settings metadata must not turn Launchpad overlays into editor boot paths.@@ -216,11 +227,29 @@ try {}}- const reportPath = resolve(root, 'artifacts/architecture-performance/build-report.json');- await mkdir(dirname(reportPath), { recursive: true });+ const reportPath = resolve(artifactDir, 'build-report.json');await writeFile(reportPath,- `${JSON.stringify({ baselineCapturedAt: baseline.capturedAt, failures, importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`+ `${JSON.stringify(+ {+ baselineCapturedAt: baseline.capturedAt,+ capturedAt: new Date().toISOString(),+ failures,+ importerCounts: Object.fromEntries(importerCounts),+ measurements,+ reference: referenceDir+ ? {+ applied: reference !== null,+ capturedAt: reference?.capturedAt ?? null,+ label: referenceLabel,+ reason: referenceReason,+ uncoveredRoutes,+ }+ : null,+ },+ null,+ 2+ )}\n`);if (failures.length > 0) {@@ -231,6 +260,7 @@ try {`${failure.message} Owner: ${failure.owner}. Remediation: ${failure.remediationTicket}. Route: ${failure.routeId}.`).join('\n')+ .concat(failures.some((failure) => isBudgetFailure(failure.message)) ? `\n${BUDGET_REMEDY}` : ''));}diff --git a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjsindex 3dcfec0be2..84e69fc7a2 100644--- a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs+++ b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs@@ -6,13 +6,21 @@ import { chromium } from 'playwright';import { startMockBackend } from './mock-backend.mjs';import {BROWSER_RESOURCE_METRIC_KEYS,+ applyBrowserReference,+ BROWSER_REFERENCE_FILE,+ BUDGET_REMEDY,checkBrowserRouteBudget,+ createBrowserReference,+ isBudgetFailure,+ loadPerformanceReference,createBrowserSamplePlan,summarizeBrowserResources,validateBrowserBaseline,validateChunkSourceManifest,waitForRequiredRequests,waitForStableRequests,+ PERFORMANCE_REFERENCE_DIR_VARIABLE,+ PERFORMANCE_REFERENCE_LABEL_VARIABLE,} from './performance-budgets.mjs';import { killPreview, spawnPreview } from './preview-server.mjs';import { getWidgetId } from './widget-sources.mjs';@@ -56,6 +64,8 @@ const origin = `http://127.0.0.1:${String(port)}`;const backendPort = Number(process.env.INVOKEAI_PERFORMANCE_BACKEND_PORT ?? 4177);const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;const updateBaseline = process.argv.includes('--update-baseline');+const referenceDir = process.env[PERFORMANCE_REFERENCE_DIR_VARIABLE] || null;+const referenceLabel = process.env[PERFORMANCE_REFERENCE_LABEL_VARIABLE] || null;const median = (values) => {const sorted = [...values].sort((left, right) => left - right);@@ -228,16 +238,6 @@ const createSourceOwnerSets = (routes) => {return { routeSetIds, sets };};-const createResourceLimits = (resources) =>- Object.fromEntries(- BROWSER_RESOURCE_METRIC_KEYS.map((key) => {- if (key === 'requestCount' || key === 'scriptRequestCount') {- return [key, resources[key]];- }- return [key, Math.ceil(resources[key] * 1.01)];- })- );-const getMaximumResourceSummary = (samples, key) =>Object.fromEntries(BROWSER_RESOURCE_METRIC_KEYS.map((metric) => [metric, Math.max(...samples.map((sample) => sample[key][metric]))])@@ -728,16 +728,44 @@ try {});}+ // Written before any check so a failing main still records what it measured for the next PR.+ await mkdir(dirname(artifactPath), { recursive: true });+ await writeFile(+ resolve(dirname(artifactPath), BROWSER_REFERENCE_FILE),+ `${JSON.stringify(createBrowserReference(routeReports), null, 2)}\n`+ );++ const referenceName = referenceLabel ? `base-branch reference ${referenceLabel}` : 'base-branch reference';+ let reference = null;+ let referenceReason = null;+ if (referenceDir && !updateBaseline) {+ const loaded = await loadPerformanceReference({+ directory: referenceDir,+ fileName: BROWSER_REFERENCE_FILE,+ kind: 'browser',+ metricKeys: BROWSER_RESOURCE_METRIC_KEYS,+ root,+ });+ referenceReason = loaded.reason;+ reference = loaded.reason ? null : loaded.reference;+ }+const report = {browserExecutable: chromium.executablePath(),capturedAt: new Date().toISOString(),+ reference: referenceDir+ ? {+ applied: reference !== null,+ capturedAt: reference?.capturedAt ?? null,+ label: referenceLabel,+ reason: referenceReason,+ uncoveredRoutes: [],+ }+ : null,routes: routeReports,sampling: sampleConfig,schemaVersion: 2,};- await mkdir(dirname(artifactPath), { recursive: true });- await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);-if (updateBaseline) {const previousBaseline = JSON.parse(await readFile(baselinePath, 'utf8'));const sourceOwnerSets = createSourceOwnerSets(routeReports);@@ -746,7 +774,6 @@ try {capturedAt: new Date().toISOString().slice(0, 10),routes: routeReports.map((route) => ({activatedResourceBaseline: route.activatedResources,- activatedResourceLimits: createResourceLimits(route.activatedResources),domContentLoadedMedianMs: route.domContentLoadedMedianMs,id: route.id,layoutAckMedianMs: route.layoutAckMedianMs,@@ -759,7 +786,6 @@ try {readyMark: route.readyMark,remediationTicket: route.remediationTicket,resourceBaseline: route.resources,- resourceLimits: createResourceLimits(route.resources),routeReadyMedianMs: route.routeReadyMedianMs,scriptSourceOwnerSet: sourceOwnerSets.routeSetIds.get(`${route.id}:${route.stateProfile}`),stateProfile: route.stateProfile,@@ -784,8 +810,26 @@ try {};validateBrowserBaseline(baseline, fixtures);await writeFile(baselinePath, `${JSON.stringify(baseline, null, 2)}\n`);+ await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);} else {const baseline = validateBrowserBaseline(JSON.parse(await readFile(baselinePath, 'utf8')), fixtures);+ const { routes: expectedRoutes, uncovered: uncoveredRoutes } = applyBrowserReference(baseline.routes, reference);+ if (report.reference) {+ report.reference.uncoveredRoutes = uncoveredRoutes;+ }+ await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);+ process.stdout.write(+ reference+ ? `Resource budgets: delta against ${referenceName} captured ${reference.capturedAt}.\n`+ : referenceReason+ ? `Resource budgets: against committed baseline captured ${baseline.capturedAt}; ${referenceName} was recorded with ${referenceReason} and cannot be applied.\n`+ : `Resource budgets: against committed baseline captured ${baseline.capturedAt}.\n`+ );+ if (uncoveredRoutes.length > 0) {+ process.stdout.write(+ `Routes absent from the reference use the committed baseline: ${uncoveredRoutes.join(', ')}.\n`+ );+ }const failures = [];if (JSON.stringify(baseline.sampling) !== JSON.stringify(sampleConfig)) {failures.push(@@ -795,7 +839,7 @@ try {);}for (const route of routeReports) {- const expected = baseline.routes.find(+ const expected = expectedRoutes.find((candidate) => candidate.id === route.id && candidate.stateProfile === route.stateProfile);if (!expected) {@@ -822,7 +866,7 @@ try {}}if (failures.length > 0) {- throw new Error(failures.join('\n'));+ throw new Error(`${failures.join('\n')}${failures.some(isBudgetFailure) ? `\n${BUDGET_REMEDY}` : ''}`);}}diff --git a/invokeai/frontend/webv2/scripts/performance-budgets.mjs b/invokeai/frontend/webv2/scripts/performance-budgets.mjsindex 2e14b8ea9e..ce3139b332 100644--- a/invokeai/frontend/webv2/scripts/performance-budgets.mjs+++ b/invokeai/frontend/webv2/scripts/performance-budgets.mjs@@ -1,3 +1,5 @@+import { readFile } from 'node:fs/promises';+import { resolve } from 'node:path';import { brotliCompressSync, constants, gzipSync } from 'node:zlib';export const BUILD_METRIC_KEYS = [@@ -157,6 +159,246 @@ export const validateChunkSourceManifest = (value) => {return value;};+/**+ * A route's ceiling is derived from a baseline measurement rather than committed alongside it, so+ * the recorded file states only what was measured and a re-record touches one number per metric.+ *+ * Two bounds apply and the lower wins:+ *+ * - The allowance, `max(1%, 4 KB)` over the baseline being compared against. Neither term works+ * alone: 1% of 2 KB of CSS is 22 bytes, and a flat floor is meaningless against a 3 MB route. It+ * is deliberately loose, because what catches an architectural regression is `sourceOwners`,+ * pinned exactly, which fails on a module entering a route's initial graph even at zero bytes;+ * the byte budgets only need to catch gross size changes.+ * - The hard ceiling, `max(10%, 32 KB)` over the *committed* baseline. In CI the allowance is taken+ * over the base branch's own measurement, which moves with every merge; without a second bound+ * the committed file would have no effect before a merge and allowance-sized pull requests could+ * compound without limit. The ceiling keeps the committed file the outer bound a person has+ * reviewed, and a deliberate downward re-record takes effect on the next pull request.+ *+ * Request counts are capped exactly by both: an extra initial request is structural, not growth.+ */+export const GROWTH_ALLOWANCE_PERCENT = 0.01;+export const GROWTH_ALLOWANCE_FLOOR_BYTES = 4096;+export const HARD_CEILING_PERCENT = 0.1;+export const HARD_CEILING_FLOOR_BYTES = 32768;++const EXACT_METRIC_KEYS = new Set(['requestCount', 'scriptRequestCount']);++const allowanceOver = (value, percent, floor) => value + Math.max(Math.ceil(value * percent), floor);++export const deriveLimit = (key, baselineValue, committedValue = baselineValue) => {+ if (EXACT_METRIC_KEYS.has(key)) {+ return Math.min(baselineValue, committedValue);+ }+ return Math.min(+ allowanceOver(baselineValue, GROWTH_ALLOWANCE_PERCENT, GROWTH_ALLOWANCE_FLOOR_BYTES),+ allowanceOver(committedValue, HARD_CEILING_PERCENT, HARD_CEILING_FLOOR_BYTES)+ );+};++export const deriveLimits = (baseline, keys, committed = baseline) =>+ Object.fromEntries(keys.map((key) => [key, deriveLimit(key, baseline[key], committed[key])]));++/**+ * The base branch's own measurements, handed to a pull-request run by CI so the byte budgets are+ * judged as a delta: the pull request answers for what it adds, not for growth main has accepted+ * since the committed baseline was captured. `sourceOwners` and every structural rule still come+ * from the committed baseline, which is the deliberate record and is meant to keep failing until+ * someone updates it.+ *+ * Each gate writes its reference file next to its report, before it checks anything, so a failing+ * main still records what it measured. The file is deliberately small and versioned: it is read by+ * a *different* commit's copy of these scripts, so a version or metric-set mismatch is an expected+ * event that falls back to the committed baseline with the reason logged, not a wiring fault.+ * A set directory that lacks the file, or a file that carries no other integer `schemaVersion` and+ * is not this shape, is a wiring fault and fails with the variable and path named.+ *+ * Unset locally and on pushes to main. There the committed baseline is the reference, so a main+ * that has outgrown the allowance since its last capture fails, which is the signal that a+ * deliberate re-record is due, rather than its ceiling ratcheting up unreviewed.+ */+export const PERFORMANCE_REFERENCE_DIR_VARIABLE = 'WEBV2_PERF_REFERENCE_DIR';+/** Whatever CI wants the reference called in logs and reports -- the cache key it restored. */+export const PERFORMANCE_REFERENCE_LABEL_VARIABLE = 'WEBV2_PERF_REFERENCE_LABEL';+export const PERFORMANCE_REFERENCE_SCHEMA_VERSION = 1;+export const BUILD_REFERENCE_FILE = 'build-reference.json';+export const BROWSER_REFERENCE_FILE = 'browser-reference.json';++export const BUDGET_REMEDY =+ 'If this growth is intended, re-record the committed baselines with `pnpm run test:performance:build:update-baseline` ' ++ 'and `pnpm run test:performance:browser:update-baseline`. A byte limit shown with `reference ..., committed ...` is the ' ++ 'lower of the allowance over the base branch and the hard ceiling over the committed baseline; one shown with ' ++ '`captured ...` was compared against the committed baseline directly. Request counts have no allowance: their limit ' ++ 'is the lower of the two counts.';++const projectMetrics = (source, keys) => Object.fromEntries(keys.map((key) => [key, source[key]]));++export const createBuildReference = (measurements) => ({+ capturedAt: new Date().toISOString(),+ kind: 'build',+ metricKeys: [...BUILD_METRIC_KEYS],+ routes: Object.fromEntries(+ measurements.map((measurement) => [measurement.routeId, projectMetrics(measurement, BUILD_METRIC_KEYS)])+ ),+ schemaVersion: PERFORMANCE_REFERENCE_SCHEMA_VERSION,+});++export const createBrowserReference = (routeReports) => ({+ capturedAt: new Date().toISOString(),+ kind: 'browser',+ metricKeys: [...BROWSER_RESOURCE_METRIC_KEYS],+ routes: Object.fromEntries(+ routeReports.map((route) => [+ `${route.id}:${route.stateProfile}`,+ {+ activatedResources: projectMetrics(route.activatedResources, BROWSER_RESOURCE_METRIC_KEYS),+ resources: projectMetrics(route.resources, BROWSER_RESOURCE_METRIC_KEYS),+ },+ ])+ ),+ schemaVersion: PERFORMANCE_REFERENCE_SCHEMA_VERSION,+});++/** Structural shape only; version and metric-set drift are judged separately, since they fall back. */+export const validatePerformanceReference = (value, path) => {+ assertExactKeys(value, ['capturedAt', 'kind', 'metricKeys', 'routes', 'schemaVersion'], path);+ assertNonEmptyString(value.capturedAt, `${path}.capturedAt`);+ if (value.kind !== 'build' && value.kind !== 'browser') {+ throw new TypeError(`${path}.kind must be "build" or "browser".`);+ }+ if (!Array.isArray(value.metricKeys) || value.metricKeys.some((key) => typeof key !== 'string')) {+ throw new TypeError(`${path}.metricKeys must be an array of strings.`);+ }+ assertPlainObject(value.routes, `${path}.routes`);+ if (!Number.isInteger(value.schemaVersion)) {+ throw new TypeError(`${path}.schemaVersion must be an integer.`);+ }+ return value;+};++/** Why this reference cannot be applied by this copy of the scripts, or null when it can. */+export const referenceIncompatibility = (reference, kind, metricKeys) => {+ if (reference.schemaVersion !== PERFORMANCE_REFERENCE_SCHEMA_VERSION) {+ return `schemaVersion ${String(reference.schemaVersion)} (this checkout writes ${String(PERFORMANCE_REFERENCE_SCHEMA_VERSION)})`;+ }+ if (reference.kind !== kind) {+ return `kind "${reference.kind}" (expected "${kind}")`;+ }+ if (JSON.stringify(reference.metricKeys) !== JSON.stringify(metricKeys)) {+ return `metric set ${JSON.stringify(reference.metricKeys)} (this checkout measures ${JSON.stringify(metricKeys)})`;+ }+ return null;+};++/**+ * Reads the reference CI restored. Any problem short of an expected version or metric-set drift+ * is thrown with the variable and path named, so a broken restore never passes as "no reference".+ */+export const loadPerformanceReference = async ({ directory, fileName, kind, metricKeys, root }) => {+ const path = resolve(root, directory, fileName);+ let raw;+ try {+ raw = await readFile(path, 'utf8');+ } catch (error) {+ throw new Error(+ `${PERFORMANCE_REFERENCE_DIR_VARIABLE} is set to "${directory}" but ${path} could not be read: ${error.message}`+ );+ }+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ throw new Error(`${path} is not valid JSON: ${error.message}`);+ }+ // Judged before the shape is validated: a reference from a checkout with a different schema+ // version may legitimately have a different shape, and that is the drift the fallback is for.+ // Only an integer version that differs is drift; a file with no version at all was never+ // written by any checkout and stays a wiring fault.+ const version = parsed?.schemaVersion;+ if (Number.isInteger(version) && version !== PERFORMANCE_REFERENCE_SCHEMA_VERSION) {+ return {+ reason: `schemaVersion ${String(version)} (this checkout writes ${String(PERFORMANCE_REFERENCE_SCHEMA_VERSION)})`,+ reference: null,+ };+ }+ const reference = validatePerformanceReference(parsed, `performance reference ${fileName}`);++ return { reason: referenceIncompatibility(reference, kind, metricKeys), reference };+};++/**+ * Whether a failure line is a byte or request budget being exceeded, as opposed to a source-owner+ * graph or importer-count change. Only the former is answered by re-recording a baseline; for an+ * owner-graph leak that advice would erase the very signal the pin exists to give.+ */+export const isBudgetFailure = (message) => / reached \d+ .*\(limit /.test(message);++/**+ * Committed route budgets with their byte baselines replaced by the reference's, keeping the+ * committed numbers alongside for the hard ceiling and for failure messages. Routes the reference+ * does not cover keep the committed baseline and are reported so the log can say so.+ */+export const applyBuildReference = (build, reference) => {+ if (!reference) {+ return { build, uncovered: [] };+ }+ const uncovered = [];+ const applied = Object.fromEntries(+ Object.entries(build).map(([routeId, budget]) => {+ const metrics = reference.routes[routeId];+ if (!metrics) {+ uncovered.push(routeId);+ return [routeId, budget];+ }+ // A malformed route must fail here: an undefined metric would derive a NaN ceiling, and+ // every comparison against NaN is false, which would wave the whole route through.+ validateMetricObject(metrics, BUILD_METRIC_KEYS, `reference build route ${routeId}`);++ return [+ routeId,+ {+ ...budget,+ baseline: { ...budget.baseline, ...metrics },+ committed: projectMetrics(budget.baseline, BUILD_METRIC_KEYS),+ },+ ];+ })+ );++ return { build: applied, uncovered };+};++/** The browser-gate counterpart of `applyBuildReference`. */+export const applyBrowserReference = (routes, reference) => {+ if (!reference) {+ return { routes, uncovered: [] };+ }+ const uncovered = [];+ const applied = routes.map((expected) => {+ const key = `${expected.id}:${expected.stateProfile}`;+ const entry = reference.routes[key];+ if (!entry) {+ uncovered.push(key);+ return expected;+ }+ const path = `reference browser route ${key}`;+ assertExactKeys(entry, ['activatedResources', 'resources'], path);+ validateMetricObject(entry.resources, BROWSER_RESOURCE_METRIC_KEYS, `${path}.resources`);+ validateMetricObject(entry.activatedResources, BROWSER_RESOURCE_METRIC_KEYS, `${path}.activatedResources`);++ return {+ ...expected,+ activatedResourceBaseline: entry.activatedResources,+ committedActivatedResourceBaseline: expected.activatedResourceBaseline,+ committedResourceBaseline: expected.resourceBaseline,+ resourceBaseline: entry.resources,+ };+ });++ return { routes: applied, uncovered };+};+export const validateArchitectureBaseline = (value) => {assertExactKeys(value,@@ -173,7 +415,7 @@ export const validateArchitectureBaseline = (value) => {for (const [routeId, budget] of Object.entries(value.build)) {const path = `architecture baseline.build.${routeId}`;- assertExactKeys(budget, ['baseline', 'limits', 'owner', 'remediationTicket', 'source'], path);+ assertExactKeys(budget, ['baseline', 'owner', 'remediationTicket', 'source'], path);assertNonEmptyString(budget.source, `${path}.source`);assertNonEmptyString(budget.owner, `${path}.owner`);assertNonEmptyString(budget.remediationTicket, `${path}.remediationTicket`);@@ -184,12 +426,6 @@ export const validateArchitectureBaseline = (value) => {`${path}.baseline metrics`);assertStringArray(budget.baseline.sourceOwners, `${path}.baseline.sourceOwners`);- validateMetricObject(budget.limits, BUILD_METRIC_KEYS, `${path}.limits`);- for (const key of BUILD_METRIC_KEYS) {- if (budget.limits[key] < budget.baseline[key]) {- throw new Error(`${path}.limits.${key} cannot be below its captured baseline.`);- }- }}assertExactKeys(@@ -229,7 +465,6 @@ const validateBrowserRoute = (route, path) => {['domContentLoadedMedianMs','activatedResourceBaseline',- 'activatedResourceLimits','id','layoutAckMedianMs','layoutReturnSwitchMedianMs',@@ -241,7 +476,6 @@ const validateBrowserRoute = (route, path) => {'readyMark','remediationTicket','resourceBaseline',- 'resourceLimits','routeReadyMedianMs','scriptSourceOwnerSet','stateProfile',@@ -268,19 +502,7 @@ const validateBrowserRoute = (route, path) => {BROWSER_RESOURCE_METRIC_KEYS,`${path}.activatedResourceBaseline`);- validateMetricObject(route.activatedResourceLimits, BROWSER_RESOURCE_METRIC_KEYS, `${path}.activatedResourceLimits`);- for (const key of BROWSER_RESOURCE_METRIC_KEYS) {- if (route.activatedResourceLimits[key] < route.activatedResourceBaseline[key]) {- throw new Error(`${path}.activatedResourceLimits.${key} cannot be below its captured baseline.`);- }- }validateMetricObject(route.resourceBaseline, BROWSER_RESOURCE_METRIC_KEYS, `${path}.resourceBaseline`);- validateMetricObject(route.resourceLimits, BROWSER_RESOURCE_METRIC_KEYS, `${path}.resourceLimits`);- for (const key of BROWSER_RESOURCE_METRIC_KEYS) {- if (route.resourceLimits[key] < route.resourceBaseline[key]) {- throw new Error(`${path}.resourceLimits.${key} cannot be below its captured baseline.`);- }- }assertNonEmptyString(route.scriptSourceOwnerSet, `${path}.scriptSourceOwnerSet`);};@@ -535,18 +757,23 @@ const diffSortedValues = (expected, actual) => ({export const checkRouteBudget = (measurement, budget) => {const failures = [];+ const committed = budget.committed ?? budget.baseline;+ const limits = deriveLimits(budget.baseline, BUILD_METRIC_KEYS, committed);for (const key of BUILD_METRIC_KEYS) {- if (measurement[key] > budget.limits[key]) {+ if (measurement[key] > limits[key]) {+ const origin = budget.committed+ ? `reference ${String(budget.baseline[key])}, committed ${String(committed[key])}`+ : `captured ${String(budget.baseline[key])}`;failures.push(createFailure(measurement,budget,`${measurement.routeId} ${METRIC_LABELS[key]} reached ${String(measurement[key])} bytes/requests (limit ${String(- budget.limits[key]- )}, captured ${String(budget.baseline[key])}).`,+ limits[key]+ )}, ${origin}).`,measurement[key],- budget.limits[key]+ limits[key]));}@@ -614,20 +841,35 @@ export const summarizeBrowserResources = (resources) => {export const checkBrowserRouteBudget = (route, expected, timingPolicy, expectedScriptSourceOwners) => {const failures = [];const label = `${route.id}/${route.stateProfile}`;+ const committedResources = expected.committedResourceBaseline ?? expected.resourceBaseline;+ const committedActivated = expected.committedActivatedResourceBaseline ?? expected.activatedResourceBaseline;+ const resourceLimits = deriveLimits(expected.resourceBaseline, BROWSER_RESOURCE_METRIC_KEYS, committedResources);+ const activatedResourceLimits = deriveLimits(+ expected.activatedResourceBaseline,+ BROWSER_RESOURCE_METRIC_KEYS,+ committedActivated+ );+ const origin = (baselineValue, committedValue) =>+ expected.committedResourceBaseline+ ? `reference ${String(baselineValue)}, committed ${String(committedValue)}`+ : `captured ${String(baselineValue)}`;for (const key of BROWSER_RESOURCE_METRIC_KEYS) {- if (route.resources[key] > expected.resourceLimits[key]) {+ if (route.resources[key] > resourceLimits[key]) {failures.push(- `${label} ${key} reached ${String(route.resources[key])} (limit ${String(expected.resourceLimits[key])}, owner ${- route.owner- }, remediation ${route.remediationTicket}).`+ `${label} ${key} reached ${String(route.resources[key])} (limit ${String(resourceLimits[key])}, ${origin(+ expected.resourceBaseline[key],+ committedResources[key]+ )}, owner ${route.owner}, remediation ${route.remediationTicket}).`);}- if (route.activatedResources[key] > expected.activatedResourceLimits[key]) {+ if (route.activatedResources[key] > activatedResourceLimits[key]) {failures.push(`${label} activated ${key} reached ${String(route.activatedResources[key])} (limit ${String(- expected.activatedResourceLimits[key]- )}, owner ${route.owner}, remediation ${route.remediationTicket}).`+ activatedResourceLimits[key]+ )}, ${origin(expected.activatedResourceBaseline[key], committedActivated[key])}, owner ${route.owner}, remediation ${+ route.remediationTicket+ }).`);}}diff --git a/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs b/invokeai/frontend/webv2/scripts/performance-budgets.test.mjsindex b56581ed13..58420883a4 100644--- a/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs+++ b/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs@@ -1,11 +1,26 @@import assert from 'node:assert/strict';+import { mkdtemp, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { describe, it } from 'node:test';import { createChunkSourceManifest, getModuleSourceOwner } from './chunk-source-manifest.mjs';import {BUILD_METRIC_KEYS,checkBrowserRouteBudget,+ applyBrowserReference,+ applyBuildReference,checkRouteBudget,+ createBrowserReference,+ createBuildReference,+ deriveLimit,+ GROWTH_ALLOWANCE_FLOOR_BYTES,+ HARD_CEILING_FLOOR_BYTES,+ isBudgetFailure,+ loadPerformanceReference,+ PERFORMANCE_REFERENCE_SCHEMA_VERSION,+ referenceIncompatibility,+ validatePerformanceReference,createBrowserSamplePlan,measureRouteBuild,summarizeBrowserResources,@@ -58,7 +73,6 @@ const createArchitectureBaseline = (measurement) => ({...BUILD_METRIC_KEYS.map((key) => [key, measurement[key]]),['sourceOwners', measurement.sourceOwners],]),- limits: Object.fromEntries(BUILD_METRIC_KEYS.map((key) => [key, measurement[key]])),owner: 'app',remediationTicket: 'performance-gates',source: 'entry.ts',@@ -97,17 +111,6 @@ const createBrowserBaseline = () => ({scriptRequestCount: 0,totalRawBytes: 0,},- activatedResourceLimits: {- cssRawBytes: 0,- fontRawBytes: 0,- imageRawBytes: 0,- largestAssetRawBytes: 0,- otherRawBytes: 0,- requestCount: 0,- scriptRawBytes: 0,- scriptRequestCount: 0,- totalRawBytes: 0,- },domContentLoadedMedianMs: 100,id: 'launchpad',layoutAckMedianMs: 0,@@ -130,17 +133,6 @@ const createBrowserBaseline = () => ({scriptRequestCount: 1,totalRawBytes: 20,},- resourceLimits: {- cssRawBytes: 1,- fontRawBytes: 2,- imageRawBytes: 3,- largestAssetRawBytes: 10,- otherRawBytes: 4,- requestCount: 5,- scriptRawBytes: 10,- scriptRequestCount: 1,- totalRawBytes: 20,- },routeReadyMedianMs: 120,scriptSourceOwnerSet: 'launchpad',stateProfile: 'empty',@@ -214,7 +206,7 @@ describe('build performance budgets', () => {it('rejects unused budget schema keys', () => {const measurement = createSyntheticBuild(1_000);const baseline = createArchitectureBaseline(measurement);- baseline.build.launchpad.limits.unusedBudget = 123;+ baseline.build.launchpad.baseline.unusedBudget = 123;assert.throws(() => validateArchitectureBaseline(baseline), /Unknown keys: unusedBudget/);});@@ -511,3 +503,388 @@ describe('browser performance sampling and policy', () => {);});});++describe('derived growth allowance', () => {+ it('absorbs ordinary growth instead of failing on a handful of bytes', () => {+ // The regression this replaces: a route whose captured ceiling equalled its measurement, so+ // any byte of growth failed and every PR paid a re-record for whatever main had drifted.+ const measurement = createSyntheticBuild(1_000);+ const budget = createArchitectureBaseline(measurement).build.launchpad;+ const grown = { ...measurement, ownedRawBytes: measurement.ownedRawBytes + 64 };++ assert.deepEqual(checkRouteBudget(grown, budget), []);+ });++ it('still fails growth beyond the allowance', () => {+ const measurement = createSyntheticBuild(1_000);+ const budget = createArchitectureBaseline(measurement).build.launchpad;+ const bloated = { ...measurement, ownedRawBytes: measurement.ownedRawBytes + 4096 + 1 };++ const failures = checkRouteBudget(bloated, budget);++ assert.equal(failures.length, 1);+ assert.match(failures[0].message, /owned JavaScript reached .* captured /);+ });++ it('gives a small metric a usable byte allowance and a large one a proportional share', () => {+ // Percent alone is useless on a 2 KB metric; a flat floor alone is meaningless on a 3 MB one.+ assert.equal(deriveLimit('cssRawBytes', 2159), 2159 + 4096);+ assert.equal(deriveLimit('initialRawBytes', 2992581), 2992581 + 29926);+ });++ it('allows the floor over a zero baseline, which the exact request counts bound', () => {+ // Six committed browser routes have all-zero activated resources; "zero" now means "up to the+ // floor", and it is the exact request cap that keeps a new asset from arriving unnoticed.+ assert.equal(deriveLimit('otherAssetRawBytes', 0), GROWTH_ALLOWANCE_FLOOR_BYTES);+ assert.equal(deriveLimit('requestCount', 0), 0);+ });++ it('caps request counts exactly, since an extra initial request is structural', () => {+ assert.equal(deriveLimit('requestCount', 106), 106);+ assert.equal(deriveLimit('scriptRequestCount', 90), 90);+ });++ it('keeps the source-owner graph pinned exactly regardless of the byte allowance', () => {+ const measurement = createSyntheticBuild(1_000);+ const budget = createArchitectureBaseline(measurement).build.launchpad;+ const leaked = { ...measurement, sourceOwners: [...measurement.sourceOwners, 'source:src/leaked.ts'] };++ const failures = checkRouteBudget(leaked, budget);++ assert.equal(failures.length, 1);+ assert.match(failures[0].message, /source-owner graph changed/);+ });+});++describe('hard ceiling over the committed baseline', () => {+ it('bounds a moving reference by the committed baseline', () => {+ // A run of allowance-sized merges moves the reference; the committed file must still be the+ // outer bound, or the budgets would be advisory before a merge.+ const committed = 100_000;+ const reference = committed + HARD_CEILING_FLOOR_BYTES - 1000;++ assert.equal(deriveLimit('ownedRawBytes', reference, committed), committed + HARD_CEILING_FLOOR_BYTES);+ });++ it('is the allowance when the reference is the committed baseline', () => {+ assert.equal(deriveLimit('ownedRawBytes', 100_000, 100_000), 100_000 + 4096);+ });++ it('caps request counts at the lower of the two, so a flaky extra request in one main run does not stick', () => {+ assert.equal(deriveLimit('requestCount', 107, 106), 106);+ assert.equal(deriveLimit('requestCount', 106, 107), 106);+ });+});++describe('base-branch reference', () => {+ const buildReference = (measurements) => createBuildReference(measurements);++ it('judges bytes against the reference while the committed source-owner pin still fails a leak', () => {+ // The committed baseline is stale by 20 KB of growth that main has already accepted. Against+ // it the pull request would fail for main's drift; against the reference it answers only for+ // its own bytes -- and a module that leaked into the graph still fails at zero bytes.+ const committed = createSyntheticBuild(1_000);+ const mainNow = {+ ...createSyntheticBuild(21_000),+ sourceOwners: [...createSyntheticBuild(21_000).sourceOwners, 'source:src/main-added.ts'],+ };+ const build = createArchitectureBaseline(committed).build;+ const pullRequest = { ...mainNow, ownedRawBytes: mainNow.ownedRawBytes + 64 };++ assert.ok(checkRouteBudget(pullRequest, build.launchpad).length > 0);++ const { build: budgets, uncovered } = applyBuildReference(build, buildReference([mainNow]));++ assert.deepEqual(uncovered, []);+ const failures = checkRouteBudget(pullRequest, budgets.launchpad);+ assert.equal(failures.length, 1);+ assert.match(failures[0].message, /source-owner graph changed.*main-added/);+ assert.deepEqual(budgets.launchpad.baseline.sourceOwners, committed.sourceOwners);+ });++ it('names both origins in a failure so a reader can find the numbers', () => {+ const committed = createSyntheticBuild(1_000);+ const mainNow = createSyntheticBuild(21_000);+ const { build: budgets } = applyBuildReference(+ createArchitectureBaseline(committed).build,+ buildReference([mainNow])+ );+ const bloated = { ...mainNow, ownedRawBytes: mainNow.ownedRawBytes + 4096 + 1 };++ const [failure] = checkRouteBudget(bloated, budgets.launchpad);++ assert.match(+ failure.message,+ new RegExp(`reference ${mainNow.ownedRawBytes}, committed ${committed.ownedRawBytes}`)+ );+ });++ it('applies the reference by route id, not by position, and reports routes it does not cover', () => {+ const committed = createSyntheticBuild(1_000);+ const decoy = { ...createSyntheticBuild(21_000), routeId: 'other' };+ const build = createArchitectureBaseline(committed).build;++ const { build: budgets, uncovered } = applyBuildReference(build, buildReference([decoy]));++ assert.deepEqual(uncovered, ['launchpad']);+ assert.equal(budgets.launchpad.baseline.ownedRawBytes, committed.ownedRawBytes);+ assert.equal(budgets.launchpad.committed, undefined);+ });++ it('is a no-op without a reference', () => {+ const build = createArchitectureBaseline(createSyntheticBuild(1_000)).build;++ assert.deepEqual(applyBuildReference(build, null), { build, uncovered: [] });+ });++ it('refuses a route missing a metric rather than deriving a NaN ceiling', () => {+ // Every comparison against NaN is false, so a silent fallback here would pass any route.+ const committed = createSyntheticBuild(1_000);+ const build = createArchitectureBaseline(committed).build;+ const reference = buildReference([committed]);+ delete reference.routes.launchpad.ownedRawBytes;++ assert.throws(() => applyBuildReference(build, reference), /reference build route launchpad/);+ });++ it('is written as a small versioned file that validates', () => {+ const reference = buildReference([createSyntheticBuild(1_000)]);++ assert.equal(validatePerformanceReference(reference, 'test'), reference);+ assert.equal(reference.schemaVersion, PERFORMANCE_REFERENCE_SCHEMA_VERSION);+ assert.deepEqual(Object.keys(reference.routes), ['launchpad']);+ assert.deepEqual(Object.keys(reference.routes.launchpad), BUILD_METRIC_KEYS);+ });++ it('is judged incompatible, not broken, when written by a checkout with a different metric set', () => {+ // The reference is read by a different commit's copy of these scripts. A pull request that+ // adds or removes a metric must fall back with a reason, not wedge its own CI.+ const reference = buildReference([createSyntheticBuild(1_000)]);++ assert.equal(referenceIncompatibility(reference, 'build', BUILD_METRIC_KEYS), null);+ assert.match(referenceIncompatibility(reference, 'build', [...BUILD_METRIC_KEYS, 'webpRawBytes']), /metric set/);+ assert.match(referenceIncompatibility(reference, 'browser', BUILD_METRIC_KEYS), /kind "build"/);+ assert.match(+ referenceIncompatibility({ ...reference, schemaVersion: 99 }, 'build', BUILD_METRIC_KEYS),+ /schemaVersion 99/+ );+ });++ it('rejects a file that is not a reference at all, naming what is wrong', () => {+ assert.throws(() => validatePerformanceReference({ routes: {} }, 'performance reference x'), /Missing keys/);+ assert.throws(+ () =>+ validatePerformanceReference(+ { capturedAt: 'now', kind: 'nope', metricKeys: [], routes: {}, schemaVersion: 1 },+ 'x'+ ),+ /kind must be/+ );+ });+});++describe('base-branch reference, browser gate', () => {+ const routeFor = (expected, overrides = {}) => ({+ activatedResources: expected.activatedResourceBaseline,+ domContentLoadedMedianMs: expected.domContentLoadedMedianMs,+ id: expected.id,+ layoutAckMedianMs: expected.layoutAckMedianMs,+ layoutReturnSwitchMedianMs: expected.layoutReturnSwitchMedianMs,+ layoutSwitchMedianMs: expected.layoutSwitchMedianMs,+ loadMedianMs: expected.loadMedianMs,+ longestTaskMaxMs: expected.longestTaskMaxMs,+ owner: expected.owner,+ projectSwitchMedianMs: expected.projectSwitchMedianMs,+ remediationTicket: expected.remediationTicket,+ resources: expected.resourceBaseline,+ routeReadyMedianMs: expected.routeReadyMedianMs,+ scriptSourceOwners: [],+ stateProfile: expected.stateProfile,+ ...overrides,+ });+ const check = (route, expected, baseline) =>+ checkBrowserRouteBudget(route, expected, baseline.timingPolicy, route.scriptSourceOwners);++ it('passes growth within the allowance and fails growth beyond it, through the gate itself', () => {+ const baseline = createBrowserBaseline();+ const [expected] = baseline.routes;+ const within = routeFor(expected, {+ resources: { ...expected.resourceBaseline, scriptRawBytes: expected.resourceBaseline.scriptRawBytes + 4096 },+ });+ const beyond = routeFor(expected, {+ resources: { ...expected.resourceBaseline, scriptRawBytes: expected.resourceBaseline.scriptRawBytes + 4097 },+ });++ assert.deepEqual(check(within, expected, baseline), []);+ const failures = check(beyond, expected, baseline);+ assert.equal(failures.length, 1);+ assert.match(failures[0], /scriptRawBytes reached .* captured /);+ });++ it('caps request counts and activated resources exactly and separately', () => {+ const baseline = createBrowserBaseline();+ const [expected] = baseline.routes;+ const extraRequest = routeFor(expected, {+ resources: { ...expected.resourceBaseline, requestCount: expected.resourceBaseline.requestCount + 1 },+ });+ const extraActivated = routeFor(expected, {+ activatedResources: {+ ...expected.activatedResourceBaseline,+ scriptRequestCount: expected.activatedResourceBaseline.scriptRequestCount + 1,+ },+ });++ assert.match(check(extraRequest, expected, baseline)[0], /^\S+ requestCount reached/);+ assert.match(check(extraActivated, expected, baseline)[0], /activated scriptRequestCount reached/);+ });++ it('judges a route against the reference by id and profile, keeping the committed numbers for the ceiling', () => {+ const baseline = createBrowserBaseline();+ const [expected] = baseline.routes;+ const grownResources = {+ ...expected.resourceBaseline,+ scriptRawBytes: expected.resourceBaseline.scriptRawBytes + 5_000,+ };+ const decoyResources = { ...expected.resourceBaseline, scriptRawBytes: 1 };+ const reference = createBrowserReference([+ {+ activatedResources: expected.activatedResourceBaseline,+ id: 'decoy',+ resources: decoyResources,+ stateProfile: expected.stateProfile,+ },+ {+ activatedResources: expected.activatedResourceBaseline,+ id: expected.id,+ resources: grownResources,+ stateProfile: expected.stateProfile,+ },+ ]);++ const { routes, uncovered } = applyBrowserReference(baseline.routes, reference);+ const [applied] = routes;++ assert.deepEqual(+ uncovered,+ baseline.routes.slice(1).map((route) => `${route.id}:${route.stateProfile}`)+ );+ assert.deepEqual(applied.resourceBaseline, grownResources);+ assert.deepEqual(applied.committedResourceBaseline, expected.resourceBaseline);+ assert.equal(applied.scriptSourceOwnerSet, expected.scriptSourceOwnerSet);++ // 5 KB over the committed number would fail against the committed baseline alone...+ const route = routeFor(expected, {+ resources: { ...grownResources, scriptRawBytes: grownResources.scriptRawBytes + 64 },+ });+ assert.ok(check(route, expected, baseline).length > 0);+ // ...and passes against the reference, with both origins named if it ever fails.+ assert.deepEqual(check(route, applied, baseline), []);+ const [failure] = check(+ routeFor(expected, { resources: { ...grownResources, scriptRawBytes: grownResources.scriptRawBytes + 4097 } }),+ applied,+ baseline+ );+ assert.match(failure, /reference \d+, committed \d+/);+ });++ it('refuses a reference route missing activated resources rather than deriving NaN ceilings', () => {+ const baseline = createBrowserBaseline();+ const [expected] = baseline.routes;+ const reference = createBrowserReference([+ {+ activatedResources: expected.activatedResourceBaseline,+ id: expected.id,+ resources: expected.resourceBaseline,+ stateProfile: expected.stateProfile,+ },+ ]);+ delete reference.routes[`${expected.id}:${expected.stateProfile}`].activatedResources.requestCount;++ assert.throws(() => applyBrowserReference(baseline.routes, reference), /activatedResources/);+ });+});++describe('baseline schema', () => {+ it('rejects the committed limit blocks the derivation replaced', () => {+ const measurement = createSyntheticBuild(1_000);+ const withLimits = createArchitectureBaseline(measurement);+ withLimits.build.launchpad.limits = {};++ assert.throws(() => validateArchitectureBaseline(withLimits), /Unknown keys: limits/);++ for (const key of ['resourceLimits', 'activatedResourceLimits']) {+ const browser = createBrowserBaseline();+ browser.routes[0][key] = {};+ assert.throws(() => validateBrowserBaseline(browser, fixtures), new RegExp(`Unknown keys: ${key}`));+ }+ });+});++describe('loading a reference from disk', () => {+ const stage = async (contents) => {+ const root = await mkdtemp(join(tmpdir(), 'perf-reference-'));+ await writeFile(+ join(root, 'build-reference.json'),+ typeof contents === 'string' ? contents : JSON.stringify(contents)+ );+ return root;+ };+ const load = (root) =>+ loadPerformanceReference({+ directory: '.',+ fileName: 'build-reference.json',+ kind: 'build',+ metricKeys: BUILD_METRIC_KEYS,+ root,+ });++ it('falls back with a reason on a different schema version even when the shape is foreign', async () => {+ // The version is judged before the shape, or a bump that also changes shape could never fall back.+ const root = await stage({ schemaVersion: 99, whatever: true });++ const loaded = await load(root);++ assert.equal(loaded.reference, null);+ assert.match(loaded.reason, /schemaVersion 99/);+ });++ it('names the variable and path when the file is missing, and the path when it is not JSON', async () => {+ const empty = await mkdtemp(join(tmpdir(), 'perf-reference-'));+ await assert.rejects(+ load(empty),+ /WEBV2_PERF_REFERENCE_DIR is set to "\." but .*build-reference\.json could not be read/+ );++ const broken = await stage('{ not json');+ await assert.rejects(load(broken), /is not valid JSON/);+ });++ it('treats a file with no integer schemaVersion as a wiring fault, not drift', async () => {+ // An empty object is what a broken stage step produces; it was never written by any checkout.+ const empty = await stage({});+ await assert.rejects(load(empty), /performance reference build-reference\.json/);+ });++ it('applies a current, well-formed reference', async () => {+ const root = await stage(createBuildReference([createSyntheticBuild(1_000)]));++ const loaded = await load(root);++ assert.equal(loaded.reason, null);+ assert.deepEqual(Object.keys(loaded.reference.routes), ['launchpad']);+ });+});++describe('the remedy is offered only for budget failures', () => {+ it('recognises byte and request limits from both gates but not structural failures', () => {+ assert.ok(isBudgetFailure('launchpad owned JavaScript reached 4197 bytes/requests (limit 4196, captured 100).'));+ assert.ok(+ isBudgetFailure(+ 'launchpad/empty scriptRawBytes reached 4107 (limit 4106, captured 10, owner app, remediation x).'+ )+ );+ // Re-recording would erase exactly the signal these give.+ assert.ok(!isBudgetFailure('launchpad initial source-owner graph changed. Added: source:src/leaked.ts.'));+ assert.ok(!isBudgetFailure('ui has 3 direct importers (budget 1).'));+ });+});