Compare commits

...
Author SHA1 Message Date
Cursor Agent e26c2abd97 fix: only enable perf provider env when providerScenarioId is set
Move PERF_PROVIDER_ENV inside the conditional alongside PERF_SCENARIO_ENV
so the perf provider mock is only activated when a provider scenario is
specified, consistent with open-perf-app.ts.
2026-04-02 07:42:21 +00:00
Julius Marminge 062c809aa0 Clean up perf run dirs and cover collector reset
- Persist and remove the seeded run parent directory after perf runs
- Add regression coverage for seed cleanup, percentile clamping, and RAF reset
2026-04-02 00:37:23 -07:00
Julius Marminge b8fba18575 Document local performance benchmark harness
- Add README entry for perf benchmarks
- Document scenarios, commands, artifacts, and env vars
2026-04-02 00:14:42 -07:00
Julius Marminge f1f234d2a0 Exclude perf tests from Vitest default runs
- Keep `bun run test` focused on non-perf suites
2026-04-02 00:04:00 -07:00
Julius Marminge 18f19a6fe8 Add perf regression coverage for dense stream workloads
- Expand perf fixtures with multi-thread live stream events and namespaced IDs
- Harden stream getters and update web perf tests for the heavier workload
2026-04-01 18:56:42 -07:00
32 changed files with 1938 additions and 531 deletions

No files matched your search

