Add perf regression test harnesses
- Seed reusable perf fixtures for server scenarios - Add perf provider adapter and web perf tests - Capture artifacts for virtualization and websocket runs
This commit is contained in:
1 parent
1bf048eb8b
commit
eecc2bc28d
26 files changed
+3688
-5
No files matched your search
@@ -11,7 +11,9 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test:browser:install": "playwright install --with-deps chromium",
|
||||
"test:perf": "vitest run --config vitest.perf.config.ts",
|
||||
"test:perf:install": "playwright install --with-deps chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, mkdir, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { once } from "node:events";
|
||||
|
||||
import { chromium, type Page } from "playwright";
|
||||
|
||||
import {
|
||||
type BrowserPerfMetrics,
|
||||
summarizeBrowserPerfMetrics,
|
||||
type PerfRunArtifact,
|
||||
type PerfServerMetricSample,
|
||||
writePerfArtifact,
|
||||
} from "../../../../test/perf/support/artifact";
|
||||
import {
|
||||
installBrowserPerfCollector,
|
||||
PERF_BROWSER_GLOBAL,
|
||||
} from "../../../../test/perf/support/browserMetrics";
|
||||
import type { PerfThresholdProfile } from "../../../../test/perf/support/thresholds";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import {
|
||||
NoopServerSampler,
|
||||
type PerfServerSampler,
|
||||
} from "../../../../test/perf/support/serverSampler";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const serverBinPath = resolve(repoRoot, "apps/server/dist/bin.mjs");
|
||||
const serverClientIndexPath = resolve(repoRoot, "apps/server/dist/client/index.html");
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
|
||||
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
|
||||
interface PerfSeedThreadSummary {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly messageCount: number;
|
||||
readonly activityCount: number;
|
||||
readonly proposedPlanCount: number;
|
||||
readonly checkpointCount: number;
|
||||
}
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
|
||||
}
|
||||
|
||||
interface StartPerfAppHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
readonly serverSampler?: PerfServerSampler;
|
||||
}
|
||||
|
||||
interface FinishPerfRunOptions {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly thresholds: PerfThresholdProfile;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
readonly actionSummary?: {
|
||||
readonly threadSwitchActionPrefix?: string;
|
||||
readonly burstActionName?: string;
|
||||
};
|
||||
readonly artifactBasename?: string;
|
||||
}
|
||||
|
||||
export interface PerfAppHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly page: Page;
|
||||
readonly url: string;
|
||||
readonly artifactDir: string;
|
||||
readonly startAction: (name: string) => Promise<void>;
|
||||
readonly endAction: (name: string) => Promise<number | null>;
|
||||
readonly resetBrowserMetrics: () => Promise<void>;
|
||||
readonly sampleMountedRows: (label: string) => Promise<number>;
|
||||
readonly snapshotBrowserMetrics: () => Promise<BrowserPerfMetrics>;
|
||||
readonly finishRun: (options: FinishPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: PerfRunArtifact;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForServerReady(url: string, process: ChildProcess): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
const timeoutMs = 45_000;
|
||||
const requestTimeoutMs = 1_000;
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(requestTimeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Ignore connection races while the server is still starting.
|
||||
}
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for perf server readiness at ${url}.`);
|
||||
}
|
||||
|
||||
async function verifyBuiltArtifacts(): Promise<void> {
|
||||
await Promise.all([access(serverBinPath), access(serverClientIndexPath)]).catch(() => {
|
||||
throw new Error(
|
||||
`Built perf artifacts are missing. Expected ${serverBinPath} and ${serverClientIndexPath}. Run bun run test:perf:web or build the app first.`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
async function invokeBrowserCollector<T>(
|
||||
page: Page,
|
||||
fn: (collectorName: string, ...args: ReadonlyArray<unknown>) => T,
|
||||
...args: ReadonlyArray<unknown>
|
||||
): Promise<T> {
|
||||
return await page.evaluate(
|
||||
({ collectorName, args: serializedArgs, fnSource }) => {
|
||||
const runtimeFn = new Function(
|
||||
"collectorName",
|
||||
"args",
|
||||
`return (${fnSource})(collectorName, ...args);`,
|
||||
) as (collectorName: string, args: ReadonlyArray<unknown>) => T;
|
||||
return runtimeFn(collectorName, serializedArgs);
|
||||
},
|
||||
{
|
||||
collectorName: PERF_BROWSER_GLOBAL,
|
||||
args,
|
||||
fnSource: fn.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function parsePerfSeededState(stdout: string): PerfSeededState {
|
||||
const startIndex = stdout.lastIndexOf(PERF_SEED_JSON_START);
|
||||
const endIndex = stdout.lastIndexOf(PERF_SEED_JSON_END);
|
||||
|
||||
if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
|
||||
const payload = stdout.slice(startIndex + PERF_SEED_JSON_START.length, endIndex).trim();
|
||||
return JSON.parse(payload) as PerfSeededState;
|
||||
}
|
||||
|
||||
return JSON.parse(stdout) as PerfSeededState;
|
||||
}
|
||||
|
||||
export async function startPerfAppHarness(
|
||||
options: StartPerfAppHarnessOptions,
|
||||
): Promise<PerfAppHarness> {
|
||||
await verifyBuiltArtifacts();
|
||||
|
||||
const seededState = await (async () => {
|
||||
const seedProcess = spawn(
|
||||
"bun",
|
||||
["run", "apps/server/scripts/seedPerfState.ts", options.seedScenarioId],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
seedProcess.stdout?.on("data", (chunk) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
seedProcess.stderr?.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const [exitCode] = (await once(seedProcess, "exit")) as [number | null];
|
||||
if (exitCode !== 0) {
|
||||
throw new Error(`Perf seed command failed with code ${exitCode ?? "unknown"}.\n${stderr}`);
|
||||
}
|
||||
return parsePerfSeededState(stdout);
|
||||
})();
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const url = `http://127.0.0.1:${port}/`;
|
||||
const env = {
|
||||
...process.env,
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
...(options.providerScenarioId ? { [PERF_SCENARIO_ENV]: options.providerScenarioId } : {}),
|
||||
};
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
const serverProcess = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
serverBinPath,
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
|
||||
await waitForServerReady(url, serverProcess);
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: process.env[PERF_HEADFUL_ENV] !== "1",
|
||||
});
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 960 },
|
||||
});
|
||||
await context.addInitScript(installBrowserPerfCollector, "[data-timeline-row-kind]");
|
||||
const page = await context.newPage();
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
|
||||
const firstProjectTitle =
|
||||
seededState.projectTitle ?? getPerfSeedScenario(options.seedScenarioId).project.title;
|
||||
if (!firstProjectTitle) {
|
||||
throw new Error(`Seed scenario '${options.seedScenarioId}' produced no projects.`);
|
||||
}
|
||||
await page.getByText(firstProjectTitle, { exact: true }).first().waitFor({ timeout: 45_000 });
|
||||
|
||||
const sampler = options.serverSampler ?? new NoopServerSampler();
|
||||
if (serverProcess.pid) {
|
||||
await sampler.start({ pid: serverProcess.pid });
|
||||
}
|
||||
const runStartedAt = new Date().toISOString();
|
||||
|
||||
let finishPromise: Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: PerfRunArtifact;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
}> | null = null;
|
||||
|
||||
const teardown = async () => {
|
||||
await Promise.allSettled([context.close(), browser.close()]);
|
||||
await stopChildProcess(serverProcess);
|
||||
};
|
||||
|
||||
return {
|
||||
seededState,
|
||||
page,
|
||||
url,
|
||||
artifactDir,
|
||||
startAction: (name) =>
|
||||
invokeBrowserCollector(
|
||||
page,
|
||||
(collectorName, actionName) => {
|
||||
(window as Window & Record<string, any>)[collectorName]?.startAction(
|
||||
actionName as string,
|
||||
);
|
||||
},
|
||||
name,
|
||||
),
|
||||
endAction: (name) =>
|
||||
invokeBrowserCollector(
|
||||
page,
|
||||
(collectorName, actionName) => {
|
||||
return (
|
||||
(window as Window & Record<string, any>)[collectorName]?.endAction(
|
||||
actionName as string,
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
name,
|
||||
),
|
||||
resetBrowserMetrics: () =>
|
||||
invokeBrowserCollector(page, (collectorName) => {
|
||||
(window as Window & Record<string, any>)[collectorName]?.reset();
|
||||
}),
|
||||
sampleMountedRows: (label) =>
|
||||
invokeBrowserCollector(
|
||||
page,
|
||||
(collectorName, sampleLabel) => {
|
||||
return (
|
||||
(window as Window & Record<string, any>)[collectorName]?.sampleMountedRows(
|
||||
sampleLabel as string,
|
||||
) ?? 0
|
||||
);
|
||||
},
|
||||
label,
|
||||
),
|
||||
snapshotBrowserMetrics: () =>
|
||||
invokeBrowserCollector(page, (collectorName) => {
|
||||
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
}) as BrowserPerfMetrics;
|
||||
}),
|
||||
finishRun: async (finishOptions) => {
|
||||
if (finishPromise) {
|
||||
return await finishPromise;
|
||||
}
|
||||
|
||||
finishPromise = (async () => {
|
||||
const completedAt = new Date().toISOString();
|
||||
const browserMetrics = await (async () => {
|
||||
try {
|
||||
return await invokeBrowserCollector(page, (collectorName) => {
|
||||
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
}) as BrowserPerfMetrics;
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
} satisfies BrowserPerfMetrics;
|
||||
}
|
||||
})();
|
||||
const serverMetrics = await sampler.stop();
|
||||
await teardown();
|
||||
|
||||
const basename =
|
||||
finishOptions.artifactBasename ?? `${finishOptions.suite}-${finishOptions.scenarioId}`;
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifact: PerfRunArtifact = {
|
||||
suite: finishOptions.suite,
|
||||
scenarioId: finishOptions.scenarioId,
|
||||
startedAt: runStartedAt,
|
||||
completedAt,
|
||||
thresholds: finishOptions.thresholds,
|
||||
summary: summarizeBrowserPerfMetrics(browserMetrics, finishOptions.actionSummary),
|
||||
browserMetrics,
|
||||
serverMetrics,
|
||||
...(finishOptions.metadata ? { metadata: finishOptions.metadata } : {}),
|
||||
};
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writePerfArtifact(artifactPath, artifact);
|
||||
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
browserMetrics,
|
||||
serverMetrics,
|
||||
};
|
||||
})();
|
||||
|
||||
return await finishPromise;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { Page } from "playwright";
|
||||
|
||||
import type { PerfAppHarness } from "./appHarness";
|
||||
|
||||
export async function ensureThreadRowVisible(
|
||||
page: Page,
|
||||
projectTitle: string,
|
||||
threadId: string,
|
||||
): Promise<void> {
|
||||
const threadRow = page.getByTestId(`thread-row-${threadId}`);
|
||||
if (await threadRow.isVisible().catch(() => false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectToggle = page.getByText(projectTitle, { exact: true }).first();
|
||||
await projectToggle.click();
|
||||
await threadRow.waitFor({ state: "visible", timeout: 20_000 });
|
||||
}
|
||||
|
||||
export async function waitForThreadRoute(
|
||||
page: Page,
|
||||
input: {
|
||||
readonly threadId: string;
|
||||
readonly messageId?: string;
|
||||
readonly extraSelector?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const path = `/${encodeURIComponent(input.threadId)}`;
|
||||
await page.waitForFunction(
|
||||
({ expectedPath, messageSelector, extraSelector }) => {
|
||||
const pathMatches = window.location.pathname === expectedPath;
|
||||
if (!pathMatches) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (messageSelector && !document.querySelector(messageSelector)) {
|
||||
return false;
|
||||
}
|
||||
if (extraSelector && !document.querySelector(extraSelector)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
expectedPath: path,
|
||||
messageSelector: input.messageId ? `[data-message-id="${input.messageId}"]` : null,
|
||||
extraSelector: input.extraSelector ?? null,
|
||||
},
|
||||
{ timeout: 45_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function measureThreadSwitch(
|
||||
harness: PerfAppHarness,
|
||||
input: {
|
||||
readonly actionName: string;
|
||||
readonly projectTitle: string;
|
||||
readonly threadId: string;
|
||||
readonly messageId?: string;
|
||||
readonly extraSelector?: string;
|
||||
},
|
||||
): Promise<number | null> {
|
||||
await ensureThreadRowVisible(harness.page, input.projectTitle, input.threadId);
|
||||
await harness.startAction(input.actionName);
|
||||
await harness.page.getByTestId(`thread-row-${input.threadId}`).click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: input.threadId,
|
||||
...(input.messageId ? { messageId: input.messageId } : {}),
|
||||
...(input.extraSelector ? { extraSelector: input.extraSelector } : {}),
|
||||
});
|
||||
return await harness.endAction(input.actionName);
|
||||
}
|
||||
|
||||
export async function scrollTimelineTo(page: Page, position: "top" | "bottom"): Promise<void> {
|
||||
await page.evaluate(async (targetPosition) => {
|
||||
const timelineRoot = document.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
const scrollContainer = timelineRoot?.parentElement;
|
||||
if (!scrollContainer) {
|
||||
throw new Error("Messages scroll container not found.");
|
||||
}
|
||||
|
||||
scrollContainer.scrollTo({
|
||||
top: targetPosition === "bottom" ? scrollContainer.scrollHeight : 0,
|
||||
behavior: "auto",
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
}, position);
|
||||
}
|
||||
|
||||
export async function typeIntoComposerAndSend(page: Page, message: string): Promise<void> {
|
||||
const editor = page.getByTestId("composer-editor");
|
||||
await editor.click();
|
||||
await page.keyboard.type(message);
|
||||
await page.getByRole("button", { name: "Send message" }).click();
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds";
|
||||
import { startPerfAppHarness, type PerfAppHarness } from "./appHarness";
|
||||
import {
|
||||
ensureThreadRowVisible,
|
||||
measureThreadSwitch,
|
||||
scrollTimelineTo,
|
||||
waitForThreadRoute,
|
||||
} from "./pagePerfHelpers";
|
||||
|
||||
test("virtualization stays bounded and heavy thread switches remain snappy", async () => {
|
||||
const thresholds = PERF_THRESHOLDS.local;
|
||||
let harness: PerfAppHarness | null = null;
|
||||
let finished = false;
|
||||
|
||||
try {
|
||||
harness = await startPerfAppHarness({
|
||||
suite: "virtualization",
|
||||
seedScenarioId: "large_threads",
|
||||
});
|
||||
|
||||
const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace";
|
||||
const heavyThreadMessageCount =
|
||||
harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
)?.messageCount ?? 0;
|
||||
expect(heavyThreadMessageCount).toBeGreaterThanOrEqual(2_000);
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
projectTitle,
|
||||
PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyAThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
});
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
projectTitle,
|
||||
PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyBThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
});
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
|
||||
await harness.resetBrowserMetrics();
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-warmup-a",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
});
|
||||
|
||||
const mountedRows = await harness.sampleMountedRows("heavy-a-open");
|
||||
expect(mountedRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows);
|
||||
|
||||
const measuredTargets = [
|
||||
{
|
||||
actionName: "thread-switch-1",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-2",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-3",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-4",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-5",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-6",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const target of measuredTargets) {
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: target.actionName,
|
||||
projectTitle,
|
||||
threadId: target.threadId,
|
||||
messageId: target.messageId,
|
||||
});
|
||||
await harness.sampleMountedRows(`${target.actionName}-rows`);
|
||||
}
|
||||
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
await harness.sampleMountedRows("scroll-start");
|
||||
await scrollTimelineTo(harness.page, "top");
|
||||
await harness.sampleMountedRows("scroll-top");
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
await harness.sampleMountedRows("scroll-bottom");
|
||||
|
||||
const browserMetrics = await harness.snapshotBrowserMetrics();
|
||||
const summary = summarizeBrowserPerfMetrics(browserMetrics, {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
});
|
||||
|
||||
expect(summary.threadSwitchP50Ms).not.toBeNull();
|
||||
expect(summary.threadSwitchP95Ms).not.toBeNull();
|
||||
expect(summary.threadSwitchP50Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.threadSwitchP50Ms,
|
||||
);
|
||||
expect(summary.threadSwitchP95Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.threadSwitchP95Ms,
|
||||
);
|
||||
expect(summary.maxMountedTimelineRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows);
|
||||
expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs);
|
||||
expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs);
|
||||
|
||||
await harness.finishRun({
|
||||
suite: "virtualization",
|
||||
scenarioId: "large_threads",
|
||||
thresholds,
|
||||
metadata: {
|
||||
heavyThreadMessageCount,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
},
|
||||
});
|
||||
finished = true;
|
||||
} finally {
|
||||
if (harness && !finished) {
|
||||
await harness.finishRun({
|
||||
suite: "virtualization",
|
||||
scenarioId: "large_threads",
|
||||
thresholds,
|
||||
metadata: {
|
||||
heavyThreadMessageCount: harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
)?.messageCount,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact";
|
||||
import { PERF_CATALOG_IDS, PERF_PROVIDER_SCENARIOS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds";
|
||||
import { startPerfAppHarness, type PerfAppHarness } from "./appHarness";
|
||||
import {
|
||||
ensureThreadRowVisible,
|
||||
measureThreadSwitch,
|
||||
typeIntoComposerAndSend,
|
||||
waitForThreadRoute,
|
||||
} from "./pagePerfHelpers";
|
||||
|
||||
test("high-frequency websocket events stay responsive under real built-app flow", async () => {
|
||||
const thresholds = PERF_THRESHOLDS.local;
|
||||
let harness: PerfAppHarness | null = null;
|
||||
let finished = false;
|
||||
|
||||
try {
|
||||
harness = await startPerfAppHarness({
|
||||
suite: "websocket-application",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "dense_assistant_stream",
|
||||
});
|
||||
|
||||
const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace";
|
||||
const streamScenario = PERF_PROVIDER_SCENARIOS.dense_assistant_stream;
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
projectTitle,
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.burstBase.burstThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
messageId: PERF_CATALOG_IDS.burstBase.burstTerminalMessageId,
|
||||
});
|
||||
|
||||
await harness.resetBrowserMetrics();
|
||||
await harness.startAction("burst-completion");
|
||||
await typeIntoComposerAndSend(harness.page, "Run the dense websocket perf burst.");
|
||||
|
||||
await harness.page.waitForTimeout(900);
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-burst-nav",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
messageId: PERF_CATALOG_IDS.burstBase.navigationTerminalMessageId,
|
||||
});
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-burst-return",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
messageId: PERF_CATALOG_IDS.burstBase.burstTerminalMessageId,
|
||||
extraSelector: '[data-testid="composer-editor"]',
|
||||
});
|
||||
|
||||
await harness.page.waitForFunction(
|
||||
(sentinelText) => document.body.textContent?.includes(sentinelText as string) ?? false,
|
||||
streamScenario.sentinelText,
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
await harness.endAction("burst-completion");
|
||||
|
||||
const browserMetrics = await harness.snapshotBrowserMetrics();
|
||||
const summary = summarizeBrowserPerfMetrics(browserMetrics, {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
});
|
||||
|
||||
expect(summary.burstCompletionMs).not.toBeNull();
|
||||
expect(summary.burstCompletionMs ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.burstCompletionMs,
|
||||
);
|
||||
expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs);
|
||||
expect(summary.longTasksOver50Ms).toBeLessThanOrEqual(thresholds.longTasksOver50MsMax);
|
||||
expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs);
|
||||
|
||||
const burstNavActions = browserMetrics.actions.filter((action) =>
|
||||
action.name.startsWith("thread-switch-burst"),
|
||||
);
|
||||
expect(burstNavActions).toHaveLength(2);
|
||||
for (const action of burstNavActions) {
|
||||
expect(action.durationMs).toBeLessThanOrEqual(thresholds.threadSwitchP95Ms);
|
||||
}
|
||||
|
||||
await harness.finishRun({
|
||||
suite: "websocket-application",
|
||||
scenarioId: "dense_assistant_stream",
|
||||
thresholds,
|
||||
metadata: {
|
||||
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
sentinelText: streamScenario.sentinelText,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
},
|
||||
});
|
||||
finished = true;
|
||||
} finally {
|
||||
if (harness && !finished) {
|
||||
await harness.finishRun({
|
||||
suite: "websocket-application",
|
||||
scenarioId: "dense_assistant_stream",
|
||||
thresholds,
|
||||
metadata: {
|
||||
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
sentinelText: PERF_PROVIDER_SCENARIOS.dense_assistant_stream.sentinelText,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -21,5 +21,13 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "test"]
|
||||
"include": [
|
||||
"src",
|
||||
"vite.config.ts",
|
||||
"test",
|
||||
"../../test/perf/support/artifact.ts",
|
||||
"../../test/perf/support/browserMetrics.ts",
|
||||
"../../test/perf/support/serverSampler.ts",
|
||||
"../../test/perf/support/thresholds.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["test/perf/**/*.perf.test.ts"],
|
||||
environment: "node",
|
||||
fileParallelism: false,
|
||||
maxConcurrency: 1,
|
||||
testTimeout: 180_000,
|
||||
hookTimeout: 180_000,
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user