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

PiAdapterV2.testkit.ts

469 lines16.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 ProviderReplayEntry,
4 type ProviderInstanceEnvironment,
5 type ProviderReplayTranscript,
6 type ProviderReplayEntry as ProviderReplayEntryType,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Queue from "effect/Queue";
12import * as Schema from "effect/Schema";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16​
17import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
18import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver";
20import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
21import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
22import { PI_PROVIDER, PiAdapterV2Driver } from "@t3tools/provider-pi/server";
23​
24export const PI_RPC_REPLAY_PROTOCOL = "pi.rpc-jsonl";
25export const PI_REPLAY_ANY = "<any>";
26​
27const PiRpcReplayTranscript = Schema.Struct({
28 provider: Schema.Literal(PI_PROVIDER),
29 protocol: Schema.Literal(PI_RPC_REPLAY_PROTOCOL),
30 version: Schema.String,
31 scenario: Schema.String,
32 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
33 entries: Schema.Array(ProviderReplayEntry),
34});
35type PiRpcReplayTranscript = typeof PiRpcReplayTranscript.Type;
36const decodePiRpcReplayTranscript = Schema.decodeUnknownEffect(PiRpcReplayTranscript);
37​
38class PiReplayTranscriptDecodeError extends Schema.TaggedError<PiReplayTranscriptDecodeError>()(
39 "PiReplayTranscriptDecodeError",
40 {
41 driver: Schema.optional(Schema.String),
42 protocol: Schema.optional(Schema.String),
43 scenario: Schema.optional(Schema.String),
44 cause: Schema.Defect(),
45 },
46) {
47 override get message(): string {
48 return `Failed to decode Pi RPC replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
49 }
51​
52class PiReplayMismatchError extends Schema.TaggedError<PiReplayMismatchError>()(
53 "PiReplayMismatchError",
54 {
55 scenario: Schema.String,
56 cursor: Schema.Number,
57 process: Schema.Number,
58 label: Schema.optional(Schema.String),
59 actualType: Schema.optional(Schema.String),
60 expected: Schema.Unknown,
61 actual: Schema.Unknown,
62 },
63) {
64 override get message(): string {
65 return `Pi replay frame mismatch at cursor ${this.cursor} (expected ${this.label ?? "<none>"}, received ${this.actualType ?? "<untyped>"} from process ${this.process}) in scenario ${this.scenario}.`;
66 }
68​
69class PiReplayIncompleteError extends Schema.TaggedError<PiReplayIncompleteError>()(
70 "PiReplayIncompleteError",
71 {
72 scenario: Schema.String,
73 cursor: Schema.Number,
74 remaining: Schema.Number,
75 nextLabel: Schema.optional(Schema.String),
76 },
77) {
78 override get message(): string {
79 return `Pi replay ended with ${this.remaining} unconsumed entries at cursor ${this.cursor} (next ${this.nextLabel ?? "<none>"}) in scenario ${this.scenario}.`;
80 }
82​
83function entryLabel(entry: ProviderReplayEntryType | undefined): string | undefined {
84 if (entry === undefined) return undefined;
85 return entry.type === "runtime_exit" ? "runtime_exit" : (entry.label ?? entry.type);
87​
88const PiOrchestratorReplayHarnessError = Schema.Union([
89 PiReplayTranscriptDecodeError,
90 ProviderAdapterDriverCreateError,
91]);
92type PiOrchestratorReplayHarnessError = typeof PiOrchestratorReplayHarnessError.Type;
93​
94function isRecord(value: unknown): value is Record<string, unknown> {
95 return typeof value === "object" && value !== null && !Array.isArray(value);
97​
98function replayValueMatches(expected: unknown, actual: unknown): boolean {
99 if (expected === PI_REPLAY_ANY) return true;
100 if (Array.isArray(expected)) {
101 return (
102 Array.isArray(actual) &&
103 expected.length === actual.length &&
104 expected.every((entry, index) => replayValueMatches(entry, actual[index]))
105 );
106 }
107 if (isRecord(expected)) {
108 if (!isRecord(actual)) return false;
109 const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
110 return [...keys].every((key) => replayValueMatches(expected[key], actual[key]));
111 }
112 return Object.is(expected, actual);
114​
115const ADAPTER_REQUEST_ID = /^t3-\d+$/u;
116​
117function adapterRequestId(frame: unknown): string | undefined {
118 const id = isRecord(frame) ? frame.id : undefined;
119 return typeof id === "string" && ADAPTER_REQUEST_ID.test(id) ? id : undefined;
121​
122/** Rebind adapter request ids without pinning counters; provider ids that responses must echo stay exact. */
123function withRequestId(expected: unknown, actual: unknown): unknown {
124 const actualId = adapterRequestId(actual);
125 return isRecord(expected) && adapterRequestId(expected) !== undefined && actualId !== undefined
126 ? { ...expected, id: actualId }
127 : expected;
129​
130function startsTurn(entry: ProviderReplayEntryType): boolean {
131 if (entry.type !== "expect_outbound") return false;
132 const type = isRecord(entry.frame) ? entry.frame.type : undefined;
133 return type === "prompt" || type === "compact" || type === "process_start";
135​
136function processStartFrame(command: ChildProcess.Command) {
137 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
138 return { type: "process_start", args: [...args] };
140​
141function entryProcess(entry: ProviderReplayEntryType): number {
142 const label = entry.type === "runtime_exit" ? undefined : entry.label;
143 const match = label === undefined ? null : /@p(\d+)$/u.exec(label);
144 return match === null ? 1 : Number(match[1]);
146​
147function recordLabel(frame: unknown, process: number): string | undefined {
148 const base = !isRecord(frame)
149 ? undefined
150 : frame.type === "response" && typeof frame.command === "string"
151 ? `response:${frame.command}`
152 : typeof frame.type === "string"
153 ? frame.type
154 : undefined;
155 if (base === undefined || process === 1) return base;
156 return `${base}@p${process}`;
158​
159const decodeJsonLine = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
160const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
161​
162function makeLineSplitter() {
163 let buffer = "";
164 const decoder = new TextDecoder();
165 return (chunk: Uint8Array): ReadonlyArray<string> => {
166 buffer += decoder.decode(chunk, { stream: true });
167 const lines = buffer.split("\n");
168 buffer = lines.pop() ?? "";
169 return lines.map((line) => line.replace(/\r$/u, "")).filter((line) => line.length > 0);
170 };
172​
173interface PiReplayProcess {
174 readonly ordinal: number;
175 readonly stdout: Queue.Queue<Uint8Array, Cause.Done>;
176 readonly ids: Map<string, string>;
177 open: boolean;
179​
180/** Adapter fibers can reorder stdin writes; hold matches within the turn until reached, and fail unmatched writes. */
181class PiReplayController {
182 private cursor = 0;
183 private failure: unknown = null;
184 private readonly consumed = new Set<number>();
185 private readonly held: Array<{ readonly process: PiReplayProcess; readonly actual: unknown }> =
186 [];
187 private readonly processes: Array<PiReplayProcess> = [];
188 private readonly transcript: PiRpcReplayTranscript;
189​
190 constructor(transcript: PiRpcReplayTranscript) {
191 this.transcript = transcript;
192 }
193​
194 spawn(
195 command: ChildProcess.Command,
196 stdout: Queue.Queue<Uint8Array, Cause.Done>,
197 ): PiReplayProcess {
198 const process: PiReplayProcess = {
199 ordinal: this.processes.length + 1,
200 stdout,
201 ids: new Map(),
202 open: true,
203 };
204 this.processes.push(process);
205 this.receive(process, processStartFrame(command));
206 return process;
207 }
208​
209 receive(process: PiReplayProcess, actual: unknown): void {
210 if (this.failure !== null) return;
211 const entries = this.transcript.entries;
212 let possible = false;
213 for (let index = this.cursor; index < entries.length && !possible; index += 1) {
214 const entry = entries[index]!;
215 const pending = entry.type === "expect_outbound" && !this.consumed.has(index);
216 possible =
217 pending &&
218 entryProcess(entry) === process.ordinal &&
219 replayValueMatches(withRequestId(entry.frame, actual), actual);
220 if (!possible && pending && startsTurn(entry)) break;
221 }
222 if (!possible) {
223 const expected = entries[this.cursor];
224 const label = entryLabel(expected);
225 const actualType = isRecord(actual) ? actual.type : undefined;
226 this.fail(
227 new PiReplayMismatchError({
228 scenario: this.transcript.scenario,
229 cursor: this.cursor,
230 process: process.ordinal,
231 ...(label === undefined ? {} : { label }),
232 ...(typeof actualType === "string" ? { actualType } : {}),
233 expected: expected ?? null,
234 actual,
235 }),
236 );
237 return;
238 }
239 this.held.push({ process, actual });
240 this.advance();
241 }
242​
243 close(process: PiReplayProcess): void {
244 process.open = false;
245 Queue.endUnsafe(process.stdout);
246 }
247​
248 assertComplete(): void {
249 if (this.failure !== null) throw this.failure;
250 if (this.cursor !== this.transcript.entries.length || this.held.length > 0) {
251 const nextLabel = entryLabel(this.transcript.entries[this.cursor]);
252 throw new PiReplayIncompleteError({
253 scenario: this.transcript.scenario,
254 cursor: this.cursor,
255 remaining: this.transcript.entries.length - this.cursor,
256 ...(nextLabel === undefined ? {} : { nextLabel }),
257 });
258 }
259 }
260​
261 private advance(): void {
262 let progressed = true;
263 while (progressed && this.failure === null) {
264 progressed = this.drainInbound();
265 for (const [heldIndex, write] of this.held.entries()) {
266 if (this.consumePending(write.process, write.actual)) {
267 this.held.splice(heldIndex, 1);
268 progressed = true;
269 break;
270 }
271 }
272 }
273 }
274​
275 private consumePending(process: PiReplayProcess, actual: unknown): boolean {
276 const entries = this.transcript.entries;
277 for (let index = this.cursor; index < entries.length; index += 1) {
278 const entry = entries[index]!;
279 if (entry.type !== "expect_outbound") return false;
280 if (this.consumed.has(index) || entryProcess(entry) !== process.ordinal) continue;
281 if (!replayValueMatches(withRequestId(entry.frame, actual), actual)) continue;
282 const recordedId = adapterRequestId(entry.frame);
283 const actualId = adapterRequestId(actual);
284 if (recordedId !== undefined && actualId !== undefined) {
285 process.ids.set(recordedId, actualId);
286 }
287 this.consumed.add(index);
288 while (this.consumed.has(this.cursor)) this.cursor += 1;
289 return true;
290 }
291 return false;
292 }
293​
294 private drainInbound(): boolean {
295 let emitted = false;
296 while (this.failure === null) {
297 const entry = this.transcript.entries[this.cursor];
298 if (entry?.type === "runtime_exit") {
299 this.cursor += 1;
300 emitted = true;
301 const process = this.processes.at(-1);
302 if (process !== undefined) this.close(process);
303 continue;
304 }
305 if (entry?.type !== "emit_inbound") return emitted;
306 const process = this.processes[entryProcess(entry) - 1];
307 if (process === undefined) return emitted;
308 this.cursor += 1;
309 emitted = true;
310 if (!process.open) continue;
311 const frame = entry.frame;
312 const recordedId = isRecord(frame) ? frame.id : undefined;
313 const reboundId = typeof recordedId === "string" ? process.ids.get(recordedId) : undefined;
314 const rebound =
315 isRecord(frame) && reboundId !== undefined ? { ...frame, id: reboundId } : frame;
316 Queue.offerUnsafe(process.stdout, new TextEncoder().encode(`${encodeJsonLine(rebound)}\n`));
317 }
318 return emitted;
319 }
320​
321 private fail(cause: unknown): void {
322 if (this.failure !== null) return;
323 this.failure = cause;
324 for (const process of this.processes) Queue.endUnsafe(process.stdout);
325 }
327​
328/** Deliberately outside the valid pid range so PiRpc's group kill never lands. */
329const REPLAY_PID = 999_999_999;
330​
331function makePiReplaySpawner(
332 controller: PiReplayController,
333): ChildProcessSpawner.ChildProcessSpawner["Service"] {
334 return ChildProcessSpawner.make((command) =>
335 Effect.gen(function* () {
336 const process = controller.spawn(command, yield* Queue.unbounded<Uint8Array, Cause.Done>());
337 yield* Effect.addFinalizer(() => Effect.sync(() => controller.close(process)));
338 const split = makeLineSplitter();
339 return ChildProcessSpawner.makeHandle({
340 pid: ChildProcessSpawner.ProcessId(REPLAY_PID),
341 exitCode: Effect.never,
342 isRunning: Effect.succeed(true),
343 kill: () => Effect.void,
344 unref: Effect.succeed(Effect.void),
345 stdin: Sink.forEach((chunk: Uint8Array) =>
346 Effect.sync(() => {
347 for (const line of split(chunk)) controller.receive(process, decodeJsonLine(line));
348 }),
349 ),
350 stdout: Stream.fromQueue(process.stdout),
351 stderr: Stream.empty,
352 all: Stream.empty,
353 getInputFd: () => Sink.drain,
354 getOutputFd: () => Stream.empty,
355 });
356 }),
357 );
359​
360export function layer<E, R>(input: {
361 readonly scenario: string;
362 readonly spawner: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner, E, R>;
363 readonly binaryPath: string;
364 readonly launchArgs: string;
365 readonly environment?: ProviderInstanceEnvironment;
366}) {
367 return ProviderAdapterRegistry.layerFromDrivers({
368 drivers: [PiAdapterV2Driver],
369 configMap: {
370 [PI_PROVIDER]: {
371 driver: PI_PROVIDER,
372 enabled: true,
373 config: { binaryPath: input.binaryPath, launchArgs: input.launchArgs },
374 ...(input.environment === undefined ? {} : { environment: input.environment }),
375 },
376 },
377 }).pipe(
378 Layer.provide(input.spawner),
379 Layer.provide(
380 Layer.mergeAll(
381 TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)),
382 NodeServices.layer,
383 IdAllocator.layer,
384 ),
385 ),
386 );
388​
389function metadataString(transcript: PiRpcReplayTranscript, key: string): string {
390 const value = transcript.metadata?.[key];
391 return typeof value === "string" ? value : "";
393​
394export const PiOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
395 PiRpcReplayTranscript,
396 PiOrchestratorReplayHarnessError
397> = {
398 driver: PI_PROVIDER,
399 decodeTranscript: (transcript: ProviderReplayTranscript) =>
400 decodePiRpcReplayTranscript(transcript).pipe(
401 Effect.mapError(
402 (cause) =>
403 new PiReplayTranscriptDecodeError({
404 driver: transcript.provider,
405 protocol: transcript.protocol,
406 scenario: transcript.scenario,
407 cause,
408 }),
409 ),
410 ),
411 makeProviderAdapterRegistryLayer: (transcript) =>
412 layer({
413 scenario: transcript.scenario,
414 binaryPath: "pi",
415 launchArgs: metadataString(transcript, "launchArgs"),
416 spawner: Layer.effect(
417 ChildProcessSpawner.ChildProcessSpawner,
418 Effect.gen(function* () {
419 const controller = new PiReplayController(transcript);
420 yield* Effect.addFinalizer(() => Effect.sync(() => controller.assertComplete()));
421 return makePiReplaySpawner(controller);
422 }),
423 ),
424 }),
425};
426​
427export function makePiRecordingSpawner(
428 live: ChildProcessSpawner.ChildProcessSpawner["Service"],
429 entries: Array<ProviderReplayEntryType>,
430): ChildProcessSpawner.ChildProcessSpawner["Service"] {
431 let spawned = 0;
432 return ChildProcessSpawner.make((command) =>
433 Effect.gen(function* () {
434 const handle = yield* live.spawn(command);
435 const process = ++spawned;
436 const record = (type: "expect_outbound" | "emit_inbound", frame: unknown) => {
437 const label = recordLabel(frame, process);
438 entries.push({ type, ...(label === undefined ? {} : { label }), frame });
439 };
440 const recordLines = (
441 type: "expect_outbound" | "emit_inbound",
442 lines: ReadonlyArray<string>,
443 ) => {
444 for (const line of lines) {
445 try {
446 record(type, decodeJsonLine(line));
447 } catch {
448 // PiRpc drops non-JSON stdout lines, so the transcript does too.
449 }
450 }
451 };
452 record("expect_outbound", processStartFrame(command));
453 const splitIn = makeLineSplitter();
454 const splitOut = makeLineSplitter();
455 return ChildProcessSpawner.makeHandle({
456 ...handle,
457 stdin: handle.stdin.pipe(
458 Sink.mapInput((chunk: Uint8Array) => {
459 recordLines("expect_outbound", splitIn(chunk));
460 return chunk;
461 }),
462 ),
463 stdout: handle.stdout.pipe(
464 Stream.tap((chunk) => Effect.sync(() => recordLines("emit_inbound", splitOut(chunk)))),
465 ),
466 });
467 }),
468 );