Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

commands.performance.test.ts

277 lines9.4 KB

1import {
2 CommandId,
3 EnvironmentId,
4 MessageId,
5 ORCHESTRATION_V2_WS_METHODS,
6 OrchestrationV2RpcSchemas,
7 TurnItemId,
8 type OrchestrationV2Command,
9 type OrchestrationV2ProjectedTurnItem,
10 type OrchestrationV2ThreadProjection,
11 type OrchestrationV2TurnItem,
12} from "@t3tools/contracts";
13import { describe, expect, it } from "@effect/vitest";
14import * as Crypto from "effect/Crypto";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import type * as RpcMessage from "effect/rpc/RpcMessage";
21​
22import {
23 AVAILABLE_CONNECTION_STATE,
24 PrimaryConnectionTarget,
25 type PreparedConnection,
26} from "../connection/model.ts";
27import * as EnvironmentSupervisor from "../connection/supervisor.ts";
28import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
29import * as RpcSession from "../rpc/session.ts";
30import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
31import { startThreadTurn } from "./commands.ts";
32​
33const ROW_COUNT = 600;
34const OUTPUT_BYTES_PER_ROW = 8_192;
35​
36const HISTORICAL_FULL_PROJECTION_APPLICATION_BYTES = 10_371_419;
37const HISTORICAL_FORMER_SEND_APPLICATION_BYTES = 10_371_678;
38const FORMER_SEND_RPC_JSON_BYTES = 10_372_184;
39const MAX_CURRENT_SEND_RPC_JSON_BYTES = 1_024;
40​
41const RPC_TRACE_CONTEXT = {
42 traceId: "0".repeat(32),
43 spanId: "0".repeat(16),
44 sampled: true,
45} as const;
46​
47const encodeGetThreadProjectionInput = Schema.encodeSync(
48 Schema.toCodecJson(OrchestrationV2RpcSchemas.getThreadProjection.input),
49);
50const encodeGetThreadProjectionOutput = Schema.encodeSync(
51 Schema.toCodecJson(OrchestrationV2RpcSchemas.getThreadProjection.output),
52);
53const encodeDispatchCommandInput = Schema.encodeSync(
54 Schema.toCodecJson(OrchestrationV2RpcSchemas.dispatchCommand.input),
55);
56const encodeDispatchCommandOutput = Schema.encodeSync(
57 Schema.toCodecJson(OrchestrationV2RpcSchemas.dispatchCommand.output),
58);
59​
60function encodedBytes(value: unknown): number {
61 return new TextEncoder().encode(JSON.stringify(value)).byteLength;
63​
64function encodedRpcRequestBytes(input: {
65 readonly requestId: number;
66 readonly tag: string;
67 readonly payload: unknown;
68}): number {
69 const request = {
70 _tag: "Request",
71 id: input.requestId,
72 tag: input.tag,
73 payload: input.payload,
74 ...RPC_TRACE_CONTEXT,
75 headers: [],
76 } satisfies RpcMessage.RequestEncoded;
77 return encodedBytes(request);
79​
80function encodedRpcSuccessBytes(input: {
81 readonly requestId: number;
82 readonly value: unknown;
83}): number {
84 const response = {
85 _tag: "Exit",
86 requestId: input.requestId,
87 exit: { _tag: "Success", value: input.value },
88 } satisfies RpcMessage.ResponseExitEncoded;
89 return encodedBytes(response);
91​
92function makeLargeProjection(): OrchestrationV2ThreadProjection {
93 const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from(
94 { length: ROW_COUNT },
95 (_, index) => {
96 const item: OrchestrationV2TurnItem = {
97 id: TurnItemId.make(`item-${index}`),
98 type: "command_execution",
99 threadId: v2ThreadId,
100 runId: null,
101 nodeId: null,
102 providerThreadId: null,
103 providerTurnId: null,
104 nativeItemRef: null,
105 parentItemId: null,
106 ordinal: index + 1,
107 status: "completed",
108 title: `Command ${index}`,
109 input: `cmd-${index}`,
110 output: "x".repeat(OUTPUT_BYTES_PER_ROW),
111 exitCode: 0,
112 startedAt: v2Now,
113 completedAt: v2Now,
114 updatedAt: v2Now,
115 };
116 return {
117 position: index,
118 visibility: "local",
119 sourceThreadId: v2ThreadId,
120 sourceItemId: item.id,
121 item,
122 };
123 },
124 );
125​
126 return {
127 ...v2Projection,
128 turnItems: visibleTurnItems.map((row) => row.item),
129 visibleTurnItems,
130 };
132​
133const TARGET = new PrimaryConnectionTarget({
134 environmentId: EnvironmentId.make("environment-perf"),
135 label: "Performance fixture",
136 httpBaseUrl: "https://environment.example.test",
137 wsBaseUrl: "wss://environment.example.test",
138});
139​
140const layerTestCrypto = Layer.succeed(
141 Crypto.Crypto,
142 Crypto.make({
143 randomBytes: (size) => new Uint8Array(size),
144 digest: (_algorithm, data) => Effect.succeed(data),
145 }),
146);
147​
148const makeSupervisor = Effect.fn("CommandPerformance.makeSupervisor")(function* (input: {
149 readonly projection: OrchestrationV2ThreadProjection;
150 readonly projectionRequests: Array<unknown>;
151 readonly projectionResponseBytes: { value: number };
152 readonly commands: OrchestrationV2Command[];
153}) {
154 const client = {
155 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (requestInput: unknown) =>
156 Effect.sync(() => {
157 input.projectionRequests.push(requestInput);
158 input.projectionResponseBytes.value += encodedBytes(input.projection);
159 return input.projection;
160 }),
161 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
162 Effect.sync(() => {
163 input.commands.push(command);
164 return { sequence: input.commands.length };
165 }),
166 } as unknown as WsRpcProtocolClient;
167 const session: RpcSession.RpcSession = {
168 client,
169 initialConfig: Effect.succeed({
170 environment: {
171 capabilities: {
172 repositoryIdentity: true,
173 serverResolvedCommandContext: true,
174 },
175 },
176 } as never),
177 subscribeServerConfig: (requestInput) => client.subscribeServerConfig(requestInput),
178 ready: Effect.void,
179 probe: Effect.void,
180 inboundFrames: Effect.succeed(0),
181 closed: Effect.never,
182 };
183 return EnvironmentSupervisor.EnvironmentSupervisor.of({
184 target: TARGET,
185 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
186 session: yield* SubscriptionRef.make(Option.some(session)),
187 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
188 connect: Effect.void,
189 disconnect: Effect.void,
190 retryNow: Effect.void,
191 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
192});
193​
194describe("routine command transport budget", () => {
195 it.effect("dispatches an implicit-auto message without a full projection round trip", () =>
196 Effect.gen(function* () {
197 const projection = makeLargeProjection();
198 const projectionRequests: unknown[] = [];
199 const projectionResponseBytes = { value: 0 };
200 const commands: OrchestrationV2Command[] = [];
201 const supervisor = yield* makeSupervisor({
202 projection,
203 projectionRequests,
204 projectionResponseBytes,
205 commands,
206 });
207​
208 const receipt = yield* startThreadTurn({
209 commandId: CommandId.make("perf-send"),
210 threadId: v2ThreadId,
211 message: {
212 messageId: MessageId.make("message-perf"),
213 role: "user",
214 text: "continue",
215 attachments: [],
216 },
217 runtimeMode: "full-access",
218 interactionMode: "default",
219 titleSeed: "continue",
220 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
221​
222 const command = commands[0]!;
223 if (command.type !== "message.dispatch") {
224 throw new Error(`Expected message.dispatch, received ${command.type}`);
225 }
226 if ("projection" in receipt) {
227 throw new Error("Expected a dispatch receipt");
228 }
229 const { deliveryIntent: _deliveryIntent, ...formerCommand } = command;
230​
231 const historicalApplicationBytes =
232 encodedBytes(projection) + encodedBytes(formerCommand) + encodedBytes(receipt);
233 const projectionRequestRpcJsonBytes = encodedRpcRequestBytes({
234 requestId: 0,
235 tag: ORCHESTRATION_V2_WS_METHODS.getThreadProjection,
236 payload: encodeGetThreadProjectionInput({ threadId: v2ThreadId }),
237 });
238 const projectionResponseRpcJsonBytes = encodedRpcSuccessBytes({
239 requestId: 0,
240 value: encodeGetThreadProjectionOutput(projection),
241 });
242 const formerDispatchRequestRpcJsonBytes = encodedRpcRequestBytes({
243 requestId: 1,
244 tag: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
245 payload: encodeDispatchCommandInput(formerCommand),
246 });
247 const currentDispatchRequestRpcJsonBytes = encodedRpcRequestBytes({
248 requestId: 1,
249 tag: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
250 payload: encodeDispatchCommandInput(command),
251 });
252 const receiptRpcJsonBytes = encodedRpcSuccessBytes({
253 requestId: 1,
254 value: encodeDispatchCommandOutput(receipt),
255 });
256 const formerRpcJsonBytes =
257 projectionRequestRpcJsonBytes +
258 projectionResponseRpcJsonBytes +
259 formerDispatchRequestRpcJsonBytes +
260 receiptRpcJsonBytes;
261 const currentRpcJsonBytes = currentDispatchRequestRpcJsonBytes + receiptRpcJsonBytes;
262​
263 expect(encodedBytes(projection)).toBe(HISTORICAL_FULL_PROJECTION_APPLICATION_BYTES);
264 expect(historicalApplicationBytes).toBe(HISTORICAL_FORMER_SEND_APPLICATION_BYTES);
265 expect(formerRpcJsonBytes).toBe(FORMER_SEND_RPC_JSON_BYTES);
266 expect(projectionRequests).toEqual([]);
267 expect(projectionResponseBytes.value).toBe(0);
268 expect(command).toMatchObject({
269 type: "message.dispatch",
270 deliveryIntent: "auto",
271 dispatchMode: { type: "start_immediately" },
272 });
273 expect(currentRpcJsonBytes).toBeLessThanOrEqual(MAX_CURRENT_SEND_RPC_JSON_BYTES);
274 expect(currentRpcJsonBytes / formerRpcJsonBytes).toBeLessThanOrEqual(0.000_06);
275 }).pipe(Effect.provide(layerTestCrypto)),
276 );
277});