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

commands.performance.test.ts

276 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 closed: Effect.never,
181 };
182 return EnvironmentSupervisor.EnvironmentSupervisor.of({
183 target: TARGET,
184 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
185 session: yield* SubscriptionRef.make(Option.some(session)),
186 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
187 connect: Effect.void,
188 disconnect: Effect.void,
189 retryNow: Effect.void,
190 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
191});
192​
193describe("routine command transport budget", () => {
194 it.effect("dispatches an implicit-auto message without a full projection round trip", () =>
195 Effect.gen(function* () {
196 const projection = makeLargeProjection();
197 const projectionRequests: unknown[] = [];
198 const projectionResponseBytes = { value: 0 };
199 const commands: OrchestrationV2Command[] = [];
200 const supervisor = yield* makeSupervisor({
201 projection,
202 projectionRequests,
203 projectionResponseBytes,
204 commands,
205 });
206​
207 const receipt = yield* startThreadTurn({
208 commandId: CommandId.make("perf-send"),
209 threadId: v2ThreadId,
210 message: {
211 messageId: MessageId.make("message-perf"),
212 role: "user",
213 text: "continue",
214 attachments: [],
215 },
216 runtimeMode: "full-access",
217 interactionMode: "default",
218 titleSeed: "continue",
219 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
220​
221 const command = commands[0]!;
222 if (command.type !== "message.dispatch") {
223 throw new Error(`Expected message.dispatch, received ${command.type}`);
224 }
225 if (!("sequence" in receipt)) {
226 throw new Error("Expected a dispatch receipt");
227 }
228 const { deliveryIntent: _deliveryIntent, ...formerCommand } = command;
229​
230 const historicalApplicationBytes =
231 encodedBytes(projection) + encodedBytes(formerCommand) + encodedBytes(receipt);
232 const projectionRequestRpcJsonBytes = encodedRpcRequestBytes({
233 requestId: 0,
234 tag: ORCHESTRATION_V2_WS_METHODS.getThreadProjection,
235 payload: encodeGetThreadProjectionInput({ threadId: v2ThreadId }),
236 });
237 const projectionResponseRpcJsonBytes = encodedRpcSuccessBytes({
238 requestId: 0,
239 value: encodeGetThreadProjectionOutput(projection),
240 });
241 const formerDispatchRequestRpcJsonBytes = encodedRpcRequestBytes({
242 requestId: 1,
243 tag: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
244 payload: encodeDispatchCommandInput(formerCommand),
245 });
246 const currentDispatchRequestRpcJsonBytes = encodedRpcRequestBytes({
247 requestId: 1,
248 tag: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
249 payload: encodeDispatchCommandInput(command),
250 });
251 const receiptRpcJsonBytes = encodedRpcSuccessBytes({
252 requestId: 1,
253 value: encodeDispatchCommandOutput(receipt),
254 });
255 const formerRpcJsonBytes =
256 projectionRequestRpcJsonBytes +
257 projectionResponseRpcJsonBytes +
258 formerDispatchRequestRpcJsonBytes +
259 receiptRpcJsonBytes;
260 const currentRpcJsonBytes = currentDispatchRequestRpcJsonBytes + receiptRpcJsonBytes;
261​
262 expect(encodedBytes(projection)).toBe(HISTORICAL_FULL_PROJECTION_APPLICATION_BYTES);
263 expect(historicalApplicationBytes).toBe(HISTORICAL_FORMER_SEND_APPLICATION_BYTES);
264 expect(formerRpcJsonBytes).toBe(FORMER_SEND_RPC_JSON_BYTES);
265 expect(projectionRequests).toEqual([]);
266 expect(projectionResponseBytes.value).toBe(0);
267 expect(command).toMatchObject({
268 type: "message.dispatch",
269 deliveryIntent: "auto",
270 dispatchMode: { type: "start_immediately" },
271 });
272 expect(currentRpcJsonBytes).toBeLessThanOrEqual(MAX_CURRENT_SEND_RPC_JSON_BYTES);
273 expect(currentRpcJsonBytes / formerRpcJsonBytes).toBeLessThanOrEqual(0.000_06);
274 }).pipe(Effect.provide(layerTestCrypto)),
275 );
276});