+1
View File
@@ -21,3 +21,4 @@ apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
artifacts/
+4
View File
@@ -45,6 +45,10 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
## Performance benchmarks
See [docs/perf-benchmarks.md](./docs/perf-benchmarks.md) for the local perf harness, seeded scenarios, artifact format, and the commands for automated and manual benchmark runs.
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
@@ -488,7 +488,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
get streamEvents() {
return Stream.fromQueue(runtimeEvents);
},
};
const queueTurnResponse = (
@@ -7,20 +7,23 @@ import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
import { seedPerfState } from "./seedPerfState.ts";
describe("seedPerfState", () => {
const baseDirsToCleanup: string[] = [];
const runParentDirsToCleanup: string[] = [];
afterEach(async () => {
await Promise.all(
baseDirsToCleanup.splice(0).map((baseDir) => rm(baseDir, { recursive: true, force: true })),
runParentDirsToCleanup
.splice(0)
.map((runParentDir) => rm(runParentDir, { recursive: true, force: true })),
);
});
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
const seeded = await seedPerfState("large_threads");
baseDirsToCleanup.push(seeded.baseDir);
runParentDirsToCleanup.push(seeded.runParentDir);
expect(seeded.snapshot.projects).toHaveLength(1);
expect(seeded.snapshot.threads).toHaveLength(12);
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
const heavyThread = seeded.snapshot.threads.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
@@ -28,12 +31,13 @@ describe("seedPerfState", () => {
expect(heavyThread?.messages).toHaveLength(2_000);
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
expect((heavyThread?.checkpoints.length ?? 0) > 0).toBe(true);
expect((heavyThread?.checkpoints.length ?? 0) >= 80).toBe(true);
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
});
it("enables assistant streaming in the burst base seed for websocket perf runs", async () => {
const seeded = await seedPerfState("burst_base");
baseDirsToCleanup.push(seeded.baseDir);
runParentDirsToCleanup.push(seeded.runParentDir);
const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8");
expect(JSON.parse(rawSettings)).toMatchObject({
+64 -14
View File
@@ -34,6 +34,7 @@ import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSetti
export interface PerfSeededState {
readonly scenarioId: PerfSeedScenarioId;
readonly runParentDir: string;
readonly baseDir: string;
readonly workspaceRoot: string;
readonly snapshot: OrchestrationReadModel;
@@ -164,6 +165,67 @@ function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: nu
].join("\n");
}
function buildCheckpointFiles(
thread: PerfSeedThreadScenario,
threadOrdinal: number,
turnIndex: number,
): ReadonlyArray<{
readonly path: string;
readonly kind: string;
readonly additions: number;
readonly deletions: number;
}> {
const nestedPathTemplates = [
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "TimelineVirtualizer.tsx"],
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "ThreadSummaryPane.tsx"],
["apps", "web", "src", "hooks", `thread-${threadOrdinal + 1}`, "useThreadViewport.ts"],
["apps", "web", "src", "stores", `thread-${threadOrdinal + 1}`, "timelineStore.ts"],
[
"apps",
"server",
"src",
"orchestration",
`thread-${threadOrdinal + 1}`,
"projectionPipeline.ts",
],
["apps", "server", "src", "provider", `thread-${threadOrdinal + 1}`, "runtimeBuffer.ts"],
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "fixtureBuilders.ts"],
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "scenarioCatalog.ts"],
["packages", "contracts", "src", "orchestration", `thread-${threadOrdinal + 1}`, "schemas.ts"],
["docs", "perf", `thread-${threadOrdinal + 1}`, "notes", "regression-findings.md"],
["scripts", "perf", `thread-${threadOrdinal + 1}`, "capture-profile.ts"],
["test", "perf", "fixtures", `thread-${threadOrdinal + 1}`, "workspace-state.json"],
] as const;
const fileCount = thread.category === "heavy" ? 12 + (turnIndex % 7) : 7 + (turnIndex % 4);
return Array.from({ length: fileCount }, (_, fileIndex) => {
const template = nestedPathTemplates[fileIndex % nestedPathTemplates.length]!;
const variant = Math.floor(fileIndex / nestedPathTemplates.length);
const baseSegments = [...template];
const fileName = baseSegments.pop()!;
const variantFileName =
variant === 0
? fileName
: fileName.replace(/(\.[^.]*)$/, `-${(variant + 1).toString().padStart(2, "0")}$1`);
const path = [...baseSegments, variantFileName].join("/");
const kind =
fileIndex % 9 === 0
? "deleted"
: fileIndex % 5 === 0
? "added"
: fileIndex % 4 === 0
? "renamed"
: "modified";
return {
path,
kind,
additions: kind === "deleted" ? 0 : 4 + ((turnIndex + fileIndex) % 11),
deletions: kind === "added" ? 0 : 1 + ((threadOrdinal + fileIndex + turnIndex) % 6),
};
});
}
function buildThreadTurnEvents(
scenario: PerfSeedScenario,
thread: PerfSeedThreadScenario,
@@ -305,20 +367,7 @@ function buildThreadTurnEvents(
`refs/perf/${String(thread.id)}/${turnIndex.toString().padStart(4, "0")}`,
),
status: "ready",
files: [
{
path: `src/thread-${threadOrdinal + 1}/perf-${turnIndex}.ts`,
kind: "modified",
additions: 4 + (turnIndex % 6),
deletions: 1 + (turnIndex % 3),
},
{
path: `src/thread-${threadOrdinal + 1}/metrics-${turnIndex}.json`,
kind: "added",
additions: 2 + (turnIndex % 4),
deletions: 0,
},
],
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
assistantMessageId,
completedAt: diffOccurredAt,
},
@@ -441,6 +490,7 @@ export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<Per
return {
scenarioId,
runParentDir,
baseDir,
workspaceRoot,
snapshot,
+1
View File
@@ -13,6 +13,7 @@ const seeded = await seedPerfState(scenarioId);
const payload = JSON.stringify(
{
scenarioId: seeded.scenarioId,
runParentDir: seeded.runParentDir,
baseDir: seeded.baseDir,
workspaceRoot: seeded.workspaceRoot,
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
@@ -95,7 +95,9 @@ function createProviderServiceHarness(
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -207,7 +207,9 @@ describe("ProviderCommandReactor", () => {
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -97,7 +97,9 @@ function createProviderServiceHarness() {
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const setSession = (session: ProviderSession): void => {
@@ -11,7 +11,9 @@ const makeRuntimeReceiptBus = Effect.gen(function* () {
return {
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
stream: Stream.fromPubSub(pubSub),
get stream() {
return Stream.fromPubSub(pubSub);
},
} satisfies RuntimeReceiptBusShape;
});
+144 -12
View File
@@ -1,10 +1,11 @@
import { afterEach, describe, expect, it } from "vitest";
import { Effect, Stream } from "effect";
import { ThreadId } from "@t3tools/contracts";
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
const STREAM_SAMPLE_EVENT_COUNT = 96;
describe("PerfProviderAdapter", () => {
const previousScenarioEnv = process.env[PERF_SCENARIO_ENV];
@@ -20,7 +21,7 @@ describe("PerfProviderAdapter", () => {
it("emits canonical runtime events for the dense assistant stream scenario", async () => {
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
const adapter = await Effect.runPromise(makePerfProviderAdapter);
const threadId = ThreadId.makeUnsafe("perf-adapter-test-thread");
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
await Effect.runPromise(
adapter.startSession({
@@ -31,7 +32,7 @@ describe("PerfProviderAdapter", () => {
);
const firstEventsPromise = Effect.runPromise(
Stream.runCollect(Stream.take(adapter.streamEvents, 4)),
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
);
await Effect.runPromise(
adapter.sendTurn({
@@ -42,15 +43,146 @@ describe("PerfProviderAdapter", () => {
);
const firstEvents = Array.from(await firstEventsPromise);
expect(firstEvents.map((event) => event.type)).toEqual([
"turn.started",
"item.started",
"content.delta",
"item.completed",
]);
expect(firstEvents.every((event) => event.threadId === threadId)).toBe(true);
expect(firstEvents.filter((event) => event.type === "turn.started")).toHaveLength(3);
expect(new Set(firstEvents.slice(0, 18).map((event) => String(event.threadId)))).toEqual(
new Set([
String(threadId),
String(PERF_CATALOG_IDS.burstBase.navigationThreadId),
String(PERF_CATALOG_IDS.burstBase.fillerThreadId),
]),
);
expect(
firstEvents[2]?.type === "content.delta" ? firstEvents[2].payload.delta.length : 0,
).toBeGreaterThan(0);
firstEvents.some(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
event.type === "content.delta" &&
event.payload.delta.includes("Navigation lane"),
),
).toBe(true);
expect(
firstEvents.some(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message",
),
).toBe(true);
expect(
firstEvents.some(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.fillerThreadId &&
event.type === "item.updated" &&
event.payload.itemType === "command_execution",
),
).toBe(true);
const firstBurstFollowupCompletionIndex = firstEvents.findIndex(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message" &&
String(event.itemId ?? "").includes("followup"),
);
const burstWorklogIdsBeforeFollowup = new Set(
firstEvents
.slice(0, firstBurstFollowupCompletionIndex)
.filter(
(event) =>
event.threadId === threadId &&
event.type === "item.started" &&
event.payload.itemType === "command_execution",
)
.map((event) => String(event.itemId)),
);
const burstAssistantMessageLengths = firstEvents
.flatMap((event) => {
if (
event.threadId !== threadId ||
event.type !== "item.completed" ||
event.payload.itemType !== "assistant_message" ||
event.payload.detail === undefined
) {
return [];
}
return [event.payload.detail.length];
})
.slice(0, 4);
expect(firstBurstFollowupCompletionIndex).toBeGreaterThan(0);
expect(burstWorklogIdsBeforeFollowup.size).toBeGreaterThanOrEqual(3);
expect(new Set(burstAssistantMessageLengths).size).toBeGreaterThan(1);
});
it("assigns fresh runtime ids when the same burst thread is sent twice", async () => {
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
const adapter = await Effect.runPromise(makePerfProviderAdapter);
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
await Effect.runPromise(
adapter.startSession({
threadId,
provider: "codex",
runtimeMode: "full-access",
}),
);
const firstEventsPromise = Effect.runPromise(
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
);
await Effect.runPromise(
adapter.sendTurn({
threadId,
input: "first dense perf pass",
attachments: [],
}),
);
const firstEvents = Array.from(await firstEventsPromise);
const secondEventsPromise = Effect.runPromise(
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
);
await Effect.runPromise(
adapter.sendTurn({
threadId,
input: "second dense perf pass",
attachments: [],
}),
);
const secondEvents = Array.from(await secondEventsPromise);
const firstNavigationTurnStarted = firstEvents.find(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
event.type === "turn.started",
);
const secondNavigationTurnStarted = secondEvents.find(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
event.type === "turn.started",
);
const firstBurstAssistantCompletion = firstEvents.find(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message",
);
const secondBurstAssistantCompletion = secondEvents.find(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message",
);
const secondRunNamespaceSuffix = `--perf-run-${String(threadId)}-0002`;
expect(firstNavigationTurnStarted?.turnId).toBe(PERF_CATALOG_IDS.provider.navigationLiveTurnId);
expect(firstBurstAssistantCompletion?.itemId).toBeDefined();
expect(secondNavigationTurnStarted?.turnId).toBeDefined();
expect(secondBurstAssistantCompletion?.itemId).toBeDefined();
expect(secondNavigationTurnStarted?.turnId).not.toBe(firstNavigationTurnStarted?.turnId);
expect(secondBurstAssistantCompletion?.itemId).not.toBe(firstBurstAssistantCompletion?.itemId);
expect(String(secondNavigationTurnStarted?.turnId)).toContain(secondRunNamespaceSuffix);
expect(String(secondBurstAssistantCompletion?.itemId)).toContain(secondRunNamespaceSuffix);
});
});
+47 -8
View File
@@ -107,26 +107,58 @@ function toIdleSession(session: ProviderSession, updatedAt: string): ProviderSes
};
}
function namespacePerfFixtureId(
baseId: string,
sourceThreadId: ThreadId,
runIndex: number,
): string {
return `${baseId}--perf-run-${String(sourceThreadId)}-${runIndex.toString().padStart(4, "0")}`;
}
function buildRuntimeEvent(input: {
readonly template: TimedFixtureProviderRuntimeEvent;
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly startedAtMs: number;
readonly index: number;
readonly runIndex: number;
}): ProviderRuntimeEvent {
const eventThreadId = input.template.threadId ?? input.threadId;
const eventTurnId =
input.template.turnId === undefined
? input.turnId
: input.runIndex === 1
? input.template.turnId
: TurnId.makeUnsafe(
namespacePerfFixtureId(String(input.template.turnId), input.threadId, input.runIndex),
);
const createdAt = new Date(input.startedAtMs + (input.template.delayMs ?? 0)).toISOString();
return {
type: input.template.type,
eventId: EventId.makeUnsafe(
`perf-runtime:${String(input.threadId)}:${String(input.turnId)}:${input.index.toString().padStart(4, "0")}`,
`perf-runtime:${String(eventThreadId)}:${String(eventTurnId)}:${input.index.toString().padStart(4, "0")}`,
),
provider: "codex",
threadId: input.threadId,
turnId: input.turnId,
threadId: eventThreadId,
turnId: eventTurnId,
createdAt,
...(input.template.itemId ? { itemId: RuntimeItemId.makeUnsafe(input.template.itemId) } : {}),
...(input.template.itemId
? {
itemId: RuntimeItemId.makeUnsafe(
input.runIndex === 1
? input.template.itemId
: namespacePerfFixtureId(input.template.itemId, input.threadId, input.runIndex),
),
}
: {}),
...(input.template.requestId
? { requestId: RuntimeRequestId.makeUnsafe(input.template.requestId) }
? {
requestId: RuntimeRequestId.makeUnsafe(
input.runIndex === 1
? input.template.requestId
: namespacePerfFixtureId(input.template.requestId, input.threadId, input.runIndex),
),
}
: {}),
payload: input.template.payload,
} as ProviderRuntimeEvent;
@@ -274,6 +306,7 @@ export const makePerfProviderAdapter = Effect.gen(function* () {
turnId,
startedAtMs,
index,
runIndex: state.turnCount,
});
const delayMs = template.delayMs ?? 0;
return scheduleRuntimeEvent({
@@ -281,10 +314,14 @@ export const makePerfProviderAdapter = Effect.gen(function* () {
event,
delayMs,
onAfterEmit: () => {
if (event.type === "content.delta" && event.payload.streamKind === "assistant_text") {
if (
event.threadId === input.threadId &&
event.type === "content.delta" &&
event.payload.streamKind === "assistant_text"
) {
assistantText += event.payload.delta;
}
if (event.type === "turn.completed") {
if (event.threadId === input.threadId && event.type === "turn.completed") {
updateAssistantSnapshot(event.createdAt);
}
},
@@ -412,6 +449,8 @@ export const makePerfProviderAdapter = Effect.gen(function* () {
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
get streamEvents() {
return Stream.fromQueue(runtimeEvents);
},
} satisfies ProviderAdapterShape<ProviderAdapterError>;
});
+3 -1
View File
@@ -152,7 +152,9 @@ export const PerfProviderRegistryLive = Layer.effect(
return {
getProviders: Ref.get(providersRef),
refresh: (_provider) => refreshProviders(),
streamChanges: Stream.fromPubSub(changesPubSub),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ProviderRegistryShape;
}),
);
@@ -3054,7 +3054,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
} satisfies ClaudeAdapterShape;
});
@@ -1631,7 +1631,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
} satisfies CodexAdapterShape;
});
@@ -115,7 +115,9 @@ function makeMutableServerSettingsService(
yield* PubSub.publish(changes, next);
return next;
}),
streamChanges: Stream.fromPubSub(changes),
get streamChanges() {
return Stream.fromPubSub(changes);
},
} satisfies ServerSettingsShape;
});
}
@@ -191,7 +191,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
+4 -1
View File
@@ -3750,7 +3750,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<div
className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background"
data-testid={`chat-thread-${activeThread.id}`}
>
{/* Top bar */}
<header
className={cn(
+168 -136
View File
@@ -1,11 +1,11 @@
import { spawn, type ChildProcess } from "node:child_process";
import { access, mkdir, writeFile } from "node:fs/promises";
import { access, mkdir, rm, 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 { chromium, type Browser, type BrowserContext, type Page } from "playwright";
import {
type BrowserPerfMetrics,
@@ -50,6 +50,7 @@ interface PerfSeedThreadSummary {
export interface PerfSeededState {
readonly scenarioId: PerfSeedScenarioId;
readonly runParentDir: string;
readonly baseDir: string;
readonly workspaceRoot: string;
readonly projectTitle: string | null;
@@ -181,6 +182,10 @@ async function ensureArtifactDir(suite: string, scenarioId: string): Promise<str
return artifactDir;
}
async function cleanupPerfRunDir(runParentDir: string): Promise<void> {
await rm(runParentDir, { recursive: true, force: true });
}
async function writeServerLogs(
artifactDir: string,
stdout: string,
@@ -263,8 +268,12 @@ export async function startPerfAppHarness(
const env = {
...process.env,
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
[PERF_PROVIDER_ENV]: "1",
...(options.providerScenarioId ? { [PERF_SCENARIO_ENV]: options.providerScenarioId } : {}),
...(options.providerScenarioId
? {
[PERF_PROVIDER_ENV]: "1",
[PERF_SCENARIO_ENV]: options.providerScenarioId,
}
: {}),
};
let stdoutBuffer = "";
@@ -295,151 +304,174 @@ export async function startPerfAppHarness(
serverProcess.stderr?.on("data", (chunk) => {
stderrBuffer += chunk.toString();
});
let browser: Browser | null = null;
let context: BrowserContext | null = null;
let page: Page | null = null;
await waitForServerReady(url, serverProcess);
try {
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" });
browser = await chromium.launch({
headless: process.env[PERF_HEADFUL_ENV] !== "1",
});
context = await browser.newContext({
viewport: { width: 1440, height: 960 },
});
await context.addInitScript(installBrowserPerfCollector, "[data-timeline-row-kind]");
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 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();
const sampler = options.serverSampler ?? new NoopServerSampler();
if (serverProcess.pid) {
await sampler.start({ pid: serverProcess.pid });
}
const runStartedAt = new Date().toISOString();
const readyPage = page;
if (!readyPage) {
throw new Error("Perf app harness did not initialize a browser page.");
}
let finishPromise: Promise<{
readonly artifactPath: string;
readonly artifact: PerfRunArtifact;
readonly browserMetrics: BrowserPerfMetrics;
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
}> | null = null;
let finishPromise:
| Promise<{
readonly artifactPath: string;
readonly artifact: PerfRunArtifact;
readonly browserMetrics: BrowserPerfMetrics;
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
}>
| undefined;
const teardown = async () => {
await Promise.allSettled([context.close(), browser.close()]);
await stopChildProcess(serverProcess);
};
const teardown = async () => {
await Promise.allSettled([
context ? context.close() : Promise.resolve(),
browser ? browser.close() : Promise.resolve(),
]);
await stopChildProcess(serverProcess);
await cleanupPerfRunDir(seededState.runParentDir);
};
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(
return {
seededState,
page: readyPage,
url,
artifactDir,
startAction: (name) =>
invokeBrowserCollector(
readyPage,
(collectorName, actionName) => {
(window as Window & Record<string, any>)[collectorName]?.startAction(
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;
}
);
},
name,
),
endAction: (name) =>
invokeBrowserCollector(
readyPage,
(collectorName, actionName) => {
return (
(window as Window & Record<string, any>)[collectorName]?.endAction(
actionName as string,
) ?? null
);
},
name,
),
resetBrowserMetrics: () =>
invokeBrowserCollector(readyPage, (collectorName) => {
(window as Window & Record<string, any>)[collectorName]?.reset();
}),
sampleMountedRows: (label) =>
invokeBrowserCollector(
readyPage,
(collectorName, sampleLabel) => {
return (
(window as Window & Record<string, any>)[collectorName]?.sampleMountedRows(
sampleLabel as string,
) ?? 0
);
},
label,
),
snapshotBrowserMetrics: () =>
invokeBrowserCollector(readyPage, (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() ?? {
finishPromise = (async () => {
const completedAt = new Date().toISOString();
const browserMetrics: BrowserPerfMetrics = await (async () => {
try {
return await invokeBrowserCollector(readyPage, (collectorName) => {
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
actions: [],
longTasks: [],
rafGapsMs: [],
mountedRowSamples: [],
}) as BrowserPerfMetrics;
});
} catch {
return {
actions: [],
longTasks: [],
rafGapsMs: [],
mountedRowSamples: [],
}) as BrowserPerfMetrics;
});
} catch {
return {
actions: [],
longTasks: [],
rafGapsMs: [],
mountedRowSamples: [],
} satisfies BrowserPerfMetrics;
}
} 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,
};
})();
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;
},
};
return await finishPromise;
},
};
} catch (error) {
await Promise.allSettled([
context ? context.close() : Promise.resolve(),
browser ? browser.close() : Promise.resolve(),
]);
await stopChildProcess(serverProcess);
await cleanupPerfRunDir(seededState.runParentDir);
throw error;
}
}
+6 -1
View File
@@ -26,12 +26,16 @@ export async function waitForThreadRoute(
},
): Promise<void> {
const path = `/${encodeURIComponent(input.threadId)}`;
const threadSelector = `[data-testid="chat-thread-${input.threadId}"]`;
await page.waitForFunction(
({ expectedPath, messageSelector, extraSelector }) => {
({ expectedPath, threadSelector, messageSelector, extraSelector }) => {
const pathMatches = window.location.pathname === expectedPath;
if (!pathMatches) {
return false;
}
if (!document.querySelector(threadSelector)) {
return false;
}
if (messageSelector && !document.querySelector(messageSelector)) {
return false;
@@ -43,6 +47,7 @@ export async function waitForThreadRoute(
},
{
expectedPath: path,
threadSelector,
messageSelector: input.messageId ? `[data-message-id="${input.messageId}"]` : null,
extraSelector: input.extraSelector ?? null,
},
+52
View File
@@ -0,0 +1,52 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { percentile } from "../../../../test/perf/support/artifact";
import { installBrowserPerfCollector } from "../../../../test/perf/support/browserMetrics";
describe("percentile", () => {
it("returns the minimum value for the zero percentile", () => {
expect(percentile([9, 3, 6], 0)).toBe(3);
});
});
describe("installBrowserPerfCollector", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("cancels the previous animation frame loop before reset starts a new one", () => {
let nextHandle = 1;
const callbacks = new Map<number, FrameRequestCallback>();
const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
const handle = nextHandle++;
callbacks.set(handle, callback);
return handle;
});
const cancelAnimationFrame = vi.fn((handle: number) => {
callbacks.delete(handle);
});
vi.stubGlobal("window", {
requestAnimationFrame,
cancelAnimationFrame,
} as unknown as Window & typeof globalThis);
vi.stubGlobal("document", {
querySelectorAll: vi.fn(() => []),
} as unknown as Document);
vi.stubGlobal("PerformanceObserver", undefined);
installBrowserPerfCollector();
const collector = window.__t3PerfCollector;
expect(collector).toBeDefined();
expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
collector?.reset();
expect(cancelAnimationFrame).toHaveBeenCalledWith(1);
expect(requestAnimationFrame).toHaveBeenCalledTimes(2);
collector?.reset();
expect(cancelAnimationFrame).toHaveBeenLastCalledWith(2);
expect(requestAnimationFrame).toHaveBeenCalledTimes(3);
});
});
@@ -25,6 +25,7 @@ test("high-frequency websocket events stay responsive under real built-app flow"
const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace";
const streamScenario = PERF_PROVIDER_SCENARIOS.dense_assistant_stream;
expect(streamScenario.totalDurationMs).toBeGreaterThanOrEqual(10_000);
await ensureThreadRowVisible(
harness.page,
@@ -49,21 +50,27 @@ test("high-frequency websocket events stay responsive under real built-app flow"
actionName: "thread-switch-burst-nav",
projectTitle,
threadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
messageId: PERF_CATALOG_IDS.burstBase.navigationTerminalMessageId,
});
await harness.page.waitForFunction(
(messageNeedle) => document.body.textContent?.includes(messageNeedle as string) ?? false,
"Navigation lane",
{ timeout: 10_000 },
);
const navigationTimelineText = await harness.page
.locator('[data-timeline-root="true"]')
.textContent();
expect(navigationTimelineText ?? "").toContain("Navigation lane");
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 },
{ timeout: streamScenario.totalDurationMs + 15_000 },
);
await harness.endAction("burst-completion");
@@ -96,6 +103,10 @@ test("high-frequency websocket events stay responsive under real built-app flow"
metadata: {
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
fillerThreadId: PERF_CATALOG_IDS.burstBase.fillerThreadId,
navigationLiveAssistantMessageId:
PERF_CATALOG_IDS.provider.navigationLiveAssistantMessageId,
burstLiveAssistantMessageId: PERF_CATALOG_IDS.provider.burstLiveAssistantMessageId,
sentinelText: streamScenario.sentinelText,
},
actionSummary: {
@@ -113,6 +124,10 @@ test("high-frequency websocket events stay responsive under real built-app flow"
metadata: {
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
fillerThreadId: PERF_CATALOG_IDS.burstBase.fillerThreadId,
navigationLiveAssistantMessageId:
PERF_CATALOG_IDS.provider.navigationLiveAssistantMessageId,
burstLiveAssistantMessageId: PERF_CATALOG_IDS.provider.burstLiveAssistantMessageId,
sentinelText: PERF_PROVIDER_SCENARIOS.dense_assistant_stream.sentinelText,
},
actionSummary: {
+4
View File
@@ -2,6 +2,7 @@ import tailwindcss from "@tailwindcss/vite";
import react, { reactCompilerPreset } from "@vitejs/plugin-react";
import babel from "@rolldown/plugin-babel";
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { configDefaults } from "vitest/config";
import { defineConfig } from "vite";
import pkg from "./package.json" with { type: "json" };
@@ -56,4 +57,7 @@ export default defineConfig({
emptyOutDir: true,
sourcemap: buildSourcemap,
},
test: {
exclude: [...configDefaults.exclude, "test/perf/**/*.perf.test.ts"],
},
});
@@ -1,141 +0,0 @@
{
"suite": "virtualization",
"scenarioId": "large_threads",
"startedAt": "2026-04-01T20:57:00.745Z",
"completedAt": "2026-04-01T20:57:01.524Z",
"thresholds": {
"maxMountedTimelineRows": 140,
"threadSwitchP50Ms": 250,
"threadSwitchP95Ms": 500,
"maxLongTaskMs": 120,
"maxRafGapMs": 120,
"burstCompletionMs": 5000,
"longTasksOver50MsMax": 2
},
"summary": {
"maxMountedTimelineRows": 23,
"threadSwitchP50Ms": 49.5,
"threadSwitchP95Ms": 117,
"maxLongTaskMs": 0,
"longTasksOver50Ms": 0,
"maxRafGapMs": 25,
"burstCompletionMs": null
},
"browserMetrics": {
"actions": [
{
"name": "thread-switch-warmup-a",
"durationMs": 117,
"startedAtMs": 591,
"endedAtMs": 708
},
{
"name": "thread-switch-1",
"durationMs": 46.5,
"startedAtMs": 709.7999999523163,
"endedAtMs": 756.2999999523163
},
{
"name": "thread-switch-2",
"durationMs": 49.5,
"startedAtMs": 787.6000000238419,
"endedAtMs": 837.1000000238419
},
{
"name": "thread-switch-3",
"durationMs": 70.69999992847443,
"startedAtMs": 840.7000000476837,
"endedAtMs": 911.3999999761581
},
{
"name": "thread-switch-4",
"durationMs": 45.89999997615814,
"startedAtMs": 916,
"endedAtMs": 961.8999999761581
},
{
"name": "thread-switch-5",
"durationMs": 46.699999928474426,
"startedAtMs": 964.6000000238419,
"endedAtMs": 1011.2999999523163
},
{
"name": "thread-switch-6",
"durationMs": 49.89999997615814,
"startedAtMs": 1047.8999999761581,
"endedAtMs": 1097.7999999523163
}
],
"longTasks": [],
"rafGapsMs": [
0, 8, 0, 17, 0, 7.300000000000068, 0, 8.799999999999955, 0, 8.200000000000045, 0,
9.099999999999909, 0, 7.7000000000000455, 0, 8.399999999999977, 0, 8.800000000000068, 0, 16,
0, 8.399999999999977, 0, 9, 0, 8.299999999999955, 0, 7.600000000000023, 0, 17.100000000000023,
0, 8.600000000000023, 0, 8.299999999999955, 0, 16.200000000000045, 0, 7.899999999999977, 0,
9.299999999999955, 0, 7.399999999999977, 0, 9.200000000000045, 0, 16.700000000000045, 0, 8, 0,
8.299999999999955, 0, 7.899999999999977, 0, 8.700000000000045, 0, 17.100000000000023, 0,
8.199999999999932, 0, 16, 0, 16.600000000000023, 0, 8.399999999999977, 0, 8.899999999999977,
0, 7.800000000000068, 0, 17.399999999999977, 0, 8.299999999999955, 0, 8.300000000000068, 0,
7.699999999999932, 0, 16.700000000000045, 0, 8.100000000000023, 0, 17.399999999999977, 0,
7.7999999999999545, 0, 8.600000000000136, 0, 8.199999999999818, 0, 8.900000000000091, 0,
8.099999999999909, 0, 16.200000000000045, 0, 9.100000000000136, 0, 7.399999999999864, 0, 8.5,
0, 9, 0, 25, 0, 7.600000000000136, 0, 9.199999999999818, 0
],
"mountedRowSamples": [
{
"label": "heavy-a-open",
"count": 17,
"capturedAtMs": 708.5
},
{
"label": "thread-switch-1-rows",
"count": 17,
"capturedAtMs": 782
},
{
"label": "thread-switch-2-rows",
"count": 17,
"capturedAtMs": 837.7000000476837
},
{
"label": "thread-switch-3-rows",
"count": 17,
"capturedAtMs": 914.2000000476837
},
{
"label": "thread-switch-4-rows",
"count": 17,
"capturedAtMs": 962.5
},
{
"label": "thread-switch-5-rows",
"count": 17,
"capturedAtMs": 1034.1000000238419
},
{
"label": "thread-switch-6-rows",
"count": 17,
"capturedAtMs": 1098.3999999761581
},
{
"label": "scroll-start",
"count": 17,
"capturedAtMs": 1113.3999999761581
},
{
"label": "scroll-top",
"count": 23,
"capturedAtMs": 1148.3999999761581
},
{
"label": "scroll-bottom",
"count": 17,
"capturedAtMs": 1164.2000000476837
}
]
},
"serverMetrics": null,
"metadata": {
"heavyThreadMessageCount": 2000
}
}
@@ -1,139 +0,0 @@
{
"suite": "websocket-application",
"scenarioId": "dense_assistant_stream",
"startedAt": "2026-04-01T20:57:03.910Z",
"completedAt": "2026-04-01T20:57:07.151Z",
"thresholds": {
"maxMountedTimelineRows": 140,
"threadSwitchP50Ms": 250,
"threadSwitchP95Ms": 500,
"maxLongTaskMs": 120,
"maxRafGapMs": 120,
"burstCompletionMs": 5000,
"longTasksOver50MsMax": 2
},
"summary": {
"maxMountedTimelineRows": 0,
"threadSwitchP50Ms": 51.199999928474426,
"threadSwitchP95Ms": 52.39999997615814,
"maxLongTaskMs": 0,
"longTasksOver50Ms": 0,
"maxRafGapMs": 16.200000000000045,
"burstCompletionMs": 3135
},
"browserMetrics": {
"actions": [
{
"name": "thread-switch-burst-nav",
"durationMs": 51.199999928474426,
"startedAtMs": 1348.3999999761581,
"endedAtMs": 1399.5999999046326
},
{
"name": "thread-switch-burst-return",
"durationMs": 52.39999997615814,
"startedAtMs": 1401.1999999284744,
"endedAtMs": 1453.5999999046326
},
{
"name": "burst-completion",
"durationMs": 3135,
"startedAtMs": 332.2999999523163,
"endedAtMs": 3467.2999999523163
}
],
"longTasks": [],
"rafGapsMs": [
0, 7.899999999999977, 0, 9, 0, 7.300000000000011, 0, 8.899999999999977, 0, 7.800000000000011,
0, 9.300000000000011, 0, 8.100000000000023, 0, 7.699999999999989, 0, 9.199999999999989, 0,
7.800000000000011, 0, 7.899999999999977, 0, 9.300000000000011, 0, 7.300000000000011, 0,
9.099999999999966, 0, 7.7000000000000455, 0, 8.199999999999989, 0, 8.399999999999977, 0,
8.300000000000011, 0, 8.399999999999977, 0, 8.5, 0, 9.100000000000023, 0, 7.7000000000000455,
0, 8.199999999999932, 0, 8.600000000000023, 0, 8.799999999999955, 0, 7.7000000000000455, 0,
8.200000000000045, 0, 8.399999999999977, 0, 9.100000000000023, 0, 7.5, 0, 8.199999999999932,
0, 9.300000000000068, 0, 7.399999999999977, 0, 8.600000000000023, 0, 8.399999999999977, 0,
8.899999999999977, 0, 8.299999999999955, 0, 7.800000000000068, 0, 8, 0, 8.399999999999977, 0,
8.799999999999955, 0, 7.7000000000000455, 0, 9.299999999999955, 0, 7.400000000000091, 0,
9.299999999999955, 0, 8.299999999999955, 0, 7.7000000000000455, 0, 8.100000000000023, 0,
8.899999999999977, 0, 8.700000000000045, 0, 7.2999999999999545, 0, 9.399999999999977, 0,
8.200000000000045, 0, 8.100000000000023, 0, 7.699999999999932, 0, 9.300000000000068, 0,
8.199999999999932, 0, 8.300000000000068, 0, 7.699999999999932, 0, 8.700000000000045, 0,
8.699999999999932, 0, 7.600000000000023, 0, 8.100000000000023, 0, 8.399999999999977, 0,
8.700000000000045, 0, 8, 0, 8.699999999999932, 0, 8.200000000000045, 0, 8.799999999999955, 0,
8.5, 0, 7.800000000000068, 0, 8.5, 0, 8.600000000000023, 0, 8.399999999999977, 0,
7.899999999999977, 0, 8.100000000000023, 0, 8.100000000000023, 0, 8.399999999999977, 0,
9.299999999999955, 0, 8.100000000000023, 0, 7.5, 0, 9.200000000000045, 0, 8.5, 0,
7.899999999999864, 0, 8.800000000000182, 0, 8.199999999999818, 0, 7.800000000000182, 0, 8.5,
0, 8.199999999999818, 0, 8.900000000000091, 0, 8.299999999999955, 0, 7.900000000000091, 0,
7.899999999999864, 0, 9.300000000000182, 0, 7.599999999999909, 0, 8.400000000000091, 0, 8, 0,
8.399999999999864, 0, 9.200000000000045, 0, 7.400000000000091, 0, 9.299999999999955, 0,
8.200000000000045, 0, 7.5, 0, 9.299999999999955, 0, 8.099999999999909, 0, 7.600000000000136,
0, 9.299999999999955, 0, 8.200000000000045, 0, 8.399999999999864, 0, 7.5, 0,
8.400000000000091, 0, 8.599999999999909, 0, 7.7999999999999545, 0, 8.5, 0, 9.300000000000182,
0, 7.2999999999999545, 0, 9.399999999999864, 0, 7.5, 0, 8.100000000000136, 0, 8.5, 0,
8.099999999999909, 0, 9.100000000000136, 0, 8.599999999999909, 0, 7.5, 0, 9.099999999999909,
0, 7.600000000000136, 0, 8.399999999999864, 0, 8.100000000000136, 0, 8.399999999999864, 0,
8.200000000000045, 0, 9.299999999999955, 0, 8, 0, 16.200000000000045, 0, 9.200000000000045, 0,
8.299999999999955, 0, 8.299999999999955, 0, 8.400000000000091, 0, 7.900000000000091, 0,
8.599999999999909, 0, 8.5, 0, 8.099999999999909, 0, 7.7000000000000455, 0, 8.700000000000045,
0, 8.5, 0, 8.5, 0, 7.599999999999909, 0, 8.900000000000091, 0, 8.599999999999909, 0,
8.400000000000091, 0, 8.299999999999955, 0, 7.7999999999999545, 0, 8.600000000000136, 0,
8.200000000000045, 0, 8.799999999999955, 0, 7.599999999999909, 0, 8.100000000000136, 0,
8.599999999999909, 0, 8.299999999999955, 0, 8.100000000000136, 0, 8.599999999999909, 0,
9.099999999999909, 0, 8.200000000000045, 0, 7.400000000000091, 0, 8.899999999999864, 0, 8.5,
0, 8.5, 0, 7.900000000000091, 0, 8.799999999999955, 0, 7.400000000000091, 0,
9.299999999999955, 0, 7.400000000000091, 0, 9.299999999999955, 0, 8.299999999999955, 0,
8.299999999999955, 0, 7.400000000000091, 0, 8.899999999999864, 0, 8.800000000000182, 0,
7.599999999999909, 0, 8.099999999999909, 0, 8.200000000000045, 0, 9.400000000000091, 0,
7.7000000000000455, 0, 8.899999999999864, 0, 7.400000000000091, 0, 8.399999999999864, 0,
8.900000000000091, 0, 8, 0, 8.5, 0, 8.799999999999955, 0, 7.7000000000000455, 0,
8.200000000000045, 0, 8.700000000000045, 0, 7.899999999999864, 0, 8.799999999999955, 0,
8.400000000000091, 0, 8.099999999999909, 0, 8.200000000000045, 0, 8.200000000000045, 0,
8.200000000000045, 0, 8.799999999999955, 0, 7.7999999999999545, 0, 8.600000000000136, 0,
8.199999999999818, 0, 9.200000000000045, 0, 7.500000000000227, 0, 8.199999999999818, 0,
9.099999999999909, 0, 7.700000000000273, 0, 8.899999999999636, 0, 7.600000000000364, 0,
8.399999999999636, 0, 9.300000000000182, 0, 7.400000000000091, 0, 8.299999999999727, 0,
9.300000000000182, 0, 8.300000000000182, 0, 7.799999999999727, 0, 8.900000000000091, 0,
7.699999999999818, 0, 8.800000000000182, 0, 8.300000000000182, 0, 7.599999999999909, 0,
8.799999999999727, 0, 7.900000000000091, 0, 9.099999999999909, 0, 8.200000000000273, 0, 8, 0,
8.799999999999727, 0, 7.600000000000364, 0, 9.299999999999727, 0, 8.200000000000273, 0,
7.699999999999818, 0, 8, 0, 8.599999999999909, 0, 9.099999999999909, 0, 7.300000000000182, 0,
8.900000000000091, 0, 8.799999999999727, 0, 8.100000000000364, 0, 7.899999999999636, 0, 8, 0,
8.400000000000091, 0, 9.099999999999909, 0, 7.5, 0, 8.800000000000182, 0, 7.900000000000091,
0, 9.299999999999727, 0, 7.5, 0, 9.100000000000364, 0, 8.099999999999909, 0,
7.799999999999727, 0, 8.700000000000273, 0, 7.799999999999727, 0, 9.300000000000182, 0,
8.300000000000182, 0, 8, 0, 8.699999999999818, 0, 7.599999999999909, 0, 9.099999999999909, 0,
8.200000000000273, 0, 7.599999999999909, 0, 9.199999999999818, 0, 8.200000000000273, 0,
8.400000000000091, 0, 8.299999999999727, 0, 8.200000000000273, 0, 8.5, 0, 8.299999999999727,
0, 8.400000000000091, 0, 8.300000000000182, 0, 7.5, 0, 8.5, 0, 8.099999999999909, 0,
9.299999999999727, 0, 7.400000000000091, 0, 9, 0, 8, 0, 8.900000000000091, 0,
8.300000000000182, 0, 8.299999999999727, 0, 7.5, 0, 8.599999999999909, 0, 8, 0,
9.300000000000182, 0, 7.400000000000091, 0, 9.299999999999727, 0, 8.300000000000182, 0,
7.599999999999909, 0, 8.800000000000182, 0, 8.099999999999909, 0, 8, 0, 8.800000000000182, 0,
8.5, 0, 8.5, 0, 8.099999999999909, 0, 8.5, 0, 8, 0, 8.199999999999818, 0, 7.900000000000091,
0, 8.599999999999909, 0, 8.599999999999909, 0, 8, 0, 9.100000000000364, 0, 8.199999999999818,
0, 8.5, 0, 8, 0, 7.800000000000182, 0, 8.899999999999636, 0, 7.800000000000182, 0,
9.099999999999909, 0, 8.300000000000182, 0, 7.799999999999727, 0, 9, 0, 8.300000000000182, 0,
7.5, 0, 9.199999999999818, 0, 7.400000000000091, 0, 9.300000000000182, 0, 8, 0,
7.799999999999727, 0, 9.200000000000273, 0, 8, 0, 7.599999999999909, 0, 8.400000000000091, 0,
9.299999999999727, 0, 7.300000000000182, 0, 8.5, 0, 9.199999999999818, 0, 8.200000000000273,
0, 8.400000000000091, 0, 7.5, 0, 9.199999999999818, 0, 8.300000000000182, 0,
7.399999999999636, 0, 8.400000000000091, 0, 9, 0, 8.599999999999909, 0, 8.200000000000273, 0,
7.5, 0, 9.299999999999727, 0, 8.200000000000273, 0, 8.400000000000091, 0, 7.399999999999636,
0, 8.300000000000182, 0, 9.400000000000091, 0, 8, 0, 8.5, 0, 8.099999999999909, 0, 8, 0, 8, 0,
8.900000000000091, 0, 7.900000000000091, 0, 8.299999999999727, 0, 8.300000000000182, 0, 8.5,
0, 8.699999999999818, 0, 8.099999999999909, 0, 9, 0, 8.300000000000182, 0, 7.400000000000091,
0, 9.099999999999909, 0, 7.800000000000182, 0, 9.099999999999909, 0, 8.199999999999818, 0,
8.400000000000091, 0, 8.300000000000182, 0, 7.899999999999636, 0, 8.700000000000273, 0, 8.5,
0, 7.400000000000091, 0, 8.299999999999727, 0, 8.300000000000182, 0, 9.299999999999727, 0,
8.300000000000182, 0, 8.199999999999818, 0
],
"mountedRowSamples": []
},
"serverMetrics": null,
"metadata": {
"burstSeedThreadId": "perf-thread-burst",
"navigationThreadId": "perf-thread-light-01",
"sentinelText": "PERF_STREAM_SENTINEL:dense_assistant_stream:completed"
}
}
+267
View File
@@ -0,0 +1,267 @@
# Performance Benchmarks
This repository has a local performance regression harness for the built web app and built server. It is intentionally separate from the normal unit and browser test suites.
The benchmark is meant to answer two questions:
- Does large-thread rendering and thread-to-thread navigation stay snappy?
- Does high-frequency websocket event application stay responsive under a realistic built-app flow?
## What it runs
The perf suite does not use Vite dev mode. Each run does this:
1. Seeds a real server base dir with deterministic fixture data using the normal event store and projection pipeline.
2. Starts the built `t3` server from `apps/server/dist/bin.mjs`.
3. Serves the built web bundle from `apps/server/dist/client`.
4. Launches Chromium with Playwright.
5. Installs an in-page collector for action timings, long tasks, `requestAnimationFrame` gaps, and mounted timeline row counts.
6. Writes a JSON artifact plus server stdout and stderr logs under `artifacts/perf/`.
The current implementation is browser-focused, but the harness already reserves a server sampling hook so later server-only CPU and memory benchmarks can share the same scenarios and artifact format.
## Main pieces
- `packages/shared/src/perf/scenarioCatalog.ts`
- Shared scenario catalog for both seeded state and live provider traffic.
- `apps/server/integration/perf/seedPerfState.ts`
- Creates the temporary sqlite-backed base dir using real orchestration events and projections.
- `apps/server/src/perf/PerfProviderAdapter.ts`
- Perf-only mock provider that emits paced runtime events over the normal provider -> websocket -> client path.
- `apps/web/test/perf/appHarness.ts`
- Starts the built app, launches Chromium, installs the browser collector, and writes artifacts.
- `test/perf/support/browserMetrics.ts`
- Collects action durations, long tasks, `requestAnimationFrame` gaps, and mounted row samples inside the page.
- `test/perf/support/artifact.ts`
- Defines the JSON artifact format and summary math.
- `test/perf/support/thresholds.ts`
- Local budgets that currently gate the suite.
- `test/perf/support/serverSampler.ts`
- Extension point for future CPU and memory sampling. The current implementation is `NoopServerSampler`, so `serverMetrics` is `null` today.
## Scenarios
### `large_threads`
Seeded app state used by the virtualization benchmark.
- 1 project
- 12 threads total
- 2 heavy threads
- 1 burst thread
- 9 light filler threads
The two heavy threads currently seed:
- `1,000` turns
- `2,000` messages
- periodic worklog/activity rows
- periodic proposed-plan rows
- frequent checkpoint rows with larger changed-file trees
This means the timeline is not just alternating short user/assistant text. The heavy threads include the non-message rows that tend to stress grouping, virtualization, and diff-tree rendering.
### `burst_base`
Seeded app state used by the websocket benchmark.
- 1 burst target thread
- 1 navigation thread
- 1 filler thread
This smaller seed keeps the focus on live websocket application while still covering cross-thread background activity.
### `dense_assistant_stream`
Live provider scenario used by the websocket benchmark.
- runs for about `10` seconds
- spans `24` cycles
- updates `3` lanes at once: `burst`, `navigation`, and `filler`
- interleaves assistant messages with multiple worklog/tool lifecycles
Each cycle emits, per lane:
1. an assistant intro message
2. three worklog/tool command lifecycles with file payloads
3. an assistant followup message
The message fragments vary in length on purpose so the live stream does not render as uniformly sized chunks.
## What each benchmark asserts
### Virtualization benchmark
File: `apps/web/test/perf/virtualization.perf.test.ts`
This benchmark:
- opens the large-thread seed on the built app
- navigates between the two heavy threads through the real sidebar
- measures a warmup switch and then six measured thread switches
- samples mounted timeline row counts
- scrolls bottom -> top -> bottom to catch jank
It currently fails if the local budgets in `test/perf/support/thresholds.ts` are exceeded:
- max mounted timeline rows: `140`
- thread switch p50: `250ms`
- thread switch p95: `500ms`
- max long task: `120ms`
- max `requestAnimationFrame` gap: `120ms`
### Websocket benchmark
File: `apps/web/test/perf/websocket-application.perf.test.ts`
This benchmark:
- starts the built app with the perf provider enabled
- opens the burst thread
- sends one real composer message
- lets the mock provider emit the live multi-thread websocket burst
- switches to another thread during the burst and back again
- waits for the sentinel text that marks the end of the scenario
It currently fails if these budgets are exceeded:
- burst completion: `14,000ms`
- max long task: `120ms`
- long tasks over `50ms`: `2`
- max `requestAnimationFrame` gap: `120ms`
- burst-time thread switches: `500ms` max each
## Commands
### One-time browser setup
Install Chromium for the perf suite:
```bash
cd apps/web
bun run test:perf:install
```
### Run the full automated benchmark suite
From the repo root:
```bash
bun run test:perf:web
```
That command builds `@t3tools/web`, builds `t3`, and then runs the dedicated perf Vitest config.
### Re-run the perf suite without rebuilding
If the built artifacts already exist and you have not changed the built app since the last build:
```bash
cd apps/web
bun run test:perf
```
### Watch the automated run in a live browser
```bash
T3CODE_PERF_HEADFUL=1 bun run test:perf:web
```
If you already have fresh build artifacts:
```bash
cd apps/web
T3CODE_PERF_HEADFUL=1 bun run test:perf
```
### Open the seeded app manually for exploration
Large-thread virtualization state:
```bash
bun run perf:open:build -- --scenario large_threads --open
```
Websocket burst state:
```bash
bun run perf:open:build -- --scenario burst_base --provider dense_assistant_stream --open
```
If the app is already built, use the faster commands:
```bash
bun run perf:open -- --scenario large_threads --open
bun run perf:open -- --scenario burst_base --provider dense_assistant_stream --open
```
For the websocket scenario, open the burst thread and send one message to start the live stream.
### Inspect the seeded topology directly
The seed script prints the generated thread summaries as JSON:
```bash
bun run apps/server/scripts/seedPerfState.ts large_threads
bun run apps/server/scripts/seedPerfState.ts burst_base
```
## Artifacts
By default each run writes to:
```text
artifacts/perf/<suite>-<scenario>-<timestamp>/
```
Each run currently includes:
- `<suite>-<scenario>.json`
- `<suite>-<scenario>.server.stdout.log`
- `<suite>-<scenario>.server.stderr.log`
The JSON artifact contains:
- run metadata
- threshold profile
- summary metrics
- raw browser metrics
- `serverMetrics`, reserved for later server sampling
Current summary fields:
- `maxMountedTimelineRows`
- `threadSwitchP50Ms`
- `threadSwitchP95Ms`
- `maxLongTaskMs`
- `longTasksOver50Ms`
- `maxRafGapMs`
- `burstCompletionMs`
To change the artifact output directory for one run:
```bash
T3CODE_PERF_ARTIFACT_DIR=/tmp/t3-perf bun run test:perf:web
```
## Internal env vars
These are the perf-specific env vars in the current harness:
- `T3CODE_PERF_HEADFUL=1`
- Launch Chromium headed instead of headless.
- `T3CODE_PERF_ARTIFACT_DIR=/path/to/output`
- Override the artifact directory.
- `T3CODE_PERF_PROVIDER=1`
- Enables the perf provider path on the server.
- `T3CODE_PERF_SCENARIO=dense_assistant_stream`
- Selects the live perf provider scenario.
In normal usage, the automated harness and `perf:open` script set the provider env vars for you.
## Notes and limitations
- This is a local benchmark suite. It is not wired into CI yet.
- The normal `apps/web` test suite excludes `test/perf/**/*.perf.test.ts`. Perf tests only run through `apps/web/vitest.perf.config.ts`.
- The budgets are intentionally conservative first-pass tripwires, not tuned production SLOs.
- The current harness measures browser responsiveness only. Server sampling is an explicit extension point, not implemented metrics yet.
+2
View File
@@ -40,6 +40,8 @@
"lint": "oxlint --report-unused-disable-directives",
"test": "turbo run test",
"test:perf:web": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && cd apps/web && bun run test:perf",
"perf:open": "node scripts/open-perf-app.ts",
"perf:open:build": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && node scripts/open-perf-app.ts",
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
"fmt:check": "oxfmt --check",
+721 -55
View File
@@ -42,6 +42,8 @@ export interface PerfSeedScenario {
export interface TimedFixtureProviderRuntimeEvent {
readonly delayMs?: number;
readonly threadId?: ThreadId;
readonly turnId?: TurnId;
readonly type: ProviderRuntimeEvent["type"];
readonly itemId?: string;
readonly requestId?: string;
@@ -73,6 +75,18 @@ const makeTurnId = (threadSlug: string, index: number) =>
TurnId.makeUnsafe(`perf-turn-${threadSlug}-${index.toString().padStart(4, "0")}`);
const makeMessageId = (threadSlug: string, role: "user" | "assistant", index: number) =>
MessageId.makeUnsafe(`perf-message-${threadSlug}-${role}-${index.toString().padStart(4, "0")}`);
const makeLiveTurnId = (slug: string) => TurnId.makeUnsafe(`perf-live-turn-${slug}`);
const makeLiveAssistantItemId = (
laneKey: string,
cycleIndex: number,
segment: "intro" | "followup",
) => `perf-assistant-${laneKey}-${cycleIndex.toString().padStart(2, "0")}-${segment}`;
const makeLiveAssistantMessageId = (itemId: string) => MessageId.makeUnsafe(`assistant:${itemId}`);
const PERF_PROVIDER_LIVE_TURNS = {
navigation: makeLiveTurnId("navigation"),
filler: makeLiveTurnId("filler"),
} as const;
const LARGE_THREAD_DEFINITIONS = {
heavyA: {
@@ -85,7 +99,7 @@ const LARGE_THREAD_DEFINITIONS = {
terminalMessageId: makeMessageId("heavy-a", "assistant", 1_000),
planStride: 120,
activityStride: 32,
diffStride: 48,
diffStride: 12,
},
heavyB: {
id: makeThreadId("heavy-b"),
@@ -97,7 +111,7 @@ const LARGE_THREAD_DEFINITIONS = {
terminalMessageId: makeMessageId("heavy-b", "assistant", 1_000),
planStride: 125,
activityStride: 36,
diffStride: 54,
diffStride: 14,
},
burst: {
id: makeThreadId("burst"),
@@ -162,80 +176,720 @@ export const PERF_SEED_SCENARIOS = {
} as const satisfies Record<PerfSeedScenarioId, PerfSeedScenario>;
const DENSE_ASSISTANT_STREAM_SENTINEL = "PERF_STREAM_SENTINEL:dense_assistant_stream:completed";
const DENSE_ASSISTANT_STREAM_CYCLE_COUNT = 24;
const DENSE_ASSISTANT_STREAM_CYCLE_INTERVAL_MS = 520;
const DENSE_ASSISTANT_STREAM_LANE_STAGGER_MS = 12;
const DENSE_ASSISTANT_STREAM_TURN_COMPLETION_GAP_MS = 36;
const DENSE_ASSISTANT_STREAM_WORKLOG_ITEMS_PER_CYCLE = 3;
const DENSE_ASSISTANT_STREAM_MESSAGE_FRAGMENT_GAP_MS = 24;
const DENSE_ASSISTANT_STREAM_MESSAGE_COMPLETION_GAP_MS = 28;
const DENSE_ASSISTANT_STREAM_WORKLOG_STARTED_GAP_MS = 20;
const DENSE_ASSISTANT_STREAM_WORKLOG_UPDATED_GAP_MS = 24;
const DENSE_ASSISTANT_STREAM_WORKLOG_COMPLETED_GAP_MS = 28;
const DENSE_ASSISTANT_STREAM_WORKLOG_GROUP_GAP_MS = 12;
function buildAssistantChunk(index: number, totalSteps: number): string {
if (index === totalSteps - 1) {
return `Completed render pass. ${DENSE_ASSISTANT_STREAM_SENTINEL}`;
type DenseAssistantStreamLaneKey = "burst" | "navigation" | "filler";
interface DenseAssistantStreamLane {
readonly key: DenseAssistantStreamLaneKey;
readonly title: string;
readonly threadId?: ThreadId;
readonly turnId?: TurnId;
}
const DENSE_ASSISTANT_STREAM_LANES: ReadonlyArray<DenseAssistantStreamLane> = [
{
key: "burst",
title: "Burst thread",
},
{
key: "navigation",
title: "Navigation thread",
threadId: BURST_NAVIGATION_THREAD.id,
turnId: PERF_PROVIDER_LIVE_TURNS.navigation,
},
{
key: "filler",
title: "Filler thread",
threadId: BURST_FILLER_THREAD.id,
turnId: PERF_PROVIDER_LIVE_TURNS.filler,
},
];
type DenseAssistantSegment = ReadonlyArray<string>;
interface DenseAssistantToolSpec {
readonly title: string;
readonly detail: string;
readonly command: ReadonlyArray<string>;
readonly files: ReadonlyArray<string>;
}
type DenseAssistantSegmentStage = "intro" | "followup";
function denseAssistantLaneSeed(laneKey: DenseAssistantStreamLaneKey): number {
switch (laneKey) {
case "burst":
return 3;
case "navigation":
return 7;
case "filler":
return 11;
}
if (index % 11 === 0) {
return `Scanning synthetic shard ${index}. `;
}
function buildDenseAssistantSegmentVariation(
laneKey: DenseAssistantStreamLaneKey,
cycleIndex: number,
stage: DenseAssistantSegmentStage,
baseSegment: readonly [string, string],
): DenseAssistantSegment {
const seed = denseAssistantLaneSeed(laneKey) + cycleIndex * 5 + (stage === "followup" ? 2 : 0);
const fragments: string[] = [baseSegment[0]];
if (laneKey === "burst") {
if (seed % 2 === 0) {
fragments.push(
"I am keeping the reducer hot path narrow so the live burst still feels incremental. ",
);
}
if (seed % 5 === 0) {
fragments.push(
"The queue still has enough buffered work to show whether the main thread starts to fan out. ",
);
}
} else if (laneKey === "navigation") {
if (seed % 2 !== 0) {
fragments.push(
"This pass is deliberately touching selection state, unread counts, and sidebar summaries at the same time. ",
);
}
if (seed % 4 === 0) {
fragments.push(
"I want route updates to land while the burst thread keeps painting without forcing a reset. ",
);
}
} else {
if (seed % 3 !== 0) {
fragments.push(
"Hidden threads are still taking background work here so the test is not accidentally single-threaded. ",
);
}
if (seed % 5 === 1) {
fragments.push(
"The background file tree is large enough that badge and projection churn should stay visible in the worklog. ",
);
}
}
if (index % 7 === 0) {
return `Applying websocket delta batch ${index}. `;
if (stage === "followup" && seed % 3 === 0) {
fragments.push(
"I am holding the rest of the queue steady until this narrower update settles cleanly. ",
);
}
if (index % 5 === 0) {
return `Recomputing viewport summary ${index}. `;
fragments.push(baseSegment[1]);
return fragments;
}
function joinDenseAssistantSegment(segment: DenseAssistantSegment): string {
return segment.join("").trim();
}
function mutateDenseAssistantFilePath(filePath: string, salt: number): string {
return filePath.replace(/\.(tsx?)$/, `.${(salt % 4) + 1}.$1`);
}
function selectDenseAssistantFiles(
baseFiles: ReadonlyArray<string>,
cycleIndex: number,
toolIndex: number,
baseCount: number,
): ReadonlyArray<string> {
const count = Math.min(baseFiles.length, baseCount + ((cycleIndex + toolIndex) % 3));
const startIndex = (cycleIndex * 2 + toolIndex * 3) % baseFiles.length;
return Array.from({ length: count }, (_, index) => {
const baseFile = baseFiles[(startIndex + index) % baseFiles.length]!;
return index % 2 === 0
? baseFile
: mutateDenseAssistantFilePath(baseFile, cycleIndex + toolIndex + index);
});
}
function buildDenseAssistantIntroSegment(
laneKey: DenseAssistantStreamLaneKey,
cycleIndex: number,
): DenseAssistantSegment {
const pass = cycleIndex + 1;
if (laneKey === "burst") {
switch (cycleIndex % 4) {
case 0:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Reviewing websocket burst slice ${pass} and checking the render queue. `,
"I am about to patch the hottest reducer path before the next flush. ",
]);
case 1:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Re-reading the active thread around viewport checkpoint ${pass}. `,
"I want the next command to touch the rows that are actually visible. ",
]);
case 2:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Inspecting the event fan-out for burst batch ${pass}. `,
"The next command should trim duplicate projections before they hit React. ",
]);
default:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Checking the optimistic state that landed after websocket batch ${pass}. `,
"I am lining up another targeted update instead of doing a full recompute. ",
]);
}
}
return `chunk-${index.toString().padStart(3, "0")} `;
if (laneKey === "navigation") {
switch (cycleIndex % 3) {
case 0:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Navigation lane is reconciling sidebar counts for pass ${pass}. `,
"I am checking whether the selected thread can stay interactive during the burst. ",
]);
case 1:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Navigation lane is refreshing route state for pass ${pass}. `,
"The next command is scoped to sidebar metadata and unread markers. ",
]);
default:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Navigation lane is merging background thread summaries for pass ${pass}. `,
"I am verifying that thread switches stay cheap while other turns keep moving. ",
]);
}
}
switch (cycleIndex % 3) {
case 0:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Filler lane is compacting idle thread state for pass ${pass}. `,
"I am keeping background reconciliation active so the burst is not single-threaded. ",
]);
case 1:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Filler lane is reconciling file tree badges for pass ${pass}. `,
"The next command updates background state without stealing focus from the active lane. ",
]);
default:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "intro", [
`Filler lane is sweeping deferred projections for pass ${pass}. `,
"I am checking that hidden threads can absorb more websocket traffic without stalling. ",
]);
}
}
function buildDenseAssistantFollowupSegment(
laneKey: DenseAssistantStreamLaneKey,
cycleIndex: number,
cycleCount: number,
): DenseAssistantSegment {
const pass = cycleIndex + 1;
const isLastCycle = cycleIndex === cycleCount - 1;
if (laneKey === "burst") {
if (isLastCycle) {
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
"Applied the last reducer update and finished the visible-thread verification pass. ",
`Streaming workload drained cleanly. ${DENSE_ASSISTANT_STREAM_SENTINEL}`,
]);
}
switch (cycleIndex % 4) {
case 0:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Queued the reducer patch for burst slice ${pass}. `,
"The viewport stayed responsive, so I am moving straight to the next live diff. ",
]);
case 1:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Patched the visible rows touched by burst slice ${pass}. `,
"I can keep streaming without forcing a full timeline rebuild. ",
]);
case 2:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Folded the duplicate projection work produced by burst slice ${pass}. `,
"The next command will keep pressure on the event path instead of idling. ",
]);
default:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Settled the optimistic state from burst slice ${pass}. `,
"I am continuing with another narrow update while background threads keep progressing. ",
]);
}
}
if (laneKey === "navigation") {
if (isLastCycle) {
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
"Navigation lane finished its background reconciliation pass. ",
"Thread switching stayed live while the burst completed. ",
]);
}
switch (cycleIndex % 3) {
case 0:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Navigation lane merged sidebar counters for pass ${pass}. `,
"Selection state still looks stable under concurrent updates. ",
]);
case 1:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Navigation lane applied the route metadata refresh for pass ${pass}. `,
"Unread state is still moving without forcing a navigation reset. ",
]);
default:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Navigation lane committed background thread summaries for pass ${pass}. `,
"The sidebar stayed interactive while the active turn kept streaming. ",
]);
}
}
if (isLastCycle) {
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
"Filler lane finished compacting deferred background work. ",
"Hidden threads stayed caught up through the end of the websocket burst. ",
]);
}
switch (cycleIndex % 3) {
case 0:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Filler lane compacted idle thread state for pass ${pass}. `,
"Background threads are still accepting updates without starving the visible thread. ",
]);
case 1:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Filler lane refreshed file tree badges for pass ${pass}. `,
"The background projection load stayed incremental instead of spiking. ",
]);
default:
return buildDenseAssistantSegmentVariation(laneKey, cycleIndex, "followup", [
`Filler lane drained deferred projections for pass ${pass}. `,
"There is still enough background traffic here to catch cross-thread regressions. ",
]);
}
}
function buildDenseAssistantToolSpec(
laneKey: DenseAssistantStreamLaneKey,
cycleIndex: number,
toolIndex: number,
): DenseAssistantToolSpec {
const pass = cycleIndex + 1;
if (laneKey === "burst") {
const files = selectDenseAssistantFiles(
[
"apps/web/src/store.ts",
"apps/web/src/session-logic.ts",
"apps/web/src/components/chat/MessagesTimeline.tsx",
"apps/web/src/components/ChatView.tsx",
"apps/web/src/lib/providerReactQuery.ts",
"apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts",
"apps/server/src/wsServer.ts",
"packages/shared/src/perf/scenarioCatalog.ts",
"apps/web/src/components/sidebar/ThreadList.tsx",
"apps/server/src/orchestration/Layers/ProjectionPipeline.ts",
],
cycleIndex,
toolIndex,
5,
);
switch (toolIndex) {
case 0:
return {
title: `Burst thread scan ${pass}`,
detail: `Scanned reducer fan-out and live queue pressure for websocket batch ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=burst",
`--batch=${pass}`,
"--step=scan",
"--touch=queue,projection",
],
files,
};
case 1:
return {
title: `Burst thread patch ${pass}`,
detail: `Patched the visible reducer path and timeline projection for websocket batch ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=burst",
`--batch=${pass}`,
"--step=patch",
"--touch=render,store",
],
files,
};
default:
return {
title: `Burst thread verify ${pass}`,
detail: `Verified viewport stability and render cadence after websocket batch ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=burst",
`--batch=${pass}`,
"--step=verify",
"--touch=viewport,metrics",
],
files,
};
}
}
if (laneKey === "navigation") {
const files = selectDenseAssistantFiles(
[
"apps/web/src/components/sidebar/ThreadList.tsx",
"apps/web/src/components/sidebar/ProjectSidebar.tsx",
"apps/web/src/routes/threadRoute.ts",
"apps/web/src/store.ts",
"apps/web/src/session-logic.ts",
"apps/server/src/wsServer.ts",
"apps/web/src/components/ChatView.tsx",
"apps/web/src/lib/providerReactQuery.ts",
],
cycleIndex,
toolIndex,
4,
);
switch (toolIndex) {
case 0:
return {
title: `Navigation thread sync ${pass}`,
detail: `Synced route metadata and selected-thread state for navigation pass ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=navigation",
`--batch=${pass}`,
"--step=sync",
"--touch=route,selection",
],
files,
};
case 1:
return {
title: `Navigation thread merge ${pass}`,
detail: `Merged sidebar counters, unread markers, and project summaries for pass ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=navigation",
`--batch=${pass}`,
"--step=merge",
"--touch=sidebar,unread",
],
files,
};
default:
return {
title: `Navigation thread settle ${pass}`,
detail: `Settled thread-list focus state and background summaries for navigation pass ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=navigation",
`--batch=${pass}`,
"--step=settle",
"--touch=focus,summary",
],
files,
};
}
}
const files = selectDenseAssistantFiles(
[
"apps/web/src/store.ts",
"apps/web/src/components/chat/MessagesTimeline.tsx",
"apps/web/src/components/ChatView.tsx",
"apps/server/src/orchestration/Layers/ProjectionPipeline.ts",
"apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts",
"packages/shared/src/perf/scenarioCatalog.ts",
"apps/web/src/components/sidebar/ThreadList.tsx",
"apps/server/src/wsServer.ts",
],
cycleIndex,
toolIndex,
4,
);
switch (toolIndex) {
case 0:
return {
title: `Filler thread compact ${pass}`,
detail: `Compacted deferred background projections and idle thread state for pass ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=filler",
`--batch=${pass}`,
"--step=compact",
"--touch=background,projection",
],
files,
};
case 1:
return {
title: `Filler thread refresh ${pass}`,
detail: `Refreshed background file tree badges and hidden-thread summaries for pass ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=filler",
`--batch=${pass}`,
"--step=refresh",
"--touch=file-tree,badges",
],
files,
};
default:
return {
title: `Filler thread drain ${pass}`,
detail: `Drained deferred background churn without stealing focus from the visible thread on pass ${pass}.`,
command: [
"bun",
"x",
"perf-loop",
"--lane=filler",
`--batch=${pass}`,
"--step=drain",
"--touch=background,queue",
],
files,
};
}
}
function buildDenseAssistantToolPayload(
toolSpec: DenseAssistantToolSpec,
cycleIndex: number,
toolIndex: number,
) {
const files = toolSpec.files.map((filePath, fileIndex) => ({
path: filePath,
status:
(fileIndex + cycleIndex + toolIndex) % 4 === 0
? "modified"
: (fileIndex + cycleIndex + toolIndex) % 4 === 1
? "added"
: (fileIndex + cycleIndex + toolIndex) % 4 === 2
? "deleted"
: "renamed",
additions: 8 + fileIndex * 3 + toolIndex * 2,
deletions: 2 + fileIndex + (cycleIndex % 3),
}));
return {
command: toolSpec.command,
item: {
command: toolSpec.command,
input: {
command: toolSpec.command,
},
result: {
command: toolSpec.command,
exitCode: 0,
files,
},
},
files,
operations: files.map((file) => ({
type: file.status,
path: file.path,
})),
};
}
function buildLaneScope(lane: DenseAssistantStreamLane) {
return {
...(lane.threadId ? { threadId: lane.threadId } : {}),
...(lane.turnId ? { turnId: lane.turnId } : {}),
} as const;
}
function buildDenseAssistantStreamScenario(): PerfProviderScenario {
const events: TimedFixtureProviderRuntimeEvent[] = [
{
delayMs: 0,
const events: TimedFixtureProviderRuntimeEvent[] = [];
const cycleCount = DENSE_ASSISTANT_STREAM_CYCLE_COUNT;
const finalCycleStartMs = DENSE_ASSISTANT_STREAM_CYCLE_INTERVAL_MS * (cycleCount - 1);
let maxCycleEventOffsetMs = 0;
DENSE_ASSISTANT_STREAM_LANES.forEach((lane, laneIndex) => {
events.push({
delayMs: laneIndex,
...buildLaneScope(lane),
type: "turn.started",
payload: {
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
},
];
const stepCount = 200;
for (let index = 0; index < stepCount; index += 1) {
const stepOffsetMs = index * 15;
const toolItemId = `perf-command-${index.toString().padStart(3, "0")}`;
events.push({
delayMs: stepOffsetMs + 2,
type: "item.started",
itemId: toolItemId,
payload: {
itemType: "command_execution",
title: `Perf command ${index + 1}`,
detail: `Simulated websocket workload ${index + 1}`,
},
});
events.push({
delayMs: stepOffsetMs + 7,
type: "content.delta",
payload: {
streamKind: "assistant_text",
delta: buildAssistantChunk(index, stepCount),
},
});
events.push({
delayMs: stepOffsetMs + 11,
type: "item.completed",
itemId: toolItemId,
payload: {
itemType: "command_execution",
status: "completed",
title: `Perf command ${index + 1}`,
detail: `Simulated websocket workload ${index + 1}`,
},
});
for (let cycleIndex = 0; cycleIndex < cycleCount; cycleIndex += 1) {
const cycleOffsetMs = cycleIndex * DENSE_ASSISTANT_STREAM_CYCLE_INTERVAL_MS;
DENSE_ASSISTANT_STREAM_LANES.forEach((lane, laneIndex) => {
const laneScope = buildLaneScope(lane);
const laneOffsetMs = laneIndex * DENSE_ASSISTANT_STREAM_LANE_STAGGER_MS;
const introItemId = makeLiveAssistantItemId(lane.key, cycleIndex, "intro");
const followupItemId = makeLiveAssistantItemId(lane.key, cycleIndex, "followup");
const introSegment = buildDenseAssistantIntroSegment(lane.key, cycleIndex);
const followupSegment = buildDenseAssistantFollowupSegment(lane.key, cycleIndex, cycleCount);
let laneEventOffsetMs = 4;
for (const fragment of introSegment) {
events.push({
delayMs: cycleOffsetMs + laneOffsetMs + laneEventOffsetMs,
...laneScope,
type: "content.delta",
itemId: introItemId,
payload: {
streamKind: "assistant_text",
delta: fragment,
},
});
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_MESSAGE_FRAGMENT_GAP_MS;
}
events.push({
delayMs: cycleOffsetMs + laneOffsetMs + laneEventOffsetMs,
...laneScope,
type: "item.completed",
itemId: introItemId,
payload: {
itemType: "assistant_message",
status: "completed",
detail: joinDenseAssistantSegment(introSegment),
},
});
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_MESSAGE_COMPLETION_GAP_MS;
for (
let toolIndex = 0;
toolIndex < DENSE_ASSISTANT_STREAM_WORKLOG_ITEMS_PER_CYCLE;
toolIndex += 1
) {
const toolItemId = `perf-command-${lane.key}-${cycleIndex.toString().padStart(3, "0")}-${toolIndex.toString().padStart(2, "0")}`;
const toolSpec = buildDenseAssistantToolSpec(lane.key, cycleIndex, toolIndex);
const toolPayload = buildDenseAssistantToolPayload(toolSpec, cycleIndex, toolIndex);
events.push({
delayMs: cycleOffsetMs + laneOffsetMs + laneEventOffsetMs,
...laneScope,
type: "item.started",
itemId: toolItemId,
payload: {
itemType: "command_execution",
title: toolSpec.title,
detail: toolSpec.detail,
},
});
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_WORKLOG_STARTED_GAP_MS;
events.push({
delayMs: cycleOffsetMs + laneOffsetMs + laneEventOffsetMs,
...laneScope,
type: "item.updated",
itemId: toolItemId,
payload: {
itemType: "command_execution",
status: "inProgress",
title: toolSpec.title,
detail: toolSpec.detail,
data: toolPayload,
},
});
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_WORKLOG_UPDATED_GAP_MS;
events.push({
delayMs: cycleOffsetMs + laneOffsetMs + laneEventOffsetMs,
...laneScope,
type: "item.completed",
itemId: toolItemId,
payload: {
itemType: "command_execution",
status: "completed",
title: toolSpec.title,
detail: toolSpec.detail,
data: toolPayload,
},
});
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_WORKLOG_COMPLETED_GAP_MS;
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_WORKLOG_GROUP_GAP_MS;
}
for (const fragment of followupSegment) {
events.push({
delayMs: cycleOffsetMs + laneOffsetMs + laneEventOffsetMs,
...laneScope,
type: "content.delta",
itemId: followupItemId,
payload: {
streamKind: "assistant_text",
delta: fragment,
},
});
laneEventOffsetMs += DENSE_ASSISTANT_STREAM_MESSAGE_FRAGMENT_GAP_MS;
}
const followupCompletionDelayMs = cycleOffsetMs + laneOffsetMs + laneEventOffsetMs;
events.push({
delayMs: followupCompletionDelayMs,
...laneScope,
type: "item.completed",
itemId: followupItemId,
payload: {
itemType: "assistant_message",
status: "completed",
detail: joinDenseAssistantSegment(followupSegment),
},
});
maxCycleEventOffsetMs = Math.max(maxCycleEventOffsetMs, laneOffsetMs + laneEventOffsetMs);
});
}
events.push({
delayMs: 3_060,
type: "turn.completed",
payload: {
state: "completed",
},
const finalLaneRunStartMs = finalCycleStartMs + maxCycleEventOffsetMs;
const totalDurationMs =
finalLaneRunStartMs +
(DENSE_ASSISTANT_STREAM_LANES.length - 1) * DENSE_ASSISTANT_STREAM_TURN_COMPLETION_GAP_MS;
DENSE_ASSISTANT_STREAM_LANES.forEach((lane, laneIndex) => {
events.push({
delayMs: finalLaneRunStartMs + laneIndex * DENSE_ASSISTANT_STREAM_TURN_COMPLETION_GAP_MS,
...buildLaneScope(lane),
type: "turn.completed",
payload: {
state: "completed",
},
});
});
return {
id: "dense_assistant_stream",
provider: "codex",
sentinelText: DENSE_ASSISTANT_STREAM_SENTINEL,
totalDurationMs: 3_060,
totalDurationMs,
events,
};
}
@@ -261,9 +915,21 @@ export const PERF_CATALOG_IDS = {
navigationThreadId: BURST_NAVIGATION_THREAD.id,
navigationAnchorMessageId: BURST_NAVIGATION_THREAD.anchorMessageId,
navigationTerminalMessageId: BURST_NAVIGATION_THREAD.terminalMessageId,
fillerThreadId: BURST_FILLER_THREAD.id,
},
provider: {
denseAssistantStreamSentinel: DENSE_ASSISTANT_STREAM_SENTINEL,
navigationLiveTurnId: PERF_PROVIDER_LIVE_TURNS.navigation,
fillerLiveTurnId: PERF_PROVIDER_LIVE_TURNS.filler,
navigationLiveAssistantMessageId: makeLiveAssistantMessageId(
makeLiveAssistantItemId("navigation", 1, "followup"),
),
burstLiveAssistantMessageId: makeLiveAssistantMessageId(
makeLiveAssistantItemId("burst", 2, "intro"),
),
fillerLiveAssistantMessageId: makeLiveAssistantMessageId(
makeLiveAssistantItemId("filler", 1, "followup"),
),
},
} as const;
+385
View File
@@ -0,0 +1,385 @@
import { spawn, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import { access, rm } from "node:fs/promises";
import { createServer } from "node:net";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
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_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__";
type PerfSeedScenarioId = "large_threads" | "burst_base";
type PerfProviderScenarioId = "dense_assistant_stream";
interface PerfSeedThreadSummary {
readonly id: string;
readonly title: string;
readonly messageCount: number;
readonly activityCount: number;
readonly proposedPlanCount: number;
readonly checkpointCount: number;
}
interface PerfSeededState {
readonly scenarioId: PerfSeedScenarioId;
readonly runParentDir: string;
readonly baseDir: string;
readonly workspaceRoot: string;
readonly projectTitle: string | null;
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
}
interface CliOptions {
readonly scenarioId: PerfSeedScenarioId;
readonly providerScenarioId: PerfProviderScenarioId | null;
readonly host: string;
readonly port: number;
readonly openBrowser: boolean;
}
function printHelp(): void {
process.stdout.write(
[
"Usage: bun run perf:open -- [options]",
"",
"Options:",
" --scenario <large_threads|burst_base> Seed scenario to launch (default: large_threads)",
" --provider <dense_assistant_stream> Enable perf provider burst mode",
" --host <host> Host to bind (default: 127.0.0.1)",
" --port <port> Port to bind (default: random free port)",
" --open Open the URL in your default browser",
" --help Show this help",
"",
"Examples:",
" bun run perf:open -- --scenario large_threads --open",
" bun run perf:open -- --scenario burst_base --provider dense_assistant_stream --open",
"",
"Notes:",
" - This launches the built app, not Vite dev mode.",
" - Build artifacts must already exist. Run `bun run test:perf:web` once, or build `@t3tools/web` and `t3` manually.",
" - With `--provider dense_assistant_stream`, open the burst thread and send one message to trigger the live multi-thread websocket burst.",
"",
].join("\n"),
);
}
function parseArgs(argv: ReadonlyArray<string>): CliOptions {
let scenarioId: PerfSeedScenarioId = "large_threads";
let providerScenarioId: PerfProviderScenarioId | null = null;
let host = "127.0.0.1";
let port = 0;
let openBrowser = false;
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
switch (argument) {
case "--scenario": {
const next = argv[index + 1];
if (next !== "large_threads" && next !== "burst_base") {
throw new Error(
`Expected a valid perf seed scenario after --scenario, received '${next ?? "<missing>"}'.`,
);
}
scenarioId = next;
index += 1;
break;
}
case "--provider": {
const next = argv[index + 1];
if (next !== "dense_assistant_stream") {
throw new Error(
`Expected a valid perf provider scenario after --provider, received '${next ?? "<missing>"}'.`,
);
}
providerScenarioId = next;
index += 1;
break;
}
case "--host": {
const next = argv[index + 1];
if (!next) {
throw new Error("Expected a host value after --host.");
}
host = next;
index += 1;
break;
}
case "--port": {
const next = argv[index + 1];
const parsed = next ? Number.parseInt(next, 10) : Number.NaN;
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
throw new Error(`Expected a valid port after --port, received '${next ?? "<missing>"}'.`);
}
port = parsed;
index += 1;
break;
}
case "--open":
openBrowser = true;
break;
case "--help":
case "-h":
printHelp();
process.exit(0);
default:
throw new Error(`Unknown argument '${argument}'. Use --help for usage.`);
}
}
return {
scenarioId,
providerScenarioId,
host,
port,
openBrowser,
};
}
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;
}
server.close((closeError) => {
if (closeError) {
reject(closeError);
return;
}
resolvePort(address.port);
});
});
});
}
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.`,
);
});
}
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) {
throw new Error(`Perf seed command did not emit the expected JSON markers.\n${stdout}`);
}
const payload = stdout.slice(startIndex + PERF_SEED_JSON_START.length, endIndex).trim();
return JSON.parse(payload) as PerfSeededState;
}
async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
const seedProcess = spawn("bun", ["run", "apps/server/scripts/seedPerfState.ts", scenarioId], {
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);
}
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 during startup.
}
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
}
throw new Error(`Timed out waiting for perf server readiness at ${url}.`);
}
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 cleanupPerfRunDir(runParentDir: string): Promise<void> {
await rm(runParentDir, { recursive: true, force: true });
}
function openUrl(url: string): void {
const command: [string, ...string[]] =
process.platform === "darwin"
? ["open", url]
: process.platform === "win32"
? ["cmd", "/c", "start", "", url]
: ["xdg-open", url];
const child = spawn(command[0], command.slice(1), {
detached: true,
stdio: "ignore",
});
child.unref();
}
function printSeedSummary(
seededState: PerfSeededState,
url: string,
providerScenarioId: string | null,
): void {
process.stdout.write(`\nPerf app ready at ${url}\n`);
process.stdout.write(`Scenario: ${seededState.scenarioId}\n`);
process.stdout.write(`Base dir: ${seededState.baseDir}\n`);
process.stdout.write(`Workspace: ${seededState.workspaceRoot}\n`);
process.stdout.write(`Project: ${seededState.projectTitle ?? "<unknown>"}\n`);
process.stdout.write("Threads:\n");
for (const thread of seededState.threadSummaries.toSorted(
(left, right) =>
right.messageCount - left.messageCount || left.title.localeCompare(right.title),
)) {
process.stdout.write(
` - ${thread.title} (${thread.id}): ${thread.messageCount} messages, ${thread.activityCount} worklog rows, ${thread.proposedPlanCount} plans, ${thread.checkpointCount} checkpoints\n`,
);
}
if (providerScenarioId !== null) {
process.stdout.write("\nLive burst mode is enabled.\n");
process.stdout.write(
"Open the burst thread and send one message to trigger the multi-thread websocket burst.\n",
);
}
process.stdout.write("\nPress Ctrl+C to stop the server.\n\n");
}
async function main(): Promise<void> {
const options = parseArgs(process.argv.slice(2));
await verifyBuiltArtifacts();
const seededState = await seedPerfState(options.scenarioId);
const port = options.port === 0 ? await pickFreePort() : options.port;
const serverProcess = spawn(
"node",
[
serverBinPath,
"--mode",
"web",
"--host",
options.host,
"--port",
port.toString(),
"--base-dir",
seededState.baseDir,
"--no-browser",
],
{
cwd: repoRoot,
env: {
...process.env,
...(options.providerScenarioId
? {
[PERF_PROVIDER_ENV]: "1",
[PERF_SCENARIO_ENV]: options.providerScenarioId,
}
: {}),
},
stdio: ["ignore", "inherit", "inherit"],
},
);
let shuttingDown = false;
const shutdown = async (signal: NodeJS.Signals) => {
if (shuttingDown) {
return;
}
shuttingDown = true;
process.stdout.write(`\nReceived ${signal}. Stopping perf app...\n`);
await stopChildProcess(serverProcess);
await cleanupPerfRunDir(seededState.runParentDir);
process.exit(0);
};
process.on("SIGINT", () => {
void shutdown("SIGINT");
});
process.on("SIGTERM", () => {
void shutdown("SIGTERM");
});
try {
const url = `http://${options.host}:${port.toString()}`;
await waitForServerReady(url, serverProcess);
printSeedSummary(seededState, url, options.providerScenarioId);
if (options.openBrowser) {
openUrl(url);
}
const [exitCode] = (await once(serverProcess, "exit")) as [number | null];
if (!shuttingDown) {
await cleanupPerfRunDir(seededState.runParentDir);
process.exit(exitCode ?? 0);
}
} catch (error) {
await stopChildProcess(serverProcess);
await cleanupPerfRunDir(seededState.runParentDir);
throw error;
}
}
try {
await main();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`${message}\n`);
process.exit(1);
}
+4 -1
View File
@@ -68,7 +68,10 @@ export function percentile(values: ReadonlyArray<number>, target: number): numbe
}
const sorted = values.toSorted((left, right) => left - right);
const clampedTarget = Math.min(Math.max(target, 0), 1);
const index = Math.min(sorted.length - 1, Math.ceil(sorted.length * clampedTarget) - 1);
const index = Math.min(
sorted.length - 1,
Math.max(0, Math.ceil(sorted.length * clampedTarget) - 1),
);
return sorted[index] ?? null;
}
+5 -3
View File
@@ -30,15 +30,16 @@ export function installBrowserPerfCollector(
const rafGapsMs: number[] = [];
const mountedRowSamples: Array<BrowserPerfMetrics["mountedRowSamples"][number]> = [];
let previousAnimationFrameTs = 0;
let rafHandle = 0;
const animationFrameLoop = (timestampMs: number) => {
if (previousAnimationFrameTs > 0) {
rafGapsMs.push(timestampMs - previousAnimationFrameTs);
}
previousAnimationFrameTs = timestampMs;
window.requestAnimationFrame(animationFrameLoop);
rafHandle = window.requestAnimationFrame(animationFrameLoop);
};
window.requestAnimationFrame(animationFrameLoop);
rafHandle = window.requestAnimationFrame(animationFrameLoop);
if (typeof PerformanceObserver !== "undefined") {
try {
@@ -103,7 +104,8 @@ export function installBrowserPerfCollector(
rafGapsMs.length = 0;
mountedRowSamples.length = 0;
previousAnimationFrameTs = 0;
window.requestAnimationFrame(animationFrameLoop);
window.cancelAnimationFrame(rafHandle);
rafHandle = window.requestAnimationFrame(animationFrameLoop);
},
};
}
+1 -1
View File
@@ -15,7 +15,7 @@ export const PERF_THRESHOLDS = {
threadSwitchP95Ms: 500,
maxLongTaskMs: 120,
maxRafGapMs: 120,
burstCompletionMs: 5_000,
burstCompletionMs: 14_000,
longTasksOver50MsMax: 2,
},
} as const satisfies Record<string, PerfThresholdProfile>;