From e9fa2b75dc030f9c4fb35b61b9cae4903c1ffce4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 2 Apr 2026 02:21:06 -0700 Subject: [PATCH] Add server perf latency baselines Co-authored-by: codex --- .../perf/serverLatency.perf.test.ts | 920 ++++++++++++++++++ .../integration/perf/serverPerfHarness.ts | 393 ++++++++ apps/server/package.json | 3 +- apps/server/src/perf/config.ts | 2 +- apps/web/tsconfig.json | 1 + package.json | 1 + packages/shared/package.json | 4 + packages/shared/src/perf/artifact.ts | 73 ++ packages/shared/src/perf/scenarioCatalog.ts | 61 +- test/perf/support/artifact.ts | 31 +- 10 files changed, 1467 insertions(+), 22 deletions(-) create mode 100644 apps/server/integration/perf/serverLatency.perf.test.ts create mode 100644 apps/server/integration/perf/serverPerfHarness.ts create mode 100644 packages/shared/src/perf/artifact.ts diff --git a/apps/server/integration/perf/serverLatency.perf.test.ts b/apps/server/integration/perf/serverLatency.perf.test.ts new file mode 100644 index 0000000000..1842dee813 --- /dev/null +++ b/apps/server/integration/perf/serverLatency.perf.test.ts @@ -0,0 +1,920 @@ +import { execFileSync } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { performance } from "node:perf_hooks"; + +import { + type ClientOrchestrationCommand, + CommandId, + MessageId, + type ModelSelection, + ORCHESTRATION_WS_METHODS, + type OrchestrationEvent, + type ProjectId, + type TerminalEvent, + ThreadId, + type ThreadId as ThreadIdType, + WS_METHODS, +} from "@t3tools/contracts"; +import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog"; +import { afterEach, describe, expect, it } from "vitest"; + +import { + type ServerCommandLatencyMeasurement, + startServerPerfHarness, + summarizeCommandLatencyMeasurements, + summarizeRpcLatencySeries, + type ServerPerfHarness, + type ServerRpcLatencySeries, +} from "./serverPerfHarness.ts"; +import type { PerfLatencySample } from "@t3tools/shared/perf/artifact"; + +const CONTROL_PLANE_SAMPLE_COUNT = 4; +const GIT_RPC_SAMPLE_COUNT = 6; +const STREAM_THREAD_COUNT = 5; +const SPAM_THREAD_COUNT = 8; +const TERMINAL_SESSION_COUNT = 3; +const TERMINAL_OUTPUT_LINE_COUNT = 260; +const TERMINAL_OUTPUT_SLEEP_SECONDS = 0.04; +const GIT_BRANCH_COUNT = 240; +const GIT_UNTRACKED_FILE_COUNT = 160; +const DEFAULT_WAIT_TIMEOUT_MS = 45_000; + +interface SubscriptionCleanup { + readonly dispose: () => void; +} + +interface EventWaiter { + readonly description: string; + readonly select: (values: ReadonlyArray) => TResult | null; + readonly resolve: (value: TResult) => void; + readonly reject: (error: Error) => void; + readonly timer: ReturnType; +} + +class BufferedEventFeed implements SubscriptionCleanup { + private readonly values: TValue[] = []; + private readonly waiters = new Set>(); + + push(value: TValue) { + this.values.push(value); + for (const waiter of this.waiters) { + const match = waiter.select(this.values); + if (match === null) { + continue; + } + clearTimeout(waiter.timer); + this.waiters.delete(waiter); + waiter.resolve(match); + } + } + + waitFor( + description: string, + select: (values: ReadonlyArray) => TResult | null, + timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, + ): Promise { + const immediateMatch = select(this.values); + if (immediateMatch !== null) { + return Promise.resolve(immediateMatch); + } + + return new Promise((resolve, reject) => { + const waiter: EventWaiter = { + description, + select, + resolve, + reject, + timer: setTimeout(() => { + this.waiters.delete(waiter as EventWaiter); + reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`)); + }, timeoutMs), + }; + this.waiters.add(waiter as EventWaiter); + }); + } + + waitForEvent( + description: string, + predicate: (value: TValue) => boolean, + timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, + ): Promise { + return this.waitFor(description, (values) => values.find(predicate) ?? null, timeoutMs); + } + + waitForCount( + description: string, + predicate: (value: TValue) => boolean, + count: number, + timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, + ): Promise> { + return this.waitFor( + description, + (values) => { + const matches = values.filter(predicate); + return matches.length >= count ? matches.slice(0, count) : null; + }, + timeoutMs, + ); + } + + waitForDistinct( + description: string, + predicate: (value: TValue) => boolean, + selectKey: (value: TValue) => TKey, + count: number, + timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, + ): Promise> { + return this.waitFor( + description, + (values) => { + const distinctMatches = new Map(); + for (const value of values) { + if (!predicate(value)) { + continue; + } + const key = selectKey(value); + if (!distinctMatches.has(key)) { + distinctMatches.set(key, value); + } + } + const matches = [...distinctMatches.values()]; + return matches.length >= count ? matches : null; + }, + timeoutMs, + ); + } + + dispose() { + for (const waiter of this.waiters) { + clearTimeout(waiter.timer); + waiter.reject(new Error(`Buffered feed disposed while waiting for ${waiter.description}.`)); + } + this.waiters.clear(); + } +} + +function sleep(delayMs: number): Promise { + return new Promise((resolve) => setTimeout(resolve, delayMs)); +} + +function nowIso(): string { + return new Date().toISOString(); +} + +function runGit(cwd: string, args: ReadonlyArray) { + execFileSync("git", args, { + cwd, + stdio: ["ignore", "pipe", "pipe"], + encoding: "utf8", + }); +} + +function makeControlThreadId(label: string): ThreadIdType { + return ThreadId.makeUnsafe(`perf-control-${label}-${crypto.randomUUID()}`); +} + +function makeCommandId(label: string) { + return CommandId.makeUnsafe(`perf-command:${label}:${crypto.randomUUID()}`); +} + +function makeMessageId(label: string) { + return MessageId.makeUnsafe(`perf-message:${label}:${crypto.randomUUID()}`); +} + +async function dispatchCommand(harness: ServerPerfHarness, command: ClientOrchestrationCommand) { + return await harness.rpc.request((client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand](command), + ); +} + +async function measureCommandLatency(input: { + readonly harness: ServerPerfHarness; + readonly orchestrationEvents: BufferedEventFeed; + readonly command: ClientOrchestrationCommand; + readonly expectedEventType: OrchestrationEvent["type"]; + readonly loadProfile: string; + readonly timeoutMs?: number; + readonly metadata?: Record; +}): Promise { + const startedAt = nowIso(); + const startedAtMs = performance.now(); + const result = await dispatchCommand(input.harness, input.command); + const ackAtMs = performance.now(); + const event = await input.orchestrationEvents.waitForEvent( + `${input.expectedEventType} for ${input.command.type}`, + (candidate) => + candidate.type === input.expectedEventType && + String(candidate.commandId) === String(input.command.commandId), + input.timeoutMs, + ); + const eventAtMs = performance.now(); + + return { + commandType: input.command.type, + loadProfile: input.loadProfile, + startedAt, + dispatchToAckMs: ackAtMs - startedAtMs, + dispatchToEventMs: eventAtMs - startedAtMs, + ackToEventMs: eventAtMs - ackAtMs, + resultSequence: result.sequence, + eventSequence: event.sequence, + ...(input.metadata ? { metadata: input.metadata } : {}), + }; +} + +async function createSupportThread(input: { + readonly harness: ServerPerfHarness; + readonly orchestrationEvents: BufferedEventFeed; + readonly projectId: ProjectId; + readonly modelSelection: ModelSelection; + readonly label: string; +}): Promise { + const threadId = makeControlThreadId(`load-${input.label}`); + const command = { + type: "thread.create", + commandId: makeCommandId(`load-thread-create-${input.label}`), + threadId, + projectId: input.projectId, + title: `Perf Load ${input.label}`, + modelSelection: input.modelSelection, + interactionMode: "default", + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: nowIso(), + } as const satisfies ClientOrchestrationCommand; + + await dispatchCommand(input.harness, command); + await input.orchestrationEvents.waitForEvent( + `thread.created for load support thread ${input.label}`, + (event) => event.type === "thread.created" && event.payload.threadId === threadId, + ); + return threadId; +} + +async function captureCreateArchiveSamples(input: { + readonly harness: ServerPerfHarness; + readonly orchestrationEvents: BufferedEventFeed; + readonly loadProfile: string; + readonly sampleCount: number; + readonly projectId: ProjectId; + readonly modelSelection: ModelSelection; +}): Promise> { + const samples: ServerCommandLatencyMeasurement[] = []; + + for (let sampleIndex = 0; sampleIndex < input.sampleCount; sampleIndex += 1) { + const threadId = makeControlThreadId(`${input.loadProfile}-${sampleIndex + 1}`); + const createCommand = { + type: "thread.create", + commandId: makeCommandId(`thread-create-${input.loadProfile}-${sampleIndex + 1}`), + threadId, + projectId: input.projectId, + title: `Perf ${input.loadProfile} ${sampleIndex + 1}`, + modelSelection: input.modelSelection, + interactionMode: "default", + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: nowIso(), + } as const satisfies ClientOrchestrationCommand; + + samples.push( + await measureCommandLatency({ + harness: input.harness, + orchestrationEvents: input.orchestrationEvents, + command: createCommand, + expectedEventType: "thread.created", + loadProfile: input.loadProfile, + metadata: { + sampleIndex: sampleIndex + 1, + threadId, + }, + }), + ); + + const archiveCommand = { + type: "thread.archive", + commandId: makeCommandId(`thread-archive-${input.loadProfile}-${sampleIndex + 1}`), + threadId, + } as const satisfies ClientOrchestrationCommand; + + samples.push( + await measureCommandLatency({ + harness: input.harness, + orchestrationEvents: input.orchestrationEvents, + command: archiveCommand, + expectedEventType: "thread.archived", + loadProfile: input.loadProfile, + metadata: { + sampleIndex: sampleIndex + 1, + threadId, + }, + }), + ); + } + + return samples; +} + +async function ensureStreamingThreads(input: { + readonly harness: ServerPerfHarness; + readonly orchestrationEvents: BufferedEventFeed; + readonly projectId: ProjectId; + readonly modelSelection: ModelSelection; + readonly count: number; +}): Promise> { + const threadIds: ThreadIdType[] = [ + PERF_CATALOG_IDS.burstBase.burstThreadId, + PERF_CATALOG_IDS.burstBase.navigationThreadId, + PERF_CATALOG_IDS.burstBase.fillerThreadId, + ]; + + while (threadIds.length < input.count) { + threadIds.push( + await createSupportThread({ + harness: input.harness, + orchestrationEvents: input.orchestrationEvents, + projectId: input.projectId, + modelSelection: input.modelSelection, + label: `stream-${threadIds.length + 1}`, + }), + ); + } + + return threadIds; +} + +async function startAssistantStreamingLoad(input: { + readonly harness: ServerPerfHarness; + readonly orchestrationEvents: BufferedEventFeed; + readonly threadIds: ReadonlyArray; + readonly label: string; +}): Promise { + await Promise.all( + input.threadIds.map((threadId, index) => + dispatchCommand(input.harness, { + type: "thread.turn.start", + commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`), + threadId, + message: { + messageId: makeMessageId(`${input.label}-turn-${index + 1}`), + role: "user", + text: `Perf load ${input.label} ${index + 1}`, + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: nowIso(), + } as const satisfies ClientOrchestrationCommand), + ), + ); + + const threadIds = new Set(input.threadIds.map(String)); + await input.orchestrationEvents.waitForDistinct( + `assistant streaming output for ${input.label}`, + (event) => + event.type === "thread.message-sent" && + event.payload.role === "assistant" && + event.payload.streaming && + threadIds.has(String(event.payload.threadId)), + (event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""), + input.threadIds.length, + ); +} + +async function startCreateTurnSpamLoad(input: { + readonly harness: ServerPerfHarness; + readonly orchestrationEvents: BufferedEventFeed; + readonly projectId: ProjectId; + readonly modelSelection: ModelSelection; + readonly count: number; + readonly label: string; +}): Promise<{ + readonly threadIds: ReadonlyArray; + readonly done: Promise>; +}> { + const threadIds = Array.from({ length: input.count }, (_, index) => + makeControlThreadId(`${input.label}-${index + 1}`), + ); + const threadIdStrings = new Set(threadIds.map(String)); + + const done = Promise.all( + threadIds.map(async (threadId, index) => { + const createCommand = { + type: "thread.create", + commandId: makeCommandId(`${input.label}-create-${index + 1}`), + threadId, + projectId: input.projectId, + title: `Perf Spam ${index + 1}`, + modelSelection: input.modelSelection, + interactionMode: "default", + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: nowIso(), + } as const satisfies ClientOrchestrationCommand; + await dispatchCommand(input.harness, createCommand); + await input.orchestrationEvents.waitForEvent( + `thread.created for ${input.label}-${index + 1}`, + (event) => event.type === "thread.created" && event.payload.threadId === threadId, + ); + await dispatchCommand(input.harness, { + type: "thread.turn.start", + commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`), + threadId, + message: { + messageId: makeMessageId(`${input.label}-turn-${index + 1}`), + role: "user", + text: `Perf spam ${input.label} ${index + 1}`, + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: nowIso(), + } as const satisfies ClientOrchestrationCommand); + return threadId; + }), + ); + + await input.orchestrationEvents.waitForCount( + `thread.create spam ${input.label}`, + (event) => + event.type === "thread.created" && threadIdStrings.has(String(event.payload.threadId)), + Math.min(4, input.count), + ); + await input.orchestrationEvents.waitForDistinct( + `assistant spam output ${input.label}`, + (event) => + event.type === "thread.message-sent" && + event.payload.role === "assistant" && + event.payload.streaming && + threadIdStrings.has(String(event.payload.threadId)), + (event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""), + Math.min(4, input.count), + ); + + return { + threadIds, + done, + }; +} + +async function startTerminalLoad(input: { + readonly harness: ServerPerfHarness; + readonly terminalEvents: BufferedEventFeed; + readonly workspaceRoot: string; + readonly threadIds: ReadonlyArray; +}): Promise> { + const sessions = await Promise.all( + input.threadIds.slice(0, TERMINAL_SESSION_COUNT).map(async (threadId, index) => { + const terminalId = `perf-${index + 1}`; + await input.harness.rpc.request((client) => + client[WS_METHODS.terminalOpen]({ + threadId, + terminalId, + cwd: input.workspaceRoot, + cols: 120, + rows: 32, + }), + ); + + const command = [ + "i=1", + `while [ $i -le ${TERMINAL_OUTPUT_LINE_COUNT} ]`, + "do", + ` printf 'perf-terminal-${index + 1}-%03d\\n' "$i"`, + " i=$((i + 1))", + ` sleep ${TERMINAL_OUTPUT_SLEEP_SECONDS.toFixed(2)}`, + "done", + "", + ].join("\n"); + + await input.harness.rpc.request((client) => + client[WS_METHODS.terminalWrite]({ + threadId, + terminalId, + data: command, + }), + ); + + return { + threadId, + terminalId, + }; + }), + ); + + const terminalIds = new Set(sessions.map((session) => session.terminalId)); + await input.terminalEvents.waitForDistinct( + "terminal output load", + (event) => event.type === "output" && terminalIds.has(event.terminalId), + (event) => event.terminalId, + sessions.length, + 30_000, + ); + + return sessions; +} + +async function closeTerminalLoad( + harness: ServerPerfHarness, + sessions: ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>, +): Promise { + await Promise.all( + sessions.map((session) => + harness.rpc.request((client) => + client[WS_METHODS.terminalClose]({ + threadId: session.threadId, + terminalId: session.terminalId, + deleteHistory: true, + }), + ), + ), + ); +} + +async function seedGitPressure(workspaceRoot: string): Promise { + const untrackedDir = join(workspaceRoot, "perf-git-pressure"); + await mkdir(untrackedDir, { recursive: true }); + await Promise.all( + Array.from({ length: GIT_UNTRACKED_FILE_COUNT }, (_, index) => + writeFile( + join(untrackedDir, `untracked-${(index + 1).toString().padStart(3, "0")}.ts`), + `export const perfFile${index + 1} = ${index + 1};\n`, + "utf8", + ), + ), + ); + + for (let index = 0; index < GIT_BRANCH_COUNT; index += 1) { + runGit(workspaceRoot, ["branch", `perf/latency-${(index + 1).toString().padStart(4, "0")}`]); + } +} + +async function measureRpcLatencySeries(input: { + readonly harness: ServerPerfHarness; + readonly name: string; + readonly loadProfile: string; + readonly iterations: number; + readonly execute: () => Promise; +}): Promise { + const samples: PerfLatencySample[] = []; + + for (let iteration = 0; iteration < input.iterations; iteration += 1) { + const startedAt = nowIso(); + const startedAtMs = performance.now(); + await input.execute(); + const endedAtMs = performance.now(); + samples.push({ + name: `${input.name}-${iteration + 1}`, + durationMs: endedAtMs - startedAtMs, + startedAt, + endedAt: nowIso(), + metadata: { + iteration: iteration + 1, + loadProfile: input.loadProfile, + }, + }); + } + + return { + name: input.name, + loadProfile: input.loadProfile, + summary: summarizeRpcLatencySeries(samples), + samples, + }; +} + +function groupCommandSeries( + samples: ReadonlyArray, + loadProfile: string, +) { + const createSamples = samples.filter((sample) => sample.commandType === "thread.create"); + const archiveSamples = samples.filter((sample) => sample.commandType === "thread.archive"); + + return [ + { + name: "thread.create", + loadProfile, + summary: summarizeCommandLatencyMeasurements(createSamples), + samples: createSamples, + }, + { + name: "thread.archive", + loadProfile, + summary: summarizeCommandLatencyMeasurements(archiveSamples), + samples: archiveSamples, + }, + ] as const; +} + +describe("server perf latency", () => { + const disposables: Array = []; + + afterEach(() => { + for (const disposable of disposables.splice(0)) { + disposable.dispose(); + } + }); + + it("records idle and assistant-stream command latency at the websocket boundary", async () => { + let harness: ServerPerfHarness | null = null; + + try { + harness = await startServerPerfHarness({ + suite: "server-latency-critical-commands", + seedScenarioId: "burst_base", + providerScenarioId: "parallel_assistant_stream", + }); + const runStartedAt = nowIso(); + + const burstProject = harness.seededState.snapshot.projects.find( + (project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId, + ); + expect(burstProject).toBeTruthy(); + const modelSelection = burstProject!.defaultModelSelection; + expect(modelSelection).toBeTruthy(); + + const orchestrationEvents = new BufferedEventFeed(); + disposables.push(orchestrationEvents); + disposables.push({ + dispose: harness.rpc.subscribe( + (client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}), + (event) => orchestrationEvents.push(event), + ), + }); + + await sleep(250); + + const idleSamples = await captureCreateArchiveSamples({ + harness, + orchestrationEvents, + loadProfile: "idle", + sampleCount: CONTROL_PLANE_SAMPLE_COUNT, + projectId: burstProject!.id, + modelSelection: modelSelection!, + }); + + const streamingThreadIds = await ensureStreamingThreads({ + harness, + orchestrationEvents, + projectId: burstProject!.id, + modelSelection: modelSelection!, + count: STREAM_THREAD_COUNT, + }); + await startAssistantStreamingLoad({ + harness, + orchestrationEvents, + threadIds: streamingThreadIds, + label: "stream-control-plane", + }); + + const streamingSamples = await captureCreateArchiveSamples({ + harness, + orchestrationEvents, + loadProfile: "assistant-stream-5x", + sampleCount: CONTROL_PLANE_SAMPLE_COUNT, + projectId: burstProject!.id, + modelSelection: modelSelection!, + }); + const spamLoad = await startCreateTurnSpamLoad({ + harness, + orchestrationEvents, + projectId: burstProject!.id, + modelSelection: modelSelection!, + count: SPAM_THREAD_COUNT, + label: "create-turn-spam-8x", + }); + const spamSamples = await captureCreateArchiveSamples({ + harness, + orchestrationEvents, + loadProfile: "create-turn-spam-8x", + sampleCount: CONTROL_PLANE_SAMPLE_COUNT, + projectId: burstProject!.id, + modelSelection: modelSelection!, + }); + await spamLoad.done; + + const commandLatency = [ + ...groupCommandSeries(idleSamples, "idle"), + ...groupCommandSeries(streamingSamples, "assistant-stream-5x"), + ...groupCommandSeries(spamSamples, "create-turn-spam-8x"), + ]; + const result = await harness.finishRun({ + artifactBasename: "control-plane-stream-baseline", + artifact: { + suite: "server-latency-critical-commands", + scenarioId: "burst_base_control_plane_stream_baseline", + startedAt: runStartedAt, + completedAt: nowIso(), + commandLatency, + rpcLatency: [], + metadata: { + sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT, + streamingThreadCount: STREAM_THREAD_COUNT, + spamThreadCount: SPAM_THREAD_COUNT, + }, + }, + }); + harness = null; + + expect(result.artifact.commandLatency).toHaveLength(6); + for (const series of result.artifact.commandLatency) { + expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT); + expect(series.summary.dispatchToEventMs.p50Ms).not.toBeNull(); + expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000); + } + } finally { + await harness?.dispose(); + } + }, 180_000); + + it("records command and git rpc latency under terminal and mixed server load", async () => { + let harness: ServerPerfHarness | null = null; + let terminalSessions: ReadonlyArray<{ + readonly threadId: ThreadIdType; + readonly terminalId: string; + }> = []; + + try { + harness = await startServerPerfHarness({ + suite: "server-latency-critical-commands", + seedScenarioId: "burst_base", + providerScenarioId: "parallel_assistant_stream", + }); + const runStartedAt = nowIso(); + + const burstProject = harness.seededState.snapshot.projects.find( + (project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId, + ); + expect(burstProject).toBeTruthy(); + const modelSelection = burstProject!.defaultModelSelection; + expect(modelSelection).toBeTruthy(); + + const orchestrationEvents = new BufferedEventFeed(); + const terminalEvents = new BufferedEventFeed(); + disposables.push(orchestrationEvents, terminalEvents); + disposables.push({ + dispose: harness.rpc.subscribe( + (client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}), + (event) => orchestrationEvents.push(event), + ), + }); + disposables.push({ + dispose: harness.rpc.subscribe( + (client) => client[WS_METHODS.subscribeTerminalEvents]({}), + (event) => terminalEvents.push(event), + ), + }); + + await sleep(250); + await seedGitPressure(harness.seededState.workspaceRoot); + + const gitLatencyIdle = await Promise.all([ + measureRpcLatencySeries({ + harness, + name: "git.status", + loadProfile: "idle-repo-pressure", + iterations: GIT_RPC_SAMPLE_COUNT, + execute: () => + harness!.rpc.request((client) => + client[WS_METHODS.gitStatus]({ + cwd: harness!.seededState.workspaceRoot, + }), + ), + }), + measureRpcLatencySeries({ + harness, + name: "git.listBranches", + loadProfile: "idle-repo-pressure", + iterations: GIT_RPC_SAMPLE_COUNT, + execute: () => + harness!.rpc.request((client) => + client[WS_METHODS.gitListBranches]({ + cwd: harness!.seededState.workspaceRoot, + }), + ), + }), + ]); + + const streamingThreadIds = await ensureStreamingThreads({ + harness, + orchestrationEvents, + projectId: burstProject!.id, + modelSelection: modelSelection!, + count: STREAM_THREAD_COUNT, + }); + + terminalSessions = await startTerminalLoad({ + harness, + terminalEvents, + workspaceRoot: harness.seededState.workspaceRoot, + threadIds: streamingThreadIds, + }); + + const terminalSamples = await captureCreateArchiveSamples({ + harness, + orchestrationEvents, + loadProfile: "terminal-output-3x", + sampleCount: CONTROL_PLANE_SAMPLE_COUNT, + projectId: burstProject!.id, + modelSelection: modelSelection!, + }); + + await sleep(6_500); + await startAssistantStreamingLoad({ + harness, + orchestrationEvents, + threadIds: streamingThreadIds, + label: "mixed-load", + }); + await terminalEvents.waitForCount( + "continued terminal output during mixed load", + (event) => + event.type === "output" && + terminalSessions.some((session) => session.terminalId === event.terminalId), + TERMINAL_SESSION_COUNT, + 30_000, + ); + + const mixedSamples = await captureCreateArchiveSamples({ + harness, + orchestrationEvents, + loadProfile: "mixed-stream-terminal-git", + sampleCount: CONTROL_PLANE_SAMPLE_COUNT, + projectId: burstProject!.id, + modelSelection: modelSelection!, + }); + + const gitLatencyMixed = await Promise.all([ + measureRpcLatencySeries({ + harness, + name: "git.status", + loadProfile: "mixed-stream-terminal-git", + iterations: GIT_RPC_SAMPLE_COUNT, + execute: () => + harness!.rpc.request((client) => + client[WS_METHODS.gitStatus]({ + cwd: harness!.seededState.workspaceRoot, + }), + ), + }), + measureRpcLatencySeries({ + harness, + name: "git.listBranches", + loadProfile: "mixed-stream-terminal-git", + iterations: GIT_RPC_SAMPLE_COUNT, + execute: () => + harness!.rpc.request((client) => + client[WS_METHODS.gitListBranches]({ + cwd: harness!.seededState.workspaceRoot, + }), + ), + }), + ]); + + await closeTerminalLoad(harness, terminalSessions); + terminalSessions = []; + + const result = await harness.finishRun({ + artifactBasename: "terminal-mixed-git-baseline", + artifact: { + suite: "server-latency-critical-commands", + scenarioId: "burst_base_terminal_mixed_git_baseline", + startedAt: runStartedAt, + completedAt: nowIso(), + commandLatency: [ + ...groupCommandSeries(terminalSamples, "terminal-output-3x"), + ...groupCommandSeries(mixedSamples, "mixed-stream-terminal-git"), + ], + rpcLatency: [...gitLatencyIdle, ...gitLatencyMixed], + metadata: { + sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT, + gitRpcSampleCount: GIT_RPC_SAMPLE_COUNT, + branchCount: GIT_BRANCH_COUNT, + untrackedFileCount: GIT_UNTRACKED_FILE_COUNT, + terminalSessionCount: TERMINAL_SESSION_COUNT, + }, + }, + }); + harness = null; + + expect(result.artifact.commandLatency).toHaveLength(4); + expect(result.artifact.rpcLatency).toHaveLength(4); + for (const series of result.artifact.commandLatency) { + expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT); + expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000); + } + for (const series of result.artifact.rpcLatency) { + expect(series.samples).toHaveLength(GIT_RPC_SAMPLE_COUNT); + expect(series.summary.maxMs).toBeLessThan(30_000); + } + } finally { + if (harness && terminalSessions.length > 0) { + await closeTerminalLoad(harness, terminalSessions).catch(() => undefined); + } + await harness?.dispose(); + } + }, 180_000); +}); diff --git a/apps/server/integration/perf/serverPerfHarness.ts b/apps/server/integration/perf/serverPerfHarness.ts new file mode 100644 index 0000000000..1f3897162f --- /dev/null +++ b/apps/server/integration/perf/serverPerfHarness.ts @@ -0,0 +1,393 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdir, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:net"; +import { join, resolve } from "node:path"; +import { performance } from "node:perf_hooks"; +import { fileURLToPath } from "node:url"; + +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import { + type OrchestrationEvent, + type TerminalEvent, + WS_METHODS, + WsRpcGroup, +} from "@t3tools/contracts"; +import { + Effect, + Exit, + Layer, + ManagedRuntime, + Scope, + Stream, + type Scope as ScopeService, +} from "effect"; +import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; +import { + summarizeLatencySamples, + summarizeLatencyValues, + type PerfLatencySample, + type PerfLatencySummary, + writeJsonArtifact, +} from "@t3tools/shared/perf/artifact"; +import type { + PerfProviderScenarioId, + PerfSeedScenarioId, +} from "@t3tools/shared/perf/scenarioCatalog"; +import { seedPerfState, type PerfSeededState } from "./seedPerfState.ts"; + +const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url)); +const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR"; +const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER"; +const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO"; +const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD"; + +const makeWsRpcClient = RpcClient.make(WsRpcGroup); +type WsRpcClient = + typeof makeWsRpcClient extends Effect.Effect ? Client : never; + +export interface ServerCommandLatencyMeasurement { + readonly commandType: string; + readonly loadProfile: string; + readonly startedAt: string; + readonly dispatchToAckMs: number; + readonly dispatchToEventMs: number; + readonly ackToEventMs: number; + readonly resultSequence: number; + readonly eventSequence: number; + readonly metadata?: Record; +} + +export interface ServerCommandLatencySummary { + readonly count: number; + readonly dispatchToAckMs: PerfLatencySummary; + readonly dispatchToEventMs: PerfLatencySummary; + readonly ackToEventMs: PerfLatencySummary; +} + +export interface ServerCommandLatencySeries { + readonly name: string; + readonly loadProfile: string; + readonly summary: ServerCommandLatencySummary; + readonly samples: ReadonlyArray; +} + +export interface ServerRpcLatencySeries { + readonly name: string; + readonly loadProfile: string; + readonly summary: PerfLatencySummary; + readonly samples: ReadonlyArray; +} + +export interface ServerPerfRunArtifact { + readonly suite: string; + readonly scenarioId: string; + readonly startedAt: string; + readonly completedAt: string; + readonly commandLatency: ReadonlyArray; + readonly rpcLatency: ReadonlyArray; + readonly metadata?: Record; +} + +interface StartServerPerfHarnessOptions { + readonly suite: string; + readonly seedScenarioId: PerfSeedScenarioId; + readonly providerScenarioId?: PerfProviderScenarioId; +} + +interface FinishServerPerfRunOptions { + readonly artifactBasename?: string; + readonly artifact: ServerPerfRunArtifact; +} + +export interface ServerPerfHarness { + readonly seededState: PerfSeededState; + readonly wsUrl: string; + readonly artifactDir: string; + readonly rpc: PerfWsRpcClient; + readonly finishRun: (options: FinishServerPerfRunOptions) => Promise<{ + readonly artifactPath: string; + readonly artifact: ServerPerfRunArtifact; + }>; + readonly dispose: () => Promise; +} + +const wsRpcProtocolLayer = (wsUrl: string) => + RpcClient.layerProtocolSocket().pipe( + Layer.provide(NodeSocket.layerWebSocket(wsUrl)), + Layer.provide(RpcSerialization.layerJson), + ); + +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 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/server"), + ); + 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"), + ]); +} + +function buildPerfServerEnv( + baseEnv: NodeJS.ProcessEnv, + providerScenarioId?: PerfProviderScenarioId, +): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { + ...baseEnv, + [AUTO_BOOTSTRAP_PROJECT_ENV]: "false", + }; + + if (!providerScenarioId) { + delete env[PERF_PROVIDER_ENV]; + delete env[PERF_SCENARIO_ENV]; + return env; + } + + return { + ...env, + [PERF_PROVIDER_ENV]: "1", + [PERF_SCENARIO_ENV]: providerScenarioId, + }; +} + +export class PerfWsRpcClient { + private readonly runtime: ManagedRuntime.ManagedRuntime; + private readonly clientScope: Scope.Closeable; + private readonly clientPromise: Promise; + private disposed = false; + + constructor(private readonly wsUrl: string) { + this.runtime = ManagedRuntime.make(wsRpcProtocolLayer(wsUrl)); + this.clientScope = this.runtime.runSync(Scope.make()); + this.clientPromise = this.runtime.runPromise(Scope.provide(this.clientScope)(makeWsRpcClient)); + } + + async request( + execute: (client: WsRpcClient) => Effect.Effect, + ): Promise { + if (this.disposed) { + throw new Error(`WebSocket RPC client disposed for ${this.wsUrl}`); + } + + const client = await this.clientPromise; + return await this.runtime.runPromise(Effect.suspend(() => execute(client))); + } + + subscribe( + connect: (client: WsRpcClient) => Stream.Stream, + listener: (value: TValue) => void, + ): () => void { + if (this.disposed) { + return () => undefined; + } + + let active = true; + const cancel = this.runtime.runCallback( + Effect.promise(() => this.clientPromise).pipe( + Effect.flatMap((client) => + Stream.runForEach(connect(client), (value) => + Effect.sync(() => { + if (!active) { + return; + } + listener(value); + }), + ), + ), + ), + ); + + return () => { + active = false; + cancel(); + }; + } + + async dispose(): Promise { + if (this.disposed) { + return; + } + this.disposed = true; + await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void)); + await this.runtime.dispose(); + } +} + +async function waitForRpcReady(wsUrl: string, process: ChildProcess): Promise { + const startedAtMs = performance.now(); + const timeoutMs = 45_000; + + while (performance.now() - startedAtMs < timeoutMs) { + if (process.exitCode !== null) { + throw new Error(`Perf server exited early with code ${process.exitCode}.`); + } + + const client = new PerfWsRpcClient(wsUrl); + try { + await client.request((rpcClient) => rpcClient[WS_METHODS.serverGetSettings]({})); + await client.dispose(); + return; + } catch { + await client.dispose().catch(() => undefined); + await new Promise((resolveDelay) => setTimeout(resolveDelay, 200)); + } + } + + throw new Error(`Timed out waiting for websocket readiness at ${wsUrl}.`); +} + +export function summarizeCommandLatencyMeasurements( + samples: ReadonlyArray, +): ServerCommandLatencySummary { + return { + count: samples.length, + dispatchToAckMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToAckMs)), + dispatchToEventMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToEventMs)), + ackToEventMs: summarizeLatencyValues(samples.map((sample) => sample.ackToEventMs)), + }; +} + +export function summarizeRpcLatencySeries( + samples: ReadonlyArray, +): PerfLatencySummary { + return summarizeLatencySamples(samples); +} + +export async function startServerPerfHarness( + options: StartServerPerfHarnessOptions, +): Promise { + const seededState = await seedPerfState(options.seedScenarioId); + const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId); + const port = await pickFreePort(); + const wsUrl = `ws://127.0.0.1:${port}/ws`; + const env = buildPerfServerEnv(process.env, options.providerScenarioId); + + let stdoutBuffer = ""; + let stderrBuffer = ""; + let finished = false; + const serverProcess = spawn( + "bun", + [ + "run", + "apps/server/src/bin.ts", + "--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(); + }); + + const cleanup = async () => { + if (finished) { + return; + } + finished = true; + await stopChildProcess(serverProcess); + await rm(seededState.runParentDir, { recursive: true, force: true }); + }; + + try { + await waitForRpcReady(wsUrl, serverProcess); + const rpc = new PerfWsRpcClient(wsUrl); + + return { + seededState, + wsUrl, + artifactDir, + rpc, + finishRun: async ({ artifactBasename, artifact }) => { + const basename = artifactBasename ?? `${artifact.suite}-${artifact.scenarioId}`; + await rpc.dispose(); + await cleanup(); + await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename); + const artifactPath = join(artifactDir, `${basename}.json`); + await writeJsonArtifact(artifactPath, artifact); + return { + artifactPath, + artifact, + }; + }, + dispose: async () => { + await rpc.dispose().catch(() => undefined); + await cleanup(); + }, + }; + } catch (error) { + await cleanup(); + throw error; + } +} + +export type { OrchestrationEvent, ScopeService, TerminalEvent, WsRpcClient }; diff --git a/apps/server/package.json b/apps/server/package.json index 950079a4dc..7b2a940b1f 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -20,7 +20,8 @@ "start": "node dist/bin.mjs", "prepare": "effect-language-service patch", "typecheck": "tsc --noEmit", - "test": "vitest run" + "test": "vitest run", + "test:perf": "vitest run integration/perf" }, "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.2.77", diff --git a/apps/server/src/perf/config.ts b/apps/server/src/perf/config.ts index c921316bd6..2759fecf54 100644 --- a/apps/server/src/perf/config.ts +++ b/apps/server/src/perf/config.ts @@ -11,7 +11,7 @@ export function isPerfProviderEnabled(): boolean { export function getPerfProviderScenarioId(): PerfProviderScenarioId | null { const rawScenarioId = process.env[PERF_SCENARIO_ENV]?.trim(); - if (rawScenarioId === "dense_assistant_stream") { + if (rawScenarioId === "dense_assistant_stream" || rawScenarioId === "parallel_assistant_stream") { return rawScenarioId; } return null; diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 781e6f469a..bd141a14a9 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -25,6 +25,7 @@ "src", "vite.config.ts", "test", + "../../packages/shared/src/perf/artifact.ts", "../../test/perf/support/artifact.ts", "../../test/perf/support/browserMetrics.ts", "../../test/perf/support/serverSampler.ts", diff --git a/package.json b/package.json index f5f275f298..d305d23766 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:server": "cd apps/server && bun run test:perf", "test:perf:web": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && cd apps/web && bun run test:perf", "perf:open": "node scripts/open-perf-app.ts", "perf:open:build": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && node scripts/open-perf-app.ts", diff --git a/packages/shared/package.json b/packages/shared/package.json index 8e3b87e6a3..101eafe1ac 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -63,6 +63,10 @@ "./perf/scenarioCatalog": { "types": "./src/perf/scenarioCatalog.ts", "import": "./src/perf/scenarioCatalog.ts" + }, + "./perf/artifact": { + "types": "./src/perf/artifact.ts", + "import": "./src/perf/artifact.ts" } }, "scripts": { diff --git a/packages/shared/src/perf/artifact.ts b/packages/shared/src/perf/artifact.ts new file mode 100644 index 0000000000..1ba886153e --- /dev/null +++ b/packages/shared/src/perf/artifact.ts @@ -0,0 +1,73 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; + +export interface PerfLatencySample { + readonly name: string; + readonly durationMs: number; + readonly startedAt: string; + readonly endedAt: string; + readonly metadata?: Record; +} + +export interface PerfLatencySummary { + readonly count: number; + readonly minMs: number | null; + readonly avgMs: number | null; + readonly p50Ms: number | null; + readonly p95Ms: number | null; + readonly maxMs: number | null; +} + +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.max(0, Math.ceil(sorted.length * clampedTarget) - 1), + ); + return sorted[index] ?? null; +} + +export function summarizeLatencyValues(values: ReadonlyArray): PerfLatencySummary { + if (values.length === 0) { + return { + count: 0, + minMs: null, + avgMs: null, + p50Ms: null, + p95Ms: null, + maxMs: null, + }; + } + + const minMs = values.reduce((currentMin, value) => Math.min(currentMin, value), values[0]!); + const maxMs = values.reduce((currentMax, value) => Math.max(currentMax, value), values[0]!); + const avgMs = values.reduce((sum, value) => sum + value, 0) / values.length; + + return { + count: values.length, + minMs, + avgMs, + p50Ms: percentile(values, 0.5), + p95Ms: percentile(values, 0.95), + maxMs, + }; +} + +export function summarizeLatencySamples( + samples: ReadonlyArray, +): PerfLatencySummary { + return summarizeLatencyValues(samples.map((sample) => sample.durationMs)); +} + +export async function writeJsonArtifact( + outputPath: string, + artifact: TArtifact, +): Promise { + const resolvedOutputPath = resolve(outputPath); + await mkdir(dirname(resolvedOutputPath), { recursive: true }); + await writeFile(`${resolvedOutputPath}`, `${JSON.stringify(artifact, null, 2)}\n`, "utf8"); +} diff --git a/packages/shared/src/perf/scenarioCatalog.ts b/packages/shared/src/perf/scenarioCatalog.ts index c37c1dc29c..1c0acfc6ac 100644 --- a/packages/shared/src/perf/scenarioCatalog.ts +++ b/packages/shared/src/perf/scenarioCatalog.ts @@ -11,7 +11,7 @@ import { } from "@t3tools/contracts"; export type PerfSeedScenarioId = "large_threads" | "burst_base"; -export type PerfProviderScenarioId = "dense_assistant_stream"; +export type PerfProviderScenarioId = "dense_assistant_stream" | "parallel_assistant_stream"; export type PerfScenarioId = PerfSeedScenarioId | PerfProviderScenarioId; export interface PerfProjectScenario { @@ -382,6 +382,11 @@ const DENSE_ASSISTANT_STREAM_WORKLOG_STARTED_GAP_MS = 20; const DENSE_ASSISTANT_STREAM_WORKLOG_UPDATED_GAP_MS = 24; const DENSE_ASSISTANT_STREAM_WORKLOG_COMPLETED_GAP_MS = 28; const DENSE_ASSISTANT_STREAM_WORKLOG_GROUP_GAP_MS = 12; +const PARALLEL_ASSISTANT_STREAM_SENTINEL = + "PERF_STREAM_SENTINEL:parallel_assistant_stream:completed"; +const PARALLEL_ASSISTANT_STREAM_FRAGMENT_COUNT = 240; +const PARALLEL_ASSISTANT_STREAM_FRAGMENT_GAP_MS = 24; +const PARALLEL_ASSISTANT_STREAM_COMPLETION_GAP_MS = 48; type DenseAssistantStreamLaneKey = "burst" | "navigation" | "filler"; @@ -1089,8 +1094,61 @@ function buildDenseAssistantStreamScenario(): PerfProviderScenario { }; } +function buildParallelAssistantStreamScenario(): PerfProviderScenario { + const events: Array = [ + { + delayMs: 0, + type: "turn.started", + payload: { + model: "gpt-5.4", + }, + }, + ]; + + let delayMs = 0; + for ( + let fragmentIndex = 0; + fragmentIndex < PARALLEL_ASSISTANT_STREAM_FRAGMENT_COUNT; + fragmentIndex += 1 + ) { + delayMs += PARALLEL_ASSISTANT_STREAM_FRAGMENT_GAP_MS; + const isFinalFragment = fragmentIndex === PARALLEL_ASSISTANT_STREAM_FRAGMENT_COUNT - 1; + const cycleLabel = fragmentIndex.toString().padStart(3, "0"); + const delta = isFinalFragment + ? `parallel-cycle-${cycleLabel} ${PARALLEL_ASSISTANT_STREAM_SENTINEL}` + : `parallel-cycle-${cycleLabel} keeping provider ingestion and projection busy. `; + + events.push({ + delayMs, + type: "content.delta", + payload: { + streamKind: "assistant_text", + delta, + }, + }); + } + + delayMs += PARALLEL_ASSISTANT_STREAM_COMPLETION_GAP_MS; + events.push({ + delayMs, + type: "turn.completed", + payload: { + state: "completed", + }, + }); + + return { + id: "parallel_assistant_stream", + provider: "codex", + sentinelText: PARALLEL_ASSISTANT_STREAM_SENTINEL, + totalDurationMs: delayMs, + events, + }; +} + export const PERF_PROVIDER_SCENARIOS = { dense_assistant_stream: buildDenseAssistantStreamScenario(), + parallel_assistant_stream: buildParallelAssistantStreamScenario(), } as const satisfies Record; export const PERF_CATALOG_IDS = { @@ -1120,6 +1178,7 @@ export const PERF_CATALOG_IDS = { }, provider: { denseAssistantStreamSentinel: DENSE_ASSISTANT_STREAM_SENTINEL, + parallelAssistantStreamSentinel: PARALLEL_ASSISTANT_STREAM_SENTINEL, navigationLiveTurnId: PERF_PROVIDER_LIVE_TURNS.navigation, fillerLiveTurnId: PERF_PROVIDER_LIVE_TURNS.filler, navigationLiveAssistantMessageId: makeLiveAssistantMessageId( diff --git a/test/perf/support/artifact.ts b/test/perf/support/artifact.ts index 98b13356de..6e821044e0 100644 --- a/test/perf/support/artifact.ts +++ b/test/perf/support/artifact.ts @@ -1,6 +1,11 @@ -import { mkdir, writeFile } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; - +import { + percentile, + summarizeLatencySamples, + summarizeLatencyValues, + type PerfLatencySample, + type PerfLatencySummary, + writeJsonArtifact, +} from "../../../packages/shared/src/perf/artifact"; import type { PerfThresholdProfile } from "./thresholds.ts"; export interface PerfActionDuration { @@ -50,6 +55,9 @@ export interface PerfArtifactSummary { readonly burstCompletionMs: number | null; } +export type { PerfLatencySample, PerfLatencySummary }; +export { percentile, summarizeLatencySamples, summarizeLatencyValues, writeJsonArtifact }; + export interface PerfRunArtifact { readonly suite: string; readonly scenarioId: string; @@ -62,19 +70,6 @@ export interface PerfRunArtifact { 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.max(0, Math.ceil(sorted.length * clampedTarget) - 1), - ); - return sorted[index] ?? null; -} - export function summarizeBrowserPerfMetrics( browserMetrics: BrowserPerfMetrics, options?: { @@ -120,7 +115,5 @@ 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"); + await writeJsonArtifact(outputPath, artifact); }