Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointScopeId,
4 CommandId,
5 MessageId,
6 NodeId,
7 type OrchestrationV2AppThread,
8 type OrchestrationV2CheckpointScope,
9 type OrchestrationV2ExecutionNode,
10 type OrchestrationV2ProviderThread,
11 type OrchestrationV2Run,
12 type OrchestrationV2RunAttempt,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 ProviderSessionId,
16 ProviderThreadId,
17 ProviderTurnId,
18 RunAttemptId,
19 RunId,
20 ThreadId,
21} from "@t3tools/contracts";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Ref from "effect/Ref";
28import * as Stream from "effect/Stream";
29
30import { ServerSettingsService } from "../serverSettings.ts";
31import { CheckpointServiceV2 } from "./CheckpointService.ts";
32import { EventSinkV2 } from "./EventSink.ts";
33import { layer as idAllocatorLayer } from "./IdAllocator.ts";
34import type { ProviderAdapterV2Event, ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts";
35import { ProviderEventIngestorV2, ProviderEventNormalizeError } from "./ProviderEventIngestor.ts";
36import {
37 finalProviderThreadStatus,
38 layer as runExecutionServiceLayer,
39 makeProviderEventRoutingState,
40 type ProviderEventRouteIdentity,
41 routeProviderEvent,
42 RunExecutionServiceV2,
43} from "./RunExecutionService.ts";
44
45const driver = ProviderDriverKind.make("codex");
46
47const RunExecutionTestLayer = runExecutionServiceLayer.pipe(
48 Layer.provide(
49 Layer.mergeAll(
50 Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
51 Layer.mock(EventSinkV2)({}),
52 idAllocatorLayer,
53 Layer.mock(ProviderEventIngestorV2)({ ingestNormalized: () => Effect.succeed([]) }),
54 ServerSettingsService.layerTest(),
55 ),
56 ),
57);
58
59it("keeps recoverable turn failures reusable and reserves error for broken threads", () => {
60 assert.equal(finalProviderThreadStatus("reusable"), "idle");
61 assert.equal(finalProviderThreadStatus("broken"), "error");
62});
63
64it.effect("routes shared-runtime events only to their owning root run", () =>
65 Effect.gen(function* () {
66 const now = yield* DateTime.now;
67 const first: ProviderEventRouteIdentity = {
68 threadId: ThreadId.make("thread:shared-runtime:first"),
69 runId: RunId.make("run:shared-runtime:first"),
70 attemptId: RunAttemptId.make("attempt:shared-runtime:first"),
71 providerThreadId: ProviderThreadId.make("provider-thread:shared-runtime:first"),
72 };
73 const second: ProviderEventRouteIdentity = {
74 threadId: ThreadId.make("thread:shared-runtime:second"),
75 runId: RunId.make("run:shared-runtime:second"),
76 attemptId: RunAttemptId.make("attempt:shared-runtime:second"),
77 providerThreadId: ProviderThreadId.make("provider-thread:shared-runtime:second"),
78 };
79 const firstTurnId = ProviderTurnId.make("provider-turn:shared-runtime:first");
80 const turnEvent: ProviderAdapterV2Event = {
81 type: "provider_turn.updated",
82 driver,
83 threadId: first.threadId,
84 providerTurn: {
85 id: firstTurnId,
86 providerThreadId: first.providerThreadId,
87 nodeId: NodeId.make("node:shared-runtime:first"),
88 runAttemptId: first.attemptId,
89 nativeTurnRef: null,
90 ordinal: 1,
91 status: "running",
92 startedAt: now,
93 completedAt: null,
94 },
95 };
96 const messageEvent: ProviderAdapterV2Event = {
97 type: "message.updated",
98 driver,
99 message: {
100 createdBy: "agent",
101 creationSource: "provider",
102 id: MessageId.make("message:shared-runtime:first"),
103 threadId: first.threadId,
104 runId: first.runId,
105 nodeId: NodeId.make("node:shared-runtime:first"),
106 role: "assistant",
107 text: "first only",
108 attachments: [],
109 streaming: false,
110 createdAt: now,
111 updatedAt: now,
112 },
113 };
114 const terminalEvent: ProviderAdapterV2Event = {
115 type: "turn.terminal",
116 driver,
117 providerThreadId: first.providerThreadId,
118 providerTurnId: firstTurnId,
119 runOrdinal: 1,
120 status: "completed",
121 failure: null,
122 threadDisposition: "reusable",
123 };
124
125 const firstInitial = makeProviderEventRoutingState({
126 identity: first,
127 providerTurnId: null,
128 });
129 const secondInitial = makeProviderEventRoutingState({
130 identity: second,
131 providerTurnId: null,
132 });
133 const [firstTurnAccepted, firstAfterTurn] = routeProviderEvent(turnEvent, first, firstInitial);
134 const [secondTurnAccepted, secondAfterTurn] = routeProviderEvent(
135 turnEvent,
136 second,
137 secondInitial,
138 );
139
140 assert.isTrue(firstTurnAccepted);
141 assert.isFalse(secondTurnAccepted);
142 assert.isTrue(routeProviderEvent(messageEvent, first, firstAfterTurn)[0]);
143 assert.isFalse(routeProviderEvent(messageEvent, second, secondAfterTurn)[0]);
144 assert.isTrue(routeProviderEvent(terminalEvent, first, firstAfterTurn)[0]);
145 assert.isFalse(routeProviderEvent(terminalEvent, second, secondAfterTurn)[0]);
146 }),
147);
148
149it("does not route a superseded attempt through a reused provider thread", () => {
150 const threadId = ThreadId.make("thread:shared-runtime:restart");
151 const providerThreadId = ProviderThreadId.make("provider-thread:shared-runtime:restart");
152 const oldAttempt: ProviderEventRouteIdentity = {
153 threadId,
154 runId: RunId.make("run:shared-runtime:restart"),
155 attemptId: RunAttemptId.make("attempt:shared-runtime:restart:old"),
156 providerThreadId,
157 };
158 const newAttempt: ProviderEventRouteIdentity = {
159 ...oldAttempt,
160 attemptId: RunAttemptId.make("attempt:shared-runtime:restart:new"),
161 };
162 const oldTurnEvent: ProviderAdapterV2Event = {
163 type: "provider_turn.updated",
164 driver,
165 threadId,
166 providerTurn: {
167 id: ProviderTurnId.make("provider-turn:shared-runtime:restart:old"),
168 providerThreadId,
169 nodeId: NodeId.make("node:shared-runtime:restart:old"),
170 runAttemptId: oldAttempt.attemptId,
171 nativeTurnRef: null,
172 ordinal: 1,
173 status: "interrupted",
174 startedAt: null,
175 completedAt: null,
176 },
177 };
178
179 const newState = makeProviderEventRoutingState({ identity: newAttempt, providerTurnId: null });
180 assert.isFalse(routeProviderEvent(oldTurnEvent, newAttempt, newState)[0]);
181});
182
183it.effect("rechecks run ownership immediately before calling the provider", () =>
184 Effect.gen(function* () {
185 const runExecution = yield* RunExecutionServiceV2;
186 const guardCalls = yield* Ref.make(0);
187 const providerStarts = yield* Ref.make(0);
188 const threadId = ThreadId.make("thread:run-execution-start-guard");
189 const runId = RunId.make("run:run-execution-start-guard");
190 const attemptId = RunAttemptId.make("attempt:run-execution-start-guard");
191 const providerThreadId = ProviderThreadId.make("provider-thread:run-execution-start-guard");
192 const providerInstanceId = ProviderInstanceId.make("codex");
193 const providerSessionId = ProviderSessionId.make("session:run-execution-start-guard");
194 const rootNodeId = NodeId.make("node:run-execution-start-guard");
195 const run = {
196 id: runId,
197 threadId,
198 ordinal: 1,
199 providerInstanceId,
200 } as OrchestrationV2Run;
201 const rootNode = { id: rootNodeId } as OrchestrationV2ExecutionNode;
202 const providerThread = {
203 id: providerThreadId,
204 driver,
205 } as OrchestrationV2ProviderThread;
206 const attempt = {
207 id: attemptId,
208 providerTurnId: null,
209 } as OrchestrationV2RunAttempt;
210 const session = {
211 events: Stream.never,
212 startTurn: () => Ref.update(providerStarts, (count) => count + 1),
213 } as unknown as ProviderAdapterV2SessionRuntime;
214
215 yield* runExecution.startRootRun({
216 commandId: CommandId.make("command:run-execution-start-guard"),
217 appThread: { id: threadId } as OrchestrationV2AppThread,
218 providerSessionId,
219 session,
220 run,
221 rootNode,
222 checkpointScope: {
223 id: CheckpointScopeId.make("checkpoint-scope:run-execution-start-guard"),
224 } as OrchestrationV2CheckpointScope,
225 providerThread,
226 attempt,
227 attemptId,
228 providerTurnOrdinal: 1,
229 shouldStartProviderTurn: () =>
230 Ref.modify(guardCalls, (calls) => [calls === 0, calls + 1] as const),
231 message: {
232 messageId: MessageId.make("message:run-execution-start-guard"),
233 text: "Do not start after ownership changes.",
234 attachments: [],
235 createdBy: "user",
236 creationSource: "web",
237 },
238 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
239 runtimePolicy: {
240 runtimeMode: "full-access",
241 interactionMode: "default",
242 cwd: process.cwd(),
243 approvalPolicy: "never",
244 sandboxPolicy: {
245 type: "readOnly",
246 access: { type: "fullAccess" },
247 networkAccess: false,
248 },
249 },
250 });
251
252 assert.equal(yield* Ref.get(guardCalls), 2);
253 assert.equal(yield* Ref.get(providerStarts), 0);
254 }).pipe(Effect.provide(RunExecutionTestLayer)),
255);
256
257it.effect("keeps ingesting owned child events after the root turn terminalizes", () =>
258 Effect.gen(function* () {
259 const threadId = ThreadId.make("thread:run-execution-late-child");
260 const childThreadId = ThreadId.make("thread:run-execution-late-child:child");
261 const runId = RunId.make("run:run-execution-late-child");
262 const attemptId = RunAttemptId.make("attempt:run-execution-late-child");
263 const providerInstanceId = ProviderInstanceId.make("codex");
264 const providerSessionId = ProviderSessionId.make("session:run-execution-late-child");
265 const providerThreadId = ProviderThreadId.make("provider-thread:run-execution-late-child");
266 const childProviderThreadId = ProviderThreadId.make(
267 "provider-thread:run-execution-late-child:child",
268 );
269 const rootProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-late-child");
270 const childProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-late-child:child");
271 const rootNodeId = NodeId.make("node:run-execution-late-child");
272 const childNodeId = NodeId.make("node:run-execution-late-child:child");
273 const subagentNodeId = NodeId.make("node:run-execution-late-child:subagent");
274 const childMessageIngested = yield* Deferred.make<void>();
275 const order = yield* Ref.make<ReadonlyArray<string>>([]);
276 const testLayer = runExecutionServiceLayer.pipe(
277 Layer.provide(
278 Layer.mergeAll(
279 Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
280 Layer.mock(EventSinkV2)({
281 write: () => Effect.succeed([]),
282 writeWithEffects: (input) =>
283 Effect.gen(function* () {
284 if (
285 input.events.some(
286 (event) => event.type === "run.updated" && event.runId === runId,
287 )
288 ) {
289 yield* Ref.update(order, (current) => [...current, "root-finalized"]);
290 }
291 return [];
292 }),
293 writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }),
294 }),
295 idAllocatorLayer,
296 Layer.mock(ProviderEventIngestorV2)({
297 ingestNormalized: (input) =>
298 Effect.gen(function* () {
299 if (
300 input.event.type === "message.updated" &&
301 input.event.message.threadId === childThreadId
302 ) {
303 yield* Ref.update(order, (current) => [...current, "child-message"]);
304 yield* Deferred.succeed(childMessageIngested, undefined).pipe(Effect.ignore);
305 }
306 return [];
307 }),
308 }),
309 ServerSettingsService.layerTest(),
310 ),
311 ),
312 );
313 const events: ReadonlyArray<ProviderAdapterV2Event> = [
314 {
315 type: "app_thread.created",
316 driver,
317 appThread: {
318 id: childThreadId,
319 lineage: {
320 parentThreadId: threadId,
321 relationshipToParent: "subagent",
322 rootThreadId: threadId,
323 },
324 },
325 } as ProviderAdapterV2Event,
326 {
327 type: "provider_thread.updated",
328 driver,
329 providerThread: {
330 id: childProviderThreadId,
331 appThreadId: childThreadId,
332 },
333 } as ProviderAdapterV2Event,
334 {
335 type: "subagent.updated",
336 driver,
337 subagent: {
338 id: subagentNodeId,
339 threadId,
340 runId,
341 status: "running",
342 },
343 } as ProviderAdapterV2Event,
344 {
345 type: "provider_turn.updated",
346 driver,
347 threadId: childThreadId,
348 providerTurn: {
349 id: childProviderTurnId,
350 providerThreadId: childProviderThreadId,
351 nodeId: childNodeId,
352 runAttemptId: null,
353 status: "running",
354 },
355 } as ProviderAdapterV2Event,
356 {
357 type: "turn.terminal",
358 driver,
359 providerThreadId,
360 providerTurnId: rootProviderTurnId,
361 runOrdinal: 1,
362 status: "completed",
363 failure: null,
364 threadDisposition: "reusable",
365 },
366 {
367 type: "message.updated",
368 driver,
369 message: {
370 id: MessageId.make("message:run-execution-late-child:child"),
371 threadId: childThreadId,
372 runId: null,
373 nodeId: childNodeId,
374 role: "assistant",
375 text: "Hello.",
376 streaming: false,
377 },
378 } as ProviderAdapterV2Event,
379 {
380 type: "provider_turn.updated",
381 driver,
382 threadId: childThreadId,
383 providerTurn: {
384 id: childProviderTurnId,
385 providerThreadId: childProviderThreadId,
386 nodeId: childNodeId,
387 runAttemptId: null,
388 status: "completed",
389 },
390 } as ProviderAdapterV2Event,
391 {
392 type: "subagent.updated",
393 driver,
394 subagent: {
395 id: subagentNodeId,
396 threadId,
397 runId,
398 status: "completed",
399 },
400 } as ProviderAdapterV2Event,
401 ];
402
403 yield* Effect.gen(function* () {
404 const runExecution = yield* RunExecutionServiceV2;
405 yield* runExecution.startRootRun({
406 commandId: CommandId.make("command:run-execution-late-child"),
407 appThread: { id: threadId } as OrchestrationV2AppThread,
408 providerSessionId,
409 session: {
410 events: Stream.fromIterable(events),
411 startTurn: () => Effect.void,
412 } as unknown as ProviderAdapterV2SessionRuntime,
413 run: {
414 id: runId,
415 threadId,
416 ordinal: 1,
417 providerInstanceId,
418 } as OrchestrationV2Run,
419 rootNode: { id: rootNodeId } as OrchestrationV2ExecutionNode,
420 checkpointScope: {
421 id: CheckpointScopeId.make("checkpoint-scope:run-execution-late-child"),
422 } as OrchestrationV2CheckpointScope,
423 providerThread: {
424 id: providerThreadId,
425 driver,
426 } as OrchestrationV2ProviderThread,
427 attempt: {
428 id: attemptId,
429 providerTurnId: rootProviderTurnId,
430 } as OrchestrationV2RunAttempt,
431 attemptId,
432 providerTurnOrdinal: 1,
433 message: {
434 messageId: MessageId.make("message:run-execution-late-child:user"),
435 text: "Spawn a child and finish.",
436 attachments: [],
437 createdBy: "user",
438 creationSource: "web",
439 },
440 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
441 runtimePolicy: {
442 runtimeMode: "full-access",
443 interactionMode: "default",
444 cwd: process.cwd(),
445 approvalPolicy: "never",
446 sandboxPolicy: {
447 type: "readOnly",
448 access: { type: "fullAccess" },
449 networkAccess: false,
450 },
451 },
452 });
453 }).pipe(Effect.provide(testLayer));
454
455 const observed = yield* Deferred.await(childMessageIngested).pipe(
456 Effect.timeoutOption("2 seconds"),
457 );
458 assert.isTrue(Option.isSome(observed), "child message was not ingested after root terminal");
459 assert.deepEqual(yield* Ref.get(order), ["root-finalized", "child-message"]);
460 }),
461);
462
463it.effect("drops a poison event whose ingestion fails and keeps ingesting later events", () =>
464 Effect.gen(function* () {
465 const threadId = ThreadId.make("thread:run-execution-poison");
466 const runId = RunId.make("run:run-execution-poison");
467 const attemptId = RunAttemptId.make("attempt:run-execution-poison");
468 const providerInstanceId = ProviderInstanceId.make("codex");
469 const providerSessionId = ProviderSessionId.make("session:run-execution-poison");
470 const providerThreadId = ProviderThreadId.make("provider-thread:run-execution-poison");
471 const rootProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-poison");
472 const rootNodeId = NodeId.make("node:run-execution-poison");
473 const poisonMessageId = MessageId.make("message:run-execution-poison:poison");
474 const goodMessageId = MessageId.make("message:run-execution-poison:good");
475 const goodMessageIngested = yield* Deferred.make<void>();
476 const rootFinalized = yield* Deferred.make<void>();
477 const order = yield* Ref.make<ReadonlyArray<string>>([]);
478 const testLayer = runExecutionServiceLayer.pipe(
479 Layer.provide(
480 Layer.mergeAll(
481 Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
482 Layer.mock(EventSinkV2)({
483 write: () => Effect.succeed([]),
484 writeWithEffects: (input) =>
485 Effect.gen(function* () {
486 if (
487 input.events.some(
488 (event) => event.type === "run.updated" && event.runId === runId,
489 )
490 ) {
491 yield* Ref.update(order, (current) => [...current, "root-finalized"]);
492 yield* Deferred.succeed(rootFinalized, undefined).pipe(Effect.ignore);
493 }
494 return [];
495 }),
496 writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }),
497 }),
498 idAllocatorLayer,
499 Layer.mock(ProviderEventIngestorV2)({
500 ingestNormalized: (input) =>
501 Effect.gen(function* () {
502 if (
503 input.event.type === "message.updated" &&
504 input.event.message.id === poisonMessageId
505 ) {
506 return yield* new ProviderEventNormalizeError({
507 providerSessionId,
508 threadId,
509 providerEvent: input.event,
510 });
511 }
512 if (
513 input.event.type === "message.updated" &&
514 input.event.message.id === goodMessageId
515 ) {
516 yield* Ref.update(order, (current) => [...current, "good-message"]);
517 yield* Deferred.succeed(goodMessageIngested, undefined).pipe(Effect.ignore);
518 }
519 return [];
520 }),
521 }),
522 ServerSettingsService.layerTest(),
523 ),
524 ),
525 );
526 const events: ReadonlyArray<ProviderAdapterV2Event> = [
527 {
528 type: "message.updated",
529 driver,
530 message: {
531 id: poisonMessageId,
532 threadId,
533 runId,
534 nodeId: rootNodeId,
535 role: "assistant",
536 text: "poison",
537 streaming: false,
538 },
539 } as ProviderAdapterV2Event,
540 {
541 type: "message.updated",
542 driver,
543 message: {
544 id: goodMessageId,
545 threadId,
546 runId,
547 nodeId: rootNodeId,
548 role: "assistant",
549 text: "good",
550 streaming: false,
551 },
552 } as ProviderAdapterV2Event,
553 {
554 type: "turn.terminal",
555 driver,
556 providerThreadId,
557 providerTurnId: rootProviderTurnId,
558 runOrdinal: 1,
559 status: "completed",
560 failure: null,
561 threadDisposition: "reusable",
562 },
563 ];
564
565 yield* Effect.gen(function* () {
566 const runExecution = yield* RunExecutionServiceV2;
567 yield* runExecution.startRootRun({
568 commandId: CommandId.make("command:run-execution-poison"),
569 appThread: { id: threadId } as OrchestrationV2AppThread,
570 providerSessionId,
571 session: {
572 events: Stream.fromIterable(events),
573 startTurn: () => Effect.void,
574 } as unknown as ProviderAdapterV2SessionRuntime,
575 run: {
576 id: runId,
577 threadId,
578 ordinal: 1,
579 providerInstanceId,
580 } as OrchestrationV2Run,
581 rootNode: { id: rootNodeId } as OrchestrationV2ExecutionNode,
582 checkpointScope: {
583 id: CheckpointScopeId.make("checkpoint-scope:run-execution-poison"),
584 } as OrchestrationV2CheckpointScope,
585 providerThread: {
586 id: providerThreadId,
587 driver,
588 } as OrchestrationV2ProviderThread,
589 attempt: {
590 id: attemptId,
591 providerTurnId: rootProviderTurnId,
592 } as OrchestrationV2RunAttempt,
593 attemptId,
594 providerTurnOrdinal: 1,
595 message: {
596 messageId: MessageId.make("message:run-execution-poison:user"),
597 text: "Survive a poison event.",
598 attachments: [],
599 createdBy: "user",
600 creationSource: "web",
601 },
602 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
603 runtimePolicy: {
604 runtimeMode: "full-access",
605 interactionMode: "default",
606 cwd: process.cwd(),
607 approvalPolicy: "never",
608 sandboxPolicy: {
609 type: "readOnly",
610 access: { type: "fullAccess" },
611 networkAccess: false,
612 },
613 },
614 });
615 }).pipe(Effect.provide(testLayer));
616
617 const observed = yield* Deferred.await(goodMessageIngested).pipe(
618 Effect.timeoutOption("2 seconds"),
619 );
620 assert.isTrue(Option.isSome(observed), "good event was not ingested after the poison event");
621 const finalized = yield* Deferred.await(rootFinalized).pipe(Effect.timeoutOption("2 seconds"));
622 assert.isTrue(finalized._tag === "Some", "root run was not finalized after the poison event");
623 assert.deepEqual(yield* Ref.get(order), ["good-message", "root-finalized"]);
624 }),
625);