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

PiAdapterV2.testkit.ts

524 lines19.6 KB

1/**
2 * Pi RPC replay: swaps the `ChildProcessSpawner` that `PiAdapterV2` uses to
3 * spawn `pi --mode rpc` for one that answers from a recorded transcript. The
4 * real adapter and `PiRpc` framing run unchanged against recorded Pi output.
5 *
6 * Transcript entries are stdio records. `expect_outbound` is one JSONL record
7 * the adapter wrote to stdin and `emit_inbound` is one record Pi wrote to
8 * stdout. Pi echoes the adapter's request ids, so a recorded id is rebound to
9 * the id the replaying adapter actually sent. `<any>` in an outbound frame
10 * matches any value.
11 *
12 * Every spawned Pi process begins with a synthetic `process_start` outbound
13 * record carrying its argv. Records of the Nth process (N > 1) carry an `@pN`
14 * label suffix, because a native fork runs a short-lived `--fork` process
15 * next to the session process.
16 */
17import * as NodeServices from "@effect/platform-node/NodeServices";
18import {
19 ProviderReplayEntry,
20 type ProviderInstanceEnvironment,
21 type ProviderReplayTranscript,
22 type ProviderReplayEntry as ProviderReplayEntryType,
23} from "@t3tools/contracts";
24import * as Cause from "effect/Cause";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Queue from "effect/Queue";
28import * as Schema from "effect/Schema";
29import * as Sink from "effect/Sink";
30import * as Stream from "effect/Stream";
31import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
32​
33import * as ServerConfig from "../../config.ts";
34import * as IdAllocator from "../IdAllocator.ts";
35import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts";
36import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
37import {
38 makeReplayServerConfig,
39 type OrchestratorV2ProviderReplayHarness,
40} from "../testkit/ProviderReplayHarness.ts";
41import { PI_PROVIDER, PiAdapterV2Driver } from "./PiAdapterV2.ts";
42​
43export const PI_RPC_REPLAY_PROTOCOL = "pi.rpc-jsonl";
44export const PI_REPLAY_ANY = "<any>";
45​
46const PiRpcReplayTranscript = Schema.Struct({
47 provider: Schema.Literal(PI_PROVIDER),
48 protocol: Schema.Literal(PI_RPC_REPLAY_PROTOCOL),
49 version: Schema.String,
50 scenario: Schema.String,
51 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
52 entries: Schema.Array(ProviderReplayEntry),
53});
54type PiRpcReplayTranscript = typeof PiRpcReplayTranscript.Type;
55const decodePiRpcReplayTranscript = Schema.decodeUnknownEffect(PiRpcReplayTranscript);
56​
57class PiReplayTranscriptDecodeError extends Schema.TaggedError<PiReplayTranscriptDecodeError>()(
58 "PiReplayTranscriptDecodeError",
59 {
60 driver: Schema.optional(Schema.String),
61 protocol: Schema.optional(Schema.String),
62 scenario: Schema.optional(Schema.String),
63 cause: Schema.Defect(),
64 },
65) {
66 override get message(): string {
67 return `Failed to decode Pi RPC replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
68 }
70​
71class PiReplayMismatchError extends Schema.TaggedError<PiReplayMismatchError>()(
72 "PiReplayMismatchError",
73 {
74 scenario: Schema.String,
75 cursor: Schema.Number,
76 process: Schema.Number,
77 label: Schema.optional(Schema.String),
78 actualType: Schema.optional(Schema.String),
79 expected: Schema.Unknown,
80 actual: Schema.Unknown,
81 },
82) {
83 override get message(): string {
84 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}.`;
85 }
87​
88class PiReplayIncompleteError extends Schema.TaggedError<PiReplayIncompleteError>()(
89 "PiReplayIncompleteError",
90 {
91 scenario: Schema.String,
92 cursor: Schema.Number,
93 remaining: Schema.Number,
94 nextLabel: Schema.optional(Schema.String),
95 },
96) {
97 override get message(): string {
98 return `Pi replay ended with ${this.remaining} unconsumed entries at cursor ${this.cursor} (next ${this.nextLabel ?? "<none>"}) in scenario ${this.scenario}.`;
99 }
101​
102/** Label or, failing that, entry type: bounded context for a replay error. */
103function entryLabel(entry: ProviderReplayEntryType | undefined): string | undefined {
104 if (entry === undefined) return undefined;
105 return entry.type === "runtime_exit" ? "runtime_exit" : (entry.label ?? entry.type);
107​
108const PiOrchestratorReplayHarnessError = Schema.Union([
109 PiReplayTranscriptDecodeError,
110 ProviderAdapterDriverCreateError,
111]);
112type PiOrchestratorReplayHarnessError = typeof PiOrchestratorReplayHarnessError.Type;
113​
114function isRecord(value: unknown): value is Record<string, unknown> {
115 return typeof value === "object" && value !== null && !Array.isArray(value);
117​
118function replayValueMatches(expected: unknown, actual: unknown): boolean {
119 if (expected === PI_REPLAY_ANY) return true;
120 if (Array.isArray(expected)) {
121 return (
122 Array.isArray(actual) &&
123 expected.length === actual.length &&
124 expected.every((entry, index) => replayValueMatches(entry, actual[index]))
125 );
126 }
127 if (isRecord(expected)) {
128 if (!isRecord(actual)) return false;
129 const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
130 return [...keys].every((key) => replayValueMatches(expected[key], actual[key]));
131 }
132 return Object.is(expected, actual);
134​
135/** PiRpc numbers its correlated requests `t3-N` per process. */
136const ADAPTER_REQUEST_ID = /^t3-\d+$/u;
137​
138function adapterRequestId(frame: unknown): string | undefined {
139 const id = isRecord(frame) ? frame.id : undefined;
140 return typeof id === "string" && ADAPTER_REQUEST_ID.test(id) ? id : undefined;
142​
143/**
144 * Compares a recorded request against the adapter's own request id, so the
145 * correlation Pi recorded holds without pinning counter values. Any other id,
146 * such as the Pi request id an `extension_ui_response` must echo, stays exact.
147 */
148function withRequestId(expected: unknown, actual: unknown): unknown {
149 const actualId = adapterRequestId(actual);
150 return isRecord(expected) && adapterRequestId(expected) !== undefined && actualId !== undefined
151 ? { ...expected, id: actualId }
152 : expected;
154​
155/** A write may not match past one of these: it would be a turn early. */
156function startsTurn(entry: ProviderReplayEntryType): boolean {
157 if (entry.type !== "expect_outbound") return false;
158 const type = isRecord(entry.frame) ? entry.frame.type : undefined;
159 return type === "prompt" || type === "compact" || type === "process_start";
161​
162function processStartFrame(command: ChildProcess.Command) {
163 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
164 return { type: "process_start", args: [...args] };
166​
167/** `response:get_state@p2` belongs to the second spawned process; no suffix is the first. */
168function entryProcess(entry: ProviderReplayEntryType): number {
169 const label = entry.type === "runtime_exit" ? undefined : entry.label;
170 const match = label === undefined ? null : /@p(\d+)$/u.exec(label);
171 return match === null ? 1 : Number(match[1]);
173​
174function recordLabel(frame: unknown, process: number): string | undefined {
175 const base = !isRecord(frame)
176 ? undefined
177 : frame.type === "response" && typeof frame.command === "string"
178 ? `response:${frame.command}`
179 : typeof frame.type === "string"
180 ? frame.type
181 : undefined;
182 if (base === undefined || process === 1) return base;
183 return `${base}@p${process}`;
185​
186const decodeJsonLine = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
187const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
188​
189/** Splits a byte stream into LF-delimited records, as Pi's RPC framing requires. */
190function makeLineSplitter() {
191 let buffer = "";
192 const decoder = new TextDecoder();
193 return (chunk: Uint8Array): ReadonlyArray<string> => {
194 buffer += decoder.decode(chunk, { stream: true });
195 const lines = buffer.split("\n");
196 buffer = lines.pop() ?? "";
197 return lines.map((line) => line.replace(/\r$/u, "")).filter((line) => line.length > 0);
198 };
200​
201interface PiReplayProcess {
202 readonly ordinal: number;
203 readonly stdout: Queue.Queue<Uint8Array, Cause.Done>;
204 /** Recorded request id -> id the replaying adapter sent in its place. */
205 readonly ids: Map<string, string>;
206 open: boolean;
208​
209/**
210 * Drives every Pi process of one scenario from a single ordered transcript.
211 * Outbound records must match the recording; the inbound records that follow
212 * them are written to the stdout of the process that produced them.
213 *
214 * Independent adapter fibers (skill discovery beside thread setup, a settle
215 * probe beside a steer) can reach stdin in a different order than recorded, so
216 * a write that matches a later outbound record of the same turn is held until
217 * the transcript reaches it. A write that matches nothing before the next
218 * turn-starting record fails immediately.
219 */
220class PiReplayController {
221 private cursor = 0;
222 private failure: unknown = null;
223 private readonly consumed = new Set<number>();
224 private readonly held: Array<{ readonly process: PiReplayProcess; readonly actual: unknown }> =
225 [];
226 private readonly processes: Array<PiReplayProcess> = [];
227 private readonly transcript: PiRpcReplayTranscript;
228​
229 constructor(transcript: PiRpcReplayTranscript) {
230 this.transcript = transcript;
231 }
232​
233 spawn(
234 command: ChildProcess.Command,
235 stdout: Queue.Queue<Uint8Array, Cause.Done>,
236 ): PiReplayProcess {
237 const process: PiReplayProcess = {
238 ordinal: this.processes.length + 1,
239 stdout,
240 ids: new Map(),
241 open: true,
242 };
243 this.processes.push(process);
244 this.receive(process, processStartFrame(command));
245 return process;
246 }
247​
248 receive(process: PiReplayProcess, actual: unknown): void {
249 if (this.failure !== null) return;
250 const entries = this.transcript.entries;
251 let possible = false;
252 for (let index = this.cursor; index < entries.length && !possible; index += 1) {
253 const entry = entries[index]!;
254 const pending = entry.type === "expect_outbound" && !this.consumed.has(index);
255 possible =
256 pending &&
257 entryProcess(entry) === process.ordinal &&
258 replayValueMatches(withRequestId(entry.frame, actual), actual);
259 if (!possible && pending && startsTurn(entry)) break;
260 }
261 if (!possible) {
262 const expected = entries[this.cursor];
263 const label = entryLabel(expected);
264 const actualType = isRecord(actual) ? actual.type : undefined;
265 this.fail(
266 new PiReplayMismatchError({
267 scenario: this.transcript.scenario,
268 cursor: this.cursor,
269 process: process.ordinal,
270 ...(label === undefined ? {} : { label }),
271 ...(typeof actualType === "string" ? { actualType } : {}),
272 expected: expected ?? null,
273 actual,
274 }),
275 );
276 return;
277 }
278 this.held.push({ process, actual });
279 this.advance();
280 }
281​
282 /** The adapter released a process: its scope closed. */
283 close(process: PiReplayProcess): void {
284 process.open = false;
285 Queue.endUnsafe(process.stdout);
286 }
287​
288 assertComplete(): void {
289 if (this.failure !== null) throw this.failure;
290 if (this.cursor !== this.transcript.entries.length || this.held.length > 0) {
291 const nextLabel = entryLabel(this.transcript.entries[this.cursor]);
292 throw new PiReplayIncompleteError({
293 scenario: this.transcript.scenario,
294 cursor: this.cursor,
295 remaining: this.transcript.entries.length - this.cursor,
296 ...(nextLabel === undefined ? {} : { nextLabel }),
297 });
298 }
299 }
300​
301 /** Emits due inbound records and consumes held writes until neither can progress. */
302 private advance(): void {
303 let progressed = true;
304 while (progressed && this.failure === null) {
305 progressed = this.drainInbound();
306 for (const [heldIndex, write] of this.held.entries()) {
307 if (this.consumePending(write.process, write.actual)) {
308 this.held.splice(heldIndex, 1);
309 progressed = true;
310 break;
311 }
312 }
313 }
314 }
315​
316 /** Matches a write against the outbound records due before the next inbound one. */
317 private consumePending(process: PiReplayProcess, actual: unknown): boolean {
318 const entries = this.transcript.entries;
319 for (let index = this.cursor; index < entries.length; index += 1) {
320 const entry = entries[index]!;
321 if (entry.type !== "expect_outbound") return false;
322 if (this.consumed.has(index) || entryProcess(entry) !== process.ordinal) continue;
323 if (!replayValueMatches(withRequestId(entry.frame, actual), actual)) continue;
324 const recordedId = adapterRequestId(entry.frame);
325 const actualId = adapterRequestId(actual);
326 if (recordedId !== undefined && actualId !== undefined) {
327 process.ids.set(recordedId, actualId);
328 }
329 this.consumed.add(index);
330 while (this.consumed.has(this.cursor)) this.cursor += 1;
331 return true;
332 }
333 return false;
334 }
335​
336 private drainInbound(): boolean {
337 let emitted = false;
338 while (this.failure === null) {
339 const entry = this.transcript.entries[this.cursor];
340 if (entry?.type === "runtime_exit") {
341 // Pi exited on its own in the recording: end the newest process's
342 // stdout, which is the EOF the adapter observed.
343 this.cursor += 1;
344 emitted = true;
345 const process = this.processes.at(-1);
346 if (process !== undefined) this.close(process);
347 continue;
348 }
349 if (entry?.type !== "emit_inbound") return emitted;
350 const process = this.processes[entryProcess(entry) - 1];
351 if (process === undefined) return emitted;
352 this.cursor += 1;
353 emitted = true;
354 // Output a process wrote after the adapter released it was never observed.
355 if (!process.open) continue;
356 const frame = entry.frame;
357 const recordedId = isRecord(frame) ? frame.id : undefined;
358 const reboundId = typeof recordedId === "string" ? process.ids.get(recordedId) : undefined;
359 const rebound =
360 isRecord(frame) && reboundId !== undefined ? { ...frame, id: reboundId } : frame;
361 Queue.offerUnsafe(process.stdout, new TextEncoder().encode(`${encodeJsonLine(rebound)}\n`));
362 }
363 return emitted;
364 }
365​
366 private fail(cause: unknown): void {
367 if (this.failure !== null) return;
368 this.failure = cause;
369 for (const process of this.processes) Queue.endUnsafe(process.stdout);
370 }
372​
373/** Deliberately outside the valid pid range so PiRpc's group kill never lands. */
374const REPLAY_PID = 999_999_999;
375​
376function makePiReplaySpawner(
377 controller: PiReplayController,
378): ChildProcessSpawner.ChildProcessSpawner["Service"] {
379 return ChildProcessSpawner.make((command) =>
380 Effect.gen(function* () {
381 const process = controller.spawn(command, yield* Queue.unbounded<Uint8Array, Cause.Done>());
382 yield* Effect.addFinalizer(() => Effect.sync(() => controller.close(process)));
383 const split = makeLineSplitter();
384 return ChildProcessSpawner.makeHandle({
385 pid: ChildProcessSpawner.ProcessId(REPLAY_PID),
386 exitCode: Effect.never,
387 isRunning: Effect.succeed(true),
388 kill: () => Effect.void,
389 unref: Effect.succeed(Effect.void),
390 stdin: Sink.forEach((chunk: Uint8Array) =>
391 Effect.sync(() => {
392 for (const line of split(chunk)) controller.receive(process, decodeJsonLine(line));
393 }),
394 ),
395 stdout: Stream.fromQueue(process.stdout),
396 stderr: Stream.empty,
397 all: Stream.empty,
398 getInputFd: () => Sink.drain,
399 getOutputFd: () => Stream.empty,
400 });
401 }),
402 );
404​
405/**
406 * Registry with the real Pi driver on the given spawner. The recorder passes a
407 * spawner that tees a live `pi`; replay passes the transcript-backed one. The
408 * launch arguments are part of the recorded argv, so replay reuses them.
409 */
410export function makePiProviderAdapterRegistryLayer<E, R>(input: {
411 readonly scenario: string;
412 readonly spawner: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner, E, R>;
413 readonly binaryPath: string;
414 readonly launchArgs: string;
415 readonly environment?: ProviderInstanceEnvironment;
416}) {
417 const serverConfigLayer = Layer.effect(
418 ServerConfig.ServerConfig,
419 makeReplayServerConfig(`pi-${input.scenario}`).pipe(Effect.orDie),
420 ).pipe(Layer.provide(NodeServices.layer));
421 return ProviderAdapterRegistry.makeDriverLayer({
422 drivers: [PiAdapterV2Driver],
423 configMap: {
424 [PI_PROVIDER]: {
425 driver: PI_PROVIDER,
426 enabled: true,
427 config: { binaryPath: input.binaryPath, launchArgs: input.launchArgs },
428 ...(input.environment === undefined ? {} : { environment: input.environment }),
429 },
430 },
431 }).pipe(
432 Layer.provide(input.spawner),
433 Layer.provide(Layer.mergeAll(serverConfigLayer, NodeServices.layer, IdAllocator.layer)),
434 );
436​
437function metadataString(transcript: PiRpcReplayTranscript, key: string): string {
438 const value = transcript.metadata?.[key];
439 return typeof value === "string" ? value : "";
441​
442export const PiOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
443 PiRpcReplayTranscript,
444 PiOrchestratorReplayHarnessError
445> = {
446 driver: PI_PROVIDER,
447 decodeTranscript: (transcript: ProviderReplayTranscript) =>
448 decodePiRpcReplayTranscript(transcript).pipe(
449 Effect.mapError(
450 (cause) =>
451 new PiReplayTranscriptDecodeError({
452 driver: transcript.provider,
453 protocol: transcript.protocol,
454 scenario: transcript.scenario,
455 cause,
456 }),
457 ),
458 ),
459 makeProviderAdapterRegistryLayer: (transcript) =>
460 makePiProviderAdapterRegistryLayer({
461 scenario: transcript.scenario,
462 binaryPath: "pi",
463 launchArgs: metadataString(transcript, "launchArgs"),
464 spawner: Layer.effect(
465 ChildProcessSpawner.ChildProcessSpawner,
466 Effect.gen(function* () {
467 const controller = new PiReplayController(transcript);
468 yield* Effect.addFinalizer(() => Effect.sync(() => controller.assertComplete()));
469 return makePiReplaySpawner(controller);
470 }),
471 ),
472 }),
473};
474​
475// ── recording ─────────────────────────────────────────────────
476​
477/**
478 * Wraps a live spawner and tees every Pi process's stdin and stdout records
479 * into `entries` in the order the adapter observed them: writes as the adapter
480 * makes them, reads as the adapter pulls them.
481 */
482export function makePiRecordingSpawner(
483 live: ChildProcessSpawner.ChildProcessSpawner["Service"],
484 entries: Array<ProviderReplayEntryType>,
485): ChildProcessSpawner.ChildProcessSpawner["Service"] {
486 let spawned = 0;
487 return ChildProcessSpawner.make((command) =>
488 Effect.gen(function* () {
489 const handle = yield* live.spawn(command);
490 const process = ++spawned;
491 const record = (type: "expect_outbound" | "emit_inbound", frame: unknown) => {
492 const label = recordLabel(frame, process);
493 entries.push({ type, ...(label === undefined ? {} : { label }), frame });
494 };
495 const recordLines = (
496 type: "expect_outbound" | "emit_inbound",
497 lines: ReadonlyArray<string>,
498 ) => {
499 for (const line of lines) {
500 try {
501 record(type, decodeJsonLine(line));
502 } catch {
503 // PiRpc drops non-JSON stdout lines, so the transcript does too.
504 }
505 }
506 };
507 record("expect_outbound", processStartFrame(command));
508 const splitIn = makeLineSplitter();
509 const splitOut = makeLineSplitter();
510 return ChildProcessSpawner.makeHandle({
511 ...handle,
512 stdin: handle.stdin.pipe(
513 Sink.mapInput((chunk: Uint8Array) => {
514 recordLines("expect_outbound", splitIn(chunk));
515 return chunk;
516 }),
517 ),
518 stdout: handle.stdout.pipe(
519 Stream.tap((chunk) => Effect.sync(() => recordLines("emit_inbound", splitOut(chunk)))),
520 ),
521 });
522 }),
523 );