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
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import process from 'node:process';
import { chromium } from 'playwright';
import { observeBrowserDiagnostics, waitForRenderedMedia, runSustainedWorkload } from './browser-validation.mjs';
import { startMockBackend } from './mock-backend.mjs';
import {
BROWSER_RESOURCE_METRIC_KEYS,
applyBrowserReference,
BROWSER_REFERENCE_FILE,
BUDGET_REMEDY,
checkBrowserRouteBudget,
createBrowserReference,
isBudgetFailure,
loadPerformanceReference,
createBrowserRunPlan,
summarizeBrowserSamples,
PERFORMANCE_GUIDE,
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';
const root = resolve(import.meta.dirname, '..');
const fixtures = JSON.parse(await readFile(resolve(root, 'performance/architecture-fixtures.json'), 'utf8'));
const manifest = JSON.parse(await readFile(resolve(root, 'dist/.vite/manifest.json'), 'utf8'));
const chunkSourceManifest = validateChunkSourceManifest(
JSON.parse(await readFile(resolve(root, 'dist/.vite/chunk-sources.json'), 'utf8'))
);
const fullSampleConfig = {
scoredSamples: fixtures.scoredSamples,
traceSamples: fixtures.traceSamples,
warmups: fixtures.warmups,
};
const getScriptLabel = (source, chunk) => {
const widgetId = getWidgetId(source);
return widgetId ? `widget:${widgetId}` : (chunk.name ?? chunk.src ?? source);
};
const scriptLabelByPath = new Map(
Object.entries(manifest).map(([source, chunk]) => [`/${chunk.file}`, getScriptLabel(source, chunk)])
);
const scriptSourceOwnersByPath = new Map(
Object.values(manifest)
.filter((chunk) => chunk.file.endsWith('.js'))
.map((chunk) => {
const sourceChunk = chunkSourceManifest.chunks[chunk.file];
if (!sourceChunk) {
throw new Error(`Chunk source manifest is missing browser script ${chunk.file}.`);
}
return [`/${chunk.file}`, sourceChunk.sourceOwners];
})
);
const baselinePath = resolve(root, 'performance/browser-baseline.json');
const artifactPath = resolve(root, 'artifacts/architecture-performance/browser-report.json');
const traceDirectory = resolve(root, 'artifacts/architecture-performance/traces');
const port = Number(process.env.INVOKEAI_PERFORMANCE_PORT ?? 4176);
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 baseline = JSON.parse(await readFile(baselinePath, 'utf8'));
if (!updateBaseline) {
validateBrowserBaseline(baseline);
}
if (!updateBaseline && JSON.stringify(baseline.sampling) !== JSON.stringify(fullSampleConfig)) {
throw new Error(
`Browser sampling configuration changed. Expected ${JSON.stringify(baseline.sampling)}, received ${JSON.stringify(fullSampleConfig)}.`
);
}
const {
mode,
sampling: sampleConfig,
samples: samplePlan,
} = createBrowserRunPlan({
sampling: fullSampleConfig,
profile: process.argv.includes('--profile'),
updateBaseline,
});
const referenceDir = process.env[PERFORMANCE_REFERENCE_DIR_VARIABLE] || null;
const referenceLabel = process.env[PERFORMANCE_REFERENCE_LABEL_VARIABLE] || null;
const getRequestedScriptLabels = (scripts) =>
new Set([...scripts].map((request) => scriptLabelByPath.get(request) ?? request));
const waitForWidgetRequests = async (fixture, scripts) => {
await waitForRequiredRequests({
context: `${fixture.id}/${fixture.stateProfile}`,
getRequested: () => getRequestedScriptLabels(scripts),
requiredRequests: fixture.requiredWidgetRequests ?? [],
});
const requested = getRequestedScriptLabels(scripts);
for (const forbidden of fixture.forbiddenWidgetRequests ?? []) {
if (requested.has(forbidden)) {
throw new Error(`${fixture.id}/${fixture.stateProfile} requested inactive ${forbidden}.`);
}
}
};
const waitForPreview = async () => {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
try {
const response = await fetch(origin);
if (response.ok) {
return;
}
} catch {
// The preview server is still starting.
}
await new Promise((resolveWait) => {
setTimeout(resolveWait, 100);
});
}
throw new Error(`Vite preview did not become ready at ${origin}.`);
};
const waitForSemanticMark = async (page, mark) => {
await page.waitForFunction((markName) => performance.getEntriesByName(markName, 'mark').length > 0, mark, {
timeout: 20_000,
});
return page.evaluate((markName) => {
const entries = performance.getEntriesByName(markName, 'mark');
return entries.at(-1)?.startTime ?? 0;
}, mark);
};
const isStaticAssetPath = (path) =>
path === '/' || path === '/index.html' || path.startsWith('/assets/') || path.startsWith('/locales/');
const getBrowserResourceKind = (resourceType) => {
if (resourceType === 'script') {
return 'script';
}
if (resourceType === 'stylesheet') {
return 'css';
}
if (resourceType === 'font') {
return 'font';
}
if (resourceType === 'image') {
return 'image';
}
return 'other';
};
const createResourceCollector = (page) => {
const pending = [];
const resources = new Map();
page.on('response', (response) => {
const url = new URL(response.url());
if (url.origin !== origin || !isStaticAssetPath(url.pathname)) {
return;
}
const path = url.pathname;
const kind = getBrowserResourceKind(response.request().resourceType());
const contentLength = Number(response.headers()['content-length'] ?? 0);
const body = response
.body()
.then((bytes) => {
resources.set(path, { kind, path, rawBytes: bytes.byteLength });
})
.catch(() => {
if (contentLength > 0) {
resources.set(path, { kind, path, rawBytes: contentLength });
}
});
pending.push(body);
});
const settle = async () => {
let observedPendingCount = -1;
while (observedPendingCount !== pending.length) {
observedPendingCount = pending.length;
await Promise.all(pending);
await page.waitForTimeout(25);
}
return [...resources.values()].sort((left, right) => left.path.localeCompare(right.path));
};
return { settle };
};
const getScriptSourceOwners = (scripts) => {
const owners = new Set();
for (const request of scripts) {
const sourceOwners = scriptSourceOwnersByPath.get(request);
if (!sourceOwners) {
throw new Error(`No source ownership was emitted for requested script ${request}.`);
}
for (const sourceOwner of sourceOwners) {
owners.add(sourceOwner);
}
}
return [...owners].sort();
};
const createSourceOwnerSets = (routes) => {
const sets = {};
const setIdByFingerprint = new Map();
const routeSetIds = new Map();
for (const route of routes) {
const fingerprint = JSON.stringify(route.scriptSourceOwners);
let setId = setIdByFingerprint.get(fingerprint);
if (!setId) {
const baseId = `${route.id}-static`;
setId = baseId;
let suffix = 2;
while (sets[setId]) {
setId = `${baseId}-${String(suffix)}`;
suffix += 1;
}
sets[setId] = route.scriptSourceOwners;
setIdByFingerprint.set(fingerprint, setId);
}
routeSetIds.set(`${route.id}:${route.stateProfile}`, setId);
}
return { routeSetIds, sets };
};
/** Wait for main-thread idle between switches so the next sample excludes the previous switch's work. */
const settleMainThread = (page) =>
page.evaluate(
() =>
new Promise((resolveSettle) => {
const settle = (remaining) => {
if (remaining === 0) {
resolveSettle();
return;
}
requestAnimationFrame(() => {
requestIdleCallback(() => settle(remaining - 1), { timeout: 2000 });
});
};
settle(4);
})
);
/** Measure a warm return switch after all other samples, without perturbing their resources or timings. */
const measureLayoutReturnSwitch = async (page, fixture) => {
if (!fixture.layoutReturnPreset) {
return 0;
}
const homeTab = page.getByRole('tab', { exact: true, name: fixture.layoutPreset });
const awayTab = page.getByRole('tab', { exact: true, name: fixture.layoutReturnPreset });
await awayTab.waitFor({ timeout: 10_000 });
await page.evaluate((markName) => {
performance.clearMarks(markName);
}, fixture.layoutReturnReadyMark);
await awayTab.click();
await waitForSemanticMark(page, fixture.layoutReturnReadyMark);
await settleMainThread(page);
const interactionMark = `invokeai:interaction:${fixture.id}:${fixture.stateProfile}:layout-return-switch`;
await page.evaluate(
({ interactionMarkName, readyMark }) => {
performance.clearMarks(interactionMarkName);
performance.clearMarks(readyMark);
document.addEventListener(
'pointerdown',
() => {
performance.mark(interactionMarkName);
},
{ capture: true, once: true }
);
},
{ interactionMarkName: interactionMark, readyMark: fixture.readyMark }
);
await homeTab.click();
await waitForSemanticMark(page, fixture.readyMark);
const layoutReturnSwitchMs = await page.evaluate(
({ interactionMarkName, readyMark }) => {
const start = performance.getEntriesByName(interactionMarkName, 'mark').at(-1);
const end = performance.getEntriesByName(readyMark, 'mark').at(-1);
return start && end ? Math.max(0, end.startTime - start.startTime) : null;
},
{ interactionMarkName: interactionMark, readyMark: fixture.readyMark }
);
if (layoutReturnSwitchMs === null) {
throw new Error(`${fixture.id}/${fixture.stateProfile} did not record a layout-return-switch interaction.`);
}
return layoutReturnSwitchMs;
};
const getTiming = (page) =>
page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0];
const longTasks = window.__architectureLongTasks;
return {
domContentLoadedMs: navigation ? navigation.domContentLoadedEventEnd : 0,
loadMs: navigation ? navigation.loadEventEnd : 0,
longestTaskMs: longTasks.reduce((maximum, duration) => Math.max(maximum, duration), 0),
};
});
const runSample = async (browser, fixture, sample) => {
const reset = await fetch(`${backendOrigin}/__reset?profile=${encodeURIComponent(fixture.stateProfile)}`, {
method: 'POST',
});
if (!reset.ok) {
throw new Error(`Mock backend reset failed for profile ${fixture.stateProfile}: ${await reset.text()}`);
}
const profile = await reset.json();
if (profile.profile !== fixture.stateProfile) {
throw new Error(`Mock backend selected ${String(profile.profile)} instead of requested ${fixture.stateProfile}.`);
}
const expectedProfileCounts = fixtures.stateProfiles[fixture.stateProfile];
if (!expectedProfileCounts || JSON.stringify(profile.counts) !== JSON.stringify(expectedProfileCounts)) {
throw new Error(
`Mock backend profile ${fixture.stateProfile} has the wrong workload shape.\nExpected ${JSON.stringify(
expectedProfileCounts
)}\nReceived ${JSON.stringify(profile.counts)}`
);
}
const context = await browser.newContext();
const tracePath = resolve(traceDirectory, `${fixture.id}-${fixture.stateProfile}.zip`);
if (sample.kind === 'trace') {
await mkdir(traceDirectory, { recursive: true });
await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
}
const page = await context.newPage();
const diagnostics = await observeBrowserDiagnostics(page);
try {
await page.addInitScript(() => {
window.__architectureLongTasks = [];
new PerformanceObserver((list) => {
window.__architectureLongTasks.push(...list.getEntries().map((entry) => entry.duration));
}).observe({ buffered: true, type: 'longtask' });
});
const scripts = new Set();
page.on('response', (response) => {
if (response.request().resourceType() === 'script' && response.url().startsWith(origin)) {
scripts.add(new URL(response.url()).pathname);
}
});
const resourceCollector = createResourceCollector(page);
const expectedScript = fixture.expectedScriptPattern
? page.waitForResponse(
(response) =>
response.request().resourceType() === 'script' && response.url().includes(fixture.expectedScriptPattern),
{ timeout: 10_000 }
)
: null;
await page.goto(`${origin}${fixture.path}`, { waitUntil: 'domcontentloaded' });
await expectedScript;
let activatedResourcePaths = new Set();
let layoutSwitchMs = 0;
let layoutAckMs = 0;
if (fixture.layoutPreset || fixture.centerView) {
await waitForRequiredRequests({
context: `${fixture.id}/${fixture.stateProfile} before activation`,
getRequested: () => getRequestedScriptLabels(scripts),
requiredRequests: fixture.preActivationRequiredWidgetRequests ?? [],
});
await waitForStableRequests({
context: `${fixture.id}/${fixture.stateProfile} before activation`,
getRequested: () => scripts,
});
const activationTrigger = fixture.layoutPreset
? page.getByRole('tab', { exact: true, name: fixture.layoutPreset })
: page.getByRole('button', { name: /^Center view:/ });
await activationTrigger.waitFor({ timeout: 10_000 });
const beforeActivation = await resourceCollector.settle();
const beforePaths = new Set(beforeActivation.map((resource) => resource.path));
const interactionMark = `invokeai:interaction:${fixture.id}:${fixture.stateProfile}:layout-switch`;
const ackMark = `invokeai:interaction:${fixture.id}:${fixture.stateProfile}:layout-ack`;
let activationTarget = activationTrigger;
if (fixture.centerView) {
await activationTrigger.click();
activationTarget = page.getByRole('menuitemradio', { exact: true, name: fixture.centerView });
await activationTarget.waitFor({ timeout: 10_000 });
}
await page.evaluate(
({ ackMarkName, interactionMarkName, presetId, readyMark }) => {
performance.clearMarks(interactionMarkName);
performance.clearMarks(readyMark);
performance.clearMarks(ackMarkName);
document.addEventListener(
'pointerdown',
() => {
performance.mark(interactionMarkName);
},
{ capture: true, once: true }
);
if (!presetId) {
return;
}
const target = document.querySelector(`[data-layout-preset-id="${presetId}"]`);
if (!target) {
return;
}
const observer = new MutationObserver(() => {
if (target.getAttribute('aria-selected') === 'true') {
performance.mark(ackMarkName);
observer.disconnect();
}
});
observer.observe(target, { attributes: true, attributeFilter: ['aria-selected'] });
},
{
ackMarkName: ackMark,
interactionMarkName: interactionMark,
presetId: fixture.layoutPresetId ?? null,
readyMark: fixture.readyMark,
}
);
await activationTarget.click();
if (fixture.layoutPreset) {
const activationElement = await activationTarget.elementHandle();
await page.waitForFunction((element) => element?.getAttribute('aria-selected') === 'true', activationElement, {
timeout: 10_000,
});
} else {
await page
.getByRole('button', { exact: true, name: `Center view: ${fixture.centerView}` })
.waitFor({ timeout: 10_000 });
}
await waitForSemanticMark(page, fixture.readyMark);
layoutSwitchMs = await page.evaluate(
({ interactionMarkName, readyMark }) => {
const start = performance.getEntriesByName(interactionMarkName, 'mark').at(-1);
const end = performance.getEntriesByName(readyMark, 'mark').at(-1);
return start && end ? Math.max(0, end.startTime - start.startTime) : null;
},
{ interactionMarkName: interactionMark, readyMark: fixture.readyMark }
);
if (layoutSwitchMs === null) {
throw new Error(`${fixture.id}/${fixture.stateProfile} did not record a layout-switch interaction.`);
}
if (fixture.layoutPreset) {
layoutAckMs = await page.evaluate(
({ ackMarkName, interactionMarkName }) => {
const start = performance.getEntriesByName(interactionMarkName, 'mark').at(-1);
const end = performance.getEntriesByName(ackMarkName, 'mark').at(-1);
return start && end ? Math.max(0, end.startTime - start.startTime) : null;
},
{ ackMarkName: ackMark, interactionMarkName: interactionMark }
);
if (layoutAckMs === null) {
throw new Error(
`${fixture.id}/${fixture.stateProfile} did not record a layout-ack interaction for preset ${fixture.layoutPresetId}.`
);
}
}
const afterActivation = await resourceCollector.settle();
activatedResourcePaths = new Set(
afterActivation.filter((resource) => !beforePaths.has(resource.path)).map((resource) => resource.path)
);
} else {
await waitForSemanticMark(page, fixture.readyMark);
}
let projectSwitchMs = 0;
if (fixture.measureProjectSwitch) {
const projectSwitcher = page.getByRole('button', { name: /^Switch project\. Current project:/ });
const originalProjectName = (await projectSwitcher.textContent())?.trim();
if (!originalProjectName) {
throw new Error(`${fixture.id}/${fixture.stateProfile} project switcher did not name the active project.`);
}
await projectSwitcher.click();
const newProjectSave = page.waitForResponse(
(response) =>
response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/v1/projects/',
{ timeout: 10_000 }
);
await diagnostics.withGalleryProjectSwitch(() =>
page.getByRole('menuitem', { exact: true, name: /new project/i }).click()
);
await page.waitForFunction(
(name) => document.querySelector('button[aria-label^="Switch project."]')?.textContent?.trim() !== name,
originalProjectName
);
// Wait for first autosave reconciliation and paint so layout-switch timing excludes board assignment.
const newProjectSaveResponse = await newProjectSave;
await newProjectSaveResponse.finished();
await page.evaluate(
() =>
new Promise((resolvePaint) => {
requestAnimationFrame(() => requestAnimationFrame(resolvePaint));
})
);
await projectSwitcher.click();
const originalProject = page.getByRole('menuitemradio').filter({ hasText: originalProjectName });
await originalProject.waitFor({ timeout: 10_000 });
const projectSwitchInteractionMark = `invokeai:interaction:${fixture.id}:${fixture.stateProfile}:project-switch`;
const projectSwitchReadyMark = `invokeai:ready:${fixture.id}:${fixture.stateProfile}:project-switch`;
await page.evaluate(
({ interactionMarkName, originalName, readyMarkName }) => {
performance.clearMarks(interactionMarkName);
performance.clearMarks(readyMarkName);
const projectSwitcher = document.querySelector('button[aria-label^="Switch project."]');
if (!projectSwitcher) {
throw new Error('Project switcher trigger is missing.');
}
const markReadyWhenProjectCommits = () => {
if (projectSwitcher.getAttribute('aria-label') !== `Switch project. Current project: ${originalName}`) {
return;
}
performance.mark(readyMarkName);
observer.disconnect();
};
const observer = new MutationObserver(markReadyWhenProjectCommits);
observer.observe(projectSwitcher, { attributes: true, childList: true, subtree: true });
document.addEventListener(
'pointerdown',
() => {
performance.mark(interactionMarkName);
},
{ capture: true, once: true }
);
},
{
interactionMarkName: projectSwitchInteractionMark,
originalName: originalProjectName,
readyMarkName: projectSwitchReadyMark,
}
);
await diagnostics.withGalleryProjectSwitch(() => originalProject.click());
await waitForSemanticMark(page, projectSwitchReadyMark);
projectSwitchMs = await page.evaluate(
({ interactionMarkName, readyMarkName }) => {
const start = performance.getEntriesByName(interactionMarkName, 'mark').at(-1);
const end = performance.getEntriesByName(readyMarkName, 'mark').at(-1);
return start && end ? Math.max(0, end.startTime - start.startTime) : null;
},
{ interactionMarkName: projectSwitchInteractionMark, readyMarkName: projectSwitchReadyMark }
);
if (projectSwitchMs === null) {
throw new Error(`${fixture.id}/${fixture.stateProfile} did not record a project-switch interaction.`);
}
}
await waitForWidgetRequests(fixture, scripts);
const routeReadyMs = await waitForSemanticMark(page, fixture.readyMark);
const renderedMedia = await waitForRenderedMedia(page, {
canvas: fixture.id === 'editor-canvas' && fixture.stateProfile === 'representative',
requireImage: fixture.stateProfile === 'representative' && ['launchpad', 'editor-minimal'].includes(fixture.id),
});
const resources = await resourceCollector.settle();
const activatedResources = resources.filter((resource) => activatedResourcePaths.has(resource.path));
const timing = await getTiming(page);
const scriptSourceOwners = getScriptSourceOwners(scripts);
const layoutReturnSwitchMs = await measureLayoutReturnSwitch(page, fixture);
const sustained =
(mode === 'resources' || sample.kind === 'scored') &&
fixture.id === 'editor-minimal' &&
fixture.stateProfile === 'representative'
? await runSustainedWorkload(page)
: null;
await diagnostics.assertHealthy();
if (sustained) {
await mkdir(dirname(artifactPath), { recursive: true });
await writeFile(
resolve(dirname(artifactPath), `sustained-${sample.index}.json`),
JSON.stringify(
{
runner: process.env.GITHUB_RUNNER_NAME ?? process.env.RUNNER_NAME ?? 'local-unconfigured',
platform: process.platform,
browser: browser.version(),
renderedMedia,
mediaRequests: diagnostics.media,
sustained,
},
null,
2
)
);
}
return {
media: { renderedMedia, requests: diagnostics.media },
activatedResources: summarizeBrowserResources(activatedResources),
profileCounts: profile.counts,
resources: summarizeBrowserResources(resources),
scriptSourceOwners,
timing: {
...timing,
layoutAckMs,
layoutReturnSwitchMs,
layoutSwitchMs,
projectSwitchMs,
routeReadyMs,
},
tracePath: sample.kind === 'trace' ? tracePath : null,
};
} catch (error) {
await mkdir(dirname(artifactPath), { recursive: true });
const failurePath = resolve(
dirname(artifactPath),
`failure-${fixture.id}-${fixture.stateProfile}-${sample.kind}-${sample.index}`
);
await writeFile(
`${failurePath}.json`,
JSON.stringify(
{
error: String(error),
diagnostics: diagnostics.errors,
media: diagnostics.media,
sustained: error.sustained ?? null,
},
null,
2
)
);
await page.screenshot({ path: `${failurePath}.png`, fullPage: true }).catch(() => {});
throw error;
} finally {
if (sample.kind === 'trace') {
await context.tracing.stop({ path: tracePath });
}
await context.close();
}
};
// Use only the disposable mock backend for measurements.
const mockBackend = await startMockBackend(backendPort);
const preview = spawnPreview({
cwd: root,
env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
port,
stdio: ['ignore', 'pipe', 'pipe'],
});
let previewError = '';
preview.stderr.on('data', (chunk) => {
previewError += String(chunk);
});
let browser;
const captureFailureTrace = async (fixture) => {
if (mode !== 'resources') {
return;
}
try {
await runSample(browser, fixture, { index: 0, kind: 'trace' });
} catch (error) {
// Diagnostics must never replace the original gate failure.
process.stderr.write(`Diagnostic trace for ${fixture.id}/${fixture.stateProfile} failed: ${String(error)}\n`);
}
};
try {
await waitForPreview();
browser = await chromium.launch({ headless: true });
const routeReports = [];
for (const fixture of fixtures.routes) {
const observedSamples = [];
let traceSample = null;
try {
for (const sample of samplePlan) {
let result;
try {
result = await runSample(browser, fixture, sample);
} catch (error) {
throw new Error(
`${sample.kind} sample ${String(sample.index)} failed: ${error instanceof Error ? error.message : String(error)}`
);
}
if (sample.kind === 'trace') {
traceSample = result;
}
if (sample.kind === 'scored' || sample.kind === 'resource') {
observedSamples.push(result);
}
}
routeReports.push({
...summarizeBrowserSamples(observedSamples, mode),
mediaObservations: observedSamples.map((sample) => sample.media),
id: fixture.id,
owner: fixture.owner,
readyMark: fixture.readyMark,
remediationTicket: fixture.remediationTicket,
stateProfile: fixture.stateProfile,
traceSample,
});
} catch (error) {
await captureFailureTrace(fixture);
throw new Error(
`${fixture.id}/${fixture.stateProfile} ${error instanceof Error ? error.message : String(error)}`
);
}
}
// 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,
mode,
routes: routeReports,
sampling: sampleConfig,
schemaVersion: 2,
};
if (updateBaseline) {
const previousBaseline = JSON.parse(await readFile(baselinePath, 'utf8'));
const sourceOwnerSets = createSourceOwnerSets(routeReports);
const baseline = {
browserExecutable: report.browserExecutable,
capturedAt: new Date().toISOString().slice(0, 10),
routes: routeReports.map((route) => ({
activatedResourceBaseline: route.activatedResources,
domContentLoadedMedianMs: route.domContentLoadedMedianMs,
id: route.id,
layoutAckMedianMs: route.layoutAckMedianMs,
layoutReturnSwitchMedianMs: route.layoutReturnSwitchMedianMs,
layoutSwitchMedianMs: route.layoutSwitchMedianMs,
loadMedianMs: route.loadMedianMs,
longestTaskMaxMs: route.longestTaskMaxMs,
owner: route.owner,
projectSwitchMedianMs: route.projectSwitchMedianMs,
readyMark: route.readyMark,
remediationTicket: route.remediationTicket,
resourceBaseline: route.resources,
routeReadyMedianMs: route.routeReadyMedianMs,
scriptSourceOwnerSet: sourceOwnerSets.routeSetIds.get(`${route.id}:${route.stateProfile}`),
stateProfile: route.stateProfile,
})),
sampling: sampleConfig,
schemaVersion: 2,
scriptSourceOwnerSets: sourceOwnerSets.sets,
timingPolicy:
previousBaseline.schemaVersion === 2
? previousBaseline.timingPolicy
: {
enforce: false,
longTaskTargetMs: 50,
runner: {
id: 'unconfigured',
minimumStableRuns: 20,
observedStableRuns: 0,
stable: false,
},
tolerancePercent: 0.1,
},
};
validateBrowserBaseline(baseline);
await writeFile(baselinePath, `${JSON.stringify(baseline, null, 2)}\n`);
await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);
} else {
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: byte allowance over the higher of ${referenceName} captured ${reference.capturedAt} and committed measurements, bounded by the committed hard ceiling; request counts use the lower measurement.\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 = [];
for (const route of routeReports) {
const expected = expectedRoutes.find(
(candidate) => candidate.id === route.id && candidate.stateProfile === route.stateProfile
);
if (!expected) {
failures.push(`${route.id}/${route.stateProfile} has no checked-in browser baseline (owner ${route.owner}).`);
continue;
}
if (expected.readyMark !== route.readyMark) {
failures.push(
`${route.id}/${route.stateProfile} semantic-ready mark changed from ${expected.readyMark} to ${route.readyMark}.`
);
}
const routeFailures = checkBrowserRouteBudget(
route,
expected,
baseline.scriptSourceOwnerSets[expected.scriptSourceOwnerSet]
);
failures.push(...routeFailures);
if (routeFailures.length > 0) {
await captureFailureTrace(
fixtures.routes.find((fixture) => fixture.id === route.id && fixture.stateProfile === route.stateProfile)
);
}
}
for (const expected of baseline.routes) {
if (!routeReports.some((route) => route.id === expected.id && route.stateProfile === expected.stateProfile)) {
failures.push(`${expected.id}/${expected.stateProfile} baseline has no executable fixture.`);
}
}
if (failures.length > 0) {
throw new Error(`${failures.join('\n')}${failures.some(isBudgetFailure) ? `\n${BUDGET_REMEDY}` : ''}`);
}
}
process.stdout.write(
`${JSON.stringify(
{
artifactPath,
mode,
routes: routeReports.map((route) => ({
activatedResources: route.activatedResources,
id: route.id,
resources: route.resources,
stateProfile: route.stateProfile,
variance: route.variance,
})),
sampling: sampleConfig,
},
null,
2
)}\n`
);
} catch (error) {
throw new Error(
`${error instanceof Error ? error.message : String(error)}${previewError ? `\n${previewError}` : ''}\n${PERFORMANCE_GUIDE}`
);
} finally {
await browser?.close();
if (preview.pid) {
try {
killPreview(preview.pid, 'SIGTERM');
} catch {
// The preview process may have already exited after a startup failure.
}
}
await mockBackend.close();
}