Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 3bec3d2c8d Optimize streaming message projection path
Co-authored-by: codex <[email protected]>
2026-04-02 02:21:12 -07:00
Julius Marmingeandcodex b24b5fb8ce Trim checkpoint reactor stream fanout
Co-authored-by: codex <[email protected]>
2026-04-02 02:21:09 -07:00
Julius Marmingeandcodex 0be82d3443 Add server perf latency baselines
Co-authored-by: codex <[email protected]>
2026-04-02 02:21:06 -07:00
Julius Marminge 7a1b982926 Broaden perf seed coverage across multiple projects
- Seed large_threads across 5 projects with bounded heavy turns
- Add shared perf server env setup and update harness assertions
- Co-authored-by: codex <[email protected]>
2026-04-02 01:07:51 -07:00
24 changed files with 2337 additions and 287 deletions

No files matched your search

@@ -3,7 +3,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
import { PERF_CATALOG_IDS, getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
import { seedPerfState } from "./seedPerfState.ts";
describe("seedPerfState", () => {
@@ -20,18 +20,24 @@ describe("seedPerfState", () => {
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
const seeded = await seedPerfState("large_threads");
runParentDirsToCleanup.push(seeded.runParentDir);
const scenario = getPerfSeedScenario("large_threads");
expect(seeded.snapshot.projects).toHaveLength(1);
expect(seeded.snapshot.threads).toHaveLength(12);
expect(seeded.snapshot.projects).toHaveLength(5);
expect(seeded.snapshot.threads).toHaveLength(30);
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
expect(new Set(seeded.snapshot.threads.map((thread) => thread.projectId)).size).toBe(5);
const heavyThread = seeded.snapshot.threads.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
);
const heavyThreadScenario = scenario.threads.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
);
expect(heavyThread?.messages).toHaveLength(2_000);
expect(heavyThreadScenario?.turnCount ?? Number.POSITIVE_INFINITY).toBeLessThan(100);
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
expect((heavyThread?.checkpoints.length ?? 0) >= 80).toBe(true);
expect((heavyThread?.checkpoints.length ?? 0) >= 20).toBe(true);
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
});
+204 -113
View File
@@ -10,14 +10,17 @@ import {
EventId,
type OrchestrationEvent,
type OrchestrationReadModel,
type ProjectId,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime } from "effect";
import {
buildPerfAssistantMessageCountPlan,
getPerfSeedScenario,
perfEventId,
perfMessageIdForThread,
perfTurnIdForThread,
type PerfProjectScenario,
type PerfSeedScenario,
type PerfSeedScenarioId,
type PerfSeedThreadScenario,
@@ -73,25 +76,25 @@ function makeCommandId(prefix: string, threadId: string, turnIndex: number): Com
}
function buildProjectEvent(
scenario: PerfSeedScenario,
project: PerfProjectScenario,
workspaceRoot: string,
createdAt: string,
): Omit<OrchestrationEvent, "sequence"> {
return {
type: "project.created",
eventId: EventId.makeUnsafe(`perf-project-created:${String(scenario.project.id)}`),
eventId: EventId.makeUnsafe(`perf-project-created:${String(project.id)}`),
aggregateKind: "project",
aggregateId: scenario.project.id,
aggregateId: project.id,
occurredAt: createdAt,
commandId: CommandId.makeUnsafe(`perf-project-create:${String(scenario.project.id)}`),
commandId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
causationEventId: null,
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(scenario.project.id)}`),
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
metadata: {},
payload: {
projectId: scenario.project.id,
title: scenario.project.title,
projectId: project.id,
title: project.title,
workspaceRoot,
defaultModelSelection: scenario.project.defaultModelSelection,
defaultModelSelection: project.defaultModelSelection,
scripts: [],
createdAt,
updatedAt: createdAt,
@@ -101,7 +104,7 @@ function buildProjectEvent(
function buildThreadCreatedEvent(
thread: PerfSeedThreadScenario,
scenario: PerfSeedScenario,
project: PerfProjectScenario,
createdAt: string,
): Omit<OrchestrationEvent, "sequence"> {
return {
@@ -116,9 +119,9 @@ function buildThreadCreatedEvent(
metadata: {},
payload: {
threadId: thread.id,
projectId: scenario.project.id,
projectId: thread.projectId,
title: thread.title,
modelSelection: scenario.project.defaultModelSelection,
modelSelection: project.defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -140,19 +143,36 @@ function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number)
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.",
function buildAssistantMessageText(
thread: PerfSeedThreadScenario,
turnIndex: number,
assistantMessageIndex: number,
assistantMessageCount: number,
): string {
const phaseLabel =
assistantMessageIndex === 1
? "Opening"
: assistantMessageIndex === assistantMessageCount
? "Settled"
: assistantMessageIndex % 5 === 0
? "Checkpoint"
: "Loop";
const focusTopics = [
"checked the visible timeline window and sidebar ordering",
"trimmed redundant projection work before the next render pass",
"reviewed websocket fan-out and message grouping pressure",
"verified checkpoint rows stay bounded while hidden threads move",
"kept the active route stable while background threads kept streaming",
];
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"
: ""
}`;
const topic = focusTopics[(turnIndex + assistantMessageIndex) % focusTopics.length]!;
const threadBias =
thread.category === "heavy"
? "The thread is still dense enough to stress virtualization."
: thread.category === "burst"
? "This pass is still carrying live burst pressure."
: "Background churn is staying active without stealing focus.";
return `${thread.title} ${phaseLabel.toLowerCase()} ${assistantMessageIndex}/${assistantMessageCount} for turn ${turnIndex}: ${topic}. ${threadBias}`;
}
function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string {
@@ -227,25 +247,41 @@ function buildCheckpointFiles(
}
function buildThreadTurnEvents(
scenario: PerfSeedScenario,
thread: PerfSeedThreadScenario,
threadOrdinal: number,
projectStartMs: number,
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
const threadStartMs = projectStartMs + threadOrdinal * 60_000;
const assistantMessageCountPlan = buildPerfAssistantMessageCountPlan(thread);
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 userMessageId = perfMessageIdForThread(thread, "user", turnIndex, 1);
const assistantMessageCount = assistantMessageCountPlan[turnIndex - 1] ?? 1;
const turnBaseMs = threadStartMs + turnIndex * 1_000;
const userOccurredAt = plusMs(turnBaseMs, 0);
const assistantOccurredAt = plusMs(turnBaseMs, 320);
const activityAssistantIndex =
thread.activityStride !== null && turnIndex % thread.activityStride === 0
? Math.max(2, Math.floor(assistantMessageCount * 0.35))
: null;
const planAssistantIndex =
thread.planStride !== null && turnIndex % thread.planStride === 0
? Math.max(2, Math.floor(assistantMessageCount * 0.7))
: null;
let lastAssistantMessageId = perfMessageIdForThread(
thread,
"assistant",
turnIndex,
assistantMessageCount,
);
let turnEventOffset = 0;
const nextEventId = (prefix: string) =>
perfEventId(prefix, thread.id, turnIndex * 100 + turnEventOffset++);
events.push({
type: "thread.message-sent",
eventId: perfEventId("perf-user-message", thread.id, turnIndex * 10),
eventId: nextEventId("perf-user-message"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: userOccurredAt,
@@ -266,92 +302,113 @@ function buildThreadTurnEvents(
},
});
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,
},
});
for (
let assistantMessageIndex = 1;
assistantMessageIndex <= assistantMessageCount;
assistantMessageIndex += 1
) {
const assistantOccurredAt = plusMs(turnBaseMs, 120 + assistantMessageIndex * 40);
const assistantMessageId = perfMessageIdForThread(
thread,
"assistant",
turnIndex,
assistantMessageIndex,
);
lastAssistantMessageId = assistantMessageId;
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),
type: "thread.message-sent",
eventId: nextEventId("perf-assistant-message"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: activityOccurredAt,
commandId: makeCommandId("perf-activity", String(thread.id), turnIndex),
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,
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,
messageId: assistantMessageId,
role: "assistant",
text: buildAssistantMessageText(
thread,
turnIndex,
assistantMessageIndex,
assistantMessageCount,
),
attachments: [],
turnId,
streaming: false,
createdAt: assistantOccurredAt,
updatedAt: assistantOccurredAt,
},
});
if (activityAssistantIndex === assistantMessageIndex) {
const activityOccurredAt = plusMs(turnBaseMs, 132 + assistantMessageIndex * 40);
events.push({
type: "thread.activity-appended",
eventId: nextEventId("perf-activity"),
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}.${assistantMessageIndex}`,
payload: {
command: "perf-simulated",
batch: turnIndex,
loop: assistantMessageIndex,
threadCategory: thread.category,
},
turnId,
createdAt: activityOccurredAt,
},
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 (planAssistantIndex === assistantMessageIndex) {
const planOccurredAt = plusMs(turnBaseMs, 140 + assistantMessageIndex * 40);
events.push({
type: "thread.proposed-plan-upserted",
eventId: nextEventId("perf-plan"),
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);
const diffOccurredAt = plusMs(turnBaseMs, 180 + assistantMessageCount * 40);
events.push({
type: "thread.turn-diff-completed",
eventId: perfEventId("perf-diff", thread.id, turnIndex * 10 + 4),
eventId: nextEventId("perf-diff"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: diffOccurredAt,
@@ -368,7 +425,7 @@ function buildThreadTurnEvents(
),
status: "ready",
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
assistantMessageId,
assistantMessageId: lastAssistantMessageId,
completedAt: diffOccurredAt,
},
});
@@ -380,27 +437,57 @@ function buildThreadTurnEvents(
function buildScenarioEvents(
scenario: PerfSeedScenario,
workspaceRoot: string,
workspaceRootsByProjectId: ReadonlyMap<ProjectId, string>,
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
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),
];
}),
];
const threadsByProjectId = new Map<ProjectId, PerfSeedThreadScenario[]>();
for (const thread of scenario.threads) {
const existing = threadsByProjectId.get(thread.projectId) ?? [];
existing.push(thread);
threadsByProjectId.set(thread.projectId, existing);
}
let globalThreadOrdinal = 0;
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
for (const [projectOrdinal, project] of scenario.projects.entries()) {
const projectWorkspaceRoot = workspaceRootsByProjectId.get(project.id);
if (!projectWorkspaceRoot) {
throw new Error(`Missing workspace root for perf project '${String(project.id)}'.`);
}
const projectBaseMs = projectStartMs + projectOrdinal * 6 * 60_000;
const projectCreatedAt = plusMs(projectBaseMs, 0);
const projectThreads = threadsByProjectId.get(project.id) ?? [];
events.push(buildProjectEvent(project, projectWorkspaceRoot, projectCreatedAt));
for (const [threadOrdinalWithinProject, thread] of projectThreads.entries()) {
const threadCreatedAt = plusMs(projectBaseMs, threadOrdinalWithinProject * 45_000 + 50);
const threadEvents = buildThreadTurnEvents(thread, globalThreadOrdinal, projectBaseMs);
globalThreadOrdinal += 1;
events.push(buildThreadCreatedEvent(thread, project, threadCreatedAt), ...threadEvents);
}
}
return events;
}
async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
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 primaryProject = scenario.projects[0];
if (!primaryProject) {
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
}
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
const workspaceRootsByProjectId = new Map<ProjectId, string>(
scenario.projects.map((project) => [project.id, join(baseDir, project.workspaceDirectoryName)]),
);
await Promise.all(
scenario.projects.map((project) =>
initializeGitWorkspace(join(baseDir, project.workspaceDirectoryName)),
),
);
const seedLayer = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
@@ -424,7 +511,7 @@ async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string
enableAssistantStreaming: scenario.id === "burst_base",
});
for (const event of buildScenarioEvents(scenario, workspaceRoot)) {
for (const event of buildScenarioEvents(scenario, workspaceRootsByProjectId)) {
const storedEvent = yield* eventStore.append(event);
yield* projectionPipeline.projectEvent(storedEvent);
}
@@ -470,7 +557,11 @@ export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<Per
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 primaryProject = scenario.projects[0];
if (!primaryProject) {
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
}
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
const snapshotLayer = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
@@ -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<TValue, TResult> {
readonly description: string;
readonly select: (values: ReadonlyArray<TValue>) => TResult | null;
readonly resolve: (value: TResult) => void;
readonly reject: (error: Error) => void;
readonly timer: ReturnType<typeof setTimeout>;
}
class BufferedEventFeed<TValue> implements SubscriptionCleanup {
private readonly values: TValue[] = [];
private readonly waiters = new Set<EventWaiter<TValue, unknown>>();
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<TResult>(
description: string,
select: (values: ReadonlyArray<TValue>) => TResult | null,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<TResult> {
const immediateMatch = select(this.values);
if (immediateMatch !== null) {
return Promise.resolve(immediateMatch);
}
return new Promise<TResult>((resolve, reject) => {
const waiter: EventWaiter<TValue, TResult> = {
description,
select,
resolve,
reject,
timer: setTimeout(() => {
this.waiters.delete(waiter as EventWaiter<TValue, unknown>);
reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`));
}, timeoutMs),
};
this.waiters.add(waiter as EventWaiter<TValue, unknown>);
});
}
waitForEvent(
description: string,
predicate: (value: TValue) => boolean,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<TValue> {
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<ReadonlyArray<TValue>> {
return this.waitFor(
description,
(values) => {
const matches = values.filter(predicate);
return matches.length >= count ? matches.slice(0, count) : null;
},
timeoutMs,
);
}
waitForDistinct<TKey extends string | number>(
description: string,
predicate: (value: TValue) => boolean,
selectKey: (value: TValue) => TKey,
count: number,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<ReadonlyArray<TValue>> {
return this.waitFor(
description,
(values) => {
const distinctMatches = new Map<TKey, TValue>();
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<void> {
return new Promise((resolve) => setTimeout(resolve, delayMs));
}
function nowIso(): string {
return new Date().toISOString();
}
function runGit(cwd: string, args: ReadonlyArray<string>) {
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<OrchestrationEvent>;
readonly command: ClientOrchestrationCommand;
readonly expectedEventType: OrchestrationEvent["type"];
readonly loadProfile: string;
readonly timeoutMs?: number;
readonly metadata?: Record<string, unknown>;
}): Promise<ServerCommandLatencyMeasurement> {
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<OrchestrationEvent>;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
readonly label: string;
}): Promise<ThreadIdType> {
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<OrchestrationEvent>;
readonly loadProfile: string;
readonly sampleCount: number;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
}): Promise<ReadonlyArray<ServerCommandLatencyMeasurement>> {
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<OrchestrationEvent>;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
readonly count: number;
}): Promise<ReadonlyArray<ThreadIdType>> {
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<OrchestrationEvent>;
readonly threadIds: ReadonlyArray<ThreadIdType>;
readonly label: string;
}): Promise<void> {
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<OrchestrationEvent>;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
readonly count: number;
readonly label: string;
}): Promise<{
readonly threadIds: ReadonlyArray<ThreadIdType>;
readonly done: Promise<ReadonlyArray<ThreadIdType>>;
}> {
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<TerminalEvent>;
readonly workspaceRoot: string;
readonly threadIds: ReadonlyArray<ThreadIdType>;
}): Promise<ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>> {
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<void> {
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<void> {
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<TResult>(input: {
readonly harness: ServerPerfHarness;
readonly name: string;
readonly loadProfile: string;
readonly iterations: number;
readonly execute: () => Promise<TResult>;
}): Promise<ServerRpcLatencySeries> {
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<ServerCommandLatencyMeasurement>,
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<SubscriptionCleanup> = [];
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<OrchestrationEvent>();
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<OrchestrationEvent>();
const terminalEvents = new BufferedEventFeed<TerminalEvent>();
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);
});
@@ -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<infer Client, any, any> ? 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<string, unknown>;
}
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<ServerCommandLatencyMeasurement>;
}
export interface ServerRpcLatencySeries {
readonly name: string;
readonly loadProfile: string;
readonly summary: PerfLatencySummary;
readonly samples: ReadonlyArray<PerfLatencySample>;
}
export interface ServerPerfRunArtifact {
readonly suite: string;
readonly scenarioId: string;
readonly startedAt: string;
readonly completedAt: string;
readonly commandLatency: ReadonlyArray<ServerCommandLatencySeries>;
readonly rpcLatency: ReadonlyArray<ServerRpcLatencySeries>;
readonly metadata?: Record<string, unknown>;
}
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<void>;
}
const wsRpcProtocolLayer = (wsUrl: string) =>
RpcClient.layerProtocolSocket().pipe(
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
Layer.provide(RpcSerialization.layerJson),
);
async function pickFreePort(): Promise<number> {
return await new Promise<number>((resolvePort, reject) => {
const server = createServer();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
reject(new Error("Unable to resolve a free localhost port."));
return;
}
const { port } = address;
server.close((closeError) => {
if (closeError) {
reject(closeError);
return;
}
resolvePort(port);
});
});
});
}
async function stopChildProcess(process: ChildProcess): Promise<void> {
if (process.exitCode !== null) {
return;
}
process.kill("SIGTERM");
const exited = await new Promise<boolean>((resolveExited) => {
const timer = setTimeout(() => resolveExited(false), 5_000);
process.once("exit", () => {
clearTimeout(timer);
resolveExited(true);
});
});
if (!exited && process.exitCode === null) {
process.kill("SIGKILL");
await new Promise<void>((resolveExited) => {
process.once("exit", () => resolveExited());
});
}
}
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
const baseArtifactDir = resolve(
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf/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<void> {
await mkdir(artifactDir, { recursive: true });
await Promise.all([
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
]);
}
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<RpcClient.Protocol, never>;
private readonly clientScope: Scope.Closeable;
private readonly clientPromise: Promise<WsRpcClient>;
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<TSuccess, TError>(
execute: (client: WsRpcClient) => Effect.Effect<TSuccess, TError, never>,
): Promise<TSuccess> {
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<TValue>(
connect: (client: WsRpcClient) => Stream.Stream<TValue, Error, never>,
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<void> {
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<void> {
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<ServerCommandLatencyMeasurement>,
): 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<PerfLatencySample>,
): PerfLatencySummary {
return summarizeLatencySamples(samples);
}
export async function startServerPerfHarness(
options: StartServerPerfHarnessOptions,
): Promise<ServerPerfHarness> {
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 };
+2 -1
View File
@@ -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",
+20
View File
@@ -1,4 +1,7 @@
import { join } from "node:path";
import { seedPerfState } from "../integration/perf/seedPerfState.ts";
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
@@ -10,6 +13,10 @@ if (scenarioId !== "large_threads" && scenarioId !== "burst_base") {
}
const seeded = await seedPerfState(scenarioId);
const scenario = getPerfSeedScenario(scenarioId);
const scenarioProjectById = new Map(scenario.projects.map((project) => [project.id, project]));
const scenarioThreadById = new Map(scenario.threads.map((thread) => [thread.id, thread]));
const projectById = new Map(seeded.snapshot.projects.map((project) => [project.id, project]));
const payload = JSON.stringify(
{
scenarioId: seeded.scenarioId,
@@ -17,9 +24,22 @@ const payload = JSON.stringify(
baseDir: seeded.baseDir,
workspaceRoot: seeded.workspaceRoot,
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
projectSummaries: seeded.snapshot.projects.map((project) => ({
id: project.id,
title: project.title,
workspaceRoot:
scenarioProjectById.get(project.id)?.workspaceDirectoryName !== undefined
? join(seeded.baseDir, scenarioProjectById.get(project.id)?.workspaceDirectoryName ?? "")
: project.workspaceRoot,
threadCount: seeded.snapshot.threads.filter((thread) => thread.projectId === project.id)
.length,
})),
threadSummaries: seeded.snapshot.threads.map((thread) => ({
id: thread.id,
projectId: thread.projectId,
projectTitle: projectById.get(thread.projectId)?.title ?? null,
title: thread.title,
turnCount: scenarioThreadById.get(thread.id)?.turnCount ?? null,
messageCount: thread.messages.length,
activityCount: thread.activities.length,
proposedPlanCount: thread.proposedPlans.length,
@@ -499,21 +499,8 @@ const make = Effect.gen(function* () {
});
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
event: Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" | "thread.message-sent" }
>,
event: Extract<OrchestrationEvent, { type: "thread.turn-start-requested" }>,
) {
if (event.type === "thread.message-sent") {
if (
event.payload.role !== "user" ||
event.payload.streaming ||
event.payload.turnId !== null
) {
return;
}
}
const threadId = event.payload.threadId;
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
@@ -686,7 +673,7 @@ const make = Effect.gen(function* () {
});
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
if (event.type === "thread.turn-start-requested") {
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
return;
}
@@ -772,7 +759,6 @@ const make = Effect.gen(function* () {
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.message-sent" &&
event.type !== "thread.checkpoint-revert-requested" &&
event.type !== "thread.turn-diff-completed"
) {
@@ -623,31 +623,46 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
});
const existingMessage = existingRows.find(
(row) => row.messageId === event.payload.messageId,
);
const nextText =
existingMessage && event.payload.streaming
? `${existingMessage.text}${event.payload.text}`
: existingMessage && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
: undefined;
if (event.payload.streaming) {
yield* projectionThreadMessageRepository.appendTextDelta({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
delta: event.payload.text,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: true,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
}
const existingMessage = yield* projectionThreadMessageRepository
.getByMessageId({
messageId: event.payload.messageId,
})
.pipe(Effect.map(Option.getOrUndefined));
const nextText =
existingMessage !== undefined && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const persistedAttachments = nextAttachments ?? existingMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
...(persistedAttachments !== undefined
? { attachments: [...persistedAttachments] }
: {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
+1 -1
View File
@@ -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;
@@ -1,6 +1,6 @@
import { MessageId, ThreadId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { Effect, Layer, Option } from "effect";
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
@@ -103,4 +103,84 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.deepEqual(rows[0]?.attachments, []);
}),
);
it.effect("looks up a projected message by id", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.makeUnsafe("thread-get-by-message-id");
const messageId = MessageId.makeUnsafe("message-get-by-message-id");
const createdAt = "2026-02-28T19:20:00.000Z";
const updatedAt = "2026-02-28T19:20:01.000Z";
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "lookup me",
isStreaming: false,
createdAt,
updatedAt,
});
const maybeRow = yield* repository.getByMessageId({ messageId });
assert.isTrue(Option.isSome(maybeRow));
const row = Option.getOrThrow(maybeRow);
assert.equal(row.messageId, messageId);
assert.equal(row.threadId, threadId);
assert.equal(row.text, "lookup me");
assert.equal(row.createdAt, createdAt);
assert.equal(row.updatedAt, updatedAt);
}),
);
it.effect("appends streaming deltas without losing createdAt or attachments", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.makeUnsafe("thread-append-delta");
const messageId = MessageId.makeUnsafe("message-append-delta");
const createdAt = "2026-02-28T19:30:00.000Z";
const persistedAttachments = [
{
type: "image" as const,
id: "thread-append-delta-att-1",
name: "example.png",
mimeType: "image/png",
sizeBytes: 5,
},
];
yield* repository.appendTextDelta({
messageId,
threadId,
turnId: null,
role: "assistant",
delta: "Hello",
attachments: persistedAttachments,
isStreaming: true,
createdAt,
updatedAt: "2026-02-28T19:30:01.000Z",
});
yield* repository.appendTextDelta({
messageId,
threadId,
turnId: null,
role: "assistant",
delta: " world",
isStreaming: true,
createdAt: "2026-02-28T19:30:05.000Z",
updatedAt: "2026-02-28T19:30:06.000Z",
});
const maybeRow = yield* repository.getByMessageId({ messageId });
assert.isTrue(Option.isSome(maybeRow));
const row = Option.getOrThrow(maybeRow);
assert.equal(row.text, "Hello world");
assert.equal(row.createdAt, createdAt);
assert.equal(row.updatedAt, "2026-02-28T19:30:06.000Z");
assert.deepEqual(row.attachments, persistedAttachments);
assert.isTrue(row.isStreaming);
}),
);
});
@@ -1,10 +1,12 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
AppendProjectionThreadMessageDeltaInput,
GetProjectionThreadMessageInput,
ProjectionThreadMessageRepository,
type ProjectionThreadMessageRepositoryShape,
DeleteProjectionThreadMessagesInput,
@@ -18,6 +20,19 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
}),
);
type ProjectionThreadMessageDbRow = typeof ProjectionThreadMessageDbRowSchema.Type;
const toProjectionThreadMessage = (row: ProjectionThreadMessageDbRow) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
});
const makeProjectionThreadMessageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -95,6 +110,70 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
`,
});
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
Request: GetProjectionThreadMessageInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ messageId }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE message_id = ${messageId}
`,
});
const appendProjectionThreadMessageDeltaRow = SqlSchema.void({
Request: AppendProjectionThreadMessageDeltaInput,
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
return sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
attachments_json,
is_streaming,
created_at,
updated_at
)
VALUES (
${row.messageId},
${row.threadId},
${row.turnId},
${row.role},
${row.delta},
${nextAttachmentsJson},
${row.isStreaming ? 1 : 0},
${row.createdAt},
${row.updatedAt}
)
ON CONFLICT (message_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = COALESCE(excluded.turn_id, projection_thread_messages.turn_id),
role = excluded.role,
text = projection_thread_messages.text || excluded.text,
attachments_json = COALESCE(
excluded.attachments_json,
projection_thread_messages.attachments_json
),
is_streaming = excluded.is_streaming,
updated_at = excluded.updated_at
`;
},
});
const deleteProjectionThreadMessageRows = SqlSchema.void({
Request: DeleteProjectionThreadMessagesInput,
execute: ({ threadId }) =>
@@ -114,18 +193,21 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
),
Effect.map((rows) =>
rows.map((row) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
})),
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
),
Effect.map(Option.map(toProjectionThreadMessage)),
);
const appendTextDelta: ProjectionThreadMessageRepositoryShape["appendTextDelta"] = (input) =>
appendProjectionThreadMessageDeltaRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.appendTextDelta:query"),
),
);
@@ -139,6 +221,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
listByThreadId,
getByMessageId,
appendTextDelta,
deleteByThreadId,
} satisfies ProjectionThreadMessageRepositoryShape;
});
@@ -14,7 +14,7 @@ import {
TurnId,
IsoDateTime,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -37,11 +37,30 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({
});
export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;
export const GetProjectionThreadMessageInput = Schema.Struct({
messageId: MessageId,
});
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
threadId: ThreadId,
});
export type DeleteProjectionThreadMessagesInput = typeof DeleteProjectionThreadMessagesInput.Type;
export const AppendProjectionThreadMessageDeltaInput = Schema.Struct({
messageId: MessageId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
role: OrchestrationMessageRole,
delta: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
isStreaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
});
export type AppendProjectionThreadMessageDeltaInput =
typeof AppendProjectionThreadMessageDeltaInput.Type;
/**
* ProjectionThreadMessageRepositoryShape - Service API for projected thread messages.
*/
@@ -64,6 +83,20 @@ export interface ProjectionThreadMessageRepositoryShape {
input: ListProjectionThreadMessagesInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadMessage>, ProjectionRepositoryError>;
/**
* Look up a projected message by id.
*/
readonly getByMessageId: (
input: GetProjectionThreadMessageInput,
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
/**
* Append a streaming text delta to an existing projected message row, or insert it.
*/
readonly appendTextDelta: (
input: AppendProjectionThreadMessageDeltaInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Delete projected thread messages by thread.
*/
+16 -9
View File
@@ -28,32 +28,42 @@ import {
NoopServerSampler,
type PerfServerSampler,
} from "../../../../test/perf/support/serverSampler";
import { buildPerfServerEnv } from "./serverEnv";
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 projectId: string;
readonly projectTitle: string | null;
readonly title: string;
readonly turnCount: number | null;
readonly messageCount: number;
readonly activityCount: number;
readonly proposedPlanCount: number;
readonly checkpointCount: number;
}
interface PerfSeedProjectSummary {
readonly id: string;
readonly title: string;
readonly workspaceRoot: string;
readonly threadCount: number;
}
export interface PerfSeededState {
readonly scenarioId: PerfSeedScenarioId;
readonly runParentDir: string;
readonly baseDir: string;
readonly workspaceRoot: string;
readonly projectTitle: string | null;
readonly projectSummaries: ReadonlyArray<PerfSeedProjectSummary>;
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
}
@@ -265,12 +275,7 @@ export async function startPerfAppHarness(
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 } : {}),
};
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
let stdoutBuffer = "";
let stderrBuffer = "";
@@ -318,7 +323,9 @@ export async function startPerfAppHarness(
await page.goto(url, { waitUntil: "domcontentloaded" });
const firstProjectTitle =
seededState.projectTitle ?? getPerfSeedScenario(options.seedScenarioId).project.title;
seededState.projectSummaries[0]?.title ??
seededState.projectTitle ??
getPerfSeedScenario(options.seedScenarioId).projects[0]?.title;
if (!firstProjectTitle) {
throw new Error(`Seed scenario '${options.seedScenarioId}' produced no projects.`);
}
+27
View File
@@ -0,0 +1,27 @@
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
export 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,
};
}
+24
View File
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { percentile } from "../../../../test/perf/support/artifact";
import { installBrowserPerfCollector } from "../../../../test/perf/support/browserMetrics";
import { buildPerfServerEnv, PERF_PROVIDER_ENV, PERF_SCENARIO_ENV } from "./serverEnv";
describe("percentile", () => {
it("returns the minimum value for the zero percentile", () => {
@@ -50,3 +51,26 @@ describe("installBrowserPerfCollector", () => {
expect(requestAnimationFrame).toHaveBeenCalledTimes(3);
});
});
describe("buildPerfServerEnv", () => {
it("does not enable the perf provider when no live provider scenario is requested", () => {
const env = buildPerfServerEnv({
[PERF_PROVIDER_ENV]: "1",
[PERF_SCENARIO_ENV]: "dense_assistant_stream",
KEEP_ME: "yes",
});
expect(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).toBe("false");
expect(env[PERF_PROVIDER_ENV]).toBeUndefined();
expect(env[PERF_SCENARIO_ENV]).toBeUndefined();
expect(env.KEEP_ME).toBe("yes");
});
it("enables the perf provider only when a live provider scenario is requested", () => {
const env = buildPerfServerEnv({}, "dense_assistant_stream");
expect(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).toBe("false");
expect(env[PERF_PROVIDER_ENV]).toBe("1");
expect(env[PERF_SCENARIO_ENV]).toBe("dense_assistant_stream");
});
});
+22 -9
View File
@@ -22,16 +22,26 @@ test("virtualization stays bounded and heavy thread switches remain snappy", asy
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;
const heavyAThreadSummary = harness.seededState.threadSummaries.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
);
const heavyBThreadSummary = harness.seededState.threadSummaries.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
);
const heavyAProjectTitle =
heavyAThreadSummary?.projectTitle ?? PERF_CATALOG_IDS.largeThreads.heavyAProjectTitle;
const heavyBProjectTitle =
heavyBThreadSummary?.projectTitle ?? PERF_CATALOG_IDS.largeThreads.heavyBProjectTitle;
const heavyThreadMessageCount = heavyAThreadSummary?.messageCount ?? 0;
expect(heavyAThreadSummary).toBeDefined();
expect(heavyBThreadSummary).toBeDefined();
expect(heavyThreadMessageCount).toBeGreaterThanOrEqual(2_000);
expect(heavyAThreadSummary?.turnCount ?? 0).toBeLessThan(100);
expect(heavyBThreadSummary?.turnCount ?? 0).toBeLessThan(100);
await ensureThreadRowVisible(
harness.page,
projectTitle,
heavyAProjectTitle,
PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
);
await harness.page
@@ -45,7 +55,7 @@ test("virtualization stays bounded and heavy thread switches remain snappy", asy
await ensureThreadRowVisible(
harness.page,
projectTitle,
heavyBProjectTitle,
PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
);
await harness.page
@@ -61,7 +71,7 @@ test("virtualization stays bounded and heavy thread switches remain snappy", asy
await measureThreadSwitch(harness, {
actionName: "thread-switch-warmup-a",
projectTitle,
projectTitle: heavyAProjectTitle,
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
});
@@ -105,7 +115,10 @@ test("virtualization stays bounded and heavy thread switches remain snappy", asy
for (const target of measuredTargets) {
await measureThreadSwitch(harness, {
actionName: target.actionName,
projectTitle,
projectTitle:
target.threadId === PERF_CATALOG_IDS.largeThreads.heavyAThreadId
? heavyAProjectTitle
: heavyBProjectTitle,
threadId: target.threadId,
messageId: target.messageId,
});
+1
View File
@@ -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",
+6 -6
View File
@@ -45,21 +45,21 @@ The current implementation is browser-focused, but the harness already reserves
Seeded app state used by the virtualization benchmark.
- 1 project
- 12 threads total
- 5 projects
- 30 threads total
- 2 heavy threads
- 1 burst thread
- 9 light filler threads
- 27 light filler threads spread across all projects
The two heavy threads currently seed:
- `1,000` turns
- `84` and `96` turns
- `2,000` messages
- periodic worklog/activity rows
- periodic proposed-plan rows
- frequent checkpoint rows with larger changed-file trees
This means the timeline is not just alternating short user/assistant text. The heavy threads include the non-message rows that tend to stress grouping, virtualization, and diff-tree rendering.
This keeps the thread count and project list closer to a real workspace mix: many projects, many sidebar rows, and heavy conversations that stay under `100` turns while still retaining thousands of messages because each turn fans out into multiple assistant messages. The heavy timelines also include the non-message rows that tend to stress grouping, virtualization, and diff-tree rendering.
### `burst_base`
@@ -199,7 +199,7 @@ For the websocket scenario, open the burst thread and send one message to start
### Inspect the seeded topology directly
The seed script prints the generated thread summaries as JSON:
The seed script prints the generated project and thread summaries as JSON:
```bash
bun run apps/server/scripts/seedPerfState.ts large_threads
+1
View File
@@ -39,6 +39,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",
+4
View File
@@ -47,6 +47,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": {
+73
View File
@@ -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<string, unknown>;
}
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<number>, 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<number>): 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<PerfLatencySample>,
): PerfLatencySummary {
return summarizeLatencyValues(samples.map((sample) => sample.durationMs));
}
export async function writeJsonArtifact<TArtifact extends object>(
outputPath: string,
artifact: TArtifact,
): Promise<void> {
const resolvedOutputPath = resolve(outputPath);
await mkdir(dirname(resolvedOutputPath), { recursive: true });
await writeFile(`${resolvedOutputPath}`, `${JSON.stringify(artifact, null, 2)}\n`, "utf8");
}
+338 -77
View File
@@ -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 {
@@ -23,6 +23,7 @@ export interface PerfProjectScenario {
export interface PerfSeedThreadScenario {
readonly id: ThreadId;
readonly projectId: ProjectId;
readonly title: string;
readonly category: "heavy" | "burst" | "light";
readonly turnCount: number;
@@ -36,7 +37,7 @@ export interface PerfSeedThreadScenario {
export interface PerfSeedScenario {
readonly id: PerfSeedScenarioId;
readonly project: PerfProjectScenario;
readonly projects: ReadonlyArray<PerfProjectScenario>;
readonly threads: ReadonlyArray<PerfSeedThreadScenario>;
}
@@ -63,18 +64,26 @@ const PERF_MODEL_SELECTION: ModelSelection = {
model: DEFAULT_MODEL_BY_PROVIDER.codex,
};
const PERF_PROJECT: PerfProjectScenario = {
id: ProjectId.makeUnsafe("perf-project-primary"),
title: "Performance Workspace",
workspaceDirectoryName: "perf-workspace",
const makeProjectId = (slug: string) => ProjectId.makeUnsafe(`perf-project-${slug}`);
const makeProject = (slug: string, title: string): PerfProjectScenario => ({
id: makeProjectId(slug),
title,
workspaceDirectoryName: `perf-workspace-${slug}`,
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 makeMessageId = (
threadSlug: string,
role: "user" | "assistant",
turnIndex: number,
messageIndex = 1,
) =>
MessageId.makeUnsafe(
`perf-message-${threadSlug}-${role}-${turnIndex.toString().padStart(4, "0")}-${messageIndex.toString().padStart(2, "0")}`,
);
const makeLiveTurnId = (slug: string) => TurnId.makeUnsafe(`perf-live-turn-${slug}`);
const makeLiveAssistantItemId = (
laneKey: string,
@@ -82,6 +91,122 @@ const makeLiveAssistantItemId = (
segment: "intro" | "followup",
) => `perf-assistant-${laneKey}-${cycleIndex.toString().padStart(2, "0")}-${segment}`;
const makeLiveAssistantMessageId = (itemId: string) => MessageId.makeUnsafe(`assistant:${itemId}`);
const threadSlugFromId = (threadId: ThreadId) => threadId.replace("perf-thread-", "");
function threadSeedValue(threadSlug: string): number {
return Array.from(threadSlug).reduce(
(sum, character, index) => sum + character.charCodeAt(0) * (index + 1),
0,
);
}
function buildAssistantMessageCountPlan(
input: Pick<PerfSeedThreadScenario, "category" | "turnCount" | "messageCount"> & {
readonly threadSlug: string;
},
): ReadonlyArray<number> {
const assistantMessageCount = input.messageCount - input.turnCount;
if (assistantMessageCount < input.turnCount) {
throw new Error(
`Perf thread '${input.threadSlug}' must retain at least one assistant message per turn.`,
);
}
const averageAssistantMessages = Math.floor(assistantMessageCount / input.turnCount);
const minPerTurn = Math.max(
1,
averageAssistantMessages -
(input.category === "heavy" ? 4 : input.category === "burst" ? 2 : 1),
);
const residualAssistantMessages = assistantMessageCount - minPerTurn * input.turnCount;
const threadSeed = threadSeedValue(input.threadSlug);
const weights = Array.from({ length: input.turnCount }, (_, index) => {
const burstBias = input.category === "heavy" && index % 9 === 0 ? 3 : index % 6 === 0 ? 1 : 0;
return 1 + ((threadSeed + (index + 1) * 11) % 7) + burstBias;
});
const weightTotal = weights.reduce((sum, weight) => sum + weight, 0);
const quotas = weights.map((weight) => (residualAssistantMessages * weight) / weightTotal);
const counts = quotas.map((quota) => minPerTurn + Math.floor(quota));
let remainingMessages = assistantMessageCount - counts.reduce((sum, count) => sum + count, 0);
if (remainingMessages > 0) {
const residualOrder = quotas
.map((quota, index) => ({
index,
remainder: quota - Math.floor(quota),
}))
.toSorted((left, right) => right.remainder - left.remainder || right.index - left.index);
for (let index = 0; index < residualOrder.length && remainingMessages > 0; index += 1) {
const targetIndex = residualOrder[index]?.index;
if (targetIndex === undefined) {
break;
}
counts[targetIndex] = (counts[targetIndex] ?? minPerTurn) + 1;
remainingMessages -= 1;
}
}
return counts;
}
export function buildPerfAssistantMessageCountPlan(
thread: Pick<PerfSeedThreadScenario, "id" | "category" | "turnCount" | "messageCount">,
): ReadonlyArray<number> {
return buildAssistantMessageCountPlan({
threadSlug: threadSlugFromId(thread.id),
category: thread.category,
turnCount: thread.turnCount,
messageCount: thread.messageCount,
});
}
function makeSeedThreadScenario(input: {
readonly slug: string;
readonly projectId: ProjectId;
readonly title: string;
readonly category: PerfSeedThreadScenario["category"];
readonly turnCount: number;
readonly messageCount: number;
readonly planStride: number | null;
readonly activityStride: number | null;
readonly diffStride: number | null;
}): PerfSeedThreadScenario {
const assistantMessageCountPlan = buildAssistantMessageCountPlan({
threadSlug: input.slug,
category: input.category,
turnCount: input.turnCount,
messageCount: input.messageCount,
});
return {
id: makeThreadId(input.slug),
projectId: input.projectId,
title: input.title,
category: input.category,
turnCount: input.turnCount,
messageCount: input.messageCount,
anchorMessageId: makeMessageId(input.slug, "user", 1, 1),
terminalMessageId: makeMessageId(
input.slug,
"assistant",
input.turnCount,
assistantMessageCountPlan.at(-1) ?? 1,
),
planStride: input.planStride,
activityStride: input.activityStride,
diffStride: input.diffStride,
};
}
const PERF_PROJECTS = {
inbox: makeProject("inbox", "Inbox Refactor Workspace"),
desktop: makeProject("desktop", "Desktop Release Workspace"),
runtime: makeProject("runtime", "Runtime Orchestration Workspace"),
marketing: makeProject("marketing", "Marketing Site Workspace"),
ops: makeProject("ops", "Ops Automation Workspace"),
burstBase: makeProject("burst-base", "Burst Harness Workspace"),
} as const;
const PERF_PROVIDER_LIVE_TURNS = {
navigation: makeLiveTurnId("navigation"),
@@ -89,89 +214,159 @@ const PERF_PROVIDER_LIVE_TURNS = {
} as const;
const LARGE_THREAD_DEFINITIONS = {
heavyA: {
id: makeThreadId("heavy-a"),
title: "Large Thread A",
heavyA: makeSeedThreadScenario({
slug: "heavy-a",
projectId: PERF_PROJECTS.inbox.id,
title: "Inbox Search Regression",
category: "heavy",
turnCount: 1_000,
turnCount: 84,
messageCount: 2_000,
anchorMessageId: makeMessageId("heavy-a", "user", 1),
terminalMessageId: makeMessageId("heavy-a", "assistant", 1_000),
planStride: 120,
activityStride: 32,
diffStride: 12,
},
heavyB: {
id: makeThreadId("heavy-b"),
title: "Large Thread B",
planStride: 11,
activityStride: 4,
diffStride: 3,
}),
heavyB: makeSeedThreadScenario({
slug: "heavy-b",
projectId: PERF_PROJECTS.desktop.id,
title: "Desktop Update Rollout",
category: "heavy",
turnCount: 1_000,
turnCount: 96,
messageCount: 2_000,
anchorMessageId: makeMessageId("heavy-b", "user", 1),
terminalMessageId: makeMessageId("heavy-b", "assistant", 1_000),
planStride: 125,
activityStride: 36,
diffStride: 14,
},
burst: {
id: makeThreadId("burst"),
title: "Burst Target Thread",
planStride: 12,
activityStride: 5,
diffStride: 4,
}),
burst: makeSeedThreadScenario({
slug: "large-burst",
projectId: PERF_PROJECTS.runtime.id,
title: "Runtime Burst Coordination",
category: "burst",
turnCount: 120,
messageCount: 240,
anchorMessageId: makeMessageId("burst", "user", 1),
terminalMessageId: makeMessageId("burst", "assistant", 120),
planStride: 30,
activityStride: 10,
diffStride: 12,
},
turnCount: 48,
messageCount: 640,
planStride: 12,
activityStride: 4,
diffStride: 5,
}),
} as const satisfies Record<string, PerfSeedThreadScenario>;
const LIGHT_THREADS: ReadonlyArray<PerfSeedThreadScenario> = 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 LARGE_THREAD_LIGHT_LAYOUT = [
{
project: PERF_PROJECTS.inbox,
label: "Inbox",
count: 5,
},
);
{
project: PERF_PROJECTS.desktop,
label: "Desktop",
count: 6,
},
{
project: PERF_PROJECTS.runtime,
label: "Runtime",
count: 5,
},
{
project: PERF_PROJECTS.marketing,
label: "Marketing",
count: 6,
},
{
project: PERF_PROJECTS.ops,
label: "Ops",
count: 5,
},
] as const;
const BURST_NAVIGATION_THREAD: PerfSeedThreadScenario = {
...LIGHT_THREADS[0]!,
title: "Burst Navigation Thread",
};
const LARGE_THREAD_LIGHT_THREADS: ReadonlyArray<PerfSeedThreadScenario> =
LARGE_THREAD_LIGHT_LAYOUT.flatMap((layout, projectIndex) =>
Array.from({ length: layout.count }, (_, localIndex) => {
const globalIndex =
LARGE_THREAD_LIGHT_LAYOUT.slice(0, projectIndex).reduce(
(sum, entry) => sum + entry.count,
0,
) + localIndex;
const threadNumber = localIndex + 1;
const turnCount = 18 + ((globalIndex * 7 + projectIndex * 5 + localIndex * 3) % 8) * 7;
const messageDensity = 4 + ((globalIndex + projectIndex + localIndex) % 5);
const messageCount = Math.min(
900,
turnCount * messageDensity + 48 + ((globalIndex + projectIndex) % 5) * 18,
);
const BURST_FILLER_THREAD: PerfSeedThreadScenario = {
...LIGHT_THREADS[1]!,
title: "Burst Filler Thread",
};
return makeSeedThreadScenario({
slug: `${layout.label.toLowerCase()}-light-${threadNumber.toString().padStart(2, "0")}`,
projectId: layout.project.id,
title: `${layout.label} Thread ${threadNumber}`,
category: "light",
turnCount,
messageCount,
planStride: globalIndex % 4 === 0 ? 14 + ((globalIndex + localIndex) % 5) : null,
activityStride: 5 + ((globalIndex + localIndex) % 4),
diffStride: globalIndex % 3 === 0 ? 6 + ((projectIndex + localIndex) % 4) : null,
});
}),
);
const BURST_BASE_THREAD_DEFINITIONS = {
burst: makeSeedThreadScenario({
slug: "burst",
projectId: PERF_PROJECTS.burstBase.id,
title: "Burst Target Thread",
category: "burst",
turnCount: 36,
messageCount: 220,
planStride: 12,
activityStride: 4,
diffStride: 6,
}),
navigation: makeSeedThreadScenario({
slug: "burst-navigation",
projectId: PERF_PROJECTS.burstBase.id,
title: "Burst Navigation Thread",
category: "light",
turnCount: 28,
messageCount: 112,
planStride: null,
activityStride: 5,
diffStride: null,
}),
filler: makeSeedThreadScenario({
slug: "burst-filler",
projectId: PERF_PROJECTS.burstBase.id,
title: "Burst Filler Thread",
category: "light",
turnCount: 24,
messageCount: 96,
planStride: null,
activityStride: 6,
diffStride: null,
}),
} as const satisfies Record<string, PerfSeedThreadScenario>;
const BURST_NAVIGATION_THREAD = BURST_BASE_THREAD_DEFINITIONS.navigation;
const BURST_FILLER_THREAD = BURST_BASE_THREAD_DEFINITIONS.filler;
export const PERF_SEED_SCENARIOS = {
large_threads: {
id: "large_threads",
project: PERF_PROJECT,
projects: [
PERF_PROJECTS.inbox,
PERF_PROJECTS.desktop,
PERF_PROJECTS.runtime,
PERF_PROJECTS.marketing,
PERF_PROJECTS.ops,
],
threads: [
LARGE_THREAD_DEFINITIONS.heavyA,
LARGE_THREAD_DEFINITIONS.heavyB,
LARGE_THREAD_DEFINITIONS.burst,
...LIGHT_THREADS,
...LARGE_THREAD_LIGHT_THREADS,
],
},
burst_base: {
id: "burst_base",
project: PERF_PROJECT,
threads: [LARGE_THREAD_DEFINITIONS.burst, BURST_NAVIGATION_THREAD, BURST_FILLER_THREAD],
projects: [PERF_PROJECTS.burstBase],
threads: [BURST_BASE_THREAD_DEFINITIONS.burst, BURST_NAVIGATION_THREAD, BURST_FILLER_THREAD],
},
} as const satisfies Record<PerfSeedScenarioId, PerfSeedScenario>;
@@ -187,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";
@@ -894,24 +1094,83 @@ function buildDenseAssistantStreamScenario(): PerfProviderScenario {
};
}
function buildParallelAssistantStreamScenario(): PerfProviderScenario {
const events: Array<TimedFixtureProviderRuntimeEvent> = [
{
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<PerfProviderScenarioId, PerfProviderScenario>;
export const PERF_CATALOG_IDS = {
projectId: PERF_PROJECT.id,
projectId: PERF_PROJECTS.inbox.id,
largeThreads: {
heavyAThreadId: LARGE_THREAD_DEFINITIONS.heavyA.id,
heavyBThreadId: LARGE_THREAD_DEFINITIONS.heavyB.id,
heavyAProjectId: LARGE_THREAD_DEFINITIONS.heavyA.projectId,
heavyBProjectId: LARGE_THREAD_DEFINITIONS.heavyB.projectId,
heavyAProjectTitle: PERF_PROJECTS.inbox.title,
heavyBProjectTitle: PERF_PROJECTS.desktop.title,
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,
burstProjectId: PERF_PROJECTS.burstBase.id,
burstProjectTitle: PERF_PROJECTS.burstBase.title,
burstThreadId: BURST_BASE_THREAD_DEFINITIONS.burst.id,
burstAnchorMessageId: BURST_BASE_THREAD_DEFINITIONS.burst.anchorMessageId,
burstTerminalMessageId: BURST_BASE_THREAD_DEFINITIONS.burst.terminalMessageId,
navigationThreadId: BURST_NAVIGATION_THREAD.id,
navigationAnchorMessageId: BURST_NAVIGATION_THREAD.anchorMessageId,
navigationTerminalMessageId: BURST_NAVIGATION_THREAD.terminalMessageId,
@@ -919,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(
@@ -942,7 +1202,7 @@ export function getPerfProviderScenario(scenarioId: PerfProviderScenarioId): Per
}
export function perfTurnIdForThread(thread: PerfSeedThreadScenario, turnIndex: number): TurnId {
const threadSlug = thread.id.replace("perf-thread-", "");
const threadSlug = threadSlugFromId(thread.id);
return makeTurnId(threadSlug, turnIndex);
}
@@ -950,9 +1210,10 @@ export function perfMessageIdForThread(
thread: PerfSeedThreadScenario,
role: "user" | "assistant",
turnIndex: number,
messageIndex = 1,
): MessageId {
const threadSlug = thread.id.replace("perf-thread-", "");
return makeMessageId(threadSlug, role, turnIndex);
const threadSlug = threadSlugFromId(thread.id);
return makeMessageId(threadSlug, role, turnIndex, messageIndex);
}
export function perfEventId(prefix: string, threadId: ThreadId, index: number) {
+20 -3
View File
@@ -18,19 +18,30 @@ type PerfProviderScenarioId = "dense_assistant_stream";
interface PerfSeedThreadSummary {
readonly id: string;
readonly projectId: string;
readonly projectTitle: string | null;
readonly title: string;
readonly turnCount: number | null;
readonly messageCount: number;
readonly activityCount: number;
readonly proposedPlanCount: number;
readonly checkpointCount: number;
}
interface PerfSeedProjectSummary {
readonly id: string;
readonly title: string;
readonly workspaceRoot: string;
readonly threadCount: number;
}
interface PerfSeededState {
readonly scenarioId: PerfSeedScenarioId;
readonly runParentDir: string;
readonly baseDir: string;
readonly workspaceRoot: string;
readonly projectTitle: string | null;
readonly projectSummaries: ReadonlyArray<PerfSeedProjectSummary>;
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
}
@@ -279,15 +290,21 @@ function printSeedSummary(
process.stdout.write(`\nPerf app ready at ${url}\n`);
process.stdout.write(`Scenario: ${seededState.scenarioId}\n`);
process.stdout.write(`Base dir: ${seededState.baseDir}\n`);
process.stdout.write(`Workspace: ${seededState.workspaceRoot}\n`);
process.stdout.write(`Project: ${seededState.projectTitle ?? "<unknown>"}\n`);
process.stdout.write(`Primary workspace: ${seededState.workspaceRoot}\n`);
process.stdout.write("Projects:\n");
for (const project of seededState.projectSummaries) {
process.stdout.write(
` - ${project.title} (${project.id}): ${project.threadCount} threads, ${project.workspaceRoot}\n`,
);
}
process.stdout.write("Threads:\n");
for (const thread of seededState.threadSummaries.toSorted(
(left, right) =>
right.messageCount - left.messageCount || left.title.localeCompare(right.title),
)) {
process.stdout.write(
` - ${thread.title} (${thread.id}): ${thread.messageCount} messages, ${thread.activityCount} worklog rows, ${thread.proposedPlanCount} plans, ${thread.checkpointCount} checkpoints\n`,
` - ${thread.projectTitle ?? "<unknown project>"} / ${thread.title} (${thread.id}): ${thread.turnCount ?? "?"} turns, ${thread.messageCount} messages, ${thread.activityCount} worklog rows, ${thread.proposedPlanCount} plans, ${thread.checkpointCount} checkpoints\n`,
);
}
+12 -19
View File
@@ -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<string, unknown>;
}
export function percentile(values: ReadonlyArray<number>, 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<void> {
const resolvedOutputPath = resolve(outputPath);
await mkdir(dirname(resolvedOutputPath), { recursive: true });
await writeFile(`${resolvedOutputPath}`, `${JSON.stringify(artifact, null, 2)}\n`, "utf8");
await writeJsonArtifact(outputPath, artifact);
}