From eecc2bc28d07ce1b5fa0f973bd14ec43d0cf18df Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 1 Apr 2026 13:59:21 -0700 Subject: [PATCH] Add perf regression test harnesses - Seed reusable perf fixtures for server scenarios - Add perf provider adapter and web perf tests - Capture artifacts for virtualization and websocket runs --- .../integration/perf/seedPerfState.test.ts | 43 + apps/server/integration/perf/seedPerfState.ts | 448 ++++++++++ apps/server/scripts/seedPerfState.ts | 31 + .../src/perf/PerfProviderAdapter.test.ts | 56 ++ apps/server/src/perf/PerfProviderAdapter.ts | 417 +++++++++ apps/server/src/perf/PerfProviderLayers.ts | 29 + apps/server/src/perf/PerfProviderRegistry.ts | 158 ++++ apps/server/src/perf/config.ts | 18 + apps/server/src/server.ts | 17 +- apps/web/package.json | 4 +- apps/web/test/perf/appHarness.ts | 445 ++++++++++ apps/web/test/perf/pagePerfHelpers.ts | 98 +++ .../web/test/perf/virtualization.perf.test.ts | 168 ++++ .../perf/websocket-application.perf.test.ts | 125 +++ apps/web/tsconfig.json | 10 +- apps/web/vitest.perf.config.ts | 12 + .../virtualization-large_threads.json | 238 ++++++ ...et-application-dense_assistant_stream.json | 807 ++++++++++++++++++ package.json | 1 + packages/shared/package.json | 4 + packages/shared/src/perf/scenarioCatalog.ts | 294 +++++++ test/perf/support/artifact.ts | 123 +++ test/perf/support/browserMetrics.ts | 109 +++ test/perf/support/scenarioCatalog.ts | 1 + test/perf/support/serverSampler.ts | 14 + test/perf/support/thresholds.ts | 23 + 26 files changed, 3688 insertions(+), 5 deletions(-) create mode 100644 apps/server/integration/perf/seedPerfState.test.ts create mode 100644 apps/server/integration/perf/seedPerfState.ts create mode 100644 apps/server/scripts/seedPerfState.ts create mode 100644 apps/server/src/perf/PerfProviderAdapter.test.ts create mode 100644 apps/server/src/perf/PerfProviderAdapter.ts create mode 100644 apps/server/src/perf/PerfProviderLayers.ts create mode 100644 apps/server/src/perf/PerfProviderRegistry.ts create mode 100644 apps/server/src/perf/config.ts create mode 100644 apps/web/test/perf/appHarness.ts create mode 100644 apps/web/test/perf/pagePerfHelpers.ts create mode 100644 apps/web/test/perf/virtualization.perf.test.ts create mode 100644 apps/web/test/perf/websocket-application.perf.test.ts create mode 100644 apps/web/vitest.perf.config.ts create mode 100644 artifacts/perf/virtualization-large_threads-1775077017735/virtualization-large_threads.json create mode 100644 artifacts/perf/websocket-application-burst_base-1775077022750/websocket-application-dense_assistant_stream.json create mode 100644 packages/shared/src/perf/scenarioCatalog.ts create mode 100644 test/perf/support/artifact.ts create mode 100644 test/perf/support/browserMetrics.ts create mode 100644 test/perf/support/scenarioCatalog.ts create mode 100644 test/perf/support/serverSampler.ts create mode 100644 test/perf/support/thresholds.ts diff --git a/apps/server/integration/perf/seedPerfState.test.ts b/apps/server/integration/perf/seedPerfState.test.ts new file mode 100644 index 0000000000..995b4a3beb --- /dev/null +++ b/apps/server/integration/perf/seedPerfState.test.ts @@ -0,0 +1,43 @@ +import { readFile, rm } from "node:fs/promises"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog"; +import { seedPerfState } from "./seedPerfState.ts"; + +describe("seedPerfState", () => { + const baseDirsToCleanup: string[] = []; + + afterEach(async () => { + await Promise.all( + baseDirsToCleanup.splice(0).map((baseDir) => rm(baseDir, { 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); + + expect(seeded.snapshot.projects).toHaveLength(1); + expect(seeded.snapshot.threads).toHaveLength(12); + + const heavyThread = seeded.snapshot.threads.find( + (thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + ); + 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); + }); + + it("enables assistant streaming in the burst base seed for websocket perf runs", async () => { + const seeded = await seedPerfState("burst_base"); + baseDirsToCleanup.push(seeded.baseDir); + + const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8"); + expect(JSON.parse(rawSettings)).toMatchObject({ + enableAssistantStreaming: true, + }); + }); +}); diff --git a/apps/server/integration/perf/seedPerfState.ts b/apps/server/integration/perf/seedPerfState.ts new file mode 100644 index 0000000000..0a0f869cb8 --- /dev/null +++ b/apps/server/integration/perf/seedPerfState.ts @@ -0,0 +1,448 @@ +import { execFileSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + CheckpointRef, + CommandId, + EventId, + type OrchestrationEvent, + type OrchestrationReadModel, +} from "@t3tools/contracts"; +import { Effect, Layer, ManagedRuntime } from "effect"; + +import { + getPerfSeedScenario, + perfEventId, + perfMessageIdForThread, + perfTurnIdForThread, + type PerfSeedScenario, + type PerfSeedScenarioId, + type PerfSeedThreadScenario, +} from "@t3tools/shared/perf/scenarioCatalog"; +import { ServerConfig } from "../../src/config.ts"; +import { OrchestrationProjectionPipelineLive } from "../../src/orchestration/Layers/ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "../../src/orchestration/Layers/ProjectionSnapshotQuery.ts"; +import { OrchestrationProjectionPipeline } from "../../src/orchestration/Services/ProjectionPipeline.ts"; +import { ProjectionSnapshotQuery } from "../../src/orchestration/Services/ProjectionSnapshotQuery.ts"; +import { OrchestrationEventStoreLive } from "../../src/persistence/Layers/OrchestrationEventStore.ts"; +import { layerConfig as SqlitePersistenceLayerLive } from "../../src/persistence/Layers/Sqlite.ts"; +import { OrchestrationEventStore } from "../../src/persistence/Services/OrchestrationEventStore.ts"; +import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSettings.ts"; + +export interface PerfSeededState { + readonly scenarioId: PerfSeedScenarioId; + readonly baseDir: string; + readonly workspaceRoot: string; + readonly snapshot: OrchestrationReadModel; +} + +const templateDirPromises = new Map>(); + +function runGit(cwd: string, args: ReadonlyArray) { + execFileSync("git", args, { + cwd, + stdio: ["ignore", "pipe", "pipe"], + encoding: "utf8", + }); +} + +async function initializeGitWorkspace(workspaceRoot: string): Promise { + await mkdir(workspaceRoot, { recursive: true }); + runGit(workspaceRoot, ["init", "--initial-branch=main"]); + runGit(workspaceRoot, ["config", "user.email", "perf@example.com"]); + runGit(workspaceRoot, ["config", "user.name", "Perf Fixture"]); + await writeFile( + join(workspaceRoot, "README.md"), + "# Performance Workspace\n\nSeeded fixture state for local perf regression tests.\n", + "utf8", + ); + runGit(workspaceRoot, ["add", "."]); + runGit(workspaceRoot, ["commit", "-m", "Initial perf workspace"]); +} + +function plusMs(baseTimeMs: number, offsetMs: number): string { + return new Date(baseTimeMs + offsetMs).toISOString(); +} + +function makeCommandId(prefix: string, threadId: string, turnIndex: number): CommandId { + return CommandId.makeUnsafe(`${prefix}:${threadId}:${turnIndex.toString().padStart(4, "0")}`); +} + +function buildProjectEvent( + scenario: PerfSeedScenario, + workspaceRoot: string, + createdAt: string, +): Omit { + return { + type: "project.created", + eventId: EventId.makeUnsafe(`perf-project-created:${String(scenario.project.id)}`), + aggregateKind: "project", + aggregateId: scenario.project.id, + occurredAt: createdAt, + commandId: CommandId.makeUnsafe(`perf-project-create:${String(scenario.project.id)}`), + causationEventId: null, + correlationId: CommandId.makeUnsafe(`perf-project-create:${String(scenario.project.id)}`), + metadata: {}, + payload: { + projectId: scenario.project.id, + title: scenario.project.title, + workspaceRoot, + defaultModelSelection: scenario.project.defaultModelSelection, + scripts: [], + createdAt, + updatedAt: createdAt, + }, + }; +} + +function buildThreadCreatedEvent( + thread: PerfSeedThreadScenario, + scenario: PerfSeedScenario, + createdAt: string, +): Omit { + return { + type: "thread.created", + eventId: EventId.makeUnsafe(`perf-thread-created:${String(thread.id)}`), + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: createdAt, + commandId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`), + causationEventId: null, + correlationId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`), + metadata: {}, + payload: { + threadId: thread.id, + projectId: scenario.project.id, + title: thread.title, + modelSelection: scenario.project.defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }; +} + +function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string { + const base = `${thread.title} request ${turnIndex}: review the current workspace state and explain the next change.`; + if (turnIndex % 11 === 0) { + return `${base}\n\nFocus on virtualization, batching, and cross-thread navigation latency.`; + } + if (turnIndex % 7 === 0) { + return `${base}\n\nSummarize CPU-sensitive paths and any websocket burst handling concerns.`; + } + return base; +} + +function buildAssistantMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string { + const prefix = `${thread.title} response ${turnIndex}: `; + const paragraphs = [ + "The render path stays stable when visible rows are capped and background work is batched.", + "Navigation remains predictable when thread metadata, message slices, and work log grouping avoid unnecessary churn.", + "Websocket-heavy turns should keep incremental UI updates small so the main thread is free for scrolling and input.", + ]; + const paragraphCount = turnIndex % 9 === 0 ? 3 : turnIndex % 4 === 0 ? 2 : 1; + return `${prefix}${paragraphs.slice(0, paragraphCount).join(" ")}${ + turnIndex % 13 === 0 + ? "\n\n- Keep virtual rows bounded\n- Avoid synchronous bursts\n- Preserve responsive thread switches" + : "" + }`; +} + +function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string { + return [ + `## ${thread.title} plan ${turnIndex}`, + "", + "1. Measure the current thread switch path against a stable local budget.", + "2. Reduce avoidable render churn in the visible timeline window.", + "3. Validate websocket burst handling with real runtime events before tightening thresholds.", + ].join("\n"); +} + +function buildThreadTurnEvents( + scenario: PerfSeedScenario, + thread: PerfSeedThreadScenario, + threadOrdinal: number, + projectStartMs: number, +): ReadonlyArray> { + const events: Array> = []; + const threadStartMs = projectStartMs + threadOrdinal * 60_000; + + for (let turnIndex = 1; turnIndex <= thread.turnCount; turnIndex += 1) { + const turnId = perfTurnIdForThread(thread, turnIndex); + const userMessageId = perfMessageIdForThread(thread, "user", turnIndex); + const assistantMessageId = perfMessageIdForThread(thread, "assistant", turnIndex); + const turnBaseMs = threadStartMs + turnIndex * 1_000; + const userOccurredAt = plusMs(turnBaseMs, 0); + const assistantOccurredAt = plusMs(turnBaseMs, 320); + + events.push({ + type: "thread.message-sent", + eventId: perfEventId("perf-user-message", thread.id, turnIndex * 10), + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: userOccurredAt, + commandId: makeCommandId("perf-user-message", String(thread.id), turnIndex), + causationEventId: null, + correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex), + metadata: {}, + payload: { + threadId: thread.id, + messageId: userMessageId, + role: "user", + text: buildUserMessageText(thread, turnIndex), + attachments: [], + turnId, + streaming: false, + createdAt: userOccurredAt, + updatedAt: userOccurredAt, + }, + }); + + events.push({ + type: "thread.message-sent", + eventId: perfEventId("perf-assistant-message", thread.id, turnIndex * 10 + 1), + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: assistantOccurredAt, + commandId: makeCommandId("perf-assistant-message", String(thread.id), turnIndex), + causationEventId: null, + correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex), + metadata: {}, + payload: { + threadId: thread.id, + messageId: assistantMessageId, + role: "assistant", + text: buildAssistantMessageText(thread, turnIndex), + attachments: [], + turnId, + streaming: false, + createdAt: assistantOccurredAt, + updatedAt: assistantOccurredAt, + }, + }); + + if (thread.activityStride !== null && turnIndex % thread.activityStride === 0) { + const activityOccurredAt = plusMs(turnBaseMs, 520); + events.push({ + type: "thread.activity-appended", + eventId: perfEventId("perf-activity", thread.id, turnIndex * 10 + 2), + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: activityOccurredAt, + commandId: makeCommandId("perf-activity", String(thread.id), turnIndex), + causationEventId: null, + correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex), + metadata: {}, + payload: { + threadId: thread.id, + activity: { + id: perfEventId("perf-activity-row", thread.id, turnIndex), + tone: "tool", + kind: "tool.completed", + summary: `Synthetic command batch ${turnIndex}`, + payload: { + command: "perf-simulated", + batch: turnIndex, + threadCategory: thread.category, + }, + turnId, + createdAt: activityOccurredAt, + }, + }, + }); + } + + if (thread.planStride !== null && turnIndex % thread.planStride === 0) { + const planOccurredAt = plusMs(turnBaseMs, 640); + events.push({ + type: "thread.proposed-plan-upserted", + eventId: perfEventId("perf-plan", thread.id, turnIndex * 10 + 3), + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: planOccurredAt, + commandId: makeCommandId("perf-plan", String(thread.id), turnIndex), + causationEventId: null, + correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex), + metadata: {}, + payload: { + threadId: thread.id, + proposedPlan: { + id: `perf-plan:${String(thread.id)}:${turnIndex.toString().padStart(4, "0")}`, + turnId, + planMarkdown: buildProposedPlanMarkdown(thread, turnIndex), + implementedAt: null, + implementationThreadId: null, + createdAt: planOccurredAt, + updatedAt: planOccurredAt, + }, + }, + }); + } + + if (thread.diffStride !== null && turnIndex % thread.diffStride === 0) { + const diffOccurredAt = plusMs(turnBaseMs, 760); + events.push({ + type: "thread.turn-diff-completed", + eventId: perfEventId("perf-diff", thread.id, turnIndex * 10 + 4), + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: diffOccurredAt, + commandId: makeCommandId("perf-diff", String(thread.id), turnIndex), + causationEventId: null, + correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex), + metadata: {}, + payload: { + threadId: thread.id, + turnId, + checkpointTurnCount: turnIndex, + checkpointRef: CheckpointRef.makeUnsafe( + `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, + }, + ], + assistantMessageId, + completedAt: diffOccurredAt, + }, + }); + } + } + + return events; +} + +function buildScenarioEvents( + scenario: PerfSeedScenario, + workspaceRoot: string, +): ReadonlyArray> { + const projectStartMs = Date.parse("2026-03-01T12:00:00.000Z"); + const projectCreatedAt = plusMs(projectStartMs, 0); + return [ + buildProjectEvent(scenario, workspaceRoot, projectCreatedAt), + ...scenario.threads.flatMap((thread, threadOrdinal) => { + const threadCreatedAt = plusMs(projectStartMs, threadOrdinal * 60_000 + 50); + return [ + buildThreadCreatedEvent(thread, scenario, threadCreatedAt), + ...buildThreadTurnEvents(scenario, thread, threadOrdinal, projectStartMs), + ]; + }), + ]; +} + +async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise { + const scenario = getPerfSeedScenario(scenarioId); + const baseDir = await mkdtemp(join(tmpdir(), `t3-perf-template-${scenarioId}-`)); + const workspaceRoot = join(baseDir, scenario.project.workspaceDirectoryName); + await initializeGitWorkspace(workspaceRoot); + + const seedLayer = Layer.empty.pipe( + Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive), + Layer.provideMerge(OrchestrationProjectionPipelineLive), + Layer.provideMerge(OrchestrationEventStoreLive), + Layer.provideMerge(ServerSettingsLive), + Layer.provideMerge(SqlitePersistenceLayerLive), + Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)), + Layer.provideMerge(NodeServices.layer), + ); + const runtime = ManagedRuntime.make(seedLayer); + + const snapshot = await runtime.runPromise( + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const eventStore = yield* OrchestrationEventStore; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const snapshotQuery = yield* ProjectionSnapshotQuery; + + yield* serverSettings.updateSettings({ + enableAssistantStreaming: scenario.id === "burst_base", + }); + + for (const event of buildScenarioEvents(scenario, workspaceRoot)) { + const storedEvent = yield* eventStore.append(event); + yield* projectionPipeline.projectEvent(storedEvent); + } + + return yield* snapshotQuery.getSnapshot(); + }), + ); + + const manifestPath = join(baseDir, "perf-seed-manifest.json"); + await writeFile( + manifestPath, + `${JSON.stringify( + { + scenarioId, + workspaceRoot, + snapshotSequence: snapshot.snapshotSequence, + projectCount: snapshot.projects.length, + threadCount: snapshot.threads.length, + }, + null, + 2, + )}\n`, + "utf8", + ); + + await runtime.dispose(); + return baseDir; +} + +async function getTemplateDir(scenarioId: PerfSeedScenarioId): Promise { + const existing = templateDirPromises.get(scenarioId); + if (existing) { + return existing; + } + const created = createTemplateDir(scenarioId); + templateDirPromises.set(scenarioId, created); + return created; +} + +export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise { + const scenario = getPerfSeedScenario(scenarioId); + const templateDir = await getTemplateDir(scenarioId); + const runParentDir = await mkdtemp(join(tmpdir(), `t3-perf-run-${scenarioId}-`)); + const baseDir = join(runParentDir, "base"); + await cp(templateDir, baseDir, { recursive: true, force: true }); + const workspaceRoot = join(baseDir, scenario.project.workspaceDirectoryName); + + const snapshotLayer = Layer.empty.pipe( + Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive), + Layer.provideMerge(ServerSettingsLive), + Layer.provideMerge(SqlitePersistenceLayerLive), + Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)), + Layer.provideMerge(NodeServices.layer), + ); + const runtime = ManagedRuntime.make(snapshotLayer); + const snapshot = await runtime.runPromise( + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + return yield* snapshotQuery.getSnapshot(); + }), + ); + await runtime.dispose(); + + return { + scenarioId, + baseDir, + workspaceRoot, + snapshot, + }; +} diff --git a/apps/server/scripts/seedPerfState.ts b/apps/server/scripts/seedPerfState.ts new file mode 100644 index 0000000000..07c4170d63 --- /dev/null +++ b/apps/server/scripts/seedPerfState.ts @@ -0,0 +1,31 @@ +import { seedPerfState } from "../integration/perf/seedPerfState.ts"; + +const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__"; +const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__"; +const scenarioId = process.argv[2]; + +if (scenarioId !== "large_threads" && scenarioId !== "burst_base") { + console.error(`Expected a perf seed scenario id, received '${scenarioId ?? ""}'.`); + process.exit(1); +} + +const seeded = await seedPerfState(scenarioId); +const payload = JSON.stringify( + { + scenarioId: seeded.scenarioId, + baseDir: seeded.baseDir, + workspaceRoot: seeded.workspaceRoot, + projectTitle: seeded.snapshot.projects[0]?.title ?? null, + threadSummaries: seeded.snapshot.threads.map((thread) => ({ + id: thread.id, + title: thread.title, + messageCount: thread.messages.length, + activityCount: thread.activities.length, + proposedPlanCount: thread.proposedPlans.length, + checkpointCount: thread.checkpoints.length, + })), + }, + null, + 2, +); +process.stdout.write(`${PERF_SEED_JSON_START}\n${payload}\n${PERF_SEED_JSON_END}\n`); diff --git a/apps/server/src/perf/PerfProviderAdapter.test.ts b/apps/server/src/perf/PerfProviderAdapter.test.ts new file mode 100644 index 0000000000..d842fab9b3 --- /dev/null +++ b/apps/server/src/perf/PerfProviderAdapter.test.ts @@ -0,0 +1,56 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { Effect, Stream } from "effect"; +import { ThreadId } from "@t3tools/contracts"; + +import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts"; + +const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO"; + +describe("PerfProviderAdapter", () => { + const previousScenarioEnv = process.env[PERF_SCENARIO_ENV]; + + afterEach(() => { + if (previousScenarioEnv === undefined) { + delete process.env[PERF_SCENARIO_ENV]; + return; + } + process.env[PERF_SCENARIO_ENV] = previousScenarioEnv; + }); + + 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"); + + await Effect.runPromise( + adapter.startSession({ + threadId, + provider: "codex", + runtimeMode: "full-access", + }), + ); + + const firstEventsPromise = Effect.runPromise( + Stream.runCollect(Stream.take(adapter.streamEvents, 4)), + ); + await Effect.runPromise( + adapter.sendTurn({ + threadId, + input: "exercise the dense perf scenario", + attachments: [], + }), + ); + + 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[2]?.type === "content.delta" ? firstEvents[2].payload.delta.length : 0, + ).toBeGreaterThan(0); + }); +}); diff --git a/apps/server/src/perf/PerfProviderAdapter.ts b/apps/server/src/perf/PerfProviderAdapter.ts new file mode 100644 index 0000000000..ae8a88e890 --- /dev/null +++ b/apps/server/src/perf/PerfProviderAdapter.ts @@ -0,0 +1,417 @@ +import { + EventId, + RuntimeItemId, + RuntimeRequestId, + RuntimeSessionId, + TurnId, + type ApprovalRequestId, + type ProviderApprovalDecision, + type ProviderRuntimeEvent, + type ProviderSendTurnInput, + type ProviderSession, + type ProviderSessionStartInput, + type ProviderTurnStartResult, + type ProviderUserInputAnswers, + type ThreadId, +} from "@t3tools/contracts"; +import { Effect, Queue, Stream } from "effect"; + +import { + getPerfProviderScenario, + type PerfProviderScenario, + type TimedFixtureProviderRuntimeEvent, +} from "@t3tools/shared/perf/scenarioCatalog"; +import { + ProviderAdapterSessionNotFoundError, + ProviderAdapterValidationError, + type ProviderAdapterError, +} from "../provider/Errors.ts"; +import type { + ProviderAdapterShape, + ProviderThreadSnapshot, + ProviderThreadTurnSnapshot, +} from "../provider/Services/ProviderAdapter.ts"; +import { getPerfProviderScenarioId } from "./config.ts"; + +interface PerfSessionState { + session: ProviderSession; + snapshot: ProviderThreadSnapshot; + turnCount: number; + pendingTimers: Set>; +} + +function nowIso(): string { + return new Date().toISOString(); +} + +function sessionNotFound(threadId: ThreadId): ProviderAdapterSessionNotFoundError { + return new ProviderAdapterSessionNotFoundError({ + provider: "codex", + threadId: String(threadId), + }); +} + +function resolvePerfScenario(inputText: string | undefined): PerfProviderScenario { + const scenarioId = getPerfProviderScenarioId(); + if (scenarioId) { + return getPerfProviderScenario(scenarioId); + } + + const trimmedInput = inputText?.trim() || "perf request"; + return { + id: "dense_assistant_stream", + provider: "codex", + sentinelText: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`, + totalDurationMs: 48, + events: [ + { + delayMs: 0, + type: "turn.started", + payload: { + model: "gpt-5.4", + }, + }, + { + delayMs: 16, + type: "content.delta", + payload: { + streamKind: "assistant_text", + delta: `Perf fallback response for: ${trimmedInput}. `, + }, + }, + { + delayMs: 32, + type: "content.delta", + payload: { + streamKind: "assistant_text", + delta: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`, + }, + }, + { + delayMs: 48, + type: "turn.completed", + payload: { + state: "completed", + }, + }, + ], + }; +} + +function toIdleSession(session: ProviderSession, updatedAt: string): ProviderSession { + const { activeTurnId: _activeTurnId, ...rest } = session; + return { + ...rest, + status: "ready", + updatedAt, + }; +} + +function buildRuntimeEvent(input: { + readonly template: TimedFixtureProviderRuntimeEvent; + readonly threadId: ThreadId; + readonly turnId: TurnId; + readonly startedAtMs: number; + readonly index: number; +}): ProviderRuntimeEvent { + 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")}`, + ), + provider: "codex", + threadId: input.threadId, + turnId: input.turnId, + createdAt, + ...(input.template.itemId ? { itemId: RuntimeItemId.makeUnsafe(input.template.itemId) } : {}), + ...(input.template.requestId + ? { requestId: RuntimeRequestId.makeUnsafe(input.template.requestId) } + : {}), + payload: input.template.payload, + } as ProviderRuntimeEvent; +} + +export const makePerfProviderAdapter = Effect.gen(function* () { + const runtimeEvents = yield* Queue.unbounded(); + const sessions = new Map(); + + const clearPendingTimers = (threadId: ThreadId) => + Effect.sync(() => { + const state = sessions.get(threadId); + if (!state) { + return; + } + for (const timer of state.pendingTimers) { + clearTimeout(timer); + } + state.pendingTimers.clear(); + }); + + const scheduleRuntimeEvent = (input: { + readonly state: PerfSessionState; + readonly event: ProviderRuntimeEvent; + readonly delayMs: number; + readonly onAfterEmit?: () => void; + }) => + Effect.sync(() => { + const timer = setTimeout(() => { + input.state.pendingTimers.delete(timer); + Effect.runFork( + Queue.offer(runtimeEvents, input.event).pipe( + Effect.tap(() => Effect.sync(() => input.onAfterEmit?.())), + Effect.asVoid, + ), + ); + }, input.delayMs); + input.state.pendingTimers.add(timer); + }); + + const startSession: ProviderAdapterShape["startSession"] = ( + input: ProviderSessionStartInput, + ) => + Effect.gen(function* () { + if (input.provider !== undefined && input.provider !== "codex") { + return yield* new ProviderAdapterValidationError({ + provider: "codex", + operation: "startSession", + issue: `Perf provider only supports codex sessions, received '${input.provider}'.`, + }); + } + + const createdAt = nowIso(); + const session: ProviderSession = { + provider: "codex", + status: "ready", + runtimeMode: input.runtimeMode, + threadId: input.threadId, + ...(input.cwd ? { cwd: input.cwd } : {}), + ...(input.modelSelection?.model ? { model: input.modelSelection.model } : {}), + resumeCursor: + input.resumeCursor ?? + RuntimeSessionId.makeUnsafe(`perf-resume:${String(input.threadId)}:${Date.now()}`), + createdAt, + updatedAt: createdAt, + }; + + sessions.set(input.threadId, { + session, + snapshot: { + threadId: input.threadId, + turns: [], + }, + turnCount: 0, + pendingTimers: new Set(), + }); + + return session; + }); + + const sendTurn: ProviderAdapterShape["sendTurn"] = ( + input: ProviderSendTurnInput, + ) => + Effect.gen(function* () { + const state = sessions.get(input.threadId); + if (!state) { + return yield* Effect.fail(sessionNotFound(input.threadId)); + } + + yield* clearPendingTimers(input.threadId); + + state.turnCount += 1; + const turnId = TurnId.makeUnsafe( + `perf-turn:${String(input.threadId)}:${state.turnCount.toString().padStart(4, "0")}`, + ); + const scenario = resolvePerfScenario(input.input); + const startedAtMs = Date.now(); + const sentAt = new Date(startedAtMs).toISOString(); + + state.session = { + ...state.session, + status: "running", + activeTurnId: turnId, + updatedAt: sentAt, + }; + + const userTurnItem = { + type: "userMessage", + content: [{ type: "text", text: input.input ?? "" }], + } as const; + const nextTurn: ProviderThreadTurnSnapshot = { + id: turnId, + items: [userTurnItem], + }; + state.snapshot = { + threadId: state.snapshot.threadId, + turns: [...state.snapshot.turns, nextTurn], + }; + + let assistantText = ""; + const updateAssistantSnapshot = (completedAt: string) => { + state.session = toIdleSession(state.session, completedAt); + state.snapshot = { + threadId: state.snapshot.threadId, + turns: state.snapshot.turns.map((turn) => + turn.id === turnId + ? { + ...turn, + items: + assistantText.length > 0 + ? [...turn.items, { type: "agentMessage", text: assistantText }] + : turn.items, + } + : turn, + ), + }; + }; + + yield* Effect.forEach( + scenario.events, + (template, index) => { + const event = buildRuntimeEvent({ + template, + threadId: input.threadId, + turnId, + startedAtMs, + index, + }); + const delayMs = template.delayMs ?? 0; + return scheduleRuntimeEvent({ + state, + event, + delayMs, + onAfterEmit: () => { + if (event.type === "content.delta" && event.payload.streamKind === "assistant_text") { + assistantText += event.payload.delta; + } + if (event.type === "turn.completed") { + updateAssistantSnapshot(event.createdAt); + } + }, + }); + }, + { concurrency: 1 }, + ); + + return { + threadId: input.threadId, + turnId, + } satisfies ProviderTurnStartResult; + }); + + const interruptTurn: ProviderAdapterShape["interruptTurn"] = ( + threadId, + turnId, + ) => + Effect.gen(function* () { + const state = sessions.get(threadId); + if (!state) { + return yield* Effect.fail(sessionNotFound(threadId)); + } + yield* clearPendingTimers(threadId); + const interruptedTurnId = turnId ?? state.session.activeTurnId; + state.session = toIdleSession(state.session, nowIso()); + if (interruptedTurnId) { + yield* Queue.offer(runtimeEvents, { + type: "turn.completed", + eventId: EventId.makeUnsafe( + `perf-runtime:${String(threadId)}:${String(interruptedTurnId)}:interrupted`, + ), + provider: "codex", + threadId, + turnId: interruptedTurnId, + createdAt: nowIso(), + payload: { + state: "interrupted", + }, + } satisfies ProviderRuntimeEvent); + } + }); + + const respondToRequest: ProviderAdapterShape["respondToRequest"] = ( + threadId, + _requestId: ApprovalRequestId, + _decision: ProviderApprovalDecision, + ) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId))); + + const respondToUserInput: ProviderAdapterShape["respondToUserInput"] = ( + threadId, + _requestId, + _answers: ProviderUserInputAnswers, + ) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId))); + + const stopSession: ProviderAdapterShape["stopSession"] = (threadId) => + Effect.gen(function* () { + if (!sessions.has(threadId)) { + return yield* Effect.fail(sessionNotFound(threadId)); + } + yield* clearPendingTimers(threadId); + sessions.delete(threadId); + }); + + const listSessions: ProviderAdapterShape["listSessions"] = () => + Effect.sync(() => Array.from(sessions.values(), (state) => state.session)); + + const hasSession: ProviderAdapterShape["hasSession"] = (threadId) => + Effect.succeed(sessions.has(threadId)); + + const readThread: ProviderAdapterShape["readThread"] = (threadId) => + sessions.has(threadId) + ? Effect.succeed(sessions.get(threadId)!.snapshot) + : Effect.fail(sessionNotFound(threadId)); + + const rollbackThread: ProviderAdapterShape["rollbackThread"] = ( + threadId, + numTurns, + ) => + Effect.gen(function* () { + const state = sessions.get(threadId); + if (!state) { + return yield* Effect.fail(sessionNotFound(threadId)); + } + if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) { + return yield* new ProviderAdapterValidationError({ + provider: "codex", + operation: "rollbackThread", + issue: "numTurns must be an integer between 0 and the current turn count.", + }); + } + state.snapshot = { + threadId: state.snapshot.threadId, + turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns), + }; + state.turnCount = state.snapshot.turns.length; + return state.snapshot; + }); + + const stopAll: ProviderAdapterShape["stopAll"] = () => + Effect.gen(function* () { + yield* Effect.forEach( + Array.from(sessions.keys()), + (threadId) => clearPendingTimers(threadId), + { + concurrency: "unbounded", + }, + ); + sessions.clear(); + }); + + return { + provider: "codex", + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + readThread, + rollbackThread, + stopAll, + streamEvents: Stream.fromQueue(runtimeEvents), + } satisfies ProviderAdapterShape; +}); diff --git a/apps/server/src/perf/PerfProviderLayers.ts b/apps/server/src/perf/PerfProviderLayers.ts new file mode 100644 index 0000000000..d26f480e00 --- /dev/null +++ b/apps/server/src/perf/PerfProviderLayers.ts @@ -0,0 +1,29 @@ +import { Effect, Layer } from "effect"; + +import { ProviderSessionRuntimeRepositoryLive } from "../persistence/Layers/ProviderSessionRuntime.ts"; +import { ProviderUnsupportedError } from "../provider/Errors.ts"; +import { makeProviderServiceLive } from "../provider/Layers/ProviderService.ts"; +import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts"; +import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts"; +import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts"; + +export const PerfProviderLayerLive = Layer.unwrap( + Effect.gen(function* () { + const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(ProviderSessionRuntimeRepositoryLive), + ); + const adapter = yield* makePerfProviderAdapter; + const adapterRegistryLayer = Layer.succeed(ProviderAdapterRegistry, { + getByProvider: (provider) => + provider === adapter.provider + ? Effect.succeed(adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed([adapter.provider]), + } as typeof ProviderAdapterRegistry.Service); + + return makeProviderServiceLive().pipe( + Layer.provide(adapterRegistryLayer), + Layer.provide(providerSessionDirectoryLayer), + ); + }), +); diff --git a/apps/server/src/perf/PerfProviderRegistry.ts b/apps/server/src/perf/PerfProviderRegistry.ts new file mode 100644 index 0000000000..88895ce758 --- /dev/null +++ b/apps/server/src/perf/PerfProviderRegistry.ts @@ -0,0 +1,158 @@ +import { + DEFAULT_MODEL_BY_PROVIDER, + type ServerProvider, + type ServerProviderModel, +} from "@t3tools/contracts"; +import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect"; + +import { getClaudeModelCapabilities } from "../provider/Layers/ClaudeProvider.ts"; +import { getCodexModelCapabilities } from "../provider/Layers/CodexProvider.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { + ProviderRegistry, + type ProviderRegistryShape, +} from "../provider/Services/ProviderRegistry.ts"; + +const makeProviderModel = (input: { + readonly slug: string; + readonly name: string; + readonly capabilities: ServerProviderModel["capabilities"]; +}): ServerProviderModel => ({ + slug: input.slug, + name: input.name, + isCustom: false, + capabilities: input.capabilities, +}); + +const CODEX_MODELS: ReadonlyArray = [ + makeProviderModel({ + slug: DEFAULT_MODEL_BY_PROVIDER.codex, + name: "GPT-5.4", + capabilities: getCodexModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.codex), + }), +]; + +const CLAUDE_MODELS: ReadonlyArray = [ + makeProviderModel({ + slug: DEFAULT_MODEL_BY_PROVIDER.claudeAgent, + name: "Claude Sonnet 4.6", + capabilities: getClaudeModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.claudeAgent), + }), +]; + +const makeProviderSnapshot = (input: { + readonly provider: ServerProvider["provider"]; + readonly enabled: boolean; + readonly checkedAt: string; +}): ServerProvider => { + if (input.provider === "codex") { + return { + provider: "codex", + enabled: input.enabled, + installed: true, + version: "perf-fixture", + status: input.enabled ? "ready" : "disabled", + auth: input.enabled + ? { + status: "authenticated", + type: "perf", + label: "Local perf harness", + } + : { + status: "unknown", + }, + checkedAt: input.checkedAt, + message: input.enabled ? "Perf fixture provider active." : "Disabled in T3 Code settings.", + models: CODEX_MODELS, + }; + } + + return { + provider: "claudeAgent", + enabled: input.enabled, + installed: false, + version: null, + status: input.enabled ? "warning" : "disabled", + auth: { + status: "unknown", + }, + checkedAt: input.checkedAt, + message: input.enabled + ? "Perf harness only stubs Codex runtime sessions." + : "Disabled in T3 Code settings.", + models: CLAUDE_MODELS, + }; +}; + +const loadPerfProviderSnapshots = Effect.fn("loadPerfProviderSnapshots")(function* (input: { + readonly serverSettings: ServerSettingsService["Service"]; +}) { + const settings = yield* input.serverSettings.getSettings; + const checkedAt = new Date().toISOString(); + return [ + makeProviderSnapshot({ + provider: "codex", + enabled: settings.providers.codex.enabled, + checkedAt, + }), + makeProviderSnapshot({ + provider: "claudeAgent", + enabled: settings.providers.claudeAgent.enabled, + checkedAt, + }), + ] as const; +}); + +const loadPerfProviderSnapshotsSafely = ( + serverSettings: ServerSettingsService["Service"], + fallback: ReadonlyArray, +) => + loadPerfProviderSnapshots({ serverSettings }).pipe( + Effect.tapError(Effect.logError), + Effect.orElseSucceed(() => fallback), + ); + +export const PerfProviderRegistryLive = Layer.effect( + ProviderRegistry, + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const changesPubSub = yield* Effect.acquireRelease( + PubSub.unbounded>(), + PubSub.shutdown, + ); + const providersRef = yield* Ref.make>( + yield* loadPerfProviderSnapshotsSafely(serverSettings, [ + makeProviderSnapshot({ + provider: "codex", + enabled: true, + checkedAt: new Date().toISOString(), + }), + makeProviderSnapshot({ + provider: "claudeAgent", + enabled: false, + checkedAt: new Date().toISOString(), + }), + ]), + ); + + const refreshProviders = Effect.fn("refreshPerfProviders")(function* () { + const previous = yield* Ref.get(providersRef); + const next = yield* loadPerfProviderSnapshotsSafely(serverSettings, previous); + yield* Ref.set(providersRef, next); + if (!Equal.equals(previous, next)) { + yield* PubSub.publish(changesPubSub, next); + } + return next; + }); + + yield* Stream.runForEach(serverSettings.streamChanges, () => refreshProviders()).pipe( + Effect.forkScoped, + ); + + return { + getProviders: Ref.get(providersRef), + refresh: (_provider) => refreshProviders(), + streamChanges: Stream.fromPubSub(changesPubSub), + } satisfies ProviderRegistryShape; + }), +); diff --git a/apps/server/src/perf/config.ts b/apps/server/src/perf/config.ts new file mode 100644 index 0000000000..c921316bd6 --- /dev/null +++ b/apps/server/src/perf/config.ts @@ -0,0 +1,18 @@ +import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog"; + +export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER"; +export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO"; +export const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR"; +export const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL"; + +export function isPerfProviderEnabled(): boolean { + return process.env[PERF_PROVIDER_ENV] === "1"; +} + +export function getPerfProviderScenarioId(): PerfProviderScenarioId | null { + const rawScenarioId = process.env[PERF_SCENARIO_ENV]?.trim(); + if (rawScenarioId === "dense_assistant_stream") { + return rawScenarioId; + } + return null; +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 23c53ad07f..5125533a74 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -72,6 +72,9 @@ import { orchestrationDispatchRouteLayer, orchestrationSnapshotRouteLayer, } from "./orchestration/http"; +import { isPerfProviderEnabled } from "./perf/config"; +import { PerfProviderRegistryLive } from "./perf/PerfProviderRegistry"; +import { PerfProviderLayerLive } from "./perf/PerfProviderLayers"; const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -134,7 +137,7 @@ const CheckpointingLayerLive = Layer.empty.pipe( Layer.provideMerge(CheckpointStoreLive), ); -const ProviderLayerLive = Layer.unwrap( +const DefaultProviderLayerLive = Layer.unwrap( Effect.gen(function* () { const { providerEventLogPath } = yield* ServerConfig; const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { @@ -163,6 +166,14 @@ const ProviderLayerLive = Layer.unwrap( }), ); +const SelectedProviderLayerLive = isPerfProviderEnabled() + ? PerfProviderLayerLive + : DefaultProviderLayerLive; + +const SelectedProviderRegistryLayerLive = isPerfProviderEnabled() + ? PerfProviderRegistryLive + : ProviderRegistryLive; + const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive)); const GitManagerLayerLive = GitManagerLive.pipe( @@ -199,11 +210,11 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe( Layer.provideMerge(CheckpointingLayerLive), Layer.provideMerge(GitLayerLive), Layer.provideMerge(OrchestrationLayerLive), - Layer.provideMerge(ProviderLayerLive), + Layer.provideMerge(SelectedProviderLayerLive), Layer.provideMerge(TerminalLayerLive), Layer.provideMerge(PersistenceLayerLive), Layer.provideMerge(KeybindingsLive), - Layer.provideMerge(ProviderRegistryLive), + Layer.provideMerge(SelectedProviderRegistryLayerLive), Layer.provideMerge(ServerSettingsLive), Layer.provideMerge(WorkspaceLayerLive), Layer.provideMerge(ProjectFaviconResolverLive), diff --git a/apps/web/package.json b/apps/web/package.json index 362eeecc02..445b8929ac 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -11,7 +11,9 @@ "typecheck": "tsc --noEmit", "test": "vitest run --passWithNoTests", "test:browser": "vitest run --config vitest.browser.config.ts", - "test:browser:install": "playwright install --with-deps chromium" + "test:browser:install": "playwright install --with-deps chromium", + "test:perf": "vitest run --config vitest.perf.config.ts", + "test:perf:install": "playwright install --with-deps chromium" }, "dependencies": { "@base-ui/react": "^1.2.0", diff --git a/apps/web/test/perf/appHarness.ts b/apps/web/test/perf/appHarness.ts new file mode 100644 index 0000000000..aa1660192f --- /dev/null +++ b/apps/web/test/perf/appHarness.ts @@ -0,0 +1,445 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { access, mkdir, writeFile } from "node:fs/promises"; +import { createServer } from "node:net"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { once } from "node:events"; + +import { chromium, type Page } from "playwright"; + +import { + type BrowserPerfMetrics, + summarizeBrowserPerfMetrics, + type PerfRunArtifact, + type PerfServerMetricSample, + writePerfArtifact, +} from "../../../../test/perf/support/artifact"; +import { + installBrowserPerfCollector, + PERF_BROWSER_GLOBAL, +} from "../../../../test/perf/support/browserMetrics"; +import type { PerfThresholdProfile } from "../../../../test/perf/support/thresholds"; +import type { + PerfProviderScenarioId, + PerfSeedScenarioId, +} from "@t3tools/shared/perf/scenarioCatalog"; +import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog"; +import { + NoopServerSampler, + type PerfServerSampler, +} from "../../../../test/perf/support/serverSampler"; + +const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url)); +const serverBinPath = resolve(repoRoot, "apps/server/dist/bin.mjs"); +const serverClientIndexPath = resolve(repoRoot, "apps/server/dist/client/index.html"); +const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR"; +const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL"; +const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER"; +const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO"; +const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__"; +const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__"; + +interface PerfSeedThreadSummary { + readonly id: string; + readonly title: string; + readonly messageCount: number; + readonly activityCount: number; + readonly proposedPlanCount: number; + readonly checkpointCount: number; +} + +export interface PerfSeededState { + readonly scenarioId: PerfSeedScenarioId; + readonly baseDir: string; + readonly workspaceRoot: string; + readonly projectTitle: string | null; + readonly threadSummaries: ReadonlyArray; +} + +interface StartPerfAppHarnessOptions { + readonly suite: string; + readonly seedScenarioId: PerfSeedScenarioId; + readonly providerScenarioId?: PerfProviderScenarioId; + readonly serverSampler?: PerfServerSampler; +} + +interface FinishPerfRunOptions { + readonly suite: string; + readonly scenarioId: string; + readonly thresholds: PerfThresholdProfile; + readonly metadata?: Record; + readonly actionSummary?: { + readonly threadSwitchActionPrefix?: string; + readonly burstActionName?: string; + }; + readonly artifactBasename?: string; +} + +export interface PerfAppHarness { + readonly seededState: PerfSeededState; + readonly page: Page; + readonly url: string; + readonly artifactDir: string; + readonly startAction: (name: string) => Promise; + readonly endAction: (name: string) => Promise; + readonly resetBrowserMetrics: () => Promise; + readonly sampleMountedRows: (label: string) => Promise; + readonly snapshotBrowserMetrics: () => Promise; + readonly finishRun: (options: FinishPerfRunOptions) => Promise<{ + readonly artifactPath: string; + readonly artifact: PerfRunArtifact; + readonly browserMetrics: BrowserPerfMetrics; + readonly serverMetrics: ReadonlyArray | null; + }>; +} + +async function pickFreePort(): Promise { + return await new Promise((resolvePort, reject) => { + const server = createServer(); + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Unable to resolve a free localhost port.")); + return; + } + const { port } = address; + server.close((closeError) => { + if (closeError) { + reject(closeError); + return; + } + resolvePort(port); + }); + }); + }); +} + +async function waitForServerReady(url: string, process: ChildProcess): Promise { + const startedAt = Date.now(); + const timeoutMs = 45_000; + const requestTimeoutMs = 1_000; + + while (Date.now() - startedAt < timeoutMs) { + if (process.exitCode !== null) { + throw new Error(`Perf server exited early with code ${process.exitCode}.`); + } + try { + const response = await fetch(url, { + redirect: "manual", + signal: AbortSignal.timeout(requestTimeoutMs), + }); + if (response.ok) { + return; + } + } catch { + // Ignore connection races while the server is still starting. + } + await new Promise((resolveDelay) => setTimeout(resolveDelay, 200)); + } + + throw new Error(`Timed out waiting for perf server readiness at ${url}.`); +} + +async function verifyBuiltArtifacts(): Promise { + await Promise.all([access(serverBinPath), access(serverClientIndexPath)]).catch(() => { + throw new Error( + `Built perf artifacts are missing. Expected ${serverBinPath} and ${serverClientIndexPath}. Run bun run test:perf:web or build the app first.`, + ); + }); +} + +async function stopChildProcess(process: ChildProcess): Promise { + if (process.exitCode !== null) { + return; + } + + process.kill("SIGTERM"); + const exited = await new Promise((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((resolveExited) => { + process.once("exit", () => resolveExited()); + }); + } +} + +async function ensureArtifactDir(suite: string, scenarioId: string): Promise { + const baseArtifactDir = resolve( + process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf"), + ); + const runId = `${suite}-${scenarioId}-${Date.now().toString()}`; + const artifactDir = join(baseArtifactDir, runId); + await mkdir(artifactDir, { recursive: true }); + return artifactDir; +} + +async function writeServerLogs( + artifactDir: string, + stdout: string, + stderr: string, + basename: string, +): Promise { + await mkdir(artifactDir, { recursive: true }); + await Promise.all([ + writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"), + writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"), + ]); +} + +async function invokeBrowserCollector( + page: Page, + fn: (collectorName: string, ...args: ReadonlyArray) => T, + ...args: ReadonlyArray +): Promise { + return await page.evaluate( + ({ collectorName, args: serializedArgs, fnSource }) => { + const runtimeFn = new Function( + "collectorName", + "args", + `return (${fnSource})(collectorName, ...args);`, + ) as (collectorName: string, args: ReadonlyArray) => T; + return runtimeFn(collectorName, serializedArgs); + }, + { + collectorName: PERF_BROWSER_GLOBAL, + args, + fnSource: fn.toString(), + }, + ); +} + +function parsePerfSeededState(stdout: string): PerfSeededState { + const startIndex = stdout.lastIndexOf(PERF_SEED_JSON_START); + const endIndex = stdout.lastIndexOf(PERF_SEED_JSON_END); + + if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) { + const payload = stdout.slice(startIndex + PERF_SEED_JSON_START.length, endIndex).trim(); + return JSON.parse(payload) as PerfSeededState; + } + + return JSON.parse(stdout) as PerfSeededState; +} + +export async function startPerfAppHarness( + options: StartPerfAppHarnessOptions, +): Promise { + await verifyBuiltArtifacts(); + + const seededState = await (async () => { + const seedProcess = spawn( + "bun", + ["run", "apps/server/scripts/seedPerfState.ts", options.seedScenarioId], + { + cwd: repoRoot, + env: process.env, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + let stdout = ""; + let stderr = ""; + seedProcess.stdout?.on("data", (chunk) => { + stdout += chunk.toString(); + }); + seedProcess.stderr?.on("data", (chunk) => { + stderr += chunk.toString(); + }); + const [exitCode] = (await once(seedProcess, "exit")) as [number | null]; + if (exitCode !== 0) { + throw new Error(`Perf seed command failed with code ${exitCode ?? "unknown"}.\n${stderr}`); + } + return parsePerfSeededState(stdout); + })(); + const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId); + const port = await pickFreePort(); + const url = `http://127.0.0.1:${port}/`; + const env = { + ...process.env, + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + [PERF_PROVIDER_ENV]: "1", + ...(options.providerScenarioId ? { [PERF_SCENARIO_ENV]: options.providerScenarioId } : {}), + }; + + let stdoutBuffer = ""; + let stderrBuffer = ""; + const serverProcess = spawn( + process.execPath, + [ + serverBinPath, + "--mode", + "web", + "--host", + "127.0.0.1", + "--port", + `${port}`, + "--base-dir", + seededState.baseDir, + "--no-browser", + ], + { + cwd: repoRoot, + env, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + serverProcess.stdout?.on("data", (chunk) => { + stdoutBuffer += chunk.toString(); + }); + serverProcess.stderr?.on("data", (chunk) => { + stderrBuffer += chunk.toString(); + }); + + await waitForServerReady(url, serverProcess); + + const browser = await chromium.launch({ + headless: process.env[PERF_HEADFUL_ENV] !== "1", + }); + const context = await browser.newContext({ + viewport: { width: 1440, height: 960 }, + }); + await context.addInitScript(installBrowserPerfCollector, "[data-timeline-row-kind]"); + const page = await context.newPage(); + await page.goto(url, { waitUntil: "domcontentloaded" }); + + const firstProjectTitle = + seededState.projectTitle ?? getPerfSeedScenario(options.seedScenarioId).project.title; + if (!firstProjectTitle) { + throw new Error(`Seed scenario '${options.seedScenarioId}' produced no projects.`); + } + await page.getByText(firstProjectTitle, { exact: true }).first().waitFor({ timeout: 45_000 }); + + const sampler = options.serverSampler ?? new NoopServerSampler(); + if (serverProcess.pid) { + await sampler.start({ pid: serverProcess.pid }); + } + const runStartedAt = new Date().toISOString(); + + let finishPromise: Promise<{ + readonly artifactPath: string; + readonly artifact: PerfRunArtifact; + readonly browserMetrics: BrowserPerfMetrics; + readonly serverMetrics: ReadonlyArray | null; + }> | null = null; + + const teardown = async () => { + await Promise.allSettled([context.close(), browser.close()]); + await stopChildProcess(serverProcess); + }; + + return { + seededState, + page, + url, + artifactDir, + startAction: (name) => + invokeBrowserCollector( + page, + (collectorName, actionName) => { + (window as Window & Record)[collectorName]?.startAction( + actionName as string, + ); + }, + name, + ), + endAction: (name) => + invokeBrowserCollector( + page, + (collectorName, actionName) => { + return ( + (window as Window & Record)[collectorName]?.endAction( + actionName as string, + ) ?? null + ); + }, + name, + ), + resetBrowserMetrics: () => + invokeBrowserCollector(page, (collectorName) => { + (window as Window & Record)[collectorName]?.reset(); + }), + sampleMountedRows: (label) => + invokeBrowserCollector( + page, + (collectorName, sampleLabel) => { + return ( + (window as Window & Record)[collectorName]?.sampleMountedRows( + sampleLabel as string, + ) ?? 0 + ); + }, + label, + ), + snapshotBrowserMetrics: () => + invokeBrowserCollector(page, (collectorName) => { + return ((window as Window & Record)[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)[collectorName]?.snapshot() ?? { + actions: [], + longTasks: [], + rafGapsMs: [], + mountedRowSamples: [], + }) as BrowserPerfMetrics; + }); + } catch { + return { + actions: [], + longTasks: [], + rafGapsMs: [], + mountedRowSamples: [], + } satisfies BrowserPerfMetrics; + } + })(); + const serverMetrics = await sampler.stop(); + await teardown(); + + const basename = + finishOptions.artifactBasename ?? `${finishOptions.suite}-${finishOptions.scenarioId}`; + await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename); + const artifact: PerfRunArtifact = { + suite: finishOptions.suite, + scenarioId: finishOptions.scenarioId, + startedAt: runStartedAt, + completedAt, + thresholds: finishOptions.thresholds, + summary: summarizeBrowserPerfMetrics(browserMetrics, finishOptions.actionSummary), + browserMetrics, + serverMetrics, + ...(finishOptions.metadata ? { metadata: finishOptions.metadata } : {}), + }; + const artifactPath = join(artifactDir, `${basename}.json`); + await writePerfArtifact(artifactPath, artifact); + + return { + artifactPath, + artifact, + browserMetrics, + serverMetrics, + }; + })(); + + return await finishPromise; + }, + }; +} diff --git a/apps/web/test/perf/pagePerfHelpers.ts b/apps/web/test/perf/pagePerfHelpers.ts new file mode 100644 index 0000000000..fcba5607cb --- /dev/null +++ b/apps/web/test/perf/pagePerfHelpers.ts @@ -0,0 +1,98 @@ +import type { Page } from "playwright"; + +import type { PerfAppHarness } from "./appHarness"; + +export async function ensureThreadRowVisible( + page: Page, + projectTitle: string, + threadId: string, +): Promise { + const threadRow = page.getByTestId(`thread-row-${threadId}`); + if (await threadRow.isVisible().catch(() => false)) { + return; + } + + const projectToggle = page.getByText(projectTitle, { exact: true }).first(); + await projectToggle.click(); + await threadRow.waitFor({ state: "visible", timeout: 20_000 }); +} + +export async function waitForThreadRoute( + page: Page, + input: { + readonly threadId: string; + readonly messageId?: string; + readonly extraSelector?: string; + }, +): Promise { + const path = `/${encodeURIComponent(input.threadId)}`; + await page.waitForFunction( + ({ expectedPath, messageSelector, extraSelector }) => { + const pathMatches = window.location.pathname === expectedPath; + if (!pathMatches) { + return false; + } + + if (messageSelector && !document.querySelector(messageSelector)) { + return false; + } + if (extraSelector && !document.querySelector(extraSelector)) { + return false; + } + return true; + }, + { + expectedPath: path, + messageSelector: input.messageId ? `[data-message-id="${input.messageId}"]` : null, + extraSelector: input.extraSelector ?? null, + }, + { timeout: 45_000 }, + ); +} + +export async function measureThreadSwitch( + harness: PerfAppHarness, + input: { + readonly actionName: string; + readonly projectTitle: string; + readonly threadId: string; + readonly messageId?: string; + readonly extraSelector?: string; + }, +): Promise { + await ensureThreadRowVisible(harness.page, input.projectTitle, input.threadId); + await harness.startAction(input.actionName); + await harness.page.getByTestId(`thread-row-${input.threadId}`).click(); + await waitForThreadRoute(harness.page, { + threadId: input.threadId, + ...(input.messageId ? { messageId: input.messageId } : {}), + ...(input.extraSelector ? { extraSelector: input.extraSelector } : {}), + }); + return await harness.endAction(input.actionName); +} + +export async function scrollTimelineTo(page: Page, position: "top" | "bottom"): Promise { + await page.evaluate(async (targetPosition) => { + const timelineRoot = document.querySelector('[data-timeline-root="true"]'); + const scrollContainer = timelineRoot?.parentElement; + if (!scrollContainer) { + throw new Error("Messages scroll container not found."); + } + + scrollContainer.scrollTo({ + top: targetPosition === "bottom" ? scrollContainer.scrollHeight : 0, + behavior: "auto", + }); + + await new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }); + }, position); +} + +export async function typeIntoComposerAndSend(page: Page, message: string): Promise { + const editor = page.getByTestId("composer-editor"); + await editor.click(); + await page.keyboard.type(message); + await page.getByRole("button", { name: "Send message" }).click(); +} diff --git a/apps/web/test/perf/virtualization.perf.test.ts b/apps/web/test/perf/virtualization.perf.test.ts new file mode 100644 index 0000000000..10567ec8d9 --- /dev/null +++ b/apps/web/test/perf/virtualization.perf.test.ts @@ -0,0 +1,168 @@ +import { expect, test } from "vitest"; + +import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact"; +import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog"; +import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds"; +import { startPerfAppHarness, type PerfAppHarness } from "./appHarness"; +import { + ensureThreadRowVisible, + measureThreadSwitch, + scrollTimelineTo, + waitForThreadRoute, +} from "./pagePerfHelpers"; + +test("virtualization stays bounded and heavy thread switches remain snappy", async () => { + const thresholds = PERF_THRESHOLDS.local; + let harness: PerfAppHarness | null = null; + let finished = false; + + try { + harness = await startPerfAppHarness({ + suite: "virtualization", + seedScenarioId: "large_threads", + }); + + const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace"; + const heavyThreadMessageCount = + harness.seededState.threadSummaries.find( + (thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + )?.messageCount ?? 0; + expect(heavyThreadMessageCount).toBeGreaterThanOrEqual(2_000); + + await ensureThreadRowVisible( + harness.page, + projectTitle, + PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + ); + await harness.page + .getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyAThreadId}`) + .click(); + await waitForThreadRoute(harness.page, { + threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId, + }); + await scrollTimelineTo(harness.page, "bottom"); + + await ensureThreadRowVisible( + harness.page, + projectTitle, + PERF_CATALOG_IDS.largeThreads.heavyBThreadId, + ); + await harness.page + .getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyBThreadId}`) + .click(); + await waitForThreadRoute(harness.page, { + threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId, + }); + await scrollTimelineTo(harness.page, "bottom"); + + await harness.resetBrowserMetrics(); + + await measureThreadSwitch(harness, { + actionName: "thread-switch-warmup-a", + projectTitle, + threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId, + }); + + const mountedRows = await harness.sampleMountedRows("heavy-a-open"); + expect(mountedRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows); + + const measuredTargets = [ + { + actionName: "thread-switch-1", + threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId, + }, + { + actionName: "thread-switch-2", + threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId, + }, + { + actionName: "thread-switch-3", + threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId, + }, + { + actionName: "thread-switch-4", + threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId, + }, + { + actionName: "thread-switch-5", + threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId, + }, + { + actionName: "thread-switch-6", + threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId, + }, + ] as const; + + for (const target of measuredTargets) { + await measureThreadSwitch(harness, { + actionName: target.actionName, + projectTitle, + threadId: target.threadId, + messageId: target.messageId, + }); + await harness.sampleMountedRows(`${target.actionName}-rows`); + } + + await scrollTimelineTo(harness.page, "bottom"); + await harness.sampleMountedRows("scroll-start"); + await scrollTimelineTo(harness.page, "top"); + await harness.sampleMountedRows("scroll-top"); + await scrollTimelineTo(harness.page, "bottom"); + await harness.sampleMountedRows("scroll-bottom"); + + const browserMetrics = await harness.snapshotBrowserMetrics(); + const summary = summarizeBrowserPerfMetrics(browserMetrics, { + threadSwitchActionPrefix: "thread-switch", + }); + + expect(summary.threadSwitchP50Ms).not.toBeNull(); + expect(summary.threadSwitchP95Ms).not.toBeNull(); + expect(summary.threadSwitchP50Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual( + thresholds.threadSwitchP50Ms, + ); + expect(summary.threadSwitchP95Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual( + thresholds.threadSwitchP95Ms, + ); + expect(summary.maxMountedTimelineRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows); + expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs); + expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs); + + await harness.finishRun({ + suite: "virtualization", + scenarioId: "large_threads", + thresholds, + metadata: { + heavyThreadMessageCount, + }, + actionSummary: { + threadSwitchActionPrefix: "thread-switch", + }, + }); + finished = true; + } finally { + if (harness && !finished) { + await harness.finishRun({ + suite: "virtualization", + scenarioId: "large_threads", + thresholds, + metadata: { + heavyThreadMessageCount: harness.seededState.threadSummaries.find( + (thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId, + )?.messageCount, + }, + actionSummary: { + threadSwitchActionPrefix: "thread-switch", + }, + }); + } + } +}); diff --git a/apps/web/test/perf/websocket-application.perf.test.ts b/apps/web/test/perf/websocket-application.perf.test.ts new file mode 100644 index 0000000000..627416df06 --- /dev/null +++ b/apps/web/test/perf/websocket-application.perf.test.ts @@ -0,0 +1,125 @@ +import { expect, test } from "vitest"; + +import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact"; +import { PERF_CATALOG_IDS, PERF_PROVIDER_SCENARIOS } from "@t3tools/shared/perf/scenarioCatalog"; +import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds"; +import { startPerfAppHarness, type PerfAppHarness } from "./appHarness"; +import { + ensureThreadRowVisible, + measureThreadSwitch, + typeIntoComposerAndSend, + waitForThreadRoute, +} from "./pagePerfHelpers"; + +test("high-frequency websocket events stay responsive under real built-app flow", async () => { + const thresholds = PERF_THRESHOLDS.local; + let harness: PerfAppHarness | null = null; + let finished = false; + + try { + harness = await startPerfAppHarness({ + suite: "websocket-application", + seedScenarioId: "burst_base", + providerScenarioId: "dense_assistant_stream", + }); + + const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace"; + const streamScenario = PERF_PROVIDER_SCENARIOS.dense_assistant_stream; + + await ensureThreadRowVisible( + harness.page, + projectTitle, + PERF_CATALOG_IDS.burstBase.burstThreadId, + ); + await harness.page + .getByTestId(`thread-row-${PERF_CATALOG_IDS.burstBase.burstThreadId}`) + .click(); + await waitForThreadRoute(harness.page, { + threadId: PERF_CATALOG_IDS.burstBase.burstThreadId, + messageId: PERF_CATALOG_IDS.burstBase.burstTerminalMessageId, + }); + + await harness.resetBrowserMetrics(); + await harness.startAction("burst-completion"); + await typeIntoComposerAndSend(harness.page, "Run the dense websocket perf burst."); + + await harness.page.waitForTimeout(900); + + await measureThreadSwitch(harness, { + actionName: "thread-switch-burst-nav", + projectTitle, + threadId: PERF_CATALOG_IDS.burstBase.navigationThreadId, + messageId: PERF_CATALOG_IDS.burstBase.navigationTerminalMessageId, + }); + + await measureThreadSwitch(harness, { + actionName: "thread-switch-burst-return", + projectTitle, + threadId: PERF_CATALOG_IDS.burstBase.burstThreadId, + messageId: PERF_CATALOG_IDS.burstBase.burstTerminalMessageId, + extraSelector: '[data-testid="composer-editor"]', + }); + + await harness.page.waitForFunction( + (sentinelText) => document.body.textContent?.includes(sentinelText as string) ?? false, + streamScenario.sentinelText, + { timeout: 15_000 }, + ); + await harness.endAction("burst-completion"); + + const browserMetrics = await harness.snapshotBrowserMetrics(); + const summary = summarizeBrowserPerfMetrics(browserMetrics, { + threadSwitchActionPrefix: "thread-switch", + burstActionName: "burst-completion", + }); + + expect(summary.burstCompletionMs).not.toBeNull(); + expect(summary.burstCompletionMs ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual( + thresholds.burstCompletionMs, + ); + expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs); + expect(summary.longTasksOver50Ms).toBeLessThanOrEqual(thresholds.longTasksOver50MsMax); + expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs); + + const burstNavActions = browserMetrics.actions.filter((action) => + action.name.startsWith("thread-switch-burst"), + ); + expect(burstNavActions).toHaveLength(2); + for (const action of burstNavActions) { + expect(action.durationMs).toBeLessThanOrEqual(thresholds.threadSwitchP95Ms); + } + + await harness.finishRun({ + suite: "websocket-application", + scenarioId: "dense_assistant_stream", + thresholds, + metadata: { + burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId, + navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId, + sentinelText: streamScenario.sentinelText, + }, + actionSummary: { + threadSwitchActionPrefix: "thread-switch", + burstActionName: "burst-completion", + }, + }); + finished = true; + } finally { + if (harness && !finished) { + await harness.finishRun({ + suite: "websocket-application", + scenarioId: "dense_assistant_stream", + thresholds, + metadata: { + burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId, + navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId, + sentinelText: PERF_PROVIDER_SCENARIOS.dense_assistant_stream.sentinelText, + }, + actionSummary: { + threadSwitchActionPrefix: "thread-switch", + burstActionName: "burst-completion", + }, + }); + } + } +}); diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 178f4bcbab..781e6f469a 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -21,5 +21,13 @@ } ] }, - "include": ["src", "vite.config.ts", "test"] + "include": [ + "src", + "vite.config.ts", + "test", + "../../test/perf/support/artifact.ts", + "../../test/perf/support/browserMetrics.ts", + "../../test/perf/support/serverSampler.ts", + "../../test/perf/support/thresholds.ts" + ] } diff --git a/apps/web/vitest.perf.config.ts b/apps/web/vitest.perf.config.ts new file mode 100644 index 0000000000..79230041a9 --- /dev/null +++ b/apps/web/vitest.perf.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["test/perf/**/*.perf.test.ts"], + environment: "node", + fileParallelism: false, + maxConcurrency: 1, + testTimeout: 180_000, + hookTimeout: 180_000, + }, +}); diff --git a/artifacts/perf/virtualization-large_threads-1775077017735/virtualization-large_threads.json b/artifacts/perf/virtualization-large_threads-1775077017735/virtualization-large_threads.json new file mode 100644 index 0000000000..cf3ca8e869 --- /dev/null +++ b/artifacts/perf/virtualization-large_threads-1775077017735/virtualization-large_threads.json @@ -0,0 +1,238 @@ +{ + "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 + } +} diff --git a/artifacts/perf/websocket-application-burst_base-1775077022750/websocket-application-dense_assistant_stream.json b/artifacts/perf/websocket-application-burst_base-1775077022750/websocket-application-dense_assistant_stream.json new file mode 100644 index 0000000000..ca56de5883 --- /dev/null +++ b/artifacts/perf/websocket-application-burst_base-1775077022750/websocket-application-dense_assistant_stream.json @@ -0,0 +1,807 @@ +{ + "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" + } +} diff --git a/package.json b/package.json index 97b30e6d4d..0ac88fd8b3 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "typecheck": "turbo run typecheck", "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", "test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop", "fmt": "oxfmt", "fmt:check": "oxfmt --check", diff --git a/packages/shared/package.json b/packages/shared/package.json index ed65cbeaf3..8e3b87e6a3 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -59,6 +59,10 @@ "./qrCode": { "types": "./src/qrCode.ts", "import": "./src/qrCode.ts" + }, + "./perf/scenarioCatalog": { + "types": "./src/perf/scenarioCatalog.ts", + "import": "./src/perf/scenarioCatalog.ts" } }, "scripts": { diff --git a/packages/shared/src/perf/scenarioCatalog.ts b/packages/shared/src/perf/scenarioCatalog.ts new file mode 100644 index 0000000000..c32b7d3a29 --- /dev/null +++ b/packages/shared/src/perf/scenarioCatalog.ts @@ -0,0 +1,294 @@ +import { + DEFAULT_MODEL_BY_PROVIDER, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, + type ModelSelection, + type ProviderKind, + type ProviderRuntimeEvent, +} from "@t3tools/contracts"; + +export type PerfSeedScenarioId = "large_threads" | "burst_base"; +export type PerfProviderScenarioId = "dense_assistant_stream"; +export type PerfScenarioId = PerfSeedScenarioId | PerfProviderScenarioId; + +export interface PerfProjectScenario { + readonly id: ProjectId; + readonly title: string; + readonly workspaceDirectoryName: string; + readonly defaultModelSelection: ModelSelection; +} + +export interface PerfSeedThreadScenario { + readonly id: ThreadId; + readonly title: string; + readonly category: "heavy" | "burst" | "light"; + readonly turnCount: number; + readonly messageCount: number; + readonly anchorMessageId: MessageId; + readonly terminalMessageId: MessageId; + readonly planStride: number | null; + readonly activityStride: number | null; + readonly diffStride: number | null; +} + +export interface PerfSeedScenario { + readonly id: PerfSeedScenarioId; + readonly project: PerfProjectScenario; + readonly threads: ReadonlyArray; +} + +export interface TimedFixtureProviderRuntimeEvent { + readonly delayMs?: number; + readonly type: ProviderRuntimeEvent["type"]; + readonly itemId?: string; + readonly requestId?: string; + readonly payload: unknown; +} + +export interface PerfProviderScenario { + readonly id: PerfProviderScenarioId; + readonly provider: ProviderKind; + readonly sentinelText: string; + readonly totalDurationMs: number; + readonly events: ReadonlyArray; +} + +const PERF_MODEL_SELECTION: ModelSelection = { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, +}; + +const PERF_PROJECT: PerfProjectScenario = { + id: ProjectId.makeUnsafe("perf-project-primary"), + title: "Performance Workspace", + workspaceDirectoryName: "perf-workspace", + defaultModelSelection: PERF_MODEL_SELECTION, +}; + +const makeThreadId = (slug: string) => ThreadId.makeUnsafe(`perf-thread-${slug}`); +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 LARGE_THREAD_DEFINITIONS = { + heavyA: { + id: makeThreadId("heavy-a"), + title: "Large Thread A", + category: "heavy", + turnCount: 1_000, + messageCount: 2_000, + anchorMessageId: makeMessageId("heavy-a", "user", 1), + terminalMessageId: makeMessageId("heavy-a", "assistant", 1_000), + planStride: 120, + activityStride: 32, + diffStride: 48, + }, + heavyB: { + id: makeThreadId("heavy-b"), + title: "Large Thread B", + category: "heavy", + turnCount: 1_000, + messageCount: 2_000, + anchorMessageId: makeMessageId("heavy-b", "user", 1), + terminalMessageId: makeMessageId("heavy-b", "assistant", 1_000), + planStride: 125, + activityStride: 36, + diffStride: 54, + }, + burst: { + id: makeThreadId("burst"), + title: "Burst Target Thread", + category: "burst", + turnCount: 120, + messageCount: 240, + anchorMessageId: makeMessageId("burst", "user", 1), + terminalMessageId: makeMessageId("burst", "assistant", 120), + planStride: 30, + activityStride: 10, + diffStride: 12, + }, +} as const satisfies Record; + +const LIGHT_THREADS: ReadonlyArray = Array.from( + { length: 9 }, + (_, index) => { + const threadNumber = index + 1; + const slug = `light-${threadNumber.toString().padStart(2, "0")}`; + return { + id: makeThreadId(slug), + title: `Light Thread ${threadNumber}`, + category: "light", + turnCount: 12, + messageCount: 24, + anchorMessageId: makeMessageId(slug, "user", 1), + terminalMessageId: makeMessageId(slug, "assistant", 12), + planStride: null, + activityStride: 6, + diffStride: null, + } satisfies PerfSeedThreadScenario; + }, +); + +const BURST_NAVIGATION_THREAD: PerfSeedThreadScenario = { + ...LIGHT_THREADS[0]!, + title: "Burst Navigation Thread", +}; + +const BURST_FILLER_THREAD: PerfSeedThreadScenario = { + ...LIGHT_THREADS[1]!, + title: "Burst Filler Thread", +}; + +export const PERF_SEED_SCENARIOS = { + large_threads: { + id: "large_threads", + project: PERF_PROJECT, + threads: [ + LARGE_THREAD_DEFINITIONS.heavyA, + LARGE_THREAD_DEFINITIONS.heavyB, + LARGE_THREAD_DEFINITIONS.burst, + ...LIGHT_THREADS, + ], + }, + burst_base: { + id: "burst_base", + project: PERF_PROJECT, + threads: [LARGE_THREAD_DEFINITIONS.burst, BURST_NAVIGATION_THREAD, BURST_FILLER_THREAD], + }, +} as const satisfies Record; + +const DENSE_ASSISTANT_STREAM_SENTINEL = "PERF_STREAM_SENTINEL:dense_assistant_stream:completed"; + +function buildAssistantChunk(index: number, totalSteps: number): string { + if (index === totalSteps - 1) { + return `Completed render pass. ${DENSE_ASSISTANT_STREAM_SENTINEL}`; + } + if (index % 11 === 0) { + return `Scanning synthetic shard ${index}. `; + } + if (index % 7 === 0) { + return `Applying websocket delta batch ${index}. `; + } + if (index % 5 === 0) { + return `Recomputing viewport summary ${index}. `; + } + return `chunk-${index.toString().padStart(3, "0")} `; +} + +function buildDenseAssistantStreamScenario(): PerfProviderScenario { + const events: TimedFixtureProviderRuntimeEvent[] = [ + { + delayMs: 0, + 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}`, + }, + }); + } + events.push({ + delayMs: 3_060, + type: "turn.completed", + payload: { + state: "completed", + }, + }); + + return { + id: "dense_assistant_stream", + provider: "codex", + sentinelText: DENSE_ASSISTANT_STREAM_SENTINEL, + totalDurationMs: 3_060, + events, + }; +} + +export const PERF_PROVIDER_SCENARIOS = { + dense_assistant_stream: buildDenseAssistantStreamScenario(), +} as const satisfies Record; + +export const PERF_CATALOG_IDS = { + projectId: PERF_PROJECT.id, + largeThreads: { + heavyAThreadId: LARGE_THREAD_DEFINITIONS.heavyA.id, + heavyBThreadId: LARGE_THREAD_DEFINITIONS.heavyB.id, + heavyAAnchorMessageId: LARGE_THREAD_DEFINITIONS.heavyA.anchorMessageId, + heavyBAnchorMessageId: LARGE_THREAD_DEFINITIONS.heavyB.anchorMessageId, + heavyATerminalMessageId: LARGE_THREAD_DEFINITIONS.heavyA.terminalMessageId, + heavyBTerminalMessageId: LARGE_THREAD_DEFINITIONS.heavyB.terminalMessageId, + }, + burstBase: { + burstThreadId: LARGE_THREAD_DEFINITIONS.burst.id, + burstAnchorMessageId: LARGE_THREAD_DEFINITIONS.burst.anchorMessageId, + burstTerminalMessageId: LARGE_THREAD_DEFINITIONS.burst.terminalMessageId, + navigationThreadId: BURST_NAVIGATION_THREAD.id, + navigationAnchorMessageId: BURST_NAVIGATION_THREAD.anchorMessageId, + navigationTerminalMessageId: BURST_NAVIGATION_THREAD.terminalMessageId, + }, + provider: { + denseAssistantStreamSentinel: DENSE_ASSISTANT_STREAM_SENTINEL, + }, +} as const; + +export function getPerfSeedScenario(scenarioId: PerfSeedScenarioId): PerfSeedScenario { + return PERF_SEED_SCENARIOS[scenarioId]; +} + +export function getPerfProviderScenario(scenarioId: PerfProviderScenarioId): PerfProviderScenario { + return PERF_PROVIDER_SCENARIOS[scenarioId]; +} + +export function perfTurnIdForThread(thread: PerfSeedThreadScenario, turnIndex: number): TurnId { + const threadSlug = thread.id.replace("perf-thread-", ""); + return makeTurnId(threadSlug, turnIndex); +} + +export function perfMessageIdForThread( + thread: PerfSeedThreadScenario, + role: "user" | "assistant", + turnIndex: number, +): MessageId { + const threadSlug = thread.id.replace("perf-thread-", ""); + return makeMessageId(threadSlug, role, turnIndex); +} + +export function perfEventId(prefix: string, threadId: ThreadId, index: number) { + return EventId.makeUnsafe(`${prefix}:${threadId}:${index.toString().padStart(4, "0")}`); +} diff --git a/test/perf/support/artifact.ts b/test/perf/support/artifact.ts new file mode 100644 index 0000000000..c4f6dbef2b --- /dev/null +++ b/test/perf/support/artifact.ts @@ -0,0 +1,123 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; + +import type { PerfThresholdProfile } from "./thresholds.ts"; + +export interface PerfActionDuration { + readonly name: string; + readonly durationMs: number; + readonly startedAtMs: number; + readonly endedAtMs: number; +} + +export interface PerfLongTaskSample { + readonly startTimeMs: number; + readonly durationMs: number; + readonly name: string; +} + +export interface PerfMountedRowSample { + readonly label: string; + readonly count: number; + readonly capturedAtMs: number; +} + +export interface BrowserPerfMetrics { + readonly actions: ReadonlyArray; + readonly longTasks: ReadonlyArray; + readonly rafGapsMs: ReadonlyArray; + readonly mountedRowSamples: ReadonlyArray; +} + +export interface PerfServerMetricSample { + readonly capturedAt: string; + readonly cpuUserMicros?: number; + readonly cpuSystemMicros?: number; + readonly rssBytes?: number; + readonly heapTotalBytes?: number; + readonly heapUsedBytes?: number; + readonly externalBytes?: number; + readonly arrayBuffersBytes?: number; +} + +export interface PerfArtifactSummary { + readonly maxMountedTimelineRows: number; + readonly threadSwitchP50Ms: number | null; + readonly threadSwitchP95Ms: number | null; + readonly maxLongTaskMs: number; + readonly longTasksOver50Ms: number; + readonly maxRafGapMs: number; + readonly burstCompletionMs: number | null; +} + +export interface PerfRunArtifact { + readonly suite: string; + readonly scenarioId: string; + readonly startedAt: string; + readonly completedAt: string; + readonly thresholds: PerfThresholdProfile; + readonly summary: PerfArtifactSummary; + readonly browserMetrics: BrowserPerfMetrics; + readonly serverMetrics: ReadonlyArray | null; + readonly metadata?: Record; +} + +export function percentile(values: ReadonlyArray, target: number): number | null { + if (values.length === 0) { + return null; + } + 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); + return sorted[index] ?? null; +} + +export function summarizeBrowserPerfMetrics( + browserMetrics: BrowserPerfMetrics, + options?: { + readonly threadSwitchActionPrefix?: string; + readonly burstActionName?: string; + }, +): PerfArtifactSummary { + const threadSwitchActions = browserMetrics.actions + .filter((action) => + options?.threadSwitchActionPrefix + ? action.name.startsWith(options.threadSwitchActionPrefix) + : action.name.startsWith("thread-switch"), + ) + .map((action) => action.durationMs); + const burstCompletionAction = browserMetrics.actions.find( + (action) => action.name === (options?.burstActionName ?? "burst-completion"), + ); + const maxMountedTimelineRows = browserMetrics.mountedRowSamples.reduce( + (maxCount, sample) => Math.max(maxCount, sample.count), + 0, + ); + const maxLongTaskMs = browserMetrics.longTasks.reduce( + (maxDuration, sample) => Math.max(maxDuration, sample.durationMs), + 0, + ); + const longTasksOver50Ms = browserMetrics.longTasks.filter( + (sample) => sample.durationMs > 50, + ).length; + const maxRafGapMs = browserMetrics.rafGapsMs.reduce((maxGap, gap) => Math.max(maxGap, gap), 0); + + return { + maxMountedTimelineRows, + threadSwitchP50Ms: percentile(threadSwitchActions, 0.5), + threadSwitchP95Ms: percentile(threadSwitchActions, 0.95), + maxLongTaskMs, + longTasksOver50Ms, + maxRafGapMs, + burstCompletionMs: burstCompletionAction?.durationMs ?? null, + }; +} + +export async function writePerfArtifact( + outputPath: string, + artifact: PerfRunArtifact, +): Promise { + const resolvedOutputPath = resolve(outputPath); + await mkdir(dirname(resolvedOutputPath), { recursive: true }); + await writeFile(`${resolvedOutputPath}`, `${JSON.stringify(artifact, null, 2)}\n`, "utf8"); +} diff --git a/test/perf/support/browserMetrics.ts b/test/perf/support/browserMetrics.ts new file mode 100644 index 0000000000..dc9719e32e --- /dev/null +++ b/test/perf/support/browserMetrics.ts @@ -0,0 +1,109 @@ +import type { BrowserPerfMetrics } from "./artifact.ts"; + +export const PERF_BROWSER_GLOBAL = "__t3PerfCollector"; +const DEFAULT_TIMELINE_ROW_SELECTOR = "[data-timeline-row-kind]"; + +export interface BrowserPerfCollector { + readonly startAction: (name: string) => void; + readonly endAction: (name: string) => number | null; + readonly sampleMountedRows: (label: string) => number; + readonly snapshot: () => BrowserPerfMetrics; + readonly reset: () => void; +} + +declare global { + interface Window { + __t3PerfCollector?: BrowserPerfCollector; + } +} + +export function installBrowserPerfCollector( + timelineRowSelector = DEFAULT_TIMELINE_ROW_SELECTOR, +): void { + if (typeof window === "undefined" || window.__t3PerfCollector) { + return; + } + + const actionStarts = new Map(); + const actions: Array = []; + const longTasks: Array = []; + const rafGapsMs: number[] = []; + const mountedRowSamples: Array = []; + let previousAnimationFrameTs = 0; + + const animationFrameLoop = (timestampMs: number) => { + if (previousAnimationFrameTs > 0) { + rafGapsMs.push(timestampMs - previousAnimationFrameTs); + } + previousAnimationFrameTs = timestampMs; + window.requestAnimationFrame(animationFrameLoop); + }; + window.requestAnimationFrame(animationFrameLoop); + + if (typeof PerformanceObserver !== "undefined") { + try { + const longTaskObserver = new PerformanceObserver((list: PerformanceObserverEntryList) => { + for (const entry of list.getEntries()) { + longTasks.push({ + name: entry.name, + startTimeMs: entry.startTime, + durationMs: entry.duration, + }); + } + }); + longTaskObserver.observe({ entryTypes: ["longtask"] } as PerformanceObserverInit); + } catch { + // Ignore browsers or runtimes that do not expose long-task observation. + } + } + + const readMountedRows = () => document.querySelectorAll(timelineRowSelector).length; + + window.__t3PerfCollector = { + startAction(name: string) { + actionStarts.set(name, performance.now()); + }, + endAction(name: string) { + const startedAtMs = actionStarts.get(name); + if (startedAtMs === undefined) { + return null; + } + const endedAtMs = performance.now(); + const durationMs = endedAtMs - startedAtMs; + actions.push({ + name, + durationMs, + startedAtMs, + endedAtMs, + }); + actionStarts.delete(name); + return durationMs; + }, + sampleMountedRows(label: string) { + const count = readMountedRows(); + mountedRowSamples.push({ + label, + count, + capturedAtMs: performance.now(), + }); + return count; + }, + snapshot() { + return { + actions: [...actions], + longTasks: [...longTasks], + rafGapsMs: [...rafGapsMs], + mountedRowSamples: [...mountedRowSamples], + }; + }, + reset() { + actionStarts.clear(); + actions.length = 0; + longTasks.length = 0; + rafGapsMs.length = 0; + mountedRowSamples.length = 0; + previousAnimationFrameTs = 0; + window.requestAnimationFrame(animationFrameLoop); + }, + }; +} diff --git a/test/perf/support/scenarioCatalog.ts b/test/perf/support/scenarioCatalog.ts new file mode 100644 index 0000000000..8e237e92e2 --- /dev/null +++ b/test/perf/support/scenarioCatalog.ts @@ -0,0 +1 @@ +export * from "../../../packages/shared/src/perf/scenarioCatalog"; diff --git a/test/perf/support/serverSampler.ts b/test/perf/support/serverSampler.ts new file mode 100644 index 0000000000..265b10061e --- /dev/null +++ b/test/perf/support/serverSampler.ts @@ -0,0 +1,14 @@ +import type { PerfServerMetricSample } from "./artifact.ts"; + +export interface PerfServerSampler { + readonly start: (input: { readonly pid: number }) => Promise; + readonly stop: () => Promise | null>; +} + +export class NoopServerSampler implements PerfServerSampler { + async start(_input: { readonly pid: number }): Promise {} + + async stop(): Promise { + return null; + } +} diff --git a/test/perf/support/thresholds.ts b/test/perf/support/thresholds.ts new file mode 100644 index 0000000000..0eb049cb6e --- /dev/null +++ b/test/perf/support/thresholds.ts @@ -0,0 +1,23 @@ +export interface PerfThresholdProfile { + readonly maxMountedTimelineRows: number; + readonly threadSwitchP50Ms: number; + readonly threadSwitchP95Ms: number; + readonly maxLongTaskMs: number; + readonly maxRafGapMs: number; + readonly burstCompletionMs: number; + readonly longTasksOver50MsMax: number; +} + +export const PERF_THRESHOLDS = { + local: { + maxMountedTimelineRows: 140, + threadSwitchP50Ms: 250, + threadSwitchP95Ms: 500, + maxLongTaskMs: 120, + maxRafGapMs: 120, + burstCompletionMs: 5_000, + longTasksOver50MsMax: 2, + }, +} as const satisfies Record; + +export type PerfThresholdProfileName = keyof typeof PERF_THRESHOLDS;